text:
#ifndef __GPUTYPES_H__
#define __GPUTYPES_H__
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <cuda.h>
#include <cublas_v2.h>
#include <curand.h>
#include <cudnn.h>
#include <vector_functions.h>
#include <cuda_runtime_api.h>
#include <builtin_types.h>
#include <cstring>
#include <cstdint>
#include <assert.h>
#include <mpi.h>
#include <memory>

using namespace std;

#define VALIDATION

/* Enforce use of CUDA 5.0 due to GK110 issues with 4.2 */
#if defined(CUDA_VERSION) && (CUDA_VERSION < 5000)
#error "CUDA support requires the use of a 5.0 or later CUDA toolkit. Aborting compilation."
#endif

/* Control of single and double precision use:
   use_DPFP - use double-precision math and accumulate in 64-bit fixed point
   use_SPFP - use single-precision math and accumulate in 64-bit fixed point
   use_HPFP - Identical to SPFP except weights are stored as 16-bit floating point to save space

   By default, use_SPFP is active.  The double-precision mode exists to analyze
   numerical behavior while HPFP is a potential science experiment
   suggested by Leo Dirac.
*/

//#define use_DPFP
#define use_SPFP
//#define use_HPFP

// Enforce definition of one and only one precision mode
#if !(defined(use_DPFP) && !defined(use_HPFP) && !defined(use_SPFP)) && \
    !(defined(use_HPFP) && !defined(use_DPFP) && !defined(use_SPFP)) && \
    !(defined(use_SPFP) && !defined(use_DPFP) && !defined(use_HPFP))
#error "You must define one and only one precision mode (use_SPFP, use_HPFP, or use_DPFP). Aborting compilation."
#endif

#define ESCALE  (1ll << 30)
static const double ERRORSCALE              = ESCALE;
static const float ERRORSCALEF              = ESCALE;
static const double ONEOVERERRORSCALE       = 1.0 / (double)(ERRORSCALE);
static const float ONEOVERERRORSCALEF       = (float)(1.0 / (double)(ERRORSCALE));

typedef double                  __align__(8)    aligned_double;
typedef unsigned long int       __align__(8)    aligned_uli;
typedef long long int           __align__(8)    aligned_lli;
typedef unsigned long long int  __align__(8)    UllInt;

#if defined(use_DPFP)
typedef double                  __align__(8)    NNAccumulator;
typedef double                  __align__(8)    NNDouble;
typedef double                  __align__(8)    NNFloat;
typedef double2                 __align__(16)   NNDouble2;
typedef double4                 __align__(32)   NNDouble4;
typedef double2                 __align__(16)   NNFloat2;
typedef double4                 __align__(16)   NNFloat4;
static const MPI_Datatype MPI_NNDOUBLE          = MPI_DOUBLE_PRECISION;
static const MPI_Datatype MPI_NNFLOAT           = MPI_DOUBLE_PRECISION;
static const MPI_Datatype MPI_NNACCUMULATOR     = MPI_FLOAT;
#elif defined(use_SPFP)
typedef float                                   NNAccumulator;
typedef double                  __align__(8)    NNDouble;
typedef float                                   NNFloat;
typedef double2                 __align__(16)   NNDouble2;
typedef double4                 __align__(32)   NNDouble4;
typedef float2                  __align__(8)    NNFloat2;
typedef float4                  __align__(16)   NNFloat4;
static const MPI_Datatype MPI_NNDOUBLE          = MPI_DOUBLE_PRECISION;
static const MPI_Datatype MPI_NNFLOAT           = MPI_FLOAT;
static const MPI_Datatype MPI_NNACCUMULATOR     = MPI_LONG_LONG_INT;
#else // use_HPFP
typedef float                                   NNAccumulator;
typedef double                  __align(8)__    NNDouble;
typedef float                                   NNFloat;
typedef double2                 __align(16)__   NNDouble2;
typedef double4                 __align(32)__   NNDouble4;
typedef float2                  __align(8)__    NNFloat2;
typedef float4                  __align(16)__   NNFloat4;
static const MPI_Datatype MPI_NNDOUBLE          = MPI_DOUBLE_PRECISION;
static const MPI_Datatype MPI_NNFLOAT           = MPI_FLOAT;
static const MPI_Datatype MPI_NNACCUMULATOR     = MPI_LONG_LONG_INT;
#endif

// Kernel dimensions - we only support SM 3.0 or better due to double-precision,
// atomic operations, and a 32-bit blockDim.x
static const int SM_3X_THREADS_PER_BLOCK                        = 128;
static const int SM_5X_THREADS_PER_BLOCK                        = 128;
static const int SM_6X_THREADS_PER_BLOCK                        = 128;

#if (__CUDA_ARCH__ >= 600)
#define LAUNCH_BOUNDS() __launch_bounds__(SM_6X_THREADS_PER_BLOCK, 8)
#define LAUNCH_BOUNDS256() __launch_bounds__(256, 5)
#elif (__CUDA_ARCH__ >= 500)
#define LAUNCH_BOUNDS() __launch_bounds__(SM_5X_THREADS_PER_BLOCK, 8)
#define LAUNCH_BOUNDS256() __launch_bounds__(256, 5)
#else
#define LAUNCH_BOUNDS() __launch_bounds__(SM_3X_THREADS_PER_BLOCK, 10)
#define LAUNCH_BOUNDS256() __launch_bounds__(256, 4)
#endif
#define LAUNCH_BOUNDS512() __launch_bounds__(512, 2)
#define LAUNCH_BOUNDS1024() __launch_bounds__(1024, 1)

// Sparse kernel limits
static const uint32_t SM_6X_MAXSPARSE = 4608;
static const uint32_t SM_6X_MAXSPARSEANALOG = 2304;
static const uint32_t SM_5X_MAXSPARSE = 4608;
static const uint32_t SM_5X_MAXSPARSEANALOG = 2304;
static const uint32_t SM_3X_MAXSPARSE = 2304;
static const uint32_t SM_3X_MAXSPARSEANALOG = 1152;

static const bool bShadowedOutputBuffers                        = false;    // Turns off sysmem shadowing of really large buffers

#define FPSCALE  (1ll << 40)
#define DFSCALE (1ll << 44)

//#define GVERBOSE
//#define MEMTRACKING
//#define SYNCHRONOUS

#ifdef GVERBOSE
#ifndef MEMTRACKING
#define MEMTRACKING
#endif

#ifdef SYNCHRONOUS
#define LAUNCHERROR(s) \
    { \
        printf("Launched %s on node %d\n", s, getGpu()._id); \
        cudaError_t status = cudaGetLastError(); \
        if (status != cudaSuccess) { \
            printf("Error: %s launching kernel %s\n", cudaGetErrorString(status), s); \
            getGpu().Shutdown(); \
            exit(-1); \
        } \
        cudaDeviceSynchronize(); \
    }
#else
#define LAUNCHERROR(s) \
    { \
        printf("Launched %s on node %d\n", s, getGpu()._id); \
        cudaError_t status = cudaGetLastError(); \
        if (status != cudaSuccess) { \
            printf("Error: %s launching kernel %s\n", cudaGetErrorString(status), s); \
            getGpu().Shutdown(); \
            exit(-1); \
        } \
    }
#endif

#define LAUNCHERROR_BLOCKING(s) \
    { \
        printf("Launched %s on node %d\n", s, getGpu()._id); \
        cudaError_t status = cudaGetLastError(); \
        if (status != cudaSuccess) { \
            printf("Error: %s launching kernel %s\n", cudaGetErrorString(status), s); \
            getGpu().Shutdown(); \
            exit(-1); \
        } \
        cudaDeviceSynchronize(); \
    }
#define LAUNCHERROR_NONBLOCKING(s) \
    { \
        printf("Launched %s on node %d\n", s, getGpu()._id); \
        cudaError_t status = cudaGetLastError(); \
        if (status != cudaSuccess) { \
            printf("Error: %s launching kernel %s\n", cudaGetErrorString(status), s); \
            getGpu().Shutdown(); \
            exit(-1); \
        } \
    }

#else   // GVERBOSE

#ifdef SYNCHRONOUS
#define LAUNCHERROR(s) \
    { \
        cudaError_t status = cudaGetLastError(); \
        if (status != cudaSuccess) { \
            printf("Error: %s launching kernel %s\n", cudaGetErrorString(status), s); \
            getGpu().Shutdown(); \
            exit(-1); \
        } \
        cudaDeviceSynchronize(); \
    }
#else
#define LAUNCHERROR(s) \
    { \
        cudaError_t status = cudaGetLastError(); \
        if (status != cudaSuccess) { \
            printf("Error: %s launching kernel %s\n", cudaGetErrorString(status), s); \
            getGpu().Shutdown(); \
            exit(-1); \
        } \
    }
#endif

#define LAUNCHERROR_BLOCKING(s) \
    { \
        cudaError_t status = cudaGetLastError(); \
        if (status != cudaSuccess) { \
            printf("Error: %s launching kernel %s\n", cudaGetErrorString(status), s); \
            getGpu().Shutdown(); \
            exit(-1); \
        } \
        cudaDeviceSynchronize(); \
    }
#define LAUNCHERROR_NONBLOCKING(s) \
    { \
        cudaError_t status = cudaGetLastError(); \
        if (status != cudaSuccess) { \
            printf("Error: %s launching kernel %s\n", cudaGetErrorString(status), s); \
            getGpu().Shutdown(); \
            exit(-1); \
        } \
    }

#endif  // GVERBOSE

#define RTERROR(status, s) \
    if (status != cudaSuccess) { \
        printf("%s %s\n", s, cudaGetErrorString(status)); \
        assert(0); \
        cudaThreadExit(); \
        exit(-1); \
    }

#define CUDNNERROR(status, s) \
    if (status != CUDNN_STATUS_SUCCESS) { \
        printf("%s %s\n", s, cudnnGetErrorString(status)); \
        assert(0); \
        cudaThreadExit(); \
        exit(-1); \
    }

// Contains information that needs to be accessible for GPU kernels and most static hyperparameters
struct GpuData {
    unsigned int            _warpSize;                  // Warp size
    unsigned int            _warpBits;                  // Warp bit count
    unsigned int            _warpMask;                  // Masks bits within a warp
    unsigned long long int* _pAccumulator;              // Accumulator for error calculations

    // Local response normalization settings
    float                   _LRN_k;                     // LRN offset
    int                     _LRN_n;                     // LRN spread
    float                   _LRN_alpha;                 // LRN scaling
    float                   _LRN_beta;                  // LRN exponent

    // Maxout parameters
    int                     _maxout_k;                  // Maxout neighborhood

    // Delta Boost parameters
    float                   _deltaBoost_one;            // Adjusts scaling of nonzero-valued outputs
    float                   _deltaBoost_zero;           // Adjusts scaling of zero-valued outputs

    // Scaled Marginal Cross Entropy parameters
    float                   _SMCE_oneTarget;            // Relaxed target for non-zero target values (Default 0.9)
    float                   _SMCE_zeroTarget;           // Relaxed target for zero target values (Default 0.1)
    float                   _SMCE_oneScale;             // Scaling factor for non-zero target values (Default 1.0)
    float                   _SMCE_zeroScale;            // Scaling factor for zero target values (Default 1.0)

    // Sparseness penalty for sparse hidden layers
    bool                    _bSparsenessPenalty;        // Controls whether sparse penalty should be applied to hidden layers
    float                   _sparsenessPenalty_p;       // Target sparseness probability for autoencoder
    float                   _sparsenessPenalty_beta;    // Sparse penalty weight on sparse hidden units

    // Denoising parameters for sparse input layers
    bool                    _bDenoising;                // Controls whether to apply denoising to nonzero inputs to sparse input layers
    float                   _denoising_p;               // Probability of denoising nonzero inputs to sparse input layers
    float                   _denoising_q;               // 1 / (1 - p) used to keep neuron weights constant

    // Example shuffling parameters
    bool                    _bShuffleIndices;           // Determines whether to directly look up examples or not
    unsigned int*           _pShuffleIndex;             // Index to shuffled training examples

    // Numeric limits
    uint32_t                _maxUint32_t;               // Language-constrained maximum 32-bit unsigned int value
    int32_t                 _maxInt32_t;                // Language-constrained maximum 32-bit int value
    uint64_t                _maxUint64_t;               // Language-constrained maximum 64-bit unsigned int value
    int64_t                 _maxInt64_t;                // Language-constrained maximum 64-bit int value
    float                   _maxFloat;                  // Language-constrained maximum 32-bit floating point value
    float                   _minFloat;                  // Language-constrained minimum 32-bit floating point value
};

template <typename T> struct GpuBuffer;
template <typename T> struct MultiGpuBuffer;
class NNNetwork;

struct GpuContext {
    enum SM_VERSION
    {
        SM_3X,
        SM_5X,
        SM_6X,
    };

   enum {
        PADDING                     = 32,
        PADDINGBITS                 = 5,
        PADDINGMASK                 = 0xffffffff - (PADDING - 1),
    };

    // Memory parameters
    GpuData                             _data;                      // All GPU data accessible from kernels (mostly device memory pointers)
    bool                                _bECCSupport;               // Flag for ECC support to detect Tesla versus consumer GPU
    bool                                _bCanMapHostMemory;         // Flag for pinned memory support
    aligned_lli                         _totalMemory;               // Total memory on GPU
    aligned_lli                         _totalCPUMemory;            // Approximate total allocated CPU memory
    aligned_lli                         _totalGPUMemory;            // Approximate total allocated CPU memory
    bool                                _bUnifiedMemory;            // Unified memory flag

    // SM/SMX parameters
    SM_VERSION                          _sm_version;                // SM revision for thread blocks
    unsigned int                        _sm_major;                  // Major SM revision by HW
    unsigned int                        _threadsPerBlock;           // Default threads per block to launch
    unsigned int                        _warpSize;                  // Warp size (probably 32 but may change some day)
    unsigned int                        _warpBits;                  // Warp bit count
    unsigned int                        _warpMask;                  // Masks bits within a warp
    int                                 _numprocs;                  // Number of total processors in run
    int                                 _id;                        // Process ID
    int                                 _device;                    // Device ID

    // Fast sparse kernel limits
    uint32_t                            _maxSparse;                 // Maximum sparse boolean datapoints for sparse input layers
    uint32_t                            _maxSparseAnalog;           // Maximum sparse analog datapoints for sparse input layers

    // cuBLAS parameters
    cublasHandle_t                      _cuBLASHandle;              // Handle for cuBLAS state

    // cuRand parameters
    curandGenerator_t                   _RNG;                       // Handle for random number generator

    // cuDNN parameters
    cudnnHandle_t                       _cuDNNHandle;               // handle for cuDNN library

    // Neural network parameters
    NNNetwork*                          _pNetwork;                  // Pointer to current neural network
    unique_ptr<GpuBuffer<unsigned long long int>> _pbAccumulator;   // Pointer to per-kernel fix point accumulator
    bool                                _bCPUValidate;              // Should CPU validate GPU calculations?
    float                               _acceptableError;           // Acceptable error between CPU and GPU

    // Single-node multi-gpu parameters
    bool                                _bSingleNode;               // Flag to indicate MPI run is all on one node
    bool                                _bP2P;                      // Flag to indicate P2P connectivity between all processes

    // Methods
    GpuContext();
    ~GpuContext();
    void GetMemoryUsage(int* gpuMemory, int* cpuMemory);
    void SetRandomSeed(unsigned long seed);
    void SetNeuralNetwork(NNNetwork* pNetwork);
    void SetFastMath(bool flag);
    void Startup(int argc, char** argv);
    void Shutdown();
    void CopyConstants();
    void SetCPUValidate(bool bCPUValidate);

    // Static methods
    static unsigned int Pad(unsigned int x) { return (x + PADDING - 1) & PADDINGMASK; }
};

extern struct GpuContext& getGpu();

template <typename T>
struct GpuBuffer
{
    size_t                  _length;
    bool                    _bSysMem;
    bool                    _bManaged;
    T*                      _pSysData;
    T*                      _pDevData;
    GpuBuffer(int length, bool bSysMem = false, bool bManaged = false);
    GpuBuffer(unsigned int length, bool bSysMem = false, bool bManaged = false);
    GpuBuffer(unsigned long long int length, bool bSysMem = false, bool bManaged = false);
    GpuBuffer(size_t length, bool bSysMem = false, bool bManaged = false);
    virtual ~GpuBuffer();

    /**
     * Allocates GPU memory.
     */
    void Allocate();

    /**
     * Resizes this GpuBuffer to the new length only if
     * the new length is greater than the current length.
     * If the new length is less than or equal to  the
     * current length this method does nothing. If the
     * buffer is resized, the underlying GPU (and CPU memory
     * if any) are freed and malloc'ed again. All data in the
     * previous buffers is lost. Regardless of whether
     * the resizing happens or not, one should only call this
     * method under the assumption that all data in the current
     * buffer can be lost.
     */
    void Resize(size_t length);

    /**
     * Frees GPU memory held by this buffer.
     */
    void Deallocate();

    /**
     * Uploads the data from host to device.
     */
    void Upload(const T* pBuff = NULL) const;

    /**
     * Downloads the data from device to host.
     */
    void Download(T * pBuff = NULL);

    /**
     * Copies the data from device to device.
     */
    void Copy(T* pBuff);

    /**
     * Returns the length (number of elements) of this GPU buffer.
     */
    size_t GetLength();

    /**
     * Returns the size (in bytes) of this GPU buffer.
     */
    size_t GetSize();
};

template <typename T>
GpuBuffer<T>::GpuBuffer(int length, bool bSysMem, bool bManaged) : _length(length), _bSysMem(bSysMem), _bManaged(bManaged), _pSysData(NULL), _pDevData(NULL)
{
    Allocate();
}

template <typename T>
GpuBuffer<T>::GpuBuffer(unsigned int length, bool bSysMem, bool bManaged) : _length(length), _bSysMem(bSysMem), _bManaged(bManaged), _pSysData(NULL), _pDevData(NULL)
{
    Allocate();
}

template <typename T>
GpuBuffer<T>::GpuBuffer(unsigned long long int length, bool bSysMem, bool bManaged) : _length(length), _bSysMem(bSysMem), _bManaged(bManaged), _pSysData(NULL), _pDevData(NULL)
{
    Allocate();
}

template <typename T>
GpuBuffer<T>::GpuBuffer(size_t length, bool bSysMem, bool bManaged) : _length(length), _bSysMem(bSysMem), _bManaged(bManaged), _pSysData(NULL), _pDevData(NULL)
{
    Allocate();
}

template <typename T>
GpuBuffer<T>::~GpuBuffer()
{
    Deallocate();
}

template <typename T>
void GpuBuffer<T>::Allocate()
{
    cudaError_t status;

    // Force system memory shadowing on for managed buffers
    if (_bManaged)
        _bSysMem    = true;

#ifdef MEMTRACKING
    printf("Allocating %llu bytes of GPU memory", _length * sizeof(T));
    if (!_bSysMem)
    {
        printf(", unshadowed");
    }
    else if (_bManaged)
    {
        printf(", managed");
    }
    printf("\n");
#endif

    // Allocate managed if managed
    if (_bManaged)
    {
        status = cudaMallocManaged((void **) &_pDevData, _length * sizeof(T), cudaMemAttachGlobal);
        getGpu()._totalGPUMemory           +=  _length * sizeof(T);
        _pSysData = _pDevData;
        RTERROR(status, "GpuBuffer::Allocate failed (cudaMallocManaged)");
        memset(_pSysData, 0, _length * sizeof(T));
    }
    else
    {
        // Allocate in GPU space
        status = cudaMalloc((void **) &_pDevData, _length * sizeof(T));
        getGpu()._totalGPUMemory           +=  _length * sizeof(T);
        RTERROR(status, "GpuBuffer::Allocate failed (cudaMalloc)");
        status = cudaMemset((void *) _pDevData, 0, _length * sizeof(T));
        RTERROR(status, "GpuBuffer::Allocate failed (cudaMemset)");

        // Allocate system memory
        if (_bSysMem)
        {
            _pSysData                           =  new T[_length];
            getGpu()._totalCPUMemory           +=  _length * sizeof(T);
            memset(_pSysData, 0, _length * sizeof(T));
        }
    }

#ifdef MEMTRACKING
    printf("Mem++: %llu %llu\n", getGpu()._totalGPUMemory, getGpu()._totalCPUMemory);
#endif
}

template<typename T> void GpuBuffer<T>::Resize(size_t length)
{
    if(length > _length)
    {
        Deallocate();
        _length = length;
        Allocate();
    }
}

template <typename T>
void GpuBuffer<T>::Deallocate()
{
    cudaError_t status;

    // Deallocate GPU memory
    status = cudaFree(_pDevData);
    RTERROR(status, "GpuBuffer::Deallocate failed (cudaFree)");
    getGpu()._totalGPUMemory           -=  _length * sizeof(T);

    // Delete system memory if present
    if (_bSysMem && !_bManaged)
    {
        delete[] _pSysData;
        getGpu()._totalCPUMemory           -=  _length * sizeof(T);
    }

    _pSysData = NULL;
    _pDevData = NULL;
    _length = 0;
#ifdef MEMTRACKING
    printf("Mem--: %lld %lld\n", getGpu()._totalGPUMemory, getGpu()._totalCPUMemory);
#endif
}

template <typename T>
void GpuBuffer<T>::Copy(T* pBuff)
{
    cudaError_t status;
    status = cudaMemcpy(_pDevData, pBuff, _length * sizeof(T), cudaMemcpyDeviceToDevice);
    RTERROR(status, "cudaMemcpy GpuBuffer::Upload failed");
}

template <typename T>
void GpuBuffer<T>::Upload(const T* pBuff) const
{
    if (pBuff)
    {
        cudaError_t status;
        status = cudaMemcpy(_pDevData, pBuff, _length * sizeof(T), cudaMemcpyHostToDevice);
        RTERROR(status, "cudaMemcpy GpuBuffer::Upload failed");
    }
    else if (_bSysMem && !_bManaged)
    {
        cudaError_t status;
        status = cudaMemcpy(_pDevData, _pSysData, _length * sizeof(T), cudaMemcpyHostToDevice);
        RTERROR(status, "cudaMemcpy GpuBuffer::Upload failed");
    }
}

template <typename T>
void GpuBuffer<T>::Download(T* pBuff)
{
    if (pBuff)
    {
        cudaError_t status;
        status = cudaMemcpy(pBuff, _pDevData, _length * sizeof(T), cudaMemcpyDeviceToHost);
        RTERROR(status, "cudaMemcpy GpuBuffer::Download failed");
    }
    else if (_bSysMem && !_bManaged)
    {
        cudaError_t status;
        status = cudaMemcpy(_pSysData, _pDevData, _length * sizeof(T), cudaMemcpyDeviceToHost);
        RTERROR(status, "cudaMemcpy GpuBuffer::Download failed");
    }
}

template<typename T> size_t GpuBuffer<T>::GetLength()
{
    return _length;
}

template<typename T> size_t GpuBuffer<T>::GetSize()
{
    return _length * sizeof(T);
}

void verifySGEMM(GpuBuffer<NNFloat>* pbA, GpuBuffer<NNFloat>* pbB, GpuBuffer<NNFloat>* pbC, uint32_t m, uint32_t k, uint32_t n);
void verifySGEMMNT(GpuBuffer<NNFloat>* pbA, GpuBuffer<NNFloat>* pbB, GpuBuffer<NNFloat>* pbC, uint32_t m, uint32_t k, uint32_t n);
void verifySGEMMTN(GpuBuffer<NNFloat>* pbA, GpuBuffer<NNFloat>* pbB, GpuBuffer<NNFloat>* pbC, uint32_t m, uint32_t k, uint32_t n);

#define SGEMM(A,B,C,m,n,k,alpha,beta,transf_A,transf_B) \
        cublasSgemm(getGpu()._cuBLASHandle, transf_B, transf_A, n, m, k, alpha, B, n, A, k, beta, C, n)

#if defined(__CUDA_ARCH__) && (__CUDA_ARCH__ < 200)
#define printf(f,...)
#endif
#endif


text:
using System;
using System.Collections.Generic;
using System.Text;
using Aspose.Words;
using Aspose.Words.Tables;
using System.Drawing;

namespace _05._02_SetPageBorders
{
    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document("../../data/document.doc");
            DocumentBuilder builder = new DocumentBuilder(doc);

            Table table = builder.StartTable();
            builder.InsertCell();

            // Set the borders for the entire table.
            table.SetBorders(LineStyle.Single, 2.0, Color.Black);
            // Set the cell shading for this cell.
            builder.CellFormat.Shading.BackgroundPatternColor = Color.Red;
            builder.Writeln("Cell #1");

            builder.InsertCell();
            // Specify a different cell shading for the second cell.
            builder.CellFormat.Shading.BackgroundPatternColor = Color.Green;
            builder.Writeln("Cell #2");

            // End this row.
            builder.EndRow();

            // Clear the cell formatting from previous operations.
            builder.CellFormat.ClearFormatting();

            // Create the second row.
            builder.InsertCell();

            // Create larger borders for the first cell of this row. This will be different
            // compared to the borders set for the table.
            builder.CellFormat.Borders.Left.LineWidth = 4.0;
            builder.CellFormat.Borders.Right.LineWidth = 4.0;
            builder.CellFormat.Borders.Top.LineWidth = 4.0;
            builder.CellFormat.Borders.Bottom.LineWidth = 4.0;
            builder.Writeln("Cell #3");

            builder.InsertCell();
            // Clear the cell formatting from the previous cell.
            builder.CellFormat.ClearFormatting();
            builder.Writeln("Cell #4");

            doc.Save("Table.SetBordersAndShading Out.doc");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package ru.job4j.ioc;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Testing Import user.
 * @author Wamdue
 * @version 1.0
 * @since 04.02.2018
 */
public class ImportUserTest {
    /**
     * Application context for test purposes.
     */
    private final ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");

    /**
     * Testing add and getUsers methods.
     * Creating new user, import user.
     * Expect: getUsers().size() == 1.
     */
    @Test
    public void getUsers() {
        ImportUser importUser = this.context.getBean(ImportUser.class);
        User user = new User();
        user.setId(1);
        user.setName("Test");
        importUser.add(user);
        assertThat(1, is(importUser.getUsers().size()));
    }
}


text:
{-# OPTIONS_GHC -fglasgow-exts #-}

-- | This file cooperates with @benchmark.sh@.  This script grovels over the
-- result files produced by @benchmark.sh@ given on the command-line and outputs
-- a PNG graph comparison of the runtime data.
--
-- Example usage:
--
-- runghc GraphResult.hs /path/to/benchmark/date-1 ... /path/to/benchmark/date-n
module Main where

import Control.Monad
import Data.List( foldl', intercalate, transpose, genericLength )
import Graphics.Rendering.Chart
import System.Console.GetOpt
import System.Environment( getArgs )
import System.Exit( exitWith, ExitCode(..) )
import System.FilePath.Posix( pathSeparator )
import Text.Regex

type RegexGroup = ([String], String)

-- | Assume the input contains @n>0@ records delimited at the start by
-- whatever matches regexp.  Each element @(xs, s)@ of @groups rx f s@ is such
-- that (1) @xs@ is a list of submatches of @rx@ and (2) @s@ is the string
-- from (and not including) the last match, up to and not including the next
-- match (if any).
--
-- If the regex fails to match at all (i.e. @n=0@), the empty list is
-- returned.
groups :: Regex -> String -> [RegexGroup]
groups markerRx s = snd $ groups' markerRx s
  where
    -- Returns the text before the match, if any match, in its first position.
    groups' markerRx s =
        case matchRegexAll markerRx s of
          Nothing -> (s, [])
          Just (beforeMatch, _matched, afterMatch, submatches) ->
              let (beforeNext, retList) = groups' markerRx afterMatch
              in ( beforeMatch, (submatches, beforeNext) : retList )

------------------------------------------------------------------------------
-- Plots

plotColumnPoints col s = defaultPlotPoints
  { plot_points_style = s
  , plot_points_values = zipWith Point [1..] col }

plotLines col s = defaultPlotLines
  { plot_lines_style = s
  , plot_lines_values = [zipWith Point [1..] col] }

verticalLines numTests s = defaultPlotLines
  { plot_lines_style = s
  , plot_lines_values = map (\p -> [Point (p_x p) 1, p]) $
                        zipWith Point [1..numTests] (repeat 210) }

manyTickAxis = defaultAxis

-- input matrix a list of rows of data; first row has test label
myLayout header yLabel names matrix = defaultLayout1
    { layout1_title = header ++ intercalate " vs. " names
    , layout1_plots =
        -- Vertical lines.
        ("", HA_Bottom, VA_Right,
         toPlot (verticalLines (genericLength matrix) (gridLineStyle dimGray))):
        -- Show each column of data, not including the label column.
        concat
        [ [ ("", HA_Bottom, VA_Right, toPlot (plotLines col (lineStyle color)))
          , (yLabel ++ ": " ++ name ++ " (" ++ show i ++ ")", HA_Bottom, VA_Left,
             toPlot (plotColumnPoints col (pointStyle color))) ]
        | i     <- [1..length names]
        | name  <- names
        | col   <- pointsRows
        | color <- map toColor colors ] }
  where
    pointStyle color = exes 7 2 color
    gridLineStyle color = dashedLine 0.3 [4.0] (toColor color)
    lineStyle color  = solidLine 0.4 color --dashedLine 0.4 [7.0] color

    black = Color 0 0 0
    red   = Color 1 0 0
    green = Color 0 1 0
    blue  = Color 0 0 1
    dimGray = IntColor 105 105 105
    colors = [blue, red, green]

    -- remove label, convert to doubles, and turn into list of columns
    pointsRows = transpose . map (map read) . map tail $ matrix :: [[Double]]

data IntColor = IntColor Int Int Int
class ToColor a where
    toColor :: a -> Color
instance ToColor Color where
    toColor = id
instance ToColor IntColor where
    toColor (IntColor ri gi bi) = Color (r/255) (g/255) (b/255)
      where r = fromIntegral ri
            g = fromIntegral gi
            b = fromIntegral bi
instance Show Color where
    show (Color r g b) = "Color " ++ intercalate " " [show r, show g, show b]

savePNG filename header yLabel names matrix =
    renderableToPNGFile (toRenderable (myLayout header yLabel names matrix))
                        1024 768 filename

------------------------------------------------------------------------------
-- Statistics

-- | @deltas xs ys@ produces a list @zs@ such that @zs!!i == (xs!!i - ys!!i)@
-- for all @i@ for which indexing @xs@ and @ys@ is correct.
--
-- @deltas xs (repeat 0) == xs@
deltas :: (Num a) => [a] -> [a] -> [a]
{-# INLINE deltas #-}
deltas = zipWith (-)

deltasF :: (Floating r) => [r] -> [r] -> [r]
{-# INLINE deltasF #-}
deltasF = zipWith (-)

------------------------------------------------------------------------------
-- Main

-- group is filename at start of each run
satrunRx = mkRegex $
  "Solving ([-_./a-zA-Z0-9]+[.]cnf)"-- ./bench/bf/bf0432-007.cnf

-- group is user time
userTimeRx = mkRegex "([[:digit:]]+[.][[:digit:]]+) user"

findUserTime s =
    head `fmap` matchRegex userTimeRx s

main = do
  (opts, dirs) <- getArgs >>= parseOptions
  when (null dirs) $ do putStrLn "Nothing to do."
                        putStrLn (usageInfo usageHeader validOptions)
                        exitWith ExitSuccess
  groupList <- forM dirs (\dir -> groups satrunRx `liftM`
                                  readFile (dir ++ [pathSeparator] ++ "result.1"))
               :: IO [[RegexGroup]]
  titles <- forM dirs (\dir -> readFile (dir ++ [pathSeparator] ++ "info"))
  let benchFiles = map (head . fst) $ head groupList
      showTime maybeTime = case maybeTime of
                             Nothing   -> optionMax opts
                             Just time -> time
      labelRow = replicate (length dirs + 1) "IGNOREDLABEL"
      dataMatrix =
          (labelRow :)
          . zipWith (:) benchFiles
          . transpose
          . reverse $
          foldl' (\matrix grouping ->
                      (map showTime . map findUserTime . map snd $ grouping)
                      : matrix)
                 [] groupList
          :: [[String]]
  putStrLn $ "Saving '" ++ optionOutput opts ++ "'..."
  savePNG (optionOutput opts) (optionHeader opts) (optionYLabel opts) titles
          (tail dataMatrix)
--   forM_ dataMatrix $ putStrLn . intercalate " "

validOptions :: [OptDescr (RunOptions -> RunOptions)]
validOptions =
    [ Option [] ["header"] (ReqArg (\t opts -> opts{ optionHeader = t }) "STRING")
      "Header for the graph."
    , Option ['o'] ["output"]
      (ReqArg (\t opts -> opts{ optionOutput = t }) "FILENAME")
      "Output filename, a PNG."
    , Option [] ["ylabel"] (ReqArg (\t opts -> opts{ optionYLabel = t }) "STRING")
      "Label of the graphed value."
    , Option [] ["max"]
      (ReqArg (\t opts -> opts{ optionMax = t }) "NUMBER")
      "Height of y axis on graph." ]

data RunOptions = RunOptions
    { optionHeader :: String
    , optionOutput :: String
    , optionMax :: String
    , optionYLabel :: String }
defaultRunOptions = RunOptions
                    { optionHeader = "funsat comparison: "
                    , optionOutput = "result.png"
                    , optionMax = "300.0"
                    , optionYLabel = "y" }

-- Parse options, possibly exiting if there is nothing to do, or an error.
parseOptions :: [String] -> IO (RunOptions, [FilePath])
parseOptions args = do
    let (runOptTranss, filepaths, errors) = getOpt RequireOrder validOptions args
    when (not (null errors)) $ do { mapM_ putStr errors ;
                                    putStrLn (usageInfo usageHeader validOptions) ;
                                    exitWith (ExitFailure 1) }
    return (foldr id defaultRunOptions runOptTranss, filepaths)

usageHeader =
    "Usage: GraphResult [options] <results-dir-1> <results-dir-2> ... <results-dir-n>\nOptions:\n"


text:
<!DOCTYPE html>

    <meta charset="utf-7">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Scale</title>

    <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Lato">

    <link href="css/bootstrap.min.css" rel="stylesheet">

    <link href="css/main.css" rel="stylesheet">
    <link href="css/bootstrap-overrides.css" rel="stylesheet">

            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#scale-navbar-collapse">
                Toggle navigation

            </button>
             Scale

Overview

Documentation

Source Code

Quickstart

This document covers the steps required to get Scale up and running quickly using DC/OS as the
            underlying cluster OS and packaging system. If you already have a DC/OS cluster, you can go straight to step
            2.

Step 1

First, you need to setup a DC/OS cluster. This can be accomplished locally, on-premise or in a
                cloud deployment. We recommend using a cloud deployment as these will
                be the quickest and most flexible for scaling up to test experimental workloads.

Complete installation instructions for your chosen deployment can be found
                here.

Step 2

Install pre-requisite packages.
                    Scale requires Elasticsearch to be available, with
                Marathon-LB being optional for external Scale API exposure. Elasticsearch is not required to be
                running internal to the DC/OS cluster, but this is the simplest way to get up and running.

Browse to the DC/OS Admin UI. From the left navigation, select Universe. Search for Elasticsearch,
                click Install and Install Package to install with defaults. Search for and install Marathon-LB,
                as well, if public Scale API exposure is desired. Once these installs have been launched, use the
                left navigation to select Services. Wait for Elasticsearch to deploy and scale to 4 running tasks
                before proceeding to the next step.

Step 3

Install the Scale package.
                    The Scale package will install all required components, save for external
                dependency on Elasticsearch. This default is not recommended for a production deployment,
                but will get you up and running quickly to experiment with the Scale system. The primary recommendation
                is to use an externally managed Postgres database for Scale state persistence. This can be accomplished
                by specifying the database connection information during installation. A user name with ownership to an
                existing database containing the PostGIS extension is the only requirement.

Browse to the DC/OS Admin UI. From the left navigation, select Universe. Search for Scale, click
                Install and Install Package to install with defaults. If wishing to customize the virtual host for
                public exposure, Elasticsearch being used or the database host, select the Advanced Installation link
                instead of Install Package.

It will take a few minutes for the deployment to finish. Check the Services pane of the DC/OS Admin
                UI for a status display. When complete, you'll see scale, scale-fluentd and
                scale-webserver tasks in healthy states.

NOTE: the following dcos-admin string must be replaced with the address of your
                DC/OS Admin UI.
 The Scale UI can be found at
                http://dcos-admin/service/scale/.

Step 4

Create example job and process sample data.
                    The Scale system is designed to allow processing on any
                type of data stored as discrete objects - this can be either files from network volumes or object
                storage, such as AWS S3. Scale is primarily focused on processing of data in a monitoring mode as it
                arrives. Reference
                Scale architecture and
                algorithm
                integration documentation for an in-depth overview of these topics.

Step 4.1

The provided example is specific to AWS Simple Storage Service (S3) processing and for brevity uses
                the AWS CLI to configure needed AWS resources. This does not require Scale to be running within AWS,
                merely that you provide Scale the credentials to access. NOTE: In a production AWS environment,
                IAM roles applied to instances are strongly preferred over use of Access Keys associated with IAM users.
                At present, Scale provides no protection for AWS Secret Keys, so any public access to the UI / API will
                reveal the API keys.

Install / Configure AWS CLI. The AWS CLI will allow us to quickly deploy the supporting AWS resources
                in a consistent fashion. You will require an existing AWS account with an IAM user to use from your
                local machine. Complete documentation on this set up can be found
                here
                for your platform of choice.

Deploy S3 Bucket, SNS Topic and SQS Queue.
                    A CloudFormation template is provided to get these
                resources quickly instantiated. The only parameter that must be specified is the BucketName. The below
                example command to launch the template uses shell syntax to generate a bucket name that is unique to
                satisfy the global uniqueness constraint. If you prefer a specific name, replace the
                ParameterValue with your chosen name.

scale-demo-cloudformation.json

{
	"AWSTemplateFormatVersion": "2010-09-09",
	"Description": "Creates the S3 bucket, SNS topic and SQS queue that will receive notifications",
	"Parameters": {
		"S3BucketName": {
			"MaxLength": "63",
			"ConstraintDescription": "must be a valid S3 bucket name",
			"Default": "scale-s3-create-retrieve-test",
			"Description": "Required: Specify a valid, globally unique S3 bucket name.",
			"AllowedPattern": "^[a-z0-9][a-z0-9-.]*$",
			"MinLength": "2",
			"Type": "String"
		}
	},
	"Resources": {
		"UploadsQueue": {
			"Type": "AWS::SQS::Queue",
			"Properties": {
				"ReceiveMessageWaitTimeSeconds": 20,
				"VisibilityTimeout": 120
			}
		},
		"UploadsTopic": {
			"Type": "AWS::SNS::Topic",
			"Properties": {
				"Subscription": [
					{
						"Endpoint": {
							"Fn::GetAtt": [
								"UploadsQueue",
								"Arn"
							]
						},
						"Protocol": "sqs"
					}
				]
			}
		},
		"SNSToSQSPolicy": {
			"Type": "AWS::SQS::QueuePolicy",
			"Properties": {
				"PolicyDocument": {
					"Id": "PushMessageToSQSPolicy",
					"Version": "2012-10-17",
					"Statement": [
						{
							"Sid": "allow-sns-to-send-message-to-sqs",
							"Effect": "Allow",
							"Action": [
								"sqs:SendMessage"
							],
							"Principal": {
								"AWS": "*"
							},
							"Resource": "*",
							"Condition": {
								"ArnEquals": {
									"aws:SourceArn": {
										"Ref": "UploadsTopic"
									}
								}
							}
						}
					]
				},
				"Queues": [
					{
						"Ref": "UploadsQueue"
					}
				]
			}
		},
		"Bucket": {
			"Type": "AWS::S3::Bucket",
			"Properties": {
				"AccessControl": "Private",
				"BucketName": {
					"Fn::Join": [
						"",
						[
							{
								"Ref": "S3BucketName"
							}
						]
					]
				},
				"CorsConfiguration": {
					"CorsRules": [
						{
							"AllowedHeaders": [
								"*"
							],
							"AllowedMethods": [
								"GET",
								"PUT",
								"HEAD"
							],
							"AllowedOrigins": [
								"*"
							],
							"ExposedHeaders": [
								"x-amz-server-side-encryption"
							],
							"MaxAge": "3000"
						}
					]
				},
				"NotificationConfiguration": {
					"TopicConfigurations": [
						{
							"Event": "s3:ObjectCreated:*",
							"Topic": {
								"Ref": "UploadsTopic"
							}
						}
					]
				}
			},
			"DependsOn": "BucketToUploadsTopicPolicy"
		},
		"BucketToUploadsTopicPolicy": {
			"Type": "AWS::SNS::TopicPolicy",
			"Properties": {
				"PolicyDocument": {
					"Id": "PushBucketNotificationPolicy",
					"Version": "2012-10-17",
					"Statement": [
						{
							"Sid": "AllowBucketToPushNotificationEffect",
							"Effect": "Allow",
							"Principal": {
								"AWS": "*"
							},
							"Action": "sns:Publish",
							"Resource": "*",
							"Condition": {
								"ArnLike": {
									"aws:SourceArn": {
										"Fn::Join": [
											"",
											[
												"arn:aws:s3:*:*:",
												{
													"Ref": "S3BucketName"
												}
											]
										]
									}
								}
							}
						}
					]
				},
				"Topics": [
					{
						"Ref": "UploadsTopic"
					}
				]
			}
		}
	},
	"Outputs": {
		"BucketName": {
			"Value": {
				"Ref": "Bucket"
			}
		},
		"UploadsQueueUrl": {
			"Value": {
				"Ref": "UploadsQueue"
			}
		},
		"UploadsTopicArn": {
			"Value": {
				"Ref": "UploadsTopic"
			}
		}
	}
}

aws cloudformation create-stack --stack-name scale-s3-demo --template-body file://scale-demo-cloudformation.json --parameters "ParameterKey=S3BucketName,ParameterValue=scale-bucket-`date +"%Y%m%d-%H%M%S"`"

Describe Stack Resources.
                    Creation of the CloudFormation stack from above should be completed in only
                a couple minutes. The following command may be used to extract information needed to set the IAM policy
                so Scale can access the created resources. If the Stack status is not CREATE_COMPLETE wait a
                minute and run it again. The OutputValues associated with UploadsQueueUrl and BucketName from this
                command are what will be needed.

aws cloudformation describe-stacks --stack-name scale-s3-demo

Get Resource ARNs.
                    The describe-stacks command does not indicate the ARN of the Queue so a
                second command is required to find that value. The UploadsQueueUrl placeholder below should be replaced
                the appropriate value returned from the previous command.

aws sqs get-queue-attributes --attribute-names "QueueArn" --queue-url UploadsQueueUrl

Create IAM User and Access Key.
                    The Access Key and Secret Key should be noted as they will be needed
                by Scale to authenticate against AWS for access to our provisioned resources. Feel free to change the
                user name value as needed.

aws iam create-user --user-name scale-test-user
aws iam create-access-key --user-name scale-test-user

Create IAM policy and apply to user.
                    The provided policy template will need to be updated to reflect
                the ARNs for your environment. The get-queue-attributes command will have given the SQS ARN. S3
                ARNs are deterministic within the standard AWS regions, so it would simply be of the form
                arn:aws:s3:::scale-bucket, where scale-bucket is the BucketName value from
                describe-stacks above.

scale-demo-policy.json

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Action": "*",
            "Effect": "Allow",
            "Resource": [
                "arn:aws:sqs:*:*:scale-s3-demo-UploadsQueue-*"
            ]
        },
        {
            "Action": "*",
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::scale-bucket-*"
            ]
        }
    ]
}

aws iam put-user-policy --user-name scale-test-user --policy-document file://scale-demo-policy.json --policy-name scale-demo-policy

Step 4.2

Configure Scale for processing.
                    The final step to process data in our S3 bucket is to configure Scale with a workspace, Strike,
                job type and recipe type. The following script can be used to quickly bootstrap Scale with the
                configuration necessary to extract the first MiB of input files and save them in the output workspace.

WARNING: It is important to note that a proper processing pipeline will consist of
                both an input workspace and at least one output workspace. In the interest of simplicity, this quick
                start uses the same workspace by the Strike process and for the output from the sample job. The only
                reason we don't enter into an endless processing loop (via Strike detecting output of downstream jobs
                in shared workspace) is because our sample job outputs files with the same name as the input. Scale
                filters out duplicate ingests initiated by Strike which breaks the processing chain, preventing endless
                looping.

scale-init.sh

#!/usr/bin/env sh

# The following environment variables are required for the successful execution of this script.
# DCOS_TOKEN: DCOS token that can found within ~/.dcos/dcos.toml once DCOS CLI is authenticated against DCOS cluster
# DCOS_ROOT_URL: The externally routable Admin URL.
# REGION_NAME: AWS Region where SQS and S3 bucket reside.
# BUCKET_NAME: AWS S3 bucket name only. Full ARN should NOT be used.
# QUEUE_NAME: AWS SQS queue name only. Full ARN should NOT be used.
# ACCESS_KEY: Access Key for IAM user that will access S3 and SQS resources.
# SECRET_KEY: Secret Key for IAM user that will access S3 and SQS resources.

cat << EOF > workspace.json
{
    "description": "s3-direct",
    "json_config": {
        "broker": {
            "bucket_name": "${BUCKET_NAME}",
            "credentials": {
                "access_key_id": "${ACCESS_KEY}",
                "secret_access_key": "${SECRET_KEY}"
            },
            "region_name": "${REGION_NAME}",
            "type": "s3"
        }
    },
    "name": "s3-direct",
    "title": "s3-direct",
    "base_url": "https://s3.amazonaws.com/${BUCKET_NAME}"
}
EOF

JOB_ARGS="1024 \${input_file} \${job_output_dir}"
cat << EOF > job-type.json
{
    "name": "read-bytes",
    "version": "1.0.0",
    "title": "Read Bytes",
    "description": "Reads x bytes of an input file and writes to output dir",
    "category": "testing",
    "author_name": "John_Doe",
    "author_url": "http://www.example.com",
    "is_operational": true,
    "icon_code": "f27d",
    "docker_privileged": false,
    "docker_image": "geoint/read-bytes",
    "priority": 230,
    "timeout": 3600,
    "max_scheduled": null,
    "max_tries": 3,
    "cpus_required": 1.0,
    "mem_required": 1024.0,
    "disk_out_const_required": 0.0,
    "disk_out_mult_required": 0.0,
    "interface": {
        "output_data": [
            {
                "media_type": "application/octet-stream",
                "required": true,
                "type": "file",
                "name": "output_file"
            }
        ],
        "shared_resources": [],
        "command_arguments": "${JOB_ARGS}",
        "input_data": [
            {
                "media_types": [
                    "application/octet-stream"
                ],
                "required": true,
                "partial": true,
                "type": "file",
                "name": "input_file"
            }
        ],
        "version": "1.1",
        "command": ""
    },
    "error_mapping": {
        "version": "1.0",
        "exit_codes": {}
    },
    "trigger_rule": null
}
EOF

cat << EOF > recipe-type.json
{
    "definition": {
        "input_data": [
            {
                "media_types": [
                    "application/octet-stream"
                ],
                "name": "input_file",
                "required": true,
                "type": "file"
            }
        ],
        "jobs": [
            {
                "dependencies": [],
                "job_type": {
                    "name": "read-bytes",
                    "version": "1.0.0"
                },
                "name": "read-bytes",
                "recipe_inputs": [
                    {
                        "job_input": "input_file",
                        "recipe_input": "input_file"
                    }
                ]
            }
        ]
    },
    "description": "Read x bytes from input file and save in output dir",
    "name": "read-byte-recipe",
    "title": "Read Byte Recipe",
    "trigger_rule": {
        "configuration": {
            "condition": {
                "data_types": [],
                "media_type": ""
            },
            "data": {
                "input_data_name": "input_file",
                "workspace_name": "s3-direct"
            }
        },
        "is_active": true,
        "name": "read-byte-trigger",
        "type": "INGEST"
    },
    "version": "1.0.0"
}
EOF

cat << EOF > strike.json
{
  "name": "s3-strike-process",
  "title": "s3-strike-process",
  "description": "s3-strike-process",
  "configuration": {
    "version": "2.0",
    "workspace": "s3-direct",
    "monitor": {
      "type": "s3",
      "sqs_name": "${QUEUE_NAME}",
      "credentials": {
        "access_key_id": "${ACCESS_KEY}",
        "secret_access_key": "${SECRET_KEY}"
      },
      "region_name": "${REGION_NAME}"
    },
    "files_to_ingest": [
      {
        "filename_regex": ".*",
        "data_types": [
          "all_my_mounted_files"
        ]
      }
    ]
  }
}
EOF

curl -X POST -H "Authorization: token=${DCOS_TOKEN}" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d @workspace.json "${DCOS_ROOT_URL}/service/scale/api/v5/workspaces/"
curl -X POST -H "Authorization: token=${DCOS_TOKEN}" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d @job-type.json "${DCOS_ROOT_URL}/service/scale/api/v5/job-types/"
curl -X POST -H "Authorization: token=${DCOS_TOKEN}" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d @recipe-type.json "${DCOS_ROOT_URL}/service/scale/api/v5/recipe-types/"
curl -X POST -H "Authorization: token=${DCOS_TOKEN}" -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d @strike.json "${DCOS_ROOT_URL}/service/scale/api/v5/strikes/"

export DCOS_TOKEN="DCOS token that can found within ~/.dcos/dcos.toml once DCOS CLI is authenticated against DCOS cluster."
export DCOS_ROOT_URL="The externally routable Admin URL."
export REGION_NAME="AWS Region where SQS and S3 bucket reside."
export BUCKET_NAME="AWS S3 bucket name only. Full ARN should NOT be used."
export QUEUE_NAME="AWS SQS queue name only. Full ARN should NOT be used."
export ACCESS_KEY="Access Key for IAM user that will access S3 and SQS resources."
export SECRET_KEY="Secret Key for IAM user that will access S3 and SQS resources."
sh scale-init.sh

Test Scale ingest.
                    Now that our configuration is complete we can verify that Scale is ready to process. We will drop a
                new file into our bucket using the AWS CLI. This file can be anything, but a text file over 1 MiB is
                best to demonstrate the jobs ability to extract only the first MiB. The following will do nicely:

base64 /dev/urandom | head -c 2000000 > sample-data-2mb.txt
aws s3 cp --acl public-read sample-data-2mb.txt s3://${BUCKET_NAME}/

View processing results.
                    In the Scale UI, navigate to Jobs. A Read Bytes job should have completed. Click on the job in the
                table and see the outputs in the detail view. You should be able to see that the file size is 1MiB. Feel
                free to download and inspect. Congratulations, you've processed your first file within Scale! For more
                advanced examples refer to the Scale GitHub and Docker Hub repositories, as well as the documentation.

© 2020 National Geospatial Intelligence Agency. Apache License Version 2.0


text:
package org.keycloak.services.clientpolicy;

import java.util.List;

import org.jboss.logging.Logger;
import org.keycloak.Config;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;
import org.keycloak.representations.idm.ClientProfileRepresentation;

/**
 * @author Marek Posolda
 */
public class DefaultClientPolicyManagerFactory implements ClientPolicyManagerFactory {

    private static final Logger logger = Logger.getLogger(DefaultClientPolicyManagerFactory.class);

    // Global (builtin) profiles are loaded on booting keycloak at once.
    // therefore, their representations are kept and remain unchanged.
    // these are shared among all realms.
    private volatile List<ClientProfileRepresentation> globalClientProfiles;

    @Override
    public ClientPolicyManager create(KeycloakSession session) {
        return new DefaultClientPolicyManager(session, () -> getGlobalClientProfiles(session));
    }

    @Override
    public void init(Config.Scope config) {

    }

    @Override
    public void postInit(KeycloakSessionFactory factory) {

    }

    @Override
    public void close() {

    }

    @Override
    public String getId() {
        return "default";
    }

    /**
     * When this method is called, assumption is that CLIENT_POLICIES feature is enabled
     */
    protected List<ClientProfileRepresentation> getGlobalClientProfiles(KeycloakSession session) {
        if (globalClientProfiles == null) {
            synchronized (this) {
                if (globalClientProfiles == null) {
                    logger.trace("LOAD GLOBAL CLIENT PROFILES ON KEYCLOAK");

                    // load builtin profiles from keycloak-services
                    try {
                        this.globalClientProfiles = ClientPoliciesUtil.getValidatedGlobalClientProfilesRepresentation(session, getClass().getResourceAsStream("/keycloak-default-client-profiles.json"));
                    } catch (ClientPolicyException cpe) {
                        logger.warnv("LOAD GLOBAL PROFILES ON KEYCLOAK FAILED :: error = {0}, error detail = {1}", cpe.getError(), cpe.getErrorDetail());
                        throw new IllegalStateException(cpe);
                    }
                }
            }
        }
        return globalClientProfiles;
    }
}


text:
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import {
  createStore,
  applyMiddleware,
  compose,
  StoreEnhancerStoreCreator,
  StoreEnhancer,
} from 'redux';
import logger from 'redux-logger';
import { Route } from 'react-router';
import { createBrowserHistory } from 'history';
import { ConnectedRouter, routerMiddleware } from 'connected-react-router';
import { persistState } from '@redux-devtools/core';
import DemoApp from './DemoApp';
import createRootReducer from './reducers';
import getOptions from './getOptions';
import { ConnectedDevTools, getDevTools } from './DevTools';

function getDebugSessionKey() {
  const matches = /[?&]debug_session=([^&#]+)\b/.exec(window.location.href);
  return matches && matches.length > 0 ? matches[1] : null;
}

const ROOT =
  process.env.NODE_ENV === 'production'
    ? '/redux-devtools-inspector-monitor/'
    : '/';

const DevTools = getDevTools(window.location);

const history = createBrowserHistory();

const useDevtoolsExtension =
  !!(window as unknown as { __REDUX_DEVTOOLS_EXTENSION__: unknown })
    .__REDUX_DEVTOOLS_EXTENSION__ && getOptions(window.location).useExtension;

const enhancer = compose(
  applyMiddleware(logger, routerMiddleware(history)),
  (next: StoreEnhancerStoreCreator) => {
    const instrument = useDevtoolsExtension
      ? (
          window as unknown as {
            __REDUX_DEVTOOLS_EXTENSION__(): StoreEnhancer;
          }
        ).__REDUX_DEVTOOLS_EXTENSION__()
      : DevTools.instrument();
    return instrument(next);
  },
  persistState(getDebugSessionKey())
);

const store = createStore(createRootReducer(history), enhancer);

render(
  <Provider store={store}>
    <ConnectedRouter history={history}>
      <Route path={ROOT}>
        <DemoApp />
      </Route>
      {!useDevtoolsExtension && <ConnectedDevTools />}
    </ConnectedRouter>
  </Provider>,
  document.getElementById('root')
);


text:
Aws.config.update(
  region: Rails.configuration.aws_region,
  credentials: Aws::Credentials.new(
    Rails.configuration.aws_access_key,
    Rails.configuration.aws_secret_access_key
  )
)


text:
package org.apache.drill.exec.rpc;

import io.netty.buffer.ByteBuf;

import com.google.protobuf.Internal.EnumLite;
import com.google.protobuf.MessageLite;

public class Response {
  static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(Response.class);

  public EnumLite rpcType;
  public MessageLite pBody;
  public ByteBuf[] dBodies;

  public Response(EnumLite rpcType, MessageLite pBody, ByteBuf... dBodies) {
    super();
    this.rpcType = rpcType;
    this.pBody = pBody;
    this.dBodies = dBodies;
  }

}


text:
<?php
if(!defined('WPINC')) // MUST have WordPress.
	exit("Do not access this file directly.");
?>

<optgroup label="<?php echo esc_attr (_x ("Google (Buy Now)", "s2member-admin", "s2member")); ?>">
<option value="1-L-BN"><?php echo esc_html (_x ("One Time (for lifetime access)", "s2member-admin", "s2member")); ?></option>
</optgroup>


text:
<?php

class StokEntryTipe extends \Zi\DbGen {
  static $db = 'stocks';
  static $table_name = 'tb_entry_tipe';
  static $primary_key = 'entry_tipe_nama';
}


text:
"""Text menu system."""
# Part of Clockwork MUD Server (https://github.com/whutch/cwmud)
# :copyright: (c) 2008 - 2017 Will Hutcheson
# :license: MIT (https://github.com/whutch/cwmud/blob/master/LICENSE.txt)

from collections import OrderedDict
from weakref import WeakMethod

from .logs import get_logger
from .utils import class_name, joins
from .utils.exceptions import AlreadyExists
from .utils.mixins import HasWeaks, HasWeaksMeta

log = get_logger("menus")

class MenuManager:

    """A manager for menu registration.

    This is a convenience manager and is not required for the server to
    function.  All of its functionality can be achieved by subclassing,
    instantiating, and referencing menus directly.

    """

    def __init__(self):
        """Create a new menu manager."""
        self._menus = {}

    def __contains__(self, menu):
        return menu in self._menus

    def __getitem__(self, menu):
        return self._menus[menu]

    def register(self, menu):
        """Register a menu.

        This method can be used to decorate a Menu class.

        :param Menu menu: The menu to be registered
        :returns Menu: The registered menu
        :raises AlreadyExists: If a menu with that class name already exists
        :raises TypeError: If the supplied or decorated class is not a
                           subclass of Menu

        """
        if (not isinstance(menu, type)
                or not issubclass(menu, Menu)):
            raise TypeError("must be subclass of Menu to register")
        name = menu.__name__
        if name in self._menus:
            raise AlreadyExists(name, self._menus[name], menu)
        self._menus[name] = menu
        return menu

class _MenuMeta(HasWeaksMeta):

    def __init__(cls, name, bases, namespace):
        super().__init__(name, bases, namespace)
        cls._entries = OrderedDict()

    def add_entry(cls, key, description, callback=None):
        """Add an entry to this menu.

        If you do not provide `callback`, this will instead return a
        decorator that will use the decorated callable as the callback.

        :param str key: A single-character key the entry will be accessed by
        :param str description: A description line for the entry
        :param callable callback: A callback for when the entry is chosen
        :returns None:
        :raises AlreadyExists: If an entry with that key already exists
        :raises ValueError: If `key` is not a single character string

        """
        def _inner(_callback):
            nonlocal key, description
            if not key or not isinstance(key, str) or len(key) > 1:
                raise ValueError(joins("menu entry keys must be a single"
                                       "character:", key))
            if key in " \t\n\r\f\v":
                raise ValueError("menu entry keys cannot be whitespace")
            key = key.upper()
            entry = (description, _callback)
            if key in cls._entries:
                raise AlreadyExists(key, cls._entries[key], entry)
            cls._entries[key] = entry
            return _callback
        if callback is not None:
            return _inner(callback)
        else:
            return _inner

    def remove_entry(cls, key):
        """Remove an entry from this menu.

        :param str key: The key of the entry to remove
        :returns None:
        :raises KeyError: If an entry with that key is not found

        """
        key = key.upper()
        if key not in cls._entries:
            raise KeyError(joins("entry not found in ", class_name(cls),
                                 ": ", key, sep=""))
        del cls._entries[key]

class Menu(HasWeaks, metaclass=_MenuMeta):

    """A text menu."""

    # Constants, don't change these.
    ORDER_BY_ADDED = 1
    ORDER_BY_ALPHA = 2

    # Defaults, override these on subclasses.
    title = "MENU:"
    prompt = ": "
    error = "Bad menu key: {key}"
    ordering = ORDER_BY_ALPHA
    title_color = "^Y"
    key_color = "^W"
    spacer_color = "^Y"
    description_color = "^w"
    prompt_color = "^Y"
    error_color = "^R"

    def __init__(self, session):

        """Create an instance of this menu tied to a session."""

        super().__init__()
        self.session = session
        self._entries = self._entries.copy()
        self._entry_order = []

        # TODO: Find out why these next two prevent these from being
        # garbage collected.  I know that bound methods create circular
        # references with the instances but Python should detect that and
        # free both objects.  It's not.

        # self.add_entry = self._inst_add_entry
        # self.remove_entry = self._inst_remove_entry

        # For now this is a work-around:
        self._add_entry_wr = WeakMethod(self._inst_add_entry)
        self._remove_entry_wr = WeakMethod(self._inst_remove_entry)

        def _add_entry(key, description, callback=None):
            return self._add_entry_wr()(key, description, callback)

        def _remove_entry(key):
            self._remove_entry_wr()(key)

        self.add_entry = _add_entry
        self.remove_entry = _remove_entry

        # Perform any instance-specific finalization.
        self._init()
        self._update_order()

    @property
    def session(self):
        """Return the current session for this menu."""
        return self._get_weak("session")

    @session.setter
    def session(self, new_session):
        """Set the current session for this menu.

        :param Session new_session: The session tied to this menu
        :returns None:

        """
        self._set_weak("session", new_session)

    def _init(self):
        """Prepare this menu after instantiation.

        Override this to perform any necessary localization or additional
        entry management specific to the session.

        """

    def _inst_add_entry(self, key, description, callback=None):
        """Add an entry to this menu.

        If you do not provide `callback`, this will instead return a
        decorator that will use the decorated callable as the callback.

        :param str key: A single-character key the entry will be accessed by
        :param str description: A description line for the entry
        :param callable callback: A callback for when the entry is chosen
        :returns None:
        :raises AlreadyExists: If an entry with that key already exists
        :raises ValueError: If `key` is not a single character string

        """
        def _inner(_callback):
            nonlocal key, description
            if not key or not isinstance(key, str) or len(key) > 1:
                raise ValueError(joins("menu entry keys must be a single"
                                       "character:", key))
            if key in " \t\n\r\f\v":
                raise ValueError("menu entry keys cannot be whitespace")
            key = key.upper()
            entry = (description, _callback)
            if key in self._entries:
                raise AlreadyExists(key, self._entries[key], entry)
            self._entries[key] = entry
            self._update_order()
            return _callback
        if callback is not None:
            return _inner(callback)
        else:
            return _inner

    def _inst_remove_entry(self, key):
        """Remove an entry from this menu.

        :param str key: The key of the entry to remove
        :returns None:
        :raises KeyError: If an entry with that key is not found

        """
        key = key.upper()
        if key not in self._entries:
            raise KeyError(joins("entry not found in ", class_name(self),
                                 ": ", key, sep=""))
        del self._entries[key]
        self._update_order()

    def _update_order(self):
        """Update the menu entry order cache."""
        keys = self._entries.keys()
        if self.ordering == self.ORDER_BY_ADDED:
            self._entry_order = keys
        elif self.ordering == self.ORDER_BY_ALPHA:
            self._entry_order = list(sorted(keys))

    def display(self):
        """Send this menu to the session."""
        self.session.send("")  # Send a newline.
        if self.title is not None:
            self.session.send(self.title_color, self.title, "^~", sep="")
        for key in self._entry_order:
            description = self._entries[key][0]
            self.session.send(self.key_color, key, self.spacer_color, ") ",
                              self.description_color, description,
                              "^~", sep="")

    def get_prompt(self):
        """Generate the current prompt for this menu."""
        return joins(self.prompt_color, self.prompt, "^~", sep="")

    def parse(self, data):
        """Parse input from the client session.

        Only the first character of any input sent will be used.

        :param str data: The data to be parsed
        :returns None:

        """
        data = data[0].upper()
        if data not in self._entries:
            self.session.send(self.error_color, self.error.format(key=data),
                              "^~", sep="")
            self.display()
        else:
            callback = self._entries[data][1]
            callback(self.session)

# We create a global MenuManager here for convenience, and while the
# server will generally only need one to work with, they are NOT singletons
# and you can make more MenuManager instances if you like.
MENUS = MenuManager()


text:
'use strict';

/* global describe, beforeEach, it, expect, inject */
describe('LocationModel.', function() {
    var Location, playerService;
    beforeEach(module('veganaut.app.map'));

    beforeEach(module(function($provide) {
        // Set up all the mock dependencies
        playerService = {
            getImmediateMe: jasmine.createSpy('getImmediateMe'),
            getDeferredMe: jasmine.createSpy('getDeferredMe')
                .andReturn({
                    then: function() {
                    }
                })
        };

        $provide.value('playerService', playerService);
    }));

    beforeEach(inject(function(_Location_) {
        Location = _Location_;
    }));

    it('is defined.', function() {
        expect(Location).toBeDefined();
        expect(typeof Location).toBe('function');
    });

    it('can be created from json.', function() {
        var loc = new Location({});
        expect(loc instanceof Location).toBe(true, 'created a Location object');
    });

    it('getUrl returns the correct URL.', function() {
        var loc = new Location({id: 1234, slug: 'test-bla'});
        expect(loc.getUrl()).toBe('/location/test-bla-1234', 'correct url');
    });

    describe('getRoundedQuality.', function() {
        it('returns correct default value.', function() {
            var loc = new Location();
            expect(loc.getRoundedQuality()).toBe(0);
        });

        it('rounds correctly.', function() {
            var loc = new Location({ quality: { average: 1.2 } });
            expect(loc.getRoundedQuality()).toBe(1, 'rounds down');
            loc = new Location({ quality: { average: 2.5 } });
            expect(loc.getRoundedQuality()).toBe(3, 'rounds up');
        });

        it('returns value between 0 and 5.', function() {
            var loc = new Location({ quality: { average: 7.3 } });
            expect(loc.getRoundedQuality()).toBe(5, 'max 5');
            loc = new Location({ quality: { average: -3.2 } });
            expect(loc.getRoundedQuality()).toBe(0, 'min 0');

        });
    });

    describe('setActive and isActive.', function() {
        it('returns correct default value.', function() {
            var loc = new Location();
            expect(typeof loc.isActive).toBe('function', 'isActive is a function');
            expect(typeof loc.setActive).toBe('function', 'setActive is a function');
            expect(loc.isActive()).toBe(false);
        });

        it('can be activated.', function() {
            var loc = new Location();
            loc.setActive();
            expect(loc.isActive()).toBe(true, 'default is to set active');

            loc = new Location();
            loc.setActive(true);
            expect(loc.isActive()).toBe(true, 'can explicitly set active');
        });

        it('can be activated and deactivated.', function() {
            var loc = new Location();
            loc.setActive();
            expect(loc.isActive()).toBe(true, 'set active');
            loc.setActive(false);
            expect(loc.isActive()).toBe(false, 'set inactive');
        });
    });

    describe('setDisabled and isDisabled.', function() {
        it('returns correct default value.', function() {
            var loc = new Location();
            expect(typeof loc.isDisabled).toBe('function', 'isDisabled is a function');
            expect(typeof loc.setDisabled).toBe('function', 'setDisabled is a function');
            expect(loc.isDisabled()).toBe(false);
        });

        it('can be set to hidden.', function() {
            var loc = new Location();
            loc.setDisabled();
            expect(loc.isDisabled()).toBe(true, 'default is to set hidden');

            loc = new Location();
            loc.setDisabled(true);
            expect(loc.isDisabled()).toBe(true, 'can explicitly set hidden');
        });

        it('can be hidden and shown.', function() {
            var loc = new Location();
            loc.setDisabled();
            expect(loc.isDisabled()).toBe(true, 'set hidden');
            loc.setDisabled(false);
            expect(loc.isDisabled()).toBe(false, 'set shown');
        });
    });

    describe('markerDefinition.', function() {
        it('has a marker definition.', function() {
            var loc = new Location();
            var markerDefinition = loc.getMarkerDefinition();
            expect(typeof markerDefinition).toBe('object', 'markerDefinition is an object');

            expect(typeof markerDefinition.icon).toBe('object', 'icon is an object');
            expect(markerDefinition.icon.iconSize).toBe(null, 'correct iconSize');
            expect(typeof markerDefinition.icon.html).toBe('string', 'correct html type');
            expect(markerDefinition.icon.className).toMatch(/\bmarker\b/, 'className contains "marker"');
        });

        it('added the location name to the marker definition.', function() {
            var loc = new Location({
                name: 'test name'
            });
            expect(loc.getMarkerDefinition().base.title).toBe('test name');
        });

        it('updates marker icon className when changing active state.', function() {
            var loc = new Location();
            var classRegex = /\bmarker--active\b/;
            expect(loc.getMarkerDefinition().icon.className).not.toMatch(classRegex, 'does not have active class');
            loc.setActive();
            expect(loc.getMarkerDefinition().icon.className).toMatch(classRegex, 'has active class when setting active');
            loc.setActive(false);
            expect(loc.getMarkerDefinition().icon.className).not.toMatch(classRegex, 'active class removed when setting inactive');
        });

        it('updates marker icon className when changing disabled state.', function() {
            var loc = new Location();
            var disabledClass = /\bmarker--disabled\b/;
            var enabledClass = /\bmarker--enabled\b/;
            expect(loc.getMarkerDefinition().icon.className).not.toMatch(disabledClass, 'does not have the disabled class');
            expect(loc.getMarkerDefinition().icon.className).toMatch(enabledClass, 'has the enabled class');
            loc.setDisabled();
            expect(loc.getMarkerDefinition().icon.className).toMatch(disabledClass, 'has the disabled class when setting disabled');
            expect(loc.getMarkerDefinition().icon.className).not.toMatch(enabledClass, 'does not have the enabled class when setting disabled');
            loc.setDisabled(false);
            expect(loc.getMarkerDefinition().icon.className).not.toMatch(disabledClass, 'disabled class removed when setting enabled');
            expect(loc.getMarkerDefinition().icon.className).toMatch(enabledClass, 'enabled class added when setting enabled');
        });
    });

    describe('setLatLng.', function() {
        it('method is defined.', function() {
            var loc = new Location();
            expect(typeof loc.setLatLng).toBe('function');
        });

        it('updates lat/lng of location and of marker.', function() {
            var loc = new Location({
                lat: 1,
                lng: 2
            });
            loc.setLatLng(3, 4);
            expect(loc.lat).toBe(3, 'set correct lat');
            expect(loc.lng).toBe(4, 'set correct lng');
            var markerLatLng = loc.getMarkerDefinition().latLng;
            expect(markerLatLng[0]).toBe(3, 'set correct marker lat');
            expect(markerLatLng[1]).toBe(4, 'set correct marker lng');
        });
    });

    describe('getProductById.', function() {
        it('has method', function() {
            var loc = new Location();
            expect(typeof loc.getProductById).toBe('function', 'getProductById is a function');
            expect(typeof loc.getProductById('something')).toBe('undefined', 'returns undefined by default');
        });

        it('returns products by id', function() {
            var prod1 = {
                id: '123',
                name: 'thing'
            };
            var loc = new Location({
                products: [prod1]
            });

            expect(loc.getProductById('123')).toBe(prod1, 'finds product by id');
            expect(typeof loc.getProductById(123)).toBe('undefined', 'does strict matches');
            expect(typeof loc.getProductById('1234')).toBe('undefined', 'really checks id');
        });

        it('returns correct product with multiple products', function() {
            var prod1 = {
                id: '123',
                name: 'thing'
            };
            var prod2 = {
                id: '456',
                name: 'other'
            };
            var loc = new Location({
                products: [prod1, prod2]
            });

            expect(loc.getProductById('123')).toBe(prod1, 'finds prod1');
            expect(loc.getProductById('456')).toBe(prod2, 'finds prod2');
        });
    });

    describe('sanitiseUrl.', function() {
        var loc;
        beforeEach(function() {
            loc = new Location();
        });

        it('method exists', function() {
            expect(typeof loc.sanitiseUrl).toBe('function');
        });

        it('does not modify a valid website', function() {
            expect(loc.sanitiseUrl('http://example.com')).toBe('http://example.com', 'http website not modified');
            expect(loc.sanitiseUrl('https://www.bla.ch')).toBe('https://www.bla.ch', 'https website not modified');
        });

        it('adds http:// if not already there', function() {
            expect(loc.sanitiseUrl('example.com')).toBe('http://example.com', 'test 1');
            expect(loc.sanitiseUrl('a')).toBe('http://a', 'test 2');
            expect(loc.sanitiseUrl('ablahttp://')).toBe('http://ablahttp://', 'test 3');
        });

        it('does not modify empty website', function() {
            expect(typeof loc.sanitiseUrl(undefined)).toBe('undefined', 'test 1');
            expect(loc.sanitiseUrl('')).toBe('', 'test 1');
        });
    });
});


text: pub mod copy_from_slice;


text:
/**
 *
 */

package edu.wustl.common.util.global;

/**
 * @author prashant_bandal
 *
 */
public final class TitliSearchConstants
{

	/**
	 * private constructor.
	 */
	private TitliSearchConstants()
	{

	}
	/**
	 * Specify sorted Result Map.
	 */
	public static final String TITLI_SORTED_RESULT_MAP = "sortedResultMap";
	/**
	 * Specify insert operation.
	 */
	public static final String TITLI_INSERT_OPERATION = "insert";
	/**
	 * Specify update operation.
	 */
	public static final String TITLI_UPDATE_OPERATION = "update";
	/**
	 * Specify delete operation.
	 */
	public static final String TITLI_DELETE_OPERATION = "delete";
	/**
	 * Specify single Result.
	 */
	public static final String TITLI_SINGLE_RESULT = "singleResult";
	/**
	 * Specify TITLI_FETCH_ACTION.
	 */
	public static final String TITLI_FETCH_ACTION = "/TitliFetch.do";
}


text:
'use strict';

const fs             = require('fs');
const path           = require('path');
const gulp           = require('gulp');
const gutil          = require('gulp-util');
const del            = require('del');
const browserSync    = require('browser-sync').create();
const autoprefixer   = require('autoprefixer');
const postcss        = require('gulp-postcss');
const sass           = require('gulp-sass');
const sourcemaps     = require('gulp-sourcemaps');
const source         = require('vinyl-source-stream');
const buffer         = require('vinyl-buffer');
const browserify     = require('browserify');
const rev            = require('gulp-rev');
const revReplace     = require('gulp-rev-replace');
const uglify         = require('gulp-uglify');
const cssnano        = require('gulp-cssnano');
const htmlmin        = require('gulp-htmlmin');
const gulpif         = require('gulp-if');
const critical       = require('critical').stream;
const runSequence    = require('run-sequence');

function bundle(options) {
  options = options || {};
  const bundlerOpts = { entry: true, debug: true };
  let bundler = browserify(
    'src/js/app.js', bundlerOpts
    )
    .transform('babelify', { presets: ['es2015'] });

  function rebundle() {
    return bundler.bundle()
      .on('error', function(err) {
        gutil.log(gutil.colors.red(err.message));
        this.emit('end');
      })
      .pipe(source('bundle.js'))
      .pipe(buffer())
      .pipe(sourcemaps.init({ loadMaps: true }))
      .pipe(sourcemaps.write())
      .pipe(gulp.dest('public/js/'));
  }

  if (options.watch) {
    const watchify = require('watchify');
    bundler = watchify(bundler);
    bundler.on('update', () => {
      gutil.log('-> bundling...');
      rebundle();
    });
  }

  return rebundle();
}

gulp.task('browserify', () => {
  return bundle();
});

gulp.task('watchify', () => {
  return bundle({ watch: true });
});

gulp.task('sass', () => {
  return gulp.src('src/scss/**/*.scss')
    .pipe(sourcemaps.init())
    .pipe(sass(
      {
        includePaths: [path.join(path.dirname(require.resolve('foundation-sites')), '../scss')]
      }
    )
    .on('error', sass.logError))
    .pipe(postcss([autoprefixer]))
    .pipe(sourcemaps.write())
    .pipe(gulp.dest('public/css/'));
});

gulp.task('extras', () => {
  return gulp.src('src/**/*.{txt,json,xml,jpeg,jpg,png,gif,svg,ttf,otf,eot,woff,woff2}')
    .pipe(gulp.dest('public/'));
});

gulp.task('watch', ['sass', 'extras', 'watchify'], () => {
  browserSync.init({
    server: 'public',
    files: 'public/**/*',
    open: false
  });

  gulp.watch('src/scss/**/*.scss', ['sass']);
  gulp.watch('src/**/*.{txt,json,xml,jpeg,jpg,png,gif,svg,ttf,otf,eot,woff,woff2}', ['extras']);
});

gulp.task('rev', ['build'], () => {
  return gulp.src(['public/**/*', '!**/*.html'], { base: 'public' })
    .pipe(rev())
    .pipe(gulp.dest('public/'))
    .pipe(rev.manifest())
    .pipe(gulp.dest('public/'));
});

gulp.task('rev:replace', ['rev'], () => {
  const manifest = gulp.src('public/rev-manifest.json');
  return gulp.src('public/**/*')
    .pipe(revReplace({ manifest: manifest }))
    .pipe(gulp.dest('public/'));
});

gulp.task('minify', ['rev:replace', 'critical'], () => {
  return gulp.src(['public/**/*'], { base: 'public/' })
    // Only target the versioned files with the hash
    // Those files have a - and a 10 character string
    .pipe(gulpif(/-\w{10}\.js$/, uglify({
      preserveComments: 'license',
      compressor: {
        screw_ie8: true
      },
      output: {
        preamble: (function() {
          var banner = fs.readFileSync('banner.txt', 'utf8');
          banner = banner.replace('@date', (new Date()));
          return banner;
        }())
      }
    })))
    .pipe(gulpif(/-\w{10}\.css$/, cssnano()))
    .pipe(gulpif('*.html', htmlmin({
      collapseWhitespace: true,
      removeComments: true,
      removeRedundantAttributes: true,
      removeScriptTypeAttributes: true,
      removeStyleLinkTypeAttributes: true
    })))
    .pipe(gulp.dest('public/'));
});

gulp.task('critical', ['rev:replace'], function() {
  return gulp.src('public/**/*.html')
  .pipe(critical({
    base: 'public/',
    inline: true,
    minify: true
  }))
  .pipe(gulp.dest('public/'));
});

gulp.task('clean', () => {
  return del(['public/*', '!public/favicon.ico', '!public/favicon-152.png']);
});

gulp.task('build', (done) => {
  runSequence(
    'clean',
    ['browserify', 'sass', 'extras'],
    done
  );
});

gulp.task('build:production', (done) => {
  runSequence(
    'build',
    ['rev:replace', 'minify', 'critical'],
    done
  );
});

gulp.task('start', (done) => {
  runSequence(
    'build',
    'watch',
    done
  );
});

gulp.task('default', ['build']);


text:
import FeedParser from 'feedparser'
import fetch from 'isomorphic-fetch'
import { Readable } from 'stream'

import config from '../resources/config.json'

export const REQUEST_FEED = 'REQUEST_FEED'
export const requestFeed = url => ({
  type: REQUEST_FEED,
  url
})

export const RECEIVE_FEED_SUCCESS = 'RECEIVE_FEED_SUCCESS'
export const receiveFeedSuccess = (url, metadata, data) => ({
  type: RECEIVE_FEED_SUCCESS,
  url,
  metadata,
  data
})

export const RECEIVE_FEED_FAIL = 'RECEIVE_FEED_FAIL'
export const receiveFeedFail = (url, error) => ({
  type: RECEIVE_FEED_FAIL,
  url,
  error
})

export const fetchFeed = url => dispatch => {
  dispatch(requestFeed(url))
  return new Promise((resolve, reject) => fetch(config.corsProxyServer + url)
    .then(response => response.text())
    .then(text => {
      // Convert the retrieved data to a stream
      const feedStream = new Readable()
      feedStream.push(text)
      feedStream.push(null)

      // Read and parse the data stream
      let metadata
      const data = []

      const feedParser = new FeedParser()
      feedParser.on('end', () => resolve({metadata, data}))
      feedParser.on('meta', meta => (metadata = meta))
      feedParser.on('readable', function () {
        let item
        while ((item = this.read())) {
          data.push(item)
        }
      })
      feedParser.on('error', error => reject(error))
      feedStream.pipe(feedParser)
    })
  )
  .then(feed => dispatch(receiveFeedSuccess(url, feed.metadata, feed.data)))
  .catch(error => dispatch(receiveFeedFail(url, error.message)))
}

export const FILTER_FEED = 'FILTER_FEED'
export const filterFeed = url => ({
  type: FILTER_FEED,
  url
})

export const MARK_AS_READ = 'MARK_AS_READ'
export const markAsRead = (url, guid) => ({
  type: MARK_AS_READ,
  url,
  guid
})


text:
package org.gedcomx.record;

import org.codehaus.enunciate.ClientName;
import org.codehaus.enunciate.json.JsonName;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonTypeInfo;
import org.codehaus.jackson.map.annotate.JsonTypeIdResolver;
import org.gedcomx.rt.RDFSubClassOf;
import org.gedcomx.rt.XmlTypeIdResolver;
import org.gedcomx.rt.CommonModels;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
import java.util.List;

/**
 * A date field.
 */
@ClientName("DateInfo")
@JsonTypeInfo ( use =JsonTypeInfo.Id.CUSTOM, property = XmlTypeIdResolver.TYPE_PROPERTY_NAME)
@JsonTypeIdResolver (XmlTypeIdResolver.class)
@XmlType ( name = "Date" )
@RDFSubClassOf ( CommonModels.DUBLIN_CORE_NAMESPACE + "PeriodOfTime" )
public class Date extends Field implements Partitionable<DatePart> {

  private List<DatePart> parts;

  /**
   * The parts of the date.
   *
   * @return The parts of the date.
   */
  @XmlElement(name = "part")
  @JsonName ("parts")
  @JsonProperty ("parts")
  public List<DatePart> getParts() {
    return parts;
  }

  /**
   * The parts of the date.
   *
   * @param parts The parts of the date.
   */
  @JsonProperty ("parts")
  public void setParts(List<DatePart> parts) {
    this.parts = parts;
  }

  /**
   * Provide a simple toString() method.
   */
  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();

    sb.append(super.toString());

    if (sb.length() <= 0) {
      // Then look to the parts for something to display
      for (DatePart part : parts) {
        if (sb.length() > 0) {
          sb.append(" ");
        }
        sb.append(part.toString());
      }
    }

    return sb.toString();
  }

}


text:
TextEdit::TextEdit()
{
}

// ----------------------------------------------------------------------------
void TextEdit::load(const char* Path)
{
  _Doc = loadTextDoc(Path);
}

// ----------------------------------------------------------------------------
void TextEdit::save(const char* Path) const
{
  saveTextDoc(Path, _Doc);
}

// ----------------------------------------------------------------------------
void TextEdit::replaceContent(char* pDoc, size_t Length)
{
  _Doc.replaceContent(pDoc, Length);
}

// ----------------------------------------------------------------------------
void TextEdit::insertChars(const TextPos& pos, const char* ch)
{
  TextDoc doc(ch);
  insertContent(pos, doc);
}

// ----------------------------------------------------------------------------
void TextEdit::insertNewLine(const TextPos& pos, size_t indent)
{
  TextDoc doc(2u);
  doc.Lines[1] = std::string(indent, ' ');

  insertContent(pos, doc);
}

// ----------------------------------------------------------------------------
void TextEdit::insertNewLineBefore(size_t line, size_t indent)
{
  TextDoc doc(2u);
  doc.Lines[0] = std::string(indent, ' ');
  insertContent(TextPos(line, 0), doc);
}

// ----------------------------------------------------------------------------
void TextEdit::deleteChar(size_t line, size_t col)
{
  TextPos p0(line, col);
  TextPos p1(getNextPos(p0));

  deleteContent(p0, p1);
}

// ----------------------------------------------------------------------------
void TextEdit::deleteLine(size_t line)
{
  TextPos p0(line, 0);
  TextPos p1(line+1, 0);

  deleteContent(p0, p1);
}

// ----------------------------------------------------------------------------
void TextEdit::deleteContent(const TextPos& p0, const TextPos& p1)
{
  TextDoc undo = _Doc.getContent(p0, p1);
  _Hist.addNewCommand(EditCommand(0, p0, p1, undo));

  _Doc.deleteContent(p0, p1);
}

// ----------------------------------------------------------------------------
void TextEdit::insertContent(const TextPos& p, const TextDoc& Content)
{
  _Hist.addNewCommand(EditCommand(1, p, p + Content.getEndOfDoc(), Content));
  _Doc.insertContent(p, Content);
}

// ----------------------------------------------------------------------------
void TextEdit::undo(TextPos* pPos)
{
  if (_Hist.countUndoCommands() == 0) {
    return;
  }

  *pPos = _applyCommand(1, _Hist.undoCommand());
}

// ----------------------------------------------------------------------------
void TextEdit::redo(TextPos* pPos)
{
  if (_Hist.countRedoCommands() == 0) {
    return;
  }

  *pPos = _applyCommand(0, _Hist.redoCommand());
}

// ----------------------------------------------------------------------------
const TextPos& TextEdit::_applyCommand(uint type, const EditCommand& cmd)
{
  if (cmd.type ^ type) {
    _Doc.insertContent(cmd.p0, cmd.content);
  } else {
    _Doc.deleteContent(cmd.p0, cmd.p1);
  }

  return cmd.p0;
}


text:
"use strict"

var o = require("../../ospec/ospec")
var xhrMock = require("../../test-utils/xhrMock")
var parseQueryString = require("../../querystring/parse")

o.spec("xhrMock", function() {
	var $window, ajax
	o.beforeEach(function() {
		$window = xhrMock()
	})

	o.spec("xhr", function() {
		o("works", function(done, timeout) {
			$window.$defineRoutes({
				"GET /item": function(request) {
					o(request.url).equals("/item")
					return {status: 200, responseText: "test"}
				}
			})
			var xhr = new $window.XMLHttpRequest()
			xhr.open("GET", "/item")
			xhr.onreadystatechange = function() {
				if (xhr.readyState === 4) {
					o(xhr.status).equals(200)
					o(xhr.responseText).equals("test")
					done()
				}
			}
			xhr.send()
		})
		o("works w/ search", function(done, timeout) {
			$window.$defineRoutes({
				"GET /item": function(request) {
					o(request.query).equals("?a=b")
					return {status: 200, responseText: "test"}
				}
			})
			var xhr = new $window.XMLHttpRequest()
			xhr.open("GET", "/item?a=b")
			xhr.onreadystatechange = function() {
				if (xhr.readyState === 4) {
					done()
				}
			}
			xhr.send()
		})
		o("works w/ body", function(done, timeout) {
			$window.$defineRoutes({
				"POST /item": function(request) {
					o(request.body).equals("a=b")
					return {status: 200, responseText: "test"}
				}
			})
			var xhr = new $window.XMLHttpRequest()
			xhr.open("POST", "/item")
			xhr.onreadystatechange = function() {
				if (xhr.readyState === 4) {
					done()
				}
			}
			xhr.send("a=b")
		})
		o("handles routing error", function(done, timeout) {
			var xhr = new $window.XMLHttpRequest()
			xhr.open("GET", "/nonexistent")
			xhr.onreadystatechange = function() {
				if (xhr.readyState === 4) {
					o(xhr.status).equals(500)
					done()
				}
			}
			xhr.send("a=b")
		})
	})
	o.spec("jsonp", function() {
		o("works", function(done) {
			$window.$defineRoutes({
				"GET /test": function(request) {
					var queryData = parseQueryString(request.query)
					return {status: 200, responseText: queryData["callback"] + "(" + JSON.stringify({a: 1}) + ")"}
				}
			})

			$window["cb"] = finish

			var script = $window.document.createElement("script")
			script.src = "/test?callback=cb"
			$window.document.documentElement.appendChild(script)

			function finish(data) {
				o(data).deepEquals({a: 1})
				done()
			}
		})
		o("works w/ custom callback key", function(done) {
			$window.$defineRoutes({
				"GET /test": function(request) {
					var queryData = parseQueryString(request.query)
					return {status: 200, responseText: queryData["cb"] + "(" + JSON.stringify({a: 2}) + ")"}
				}
			})
			$window.$defineJSONPCallbackKey("cb")

			$window["customcb"] = finish2

			var script = $window.document.createElement("script")
			script.src = "/test?cb=customcb"
			$window.document.documentElement.appendChild(script)

			function finish2(data) {
				o(data).deepEquals({a: 2})
				done()
			}
		})
		o("works with other querystring params", function(done, timeout) {
			$window.$defineRoutes({
				"GET /test": function(request) {
					var queryData = parseQueryString(request.query)
					return {status: 200, responseText: queryData["callback"] + "(" + JSON.stringify({a: 3}) + ")"}
				}
			})

			$window["cbwithinparams"] = finish

			var script = $window.document.createElement("script")
			script.src = "/test?a=b&callback=cbwithinparams&c=d"
			$window.document.documentElement.appendChild(script)

			function finish(data) {
				o(data).deepEquals({a: 3})
				done()
			}
		})
		o("handles error", function(done) {
			var script = $window.document.createElement("script")
			script.onerror = finish
			script.src = "/test?cb=nonexistent"
			$window.document.documentElement.appendChild(script)

			function finish(e) {
				o(e.type).equals("error")
				done()
			}
		})
	})
})


text:
<?php

namespace Sparta\Exceptions;

/**
 * InvalidValidatorArguments Class.
 *
 * @author  Mohammed Ashour <ashoms0a@gmail.com>
 *
 * @link    http://www.coderavine.com/
 */
class InvalidValidatorArguments extends \Exception
{
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.entidad;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 *
 * @author ferna
 */
public class Album implements Serializable {
    private int codAlbum;
    private String nombreAlb;
    private String descripcionAlb;
    private Date f_creacionAlb;
    private Perfil objPerfil;
    private Categoria objCategoria;
    private List<TagAlbum> listaTagAlbum;
    private int n_publicaciones;

    public Album(){
        this.objPerfil=new Perfil();
        this.objCategoria=new Categoria();
    }

    public int getCodAlbum() {
        return codAlbum;
    }

    public void setCodAlbum(int codAlbum) {
        this.codAlbum = codAlbum;
    }

    public String getNombreAlb() {
        return nombreAlb;
    }

    public void setNombreAlb(String nombreAlb) {
        this.nombreAlb = nombreAlb;
    }

    public String getDescripcionAlb() {
        return descripcionAlb;
    }

    public void setDescripcionAlb(String descripcionAlb) {
        this.descripcionAlb = descripcionAlb;
    }

    public Date getF_creacionAlb() {
        return f_creacionAlb;
    }

    public void setF_creacionAlb(Date f_creacionAlb) {
        this.f_creacionAlb = f_creacionAlb;
    }

    public Perfil getObjPerfil() {
        return objPerfil;
    }

    public void setObjPerfil(Perfil objPerfil) {
        this.objPerfil = objPerfil;
    }

    public int getN_publicaciones() {
        return n_publicaciones;
    }

    public void setN_publicaciones(int n_publicaciones) {
        this.n_publicaciones = n_publicaciones;
    }

    public Categoria getObjCategoria() {
        return objCategoria;
    }

    public void setObjCategoria(Categoria objCategoria) {
        this.objCategoria = objCategoria;
    }

}