text:
require 'chef/resource/package'
require 'chef/provider/package/apt'

class Chef
  class Resource
    class AptPackage < Chef::Resource::Package

      provides :apt_package
      provides :package, os: "linux", platform_family: [ "debian" ]

      def initialize(name, run_context=nil)
        super
        @resource_name = :apt_package
        @default_release = nil
      end

      def default_release(arg=nil)
        set_or_return(
          :default_release,
          arg,
          :kind_of => [ String ]
        )
      end

    end
  end
end


text:
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using Internal.NativeCrypto;

namespace System.Security.Cryptography
{
    public sealed partial class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgorithm
    {
        private int _keySize;
        private CspParameters _parameters;
        private bool _randomKeyContainer;
        private SafeKeyHandle _safeKeyHandle;
        private SafeProvHandle _safeProvHandle;
        private static volatile CspProviderFlags s_UseMachineKeyStore = 0;

        public RSACryptoServiceProvider()
            : this(0, new CspParameters(CapiHelper.DefaultRsaProviderType,
                                       null,
                                       null,
                                       s_UseMachineKeyStore),
                                       true)
        {
        }

        public RSACryptoServiceProvider(int dwKeySize)
            : this(dwKeySize,
                  new CspParameters(CapiHelper.DefaultRsaProviderType,
                  null,
                  null,
                  s_UseMachineKeyStore), false)
        {
        }

        public RSACryptoServiceProvider(int dwKeySize, CspParameters parameters)
            : this(dwKeySize, parameters, false)
        {
        }

        public RSACryptoServiceProvider(CspParameters parameters)
            : this(0, parameters, true)
        {
        }

        private RSACryptoServiceProvider(int keySize, CspParameters parameters, bool useDefaultKeySize)
        {
            if (keySize < 0)
            {
                throw new ArgumentOutOfRangeException("dwKeySize", "ArgumentOutOfRange_NeedNonNegNum");
            }
            _parameters = CapiHelper.SaveCspParameters(CapiHelper.CspAlgorithmType.Rsa, parameters, s_UseMachineKeyStore, ref _randomKeyContainer);

            _keySize = useDefaultKeySize ? 1024 : keySize;

            // If this is not a random container we generate, create it eagerly
            // in the constructor so we can report any errors now.
            if (!_randomKeyContainer)
            {
                GetKeyPair();
            }
        }

        /// <summary>
        /// Retreives the key pair
        /// </summary>
        private void GetKeyPair()
        {
            if (_safeKeyHandle == null)
            {
                lock (this)
                {
                    if (_safeKeyHandle == null)
                    {
                        // We only attempt to generate a random key on desktop runtimes because the CoreCLR
                        // RSA surface area is limited to simply verifying signatures.  Since generating a
                        // random key to verify signatures will always lead to failure (unless we happend to
                        // win the lottery and randomly generate the signing key ...), there is no need
                        // to add this functionality to CoreCLR at this point.
                        CapiHelper.GetKeyPairHelper(CapiHelper.CspAlgorithmType.Rsa, _parameters,
                                            _randomKeyContainer, _keySize, ref _safeProvHandle, ref _safeKeyHandle);
                    }
                }
            }
        }

        /// <summary>
        /// CspKeyContainerInfo property
        /// </summary>
        public CspKeyContainerInfo CspKeyContainerInfo
        {
            get
            {
                GetKeyPair();
                return new CspKeyContainerInfo(_parameters, _randomKeyContainer);
            }
        }

        /// <summary>
        /// _keySize property
        /// </summary>
        public override int KeySize
        {
            get
            {
                GetKeyPair();
                byte[] keySize = (byte[])CapiHelper.GetKeyParameter(_safeKeyHandle, Constants.CLR_KEYLEN);
                _keySize = (keySize[0] | (keySize[1] << 8) | (keySize[2] << 16) | (keySize[3] << 24));
                return _keySize;
            }
        }

        public override KeySizes[] LegalKeySizes
        {
            get
            {
                return new[] { new KeySizes(384, 16384, 8) };
            }
        }

        /// <summary>
        /// get set Persisted key in CSP
        /// </summary>
        public bool PersistKeyInCsp
        {
            get
            {
                if (_safeProvHandle == null)
                {
                    lock (this)
                    {
                        if (_safeProvHandle == null)
                        {
                            _safeProvHandle = CapiHelper.CreateProvHandle(_parameters, _randomKeyContainer);
                        }
                    }
                }
                return CapiHelper.GetPersistKeyInCsp(_safeProvHandle);
            }
            set
            {
                bool oldPersistKeyInCsp = this.PersistKeyInCsp;
                if (value == oldPersistKeyInCsp)
                {
                    return; // Do nothing
                }
                CapiHelper.SetPersistKeyInCsp(_safeProvHandle, value);
            }
        }

        /// <summary>
        /// Gets the information of key if it is a public key
        /// </summary>
        public bool PublicOnly
        {
            get
            {
                GetKeyPair();
                byte[] publicKey = (byte[])CapiHelper.GetKeyParameter(_safeKeyHandle, Constants.CLR_PUBLICKEYONLY);
                return (publicKey[0] == 1);
            }
        }

        /// <summary>
        /// MachineKey store properties
        /// </summary>
        public static bool UseMachineKeyStore
        {
            get
            {
                return (s_UseMachineKeyStore == CspProviderFlags.UseMachineKeyStore);
            }
            set
            {
                s_UseMachineKeyStore = (value ? CspProviderFlags.UseMachineKeyStore : 0);
            }
        }

        /// <summary>
        ///     Decrypt raw data, generally used for decrypting symmetric key material
        /// </summary>
        /// <param name="rgb">encrypted data</param>
        /// <param name="fOAEP">true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding</param>
        /// <returns>decrypted data</returns>
        public byte[] Decrypt(byte[] rgb, bool fOAEP)
        {
            if (rgb == null)
            {
                throw new ArgumentNullException(nameof(rgb));
            }

            GetKeyPair();

            // size check -- must be at most the modulus size
            if (rgb.Length > (KeySize / 8))
            {
                throw new CryptographicException(SR.Format(SR.Cryptography_Padding_DecDataTooBig, Convert.ToString(KeySize / 8)));
            }
            byte[] decryptedKey = null;
            CapiHelper.DecryptKey(_safeKeyHandle, rgb, rgb.Length, fOAEP, out decryptedKey);
            return decryptedKey;
        }

        /// <summary>
        /// Dispose the key handles
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);

            if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed)
            {
                _safeKeyHandle.Dispose();
            }
            if (_safeProvHandle != null && !_safeProvHandle.IsClosed)
            {
                _safeProvHandle.Dispose();
            }
        }

        /// <summary>
        ///     Encrypt raw data, generally used for encrypting symmetric key material.
        /// </summary>
        /// <remarks>
        ///     This method can only encrypt (keySize - 88 bits) of data, so should not be used for encrypting
        ///     arbitrary byte arrays. Instead, encrypt a symmetric key with this method, and use the symmetric
        ///     key to encrypt the sensitive data.
        /// </remarks>
        /// <param name="rgb">raw data to encryt</param>
        /// <param name="fOAEP">true to use OAEP padding (PKCS #1 v2), false to use PKCS #1 type 2 padding</param>
        /// <returns>Encrypted key</returns>
        public byte[] Encrypt(byte[] rgb, bool fOAEP)
        {
            if (rgb == null)
            {
                throw new ArgumentNullException(nameof(rgb));
            }

            GetKeyPair();

            byte[] encryptedKey = null;
            CapiHelper.EncryptKey(_safeKeyHandle, rgb, rgb.Length, fOAEP, ref encryptedKey);
            return encryptedKey;
        }

        /// <summary>
        ///Exports a blob containing the key information associated with an RSACryptoServiceProvider object.
        /// </summary>
        public byte[] ExportCspBlob(bool includePrivateParameters)
        {
            GetKeyPair();
            return CapiHelper.ExportKeyBlob(includePrivateParameters, _safeKeyHandle);
        }

        /// <summary>
        /// Exports the RSAParameters
        /// </summary>
        public override RSAParameters ExportParameters(bool includePrivateParameters)
        {
            GetKeyPair();
            byte[] cspBlob = ExportCspBlob(includePrivateParameters);
            return cspBlob.ToRSAParameters(includePrivateParameters);
        }

        /// <summary>
        /// This method helps Acquire the default CSP and avoids the need for static SafeProvHandle
        /// in CapiHelper class
        /// </summary>
        /// <param name="safeProvHandle"> SafeProvHandle. Intialized if successful</param>
        /// <returns>does not return. AcquireCSP throw exception</returns>
        private void AcquireSafeProviderHandle(ref SafeProvHandle safeProvHandle)
        {
            CapiHelper.AcquireCsp(new CspParameters(CapiHelper.DefaultRsaProviderType), ref safeProvHandle);
        }

        /// <summary>
        /// Imports a blob that represents RSA key information
        /// </summary>
        /// <param name="keyBlob"></param>
        public void ImportCspBlob(byte[] keyBlob)
        {
            // Free the current key handle
            if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed)
            {
                _safeKeyHandle.Dispose();
                _safeKeyHandle = null;
            }
            _safeKeyHandle = SafeKeyHandle.InvalidHandle;

            if (IsPublic(keyBlob))
            {
                SafeProvHandle safeProvHandleTemp = SafeProvHandle.InvalidHandle;
                AcquireSafeProviderHandle(ref safeProvHandleTemp);
                CapiHelper.ImportKeyBlob(safeProvHandleTemp, (CspProviderFlags)0, keyBlob, ref _safeKeyHandle);
                _safeProvHandle = safeProvHandleTemp;
            }
            else
            {
                if (_safeProvHandle == null)
                {
                    _safeProvHandle = CapiHelper.CreateProvHandle(_parameters, _randomKeyContainer);
                }
                CapiHelper.ImportKeyBlob(_safeProvHandle, _parameters.Flags, keyBlob, ref _safeKeyHandle);
            }
        }

        /// <summary>
        /// Imports the specified RSAParameters
        /// </summary>
        public override void ImportParameters(RSAParameters parameters)
        {
            // Free the current key handle
            if (_safeKeyHandle != null && !_safeKeyHandle.IsClosed)
            {
                _safeKeyHandle.Dispose();
                _safeKeyHandle = null;
            }
            _safeKeyHandle = SafeKeyHandle.InvalidHandle;

            byte[] keyBlob = parameters.ToKeyBlob(CapiHelper.CALG_RSA_KEYX);
            ImportCspBlob(keyBlob);
            return;
        }

        /// <summary>
        /// Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value.
        /// </summary>
        /// <param name="buffer">The input data for which to compute the hash</param>
        /// <param name="offset">The offset into the array from which to begin using data</param>
        /// <param name="count">The number of bytes in the array to use as data. </param>
        /// <param name="halg">The hash algorithm to use to create the hash value. </param>
        /// <returns>The RSA signature for the specified data.</returns>
        public byte[] SignData(byte[] buffer, int offset, int count, Object halg)
        {
            int calgHash = CapiHelper.ObjToHashAlgId(halg);
            HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
            byte[] hashVal = hash.ComputeHash(buffer, offset, count);
            return SignHash(hashVal, calgHash);
        }

        /// <summary>
        /// Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value.
        /// </summary>
        /// <param name="buffer">The input data for which to compute the hash</param>
        /// <param name="halg">The hash algorithm to use to create the hash value. </param>
        /// <returns>The RSA signature for the specified data.</returns>
        public byte[] SignData(byte[] buffer, Object halg)
        {
            int calgHash = CapiHelper.ObjToHashAlgId(halg);
            HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
            byte[] hashVal = hash.ComputeHash(buffer);
            return SignHash(hashVal, calgHash);
        }

        /// <summary>
        /// Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value.
        /// </summary>
        /// <param name="inputStream">The input data for which to compute the hash</param>
        /// <param name="halg">The hash algorithm to use to create the hash value. </param>
        /// <returns>The RSA signature for the specified data.</returns>
        public byte[] SignData(Stream inputStream, Object halg)
        {
            int calgHash = CapiHelper.ObjToHashAlgId(halg);
            HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
            byte[] hashVal = hash.ComputeHash(inputStream);
            return SignHash(hashVal, calgHash);
        }

        /// <summary>
        /// Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value.
        /// </summary>
        /// <param name="rgbHash">The input data for which to compute the hash</param>
        /// <param name="str">The hash algorithm to use to create the hash value. </param>
        /// <returns>The RSA signature for the specified data.</returns>
        public byte[] SignHash(byte[] rgbHash, string str)
        {
            if (rgbHash == null)
                throw new ArgumentNullException(nameof(rgbHash));
            if (PublicOnly)
                throw new CryptographicException(SR.Cryptography_CSP_NoPrivateKey);

            int calgHash = CapiHelper.NameOrOidToHashAlgId(str);

            return SignHash(rgbHash, calgHash);
        }

        /// <summary>
        /// Computes the hash value of a subset of the specified byte array using the specified hash algorithm, and signs the resulting hash value.
        /// </summary>
        /// <param name="rgbHash">The input data for which to compute the hash</param>
        /// <param name="calgHash">The hash algorithm to use to create the hash value. </param>
        /// <returns>The RSA signature for the specified data.</returns>
        private byte[] SignHash(byte[] rgbHash, int calgHash)
        {
            Debug.Assert(rgbHash != null);
            GetKeyPair();
            return CapiHelper.SignValue(_safeProvHandle, _safeKeyHandle, _parameters.KeyNumber, CapiHelper.CALG_RSA_SIGN, calgHash, rgbHash);
        }

        /// <summary>
        /// Verifies the signature of a hash value.
        /// </summary>
        public bool VerifyData(byte[] buffer, object halg, byte[] signature)
        {
            int calgHash = CapiHelper.ObjToHashAlgId(halg);
            HashAlgorithm hash = CapiHelper.ObjToHashAlgorithm(halg);
            byte[] hashVal = hash.ComputeHash(buffer);
            return VerifyHash(hashVal, calgHash, signature);
        }

        /// <summary>
        /// Verifies the signature of a hash value.
        /// </summary>
        public bool VerifyHash(byte[] rgbHash, string str, byte[] rgbSignature)
        {
            if (rgbHash == null)
                throw new ArgumentNullException(nameof(rgbHash));
            if (rgbSignature == null)
                throw new ArgumentNullException(nameof(rgbSignature));

            int calgHash = CapiHelper.NameOrOidToHashAlgId(str);
            return VerifyHash(rgbHash, calgHash, rgbSignature);
        }

        /// <summary>
        /// Verifies the signature of a hash value.
        /// </summary>
        private bool VerifyHash(byte[] rgbHash, int calgHash, byte[] rgbSignature)
        {
            GetKeyPair();
            return CapiHelper.VerifySign(_safeProvHandle, _safeKeyHandle, CapiHelper.CALG_RSA_SIGN, calgHash, rgbHash, rgbSignature);
        }

        /// <summary>
        /// find whether an RSA key blob is public.
        /// </summary>
        private static bool IsPublic(byte[] keyBlob)
        {
            if (keyBlob == null)
            {
                throw new ArgumentNullException(nameof(keyBlob));
            }
            // The CAPI RSA public key representation consists of the following sequence:
            //  - BLOBHEADER
            //  - RSAPUBKEY

            // The first should be PUBLICKEYBLOB and magic should be RSA_PUB_MAGIC "RSA1"
            if (keyBlob[0] != CapiHelper.PUBLICKEYBLOB)
            {
                return false;
            }
            if (keyBlob[11] != 0x31 || keyBlob[10] != 0x41 || keyBlob[9] != 0x53 || keyBlob[8] != 0x52)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// Since P is required, we will assume its presence is synonymous to a private key.
        /// </summary>
        /// <param name="rsaParams"></param>
        /// <returns></returns>
        private static bool IsPublic(RSAParameters rsaParams)
        {
            return (rsaParams.P == null);
        }

        protected override byte[] HashData(byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
        {
            // we're sealed and the base should have checked this already
            Debug.Assert(data != null);
            Debug.Assert(count >= 0 && count <= data.Length);
            Debug.Assert(offset >= 0 && offset <= data.Length - count);
            Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name));

            using (HashAlgorithm hash = GetHashAlgorithm(hashAlgorithm))
            {
                return hash.ComputeHash(data, offset, count);
            }
        }

        protected override byte[] HashData(Stream data, HashAlgorithmName hashAlgorithm)
        {
            // we're sealed and the base should have checked this already
            Debug.Assert(data != null);
            Debug.Assert(!string.IsNullOrEmpty(hashAlgorithm.Name));

            using (HashAlgorithm hash = GetHashAlgorithm(hashAlgorithm))
            {
                return hash.ComputeHash(data);
            }
        }

        private static HashAlgorithm GetHashAlgorithm(HashAlgorithmName hashAlgorithm)
        {
            switch (hashAlgorithm.Name)
            {
                case "MD5":
                    return MD5.Create();
                case "SHA1":
                    return SHA1.Create();
                case "SHA256":
                    return SHA256.Create();
                case "SHA384":
                    return SHA384.Create();
                case "SHA512":
                    return SHA512.Create();
                default:
                    throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name);
            }
        }

        private static int GetAlgorithmId(HashAlgorithmName hashAlgorithm)
        {
            switch (hashAlgorithm.Name)
            {
                case "MD5":
                    return CapiHelper.CALG_MD5;
                case "SHA1":
                    return CapiHelper.CALG_SHA1;
                case "SHA256":
                    return CapiHelper.CALG_SHA_256;
                case "SHA384":
                    return CapiHelper.CALG_SHA_384;
                case "SHA512":
                    return CapiHelper.CALG_SHA_512;
                default:
                    throw new CryptographicException(SR.Cryptography_UnknownHashAlgorithm, hashAlgorithm.Name);
            }
        }

        public override byte[] Encrypt(byte[] data, RSAEncryptionPadding padding)
        {
            if (data == null)
                throw new ArgumentNullException(nameof(data));
            if (padding == null)
                throw new ArgumentNullException(nameof(padding));

            if (padding == RSAEncryptionPadding.Pkcs1)
            {
                return Encrypt(data, fOAEP: false);
            }
            else if (padding == RSAEncryptionPadding.OaepSHA1)
            {
                return Encrypt(data, fOAEP: true);
            }
            else
            {
                throw PaddingModeNotSupported();
            }
        }

        public override byte[] Decrypt(byte[] data, RSAEncryptionPadding padding)
        {
            if (data == null)
                throw new ArgumentNullException(nameof(data));
            if (padding == null)
                throw new ArgumentNullException(nameof(padding));

            if (padding == RSAEncryptionPadding.Pkcs1)
            {
                return Decrypt(data, fOAEP: false);
            }
            else if (padding == RSAEncryptionPadding.OaepSHA1)
            {
                return Decrypt(data, fOAEP: true);
            }
            else
            {
                throw PaddingModeNotSupported();
            }
        }

        public override byte[] SignHash(
            byte[] hash,
            HashAlgorithmName hashAlgorithm,
            RSASignaturePadding padding)
        {
            if (hash == null)
                throw new ArgumentNullException(nameof(hash));
            if (string.IsNullOrEmpty(hashAlgorithm.Name))
                throw HashAlgorithmNameNullOrEmpty();
            if (padding == null)
                throw new ArgumentNullException(nameof(padding));
            if (padding != RSASignaturePadding.Pkcs1)
                throw PaddingModeNotSupported();

            return SignHash(hash, GetAlgorithmId(hashAlgorithm));
        }

        public override bool VerifyHash(
            byte[] hash,
            byte[] signature,
            HashAlgorithmName hashAlgorithm,
            RSASignaturePadding padding)
        {
            if (hash == null)
                throw new ArgumentNullException(nameof(hash));
            if (signature == null)
                throw new ArgumentNullException(nameof(signature));
            if (string.IsNullOrEmpty(hashAlgorithm.Name))
                throw HashAlgorithmNameNullOrEmpty();
            if (padding == null)
                throw new ArgumentNullException(nameof(padding));
            if (padding != RSASignaturePadding.Pkcs1)
                throw PaddingModeNotSupported();

            return VerifyHash(hash, GetAlgorithmId(hashAlgorithm), signature);
        }

        private static Exception PaddingModeNotSupported()
        {
            return new CryptographicException(SR.Cryptography_InvalidPaddingMode);
        }

        private static Exception HashAlgorithmNameNullOrEmpty()
        {
            return new ArgumentException(SR.Cryptography_HashAlgorithmNameNullOrEmpty, "hashAlgorithm");
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<meta charset="UTF-8">
<title>TimesOfDay.<init> - biomedicus-core</title>
<link rel="stylesheet" href="../../../style.css">

biomedicus-core / edu.umn.biomedicus.time / TimesOfDay / <init>

<init>

TimesOfDay(<span class="identifier" id="edu.umn.biomedicus.time.TimesOfDay$<init>(kotlin.String)/path">path: String)

TimesOfDay(<span class="identifier" id="edu.umn.biomedicus.time.TimesOfDay$<init>(kotlin.collections.List((kotlin.String)))/values">values: List<String>)


text:
package com.flag.engine.apis;

import java.util.List;

import javax.annotation.Nullable;
import javax.inject.Named;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.flag.engine.constants.Constants;
import com.flag.engine.models.Log;
import com.flag.engine.models.PMF;
import com.google.api.server.spi.config.Api;
import com.google.api.server.spi.config.ApiMethod;

@Api(name = "flagengine", version = "v1", clientIds = { Constants.WEB_CLIENT_ID, Constants.ANDROID_CLIENT_ID, Constants.IOS_CLIENT_ID,
		Constants.API_EXPLORER_CLIENT_ID }, audiences = { Constants.ANDROID_AUDIENCE })
public class Logs {
	@ApiMethod(name = "logs.insert", path = "log", httpMethod = "post")
	public Log insertLog(Log log) {
		PersistenceManager pm = PMF.getPersistenceManagerSQL();
		pm.makePersistent(log);
		pm.close();

		return log;
	}

	@SuppressWarnings("unchecked")
	@ApiMethod(name = "logs.get", path = "log", httpMethod = "get")
	public List<Log> getLogs(@Nullable @Named("start") long start, @Nullable @Named("end") long end) {
		PersistenceManager pm = PMF.getPersistenceManagerSQL();

		Query query = pm.newQuery(Log.class);
		query.setFilter("createdAt > start && createdAt < end");
		query.declareParameters("long start, long end");
		List<Log> logs = (List<Log>) pm.newQuery(query).execute(start, end);

		return logs;
	}
}


text:
var gulp        = require('gulp'),
    browserSync = require('browser-sync').create(),
    sass        = require('gulp-sass'),
    sourcemaps  = require('gulp-sourcemaps'),
    concat      = require('gulp-concat'),
    uglify      = require('gulp-uglify'),
    gulputil    = require('gulp-util');
    gulpif      = require('gulp-if');

/*
 * Env : use --production in prod mode
 */

var envDev = !gulputil.env.production;

/*
 * Conf
 */

var config = {
    sass : {
        src : './src/Template/static/scss/*',
        dest: './web/dist/css/',
        settings : {
            outputStyle: 'compressed'
        },
        watchsrc : [
            './src/Template/static/scss/**',
            './src/Blog/static/scss/**'
        ]
    },
    js : {
        src : [
            './src/Blog/static/js/blog.js'
        ],
        dest: './web/dist/js/',
        filename: 'app.js'
    },
    browserSync: {
        proxy: {
            target: "localhost:8080",
            middleware: function (req, res, next) {
                res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
                next()
            }
        }
    }
};

/*
 * Gulp Tasks
 */

gulp.task('browserSync', function () {
    browserSync.init(config.browserSync);
});

gulp.task('sass', function () {
    return gulp.src(config.sass.src)
        .pipe(gulpif(envDev, sourcemaps.init()))
        .pipe(sass(config.sass.settings))
        .pipe(gulpif(envDev, sourcemaps.write('./')))
        .pipe(gulp.dest(config.sass.dest))
        .pipe(browserSync.reload({stream:true}));
});

gulp.task('js', function () {
    return gulp.src(config.js.src)
        .pipe(gulpif(envDev, sourcemaps.init()))
        .pipe(concat(config.js.filename))
        .pipe(gulpif(envDev, sourcemaps.write()))
        .pipe(uglify())
        .pipe(gulp.dest(config.js.dest))
        .pipe(browserSync.reload({stream:true}));
});

gulp.task('build', ['sass', 'js']);

gulp.task('watch', ['browserSync'], function() {
    gulp.watch(config.sass.watchsrc, ['sass']);
    gulp.watch(config.js.src, ['js']);
});

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


text:
<?php

namespace UOL\PagSeguro\Model;

use UOL\PagSeguro\Helper\Data;
use UOL\PagSeguro\Helper\Library;
use Magento\Sales\Model\ResourceModel\Grid;

/**
 * Class NotificationMethod
 * @package UOL\PagSeguro\Model
 */
class NotificationMethod
{

    /**
     * @var \UOL\PagSeguro\Helper\Library
     */
    private $_library;
    /**
     * @var \UOL\PagSeguro\Helper\Data
     */
    private $_helperData;
    /**
     * @var \Magento\Sales\Api\OrderRepositoryInterface
     */
    private $_order;
    /**
     * @var Magento\Sales\Model\ResourceModel\Grid;
     */
    protected $_grid;

    /**
     * Notification constructor.
     * @param \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfigInterface
     * @param \Magento\Sales\Api\OrderRepositoryInterface $order
     */
    public function __construct(
        \Magento\Framework\App\Config\ScopeConfigInterface $scopeConfigInterface,
        \Magento\Sales\Api\OrderRepositoryInterface $order,
        \Magento\Sales\Api\Data\OrderStatusHistoryInterface $history,
        \Magento\Framework\Module\ModuleList $moduleList,
        \Magento\Framework\Model\ResourceModel\Db\Context $context
    ) {
        //dependency injection
        $this->_order = $order;
        $this->_history = $history;
        // create required objects
        $this->_library = new Library(
            $scopeConfigInterface,
            $moduleList
        );
        $this->_helperData = new Data();
        $this->_grid = new Grid($context, 'pagseguro_orders', 'sales_order_grid', 'order_id');
    }

    /**
     * Initialize a notification
     */
    public function init()
    {
        $this->updateOrderStatus();
    }

    /**
     * Update status in Magento2 Order
     *
     * @return bool
     */
    private function updateOrderStatus()
    {
        $this->_library->setEnvironment();
        $this->_library->setCharset();
        $this->_library->setLog();
        $transaction = $this->getTransaction();
        $order = $this->_order->get(
            $this->_helperData->getReferenceDecryptOrderID(
                $transaction->getReference()
            )
        );

        $status = $this->_helperData->getStatusFromKey(
            $transaction->getStatus()
        );

        if (!$this->compareStatus($status, $order->getStatus())) {
            $history = array (
                'status' => $this->_history->setStatus($status),
                'comment' => $this->_history->setComment('PagSeguro Notification')
            );
            $transactionCode = $transaction->getCode();
            $orderId = $order->getId();

            $order->setStatus($status);
            $order->setStatusHistories($history);
            $order->save();

            $this->updateSalesOrderGridTransactionCode($orderId, $transactionCode);
            $this->updatePagSeguroOrdersTransactionCode($orderId, $transactionCode);
        }
        return true;
    }

    /**
     * Get payload information from Post
     * @param $post
     * @return array
     */
    private function payload($post)
    {
        return array(
            'type' => filter_var($post['notificationType'], FILTER_SANITIZE_STRING),
            'code' => filter_var($post['notificationCode'], FILTER_SANITIZE_STRING)
        );
    }

    /**
     * Get transaction from PagSeguro WS.
     * @param $code
     * @return \PagSeguroTransaction
     * @throws \Exception
     * @throws \PagSeguroServiceException
     */
    private function getTransaction()
    {
        return \PagSeguro\Services\Transactions\Notification::check(
            $this->_library->getPagSeguroCredentials()
        );
    }

    /**
     * Compare statuses
     * @param $pagseguro
     * @param $magento
     * @return bool
     */
    private function compareStatus($pagseguro, $magento)
    {
        if ($pagseguro=== $magento) {
            return true;
        }
        return false;
    }

    /**
     * Update the sales_order_grid table transaction code
     * @param int $orderId
     * @param string $transactionCode
     */
    private function updateSalesOrderGridTransactionCode($orderId, $transactionCode)
    {
        $this->_grid->getConnection()->query(
            "UPDATE sales_order_grid
            SET transaction_code='$transactionCode'
            WHERE entity_id=$orderId"
        );
    }

    /**
     * Update the pagseguro_orders table transaction code
     * @param int $orderId
     * @param string $transactionCode
     */
    private function updatePagSeguroOrdersTransactionCode($orderId, $transactionCode)
    {
        $this->_grid->getConnection()->query(
            "UPDATE pagseguro_orders
            SET transaction_code='$transactionCode'
            WHERE order_id=$orderId"
        );
    }
}


text:
package org.scalatest.examples.fixture.freespec.sharing

import java.util.concurrent.ConcurrentHashMap
import org.scalatest._
import DbServer._
import java.util.UUID.randomUUID

object DbServer { // Simulating a database server
  type Db = StringBuffer
  private val databases = new ConcurrentHashMap[String, Db]
  def createDb(name: String): Db = {
    val db = new StringBuffer
    databases.put(name, db)
    db
  }
  def removeDb(name: String) {
    databases.remove(name)
  }
}

trait DbFixture { this: fixture.TestSuite =>

  type FixtureParam = Db

  // Allow clients to populate the database after
  // it is created
  def populateDb(db: Db) {}

  def withFixture(test: OneArgTest): Outcome = {
    val dbName = randomUUID.toString
    val db = createDb(dbName) // create the fixture
    try {
      populateDb(db) // setup the fixture
      withFixture(test.toNoArgTest(db)) // "loan" the fixture to the test
    }
    finally removeDb(dbName) // clean up the fixture
  }
}

class ExampleSpec extends fixture.FreeSpec with DbFixture {

  override def populateDb(db: Db) { // setup the fixture
    db.append("ScalaTest is ")
  }

  "Testing" - {
    "should be easy" in { db =>
      db.append("easy!")
      assert(db.toString === "ScalaTest is easy!")
    }

    "should be fun" in { db =>
      db.append("fun!")
      assert(db.toString === "ScalaTest is fun!")
    }
  }

  // This test doesn't need a Db
  "Test code" - {
    "should be clear" in { () =>
      val buf = new StringBuffer
      buf.append("ScalaTest code is ")
      buf.append("clear!")
      assert(buf.toString === "ScalaTest code is clear!")
    }
  }
}


text:
package com.cezarykluczynski.stapi.etl.company.creation.processor;

import com.cezarykluczynski.stapi.etl.page.common.processor.PageHeaderProcessor;
import com.cezarykluczynski.stapi.model.company.entity.Company;
import com.cezarykluczynski.stapi.sources.mediawiki.dto.PageHeader;
import com.google.common.collect.Lists;
import org.springframework.batch.item.support.CompositeItemProcessor;
import org.springframework.stereotype.Service;

@Service
public class CompanyProcessor extends CompositeItemProcessor<PageHeader, Company> {

	public CompanyProcessor(PageHeaderProcessor pageHeaderProcessor, CompanyPageProcessor companyPageProcessor) {
		setDelegates(Lists.newArrayList(pageHeaderProcessor, companyPageProcessor));
	}

}


text:
require 'billing'
require 'billing/rails/controller_helpers'
require 'billing/rails/transaction_tracking'
require 'billing/rails/engine'

module Billing
  module Rails

  end
end


text: - [Debug tools de Chrome avec Node.JS grâce à un wrapper Electron](https://github.com/Jam3/devtool)


text:
using System;
using System.Net.Http;

namespace EmsApi.Client.V2
{
    /// <summary>
    /// Encapsulates the configuration options for the internal HttpClient which the EMS API SDK
    /// utilizes.
    /// </summary>
    /// <remarks>
    /// As we are currently maintaining .NET Standard 2.0 compatibility we can't utilize
    /// IHttpClientFactory and other bits
    /// </remarks>
    public class EmsApiServiceHttpClientConfiguration
    {
        /// <summary>
        /// Whether or not to retry transient failures.
        /// </summary>
        /// <remarks>
        /// This utilizes the Polly policy and HTTP extensions for detecting transient failures.
        /// This will retry and 408 (request timeout), 5XX (server error), or network failures (HttpRequestException).
        /// Both the token acquisition and the normal EMS API calls will be retried.
        ///
        /// This defaults to true as we believe that is the more common/desired use case.
        /// </remarks>
        public bool RetryTransientFailures { get; set; } = true;

        /// <summary>
        /// The default timeout for HTTP requests.
        /// </summary>
        /// <remarks>
        /// The HttpClient default of 100 seconds is not long enough for some of our longer EMS API calls. For
        /// instance a gnarly database query can take longer than that to return on query creation or first result
        /// extraction time, especially if the SQL server is already busy.
        /// The value we opted for here is the value used for timeouts at the application gateway level and
        /// therefore seems like a reasonable default to use.
        /// </remarks>
        public TimeSpan Timeout { get; set; } = TimeSpan.FromMinutes( 10 );

        /// <summary>
        /// A delegating handler added to the front of the HTTP message stack.
        /// </summary>
        /// <remarks>
        /// This will be the first handler called in an outgoing HTTP send.
        /// This can be useful for tracing or testing purposes.
        /// </remarks>
        public DelegatingHandler FirstHandler { get; set; }

        /// <summary>
        /// A delegating handler added to the back of the HTTP message stack.
        /// </summary>
        /// <remarks>
        /// This will be the last handler called in an outgoing HTTP send.
        /// This can be useful for tracing or testing purposes.
        /// </remarks>
        public DelegatingHandler LastHandler { get; set; }
    }
}


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

namespace Pickaxe.Sdk
{
    public class ReplaceExpression : AstNode
    {
        public string Value
        {
            get
            {
                return Children.Where(x => x.GetType() == typeof(StringLiteral)).Cast<StringLiteral>().Single().Value;
            }
        }

        public override void Accept(IAstVisitor visitor)
        {
            throw new NotImplementedException();
        }
    }
}


text:
var supertest = require('supertest');
var assert = require('assert');

var createServer = require('./fixtures/create-server');

module.exports = function () {
	'use strict';

	it('Simple request log', function (callback) {
		var saveToDatabase = function (request) {
			console.log(request);

			// it('Request log exists', function () {
				assert.equal(typeof request, 'object');
			// });

			// it('Request log contains id', function () {
				assert.equal(request._id.constructor.name, 'ObjectID');
			// });

			callback();
		};

		var port = 8000;

		createServer(port, saveToDatabase);

		supertest('http://127.0.0.1:' + port)
		.get('/api/test?test=lol#oki')
		.expect(200)
		.end(function (e, res) {});
	});

};


text:
package uk.co.bluegecko.core.test.source;

import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import org.junit.Before;
import org.junit.Test;

public class NumericSequenceSourceTest
{

	private Source< Integer > source;

	@Before
	public final void setUp()
	{
		source = new NumericSequenceSource( 0 );
	}

	@Test
	public void testSequence()
	{
		assertThat( source.next(), is( 0 ) );
		assertThat( source.next(), is( 1 ) );
		assertThat( source.next(), is( 2 ) );
		assertThat( source.next(), is( 3 ) );
		assertThat( source.next(), is( 4 ) );
	}

}


text:
from django.contrib.auth.models import Group
from django.db import models
from django.utils.translation import ugettext_lazy as _
from satchmo.product.models import Product, Price
from satchmo.product import signals
from threaded_multihost import threadlocals
import datetime
import logging

try:
    from decimal import Decimal
except:
    from django.utils._decimal import Decimal

log = logging.getLogger('tieredpricing.models')

class PricingTierManager(models.Manager):

    def by_user(self, user):
        """Get the pricing tiers for a user"""
        key = 'TIER_%i' % user.id
        current = threadlocals.get_thread_variable(key)

        if current is None:
            groups = user.groups.all()
            if groups:
                q = self.all()
                for group in groups:
                    q = q.filter(group=group)
                if q.count() > 0:
                    current = list(q)

            if current is None:
                current = "no"

            threadlocals.set_thread_variable(key, current)

        if current == "no":
            raise PricingTier.DoesNotExist

        return current

class PricingTier(models.Model):
    """A specific pricing tier, such as "trade customers"
    """
    group = models.OneToOneField(Group, help_text=_('The user group that will receive the discount'))
    title = models.CharField(_('Title'), max_length=50)
    discount_percent = models.DecimalField(_("Discount Percent"), null=True, blank=True,
        max_digits=5, decimal_places=2,
        help_text=_("This is the discount that will be applied to every product if no explicit Tiered Price exists for that product.  Leave as 0 if you don't want any automatic discount in that case."))

    objects = PricingTierManager()

    def __unicode__(self):
        return self.title

class TieredPriceManager(models.Manager):

    def by_product_qty(self, tier, product, qty=1):
        """Get the tiered price for the specified product and quantity."""

        qty_discounts = product.tieredprices.exclude(expires__isnull=False, expires__lt=datetime.date.today()).filter(quantity__lte=qty, pricingtier=tier)

        if qty_discounts.count() > 0:
            # Get the price with the quantity closest to the one specified without going over
            return qty_discounts.order_by('-quantity')[0]
        raise TieredPrice.DoesNotExist

class TieredPrice(models.Model):
    """
    A Price which applies only to special tiers.
    """
    pricingtier = models.ForeignKey(PricingTier, related_name="tieredprices")
    product = models.ForeignKey(Product, related_name="tieredprices")
    price = models.DecimalField(_("Price"), max_digits=14, decimal_places=6, )
    quantity = models.IntegerField(_("Discount Quantity"), default=1, help_text=_("Use this price only for this quantity or higher"))
    expires = models.DateField(_("Expires"), null=True, blank=True)

    objects = TieredPriceManager()

    def _dynamic_price(self):
        """Get the current price as modified by all listeners."""
        signals.satchmo_price_query.send(self, price=self)
        return self.price

    dynamic_price = property(fget=_dynamic_price)

    def save(self, force_insert=False, force_update=False):
        prices = TieredPrice.objects.filter(product=self.product, quantity=self.quantity)
        if self.expires:
            prices = prices.filter(expires=self.expires)
        else:
            prices = prices.filter(expires__isnull=True)
        if self.id:
            prices = prices.exclude(id=self.id)
        if prices.count():
            return #Duplicate Price

        super(TieredPrice, self).save(force_insert=force_insert, force_update=force_update)

    class Meta:
        ordering = ['pricingtier', 'expires', '-quantity']
        verbose_name = _("Tiered Price")
        verbose_name_plural = _("Tiered Prices")
        unique_together = (("pricingtier", "product", "quantity", "expires"),)

def tiered_price_listener(price, **kwargs):
    """Listens for satchmo_price_query signals, and returns a tiered price instead of the
    default price.

    Requires threaded_multihost.ThreadLocalMiddleware to be installed so
    that it can determine the current user."""

    if kwargs.has_key('discountable'):
        discountable = kwargs['discountable']
    else:
        discountable = price.product.is_discountable

    if discountable:
        user = threadlocals.get_current_user()
        if user and not user.is_anonymous():
            try:
                tiers = PricingTier.objects.by_user(user)
                best = None
                besttier = None
                for tier in tiers:
                    product = price.product
                    candidate = None
                    try:
                        tp = TieredPrice.objects.by_product_qty(tier, product, price.quantity)
                        log.debug("Found a Tiered Price for %s qty %s = %s", product.slug, price.quantity, tp.price)
                        candidate = tp.price
                    except TieredPrice.DoesNotExist:
                        pcnt = tier.discount_percent
                        if pcnt is not None and pcnt != 0:
                            candidate = price.price * (100-pcnt)/100

                    if best is None or (candidate and candidate < best):
                        best = candidate
                        besttier = tier

                        log.debug('best = %s', best)

                if best is not None:
                    delta = price.price - best
                    price.price = best
                    if not hasattr(price, 'discounts'):
                        price.discounts = []
                    price.discounts.append((_('Tiered Pricing for %(tier)s' % { 'tier': besttier.group.name}), delta))

            except PricingTier.DoesNotExist:
                pass

signals.satchmo_price_query.connect(tiered_price_listener)


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.resources.fluent.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** Result of the request to calculate template hash. It contains a string of minified template and its hash. */
@Fluent
public final class TemplateHashResultInner {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(TemplateHashResultInner.class);

    /*
     * The minified template string.
     */
    @JsonProperty(value = "minifiedTemplate")
    private String minifiedTemplate;

    /*
     * The template hash.
     */
    @JsonProperty(value = "templateHash")
    private String templateHash;

    /**
     * Get the minifiedTemplate property: The minified template string.
     *
     * @return the minifiedTemplate value.
     */
    public String minifiedTemplate() {
        return this.minifiedTemplate;
    }

    /**
     * Set the minifiedTemplate property: The minified template string.
     *
     * @param minifiedTemplate the minifiedTemplate value to set.
     * @return the TemplateHashResultInner object itself.
     */
    public TemplateHashResultInner withMinifiedTemplate(String minifiedTemplate) {
        this.minifiedTemplate = minifiedTemplate;
        return this;
    }

    /**
     * Get the templateHash property: The template hash.
     *
     * @return the templateHash value.
     */
    public String templateHash() {
        return this.templateHash;
    }

    /**
     * Set the templateHash property: The template hash.
     *
     * @param templateHash the templateHash value to set.
     * @return the TemplateHashResultInner object itself.
     */
    public TemplateHashResultInner withTemplateHash(String templateHash) {
        this.templateHash = templateHash;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
    }
}


text:
package net.ssm.system.web.pojo;

import java.util.Date;
/*
 * *
 */
public class SysUser {
    public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	public String getLogin_name() {
		return login_name;
	}
	public void setLogin_name(String login_name) {
		this.login_name = login_name;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getMobile() {
		return mobile;
	}
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}
	public String getLogin_ip() {
		return login_ip;
	}
	public void setLogin_ip(String login_ip) {
		this.login_ip = login_ip;
	}
	public Date getLongin_time() {
		return longin_time;
	}
	public void setLongin_time(Date longin_time) {
		this.longin_time = longin_time;
	}
	public int getLongin_times() {
		return longin_times;
	}
	public void setLongin_times(int longin_times) {
		this.longin_times = longin_times;
	}
	public String getAvatars() {
		return avatars;
	}
	public void setAvatars(String avatars) {
		this.avatars = avatars;
	}
	public String getRemarks() {
		return remarks;
	}
	public void setRemarks(String remarks) {
		this.remarks = remarks;
	}
	public Date getCreate_at() {
		return create_at;
	}
	public void setCreate_at(Date create_at) {
		this.create_at = create_at;
	}
	public Date getUpdate_at() {
		return update_at;
	}
	public void setUpdate_at(Date update_at) {
		this.update_at = update_at;
	}
	public String getStatus() {
		return status;
	}

	public void setStatus(String status) {
		this.status = status;
	}
	private Long  id;
    private String login_name;
    private String password;
    private String email;
    private String name;
    private String mobile;
    private String status;
	private String login_ip;
    private Date longin_time;
    private int longin_times;
    private String avatars;
    private String remarks;
    private Date create_at;
    private Date update_at;
}


text:
'''OpenGL extension SGIX.clipmap

This module customises the behaviour of the
OpenGL.raw.GL.SGIX.clipmap to provide a more
Python-friendly API

Overview (from the spec)

	Mipmaps provide a general but expensive solution when the texture image
	is very large.  This extension defines clipmaps, which occupy a small
	subset of the memory required by equivalent mipmaps, but provide much
	of the mipmap rendering capabilities.  Clipmaps are especially useful
	for rendering terrain.

The official definition of this extension is available here:
http://www.opengl.org/registry/specs/SGIX/clipmap.txt
'''
from OpenGL import platform, constants, constant, arrays
from OpenGL import extensions, wrapper
from OpenGL.GL import glget
import ctypes
from OpenGL.raw.GL.SGIX.clipmap import *
### END AUTOGENERATED SECTION


text:
import ObjectID from 'bson-objectid';
import omit from 'lodash/fp/omit';
import {CacheModes, AtomicityModes, ShortCache} from '../types';
import {Menu} from 'app/types';

export default class Caches {
    static $inject = ['$http'];

    cacheModes: Menu<CacheModes> = [
        {value: 'LOCAL', label: 'LOCAL'},
        {value: 'REPLICATED', label: 'REPLICATED'},
        {value: 'PARTITIONED', label: 'PARTITIONED'}
    ];

    atomicityModes: Menu<AtomicityModes> = [
        {value: 'ATOMIC', label: 'ATOMIC'},
        {value: 'TRANSACTIONAL', label: 'TRANSACTIONAL'},
        {value: 'TRANSACTIONAL_SNAPSHOT', label: 'TRANSACTIONAL_SNAPSHOT'}
    ];

    constructor(private $http: ng.IHttpService) {}

    saveCache(cache) {
        return this.$http.post('/api/v1/configuration/caches/save', cache);
    }

    getCache(cacheID: string) {
        return this.$http.get(`/api/v1/configuration/caches/${cacheID}`);
    }

    removeCache(cacheID: string) {
        return this.$http.post(`/api/v1/configuration/caches/remove/${cacheID}`);
    }

    getBlankCache() {
        return {
            _id: ObjectID.generate(),
            evictionPolicy: {},
            cacheMode: 'PARTITIONED',
            atomicityMode: 'ATOMIC',
            readFromBackup: true,
            copyOnRead: true,
            cacheStoreFactory: {
                CacheJdbcBlobStoreFactory: {
                    connectVia: 'DataSource'
                },
                CacheHibernateBlobStoreFactory: {
                    hibernateProperties: []
                }
            },
            writeBehindCoalescing: true,
            nearConfiguration: {},
            sqlFunctionClasses: [],
            domains: []
        };
    }

    toShortCache(cache: any): ShortCache {
        return {
            _id: cache._id,
            name: cache.name,
            backups: cache.backups,
            cacheMode: cache.cacheMode,
            atomicityMode: cache.atomicityMode
        };
    }

    normalize = omit(['__v', 'space', 'clusters']);

    nodeFilterKinds = [
        {value: 'IGFS', label: 'IGFS nodes'},
        {value: 'Custom', label: 'Custom'},
        {value: null, label: 'Not set'}
    ];

    memoryModes = [
        {value: 'ONHEAP_TIERED', label: 'ONHEAP_TIERED'},
        {value: 'OFFHEAP_TIERED', label: 'OFFHEAP_TIERED'},
        {value: 'OFFHEAP_VALUES', label: 'OFFHEAP_VALUES'}
    ];

    diskPageCompression = [
        {value: 'SKIP_GARBAGE', label: 'SKIP_GARBAGE'},
        {value: 'ZSTD', label: 'ZSTD'},
        {value: 'LZ4', label: 'LZ4'},
        {value: 'SNAPPY', label: 'SNAPPY'},
        {value: null, label: 'Disabled'}
    ];

    offHeapMode = {
        _val(cache) {
            return (cache.offHeapMode === null || cache.offHeapMode === void 0) ? -1 : cache.offHeapMode;
        },
        onChange: (cache) => {
            const offHeapMode = this.offHeapMode._val(cache);
            switch (offHeapMode) {
                case 1:
                    return cache.offHeapMaxMemory = cache.offHeapMaxMemory > 0 ? cache.offHeapMaxMemory : null;
                case 0:
                case -1:
                    return cache.offHeapMaxMemory = cache.offHeapMode;
                default: break;
            }
        },
        required: (cache) => cache.memoryMode === 'OFFHEAP_TIERED',
        offheapDisabled: (cache) => !(cache.memoryMode === 'OFFHEAP_TIERED' && this.offHeapMode._val(cache) === -1),
        default: 'Disabled'
    };

    offHeapModes = [
        {value: -1, label: 'Disabled'},
        {value: 1, label: 'Limited'},
        {value: 0, label: 'Unlimited'}
    ];

    offHeapMaxMemory = {
        min: 1
    };

    memoryMode = {
        default: 'ONHEAP_TIERED',
        offheapAndDomains: (cache) => {
            return !(cache.memoryMode === 'OFFHEAP_VALUES' && cache.domains.length);
        }
    };

    evictionPolicy = {
        required: (cache) => {
            return (cache.memoryMode || this.memoryMode.default) === 'ONHEAP_TIERED'
                && cache.offHeapMaxMemory > 0
                && !cache.evictionPolicy.kind;
        },
        values: [
            {value: 'LRU', label: 'LRU'},
            {value: 'FIFO', label: 'FIFO'},
            {value: 'SORTED', label: 'Sorted'},
            {value: null, label: 'Not set'}
        ],
        kind: {
            default: 'Not set'
        },
        maxMemorySize: {
            min: (evictionPolicy) => {
                const policy = evictionPolicy[evictionPolicy.kind];

                if (!policy)
                    return true;

                const maxSize = policy.maxSize === null || policy.maxSize === void 0
                    ? this.evictionPolicy.maxSize.default
                    : policy.maxSize;

                return maxSize ? 0 : 1;
            },
            default: 0
        },
        maxSize: {
            min: (evictionPolicy) => {
                const policy = evictionPolicy[evictionPolicy.kind];

                if (!policy)
                    return true;

                const maxMemorySize = policy.maxMemorySize === null || policy.maxMemorySize === void 0
                    ? this.evictionPolicy.maxMemorySize.default
                    : policy.maxMemorySize;

                return maxMemorySize ? 0 : 1;
            },
            default: 100000
        }
    };

    cacheStoreFactory = {
        kind: {
            default: 'Not set'
        },
        values: [
            {value: 'CacheJdbcPojoStoreFactory', label: 'JDBC POJO store factory'},
            {value: 'CacheJdbcBlobStoreFactory', label: 'JDBC BLOB store factory'},
            {value: 'CacheHibernateBlobStoreFactory', label: 'Hibernate BLOB store factory'},
            {value: null, label: 'Not set'}
        ],
        storeDisabledValueOff: (cache, value) => {
            return cache && cache.cacheStoreFactory.kind ? true : !value;
        },
        storeEnabledReadOrWriteOn: (cache) => {
            return cache && cache.cacheStoreFactory.kind ? (cache.readThrough || cache.writeThrough) : true;
        }
    };

    writeBehindFlush = {
        min: (cache) => {
            return cache.writeBehindFlushSize === 0 && cache.writeBehindFlushFrequency === 0
                ? 1
                : 0;
        }
    };

    getCacheBackupsCount(cache: ShortCache) {
        return this.shouldShowCacheBackupsCount(cache)
            ? (cache.backups || 0)
            : void 0;
    }

    shouldShowCacheBackupsCount(cache: ShortCache) {
        return cache && cache.cacheMode === 'PARTITIONED';
    }
}


text:
package org.talend.sdk.component.starter.server.test;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.enterprise.inject.spi.CDI;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;

import org.apache.meecrowave.Meecrowave;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.talend.sdk.component.junit.base.junit5.JUnit5InjectionSupport;

public class Client {

    @Target(TYPE)
    @Retention(RUNTIME)
    @ExtendWith(ClientRuleExtension.class)
    public @interface Active {
    }

    public static class ClientRuleExtension implements BeforeAllCallback, AfterAllCallback, JUnit5InjectionSupport {

        private static final ExtensionContext.Namespace NAMESPACE =
                ExtensionContext.Namespace.create(ClientRuleExtension.class.getName());

        @Override
        public void afterAll(final ExtensionContext context) {
            javax.ws.rs.client.Client.class
                    .cast(context.getStore(NAMESPACE).get(javax.ws.rs.client.Client.class.getName()))
                    .close();
        }

        @Override
        public void beforeAll(final ExtensionContext context) {
            final javax.ws.rs.client.Client client = ClientBuilder.newClient();
            context.getStore(NAMESPACE).put(javax.ws.rs.client.Client.class.getName(), client);
            context.getStore(NAMESPACE).put(WebTarget.class.getName(), target(client));
        }

        private WebTarget target(final javax.ws.rs.client.Client client) {
            final Meecrowave.Builder config = CDI.current().select(Meecrowave.Builder.class).get();
            return client.target("http://localhost:" + config.getHttpPort() + "/api");
        }

        @Override
        public boolean supports(final Class<?> type) {
            return WebTarget.class == type || javax.ws.rs.client.Client.class == type;
        }

        @Override
        public Object findInstance(final ExtensionContext extensionContext, final Class<?> type) {
            return extensionContext.getStore(NAMESPACE).get(type.getName());
        }

        @Override
        public Class<? extends Annotation> injectionMarker() {
            return Override.class; // ignored actually
        }
    }
}


text:
var async = require('async');
var exec = require('child_process').exec;
var green = '\u001b[42m \u001b[0m';
var red = '\u001b[41m \u001b[0m';

module.exports = {
  name: 'stash',
  description: 'Stashes any local changes across all repos',
  usage: '[-r <repoPattern>]',
};

function stash(bosco, args, progressbar, bar, orgPath, next) {
  if (!progressbar) bosco.log('Stashing ' + orgPath.blue);
  if (!bosco.exists([orgPath, '.git'].join('/'))) {
    bosco.warn('Doesn\'t seem to be a git repo: ' + orgPath.blue);
    return next();
  }

  var cmdString = 'git stash ' + args.join(' ');

  var ignoreMissingStashCommands = ['pop', 'apply'];
  var ignoreMissingStash = (ignoreMissingStashCommands.indexOf(args[0]) !== -1);
  exec(cmdString, {
    cwd: orgPath,
  }, function(error, stdout, stderr) {
    if (progressbar) bar.tick();
    var err = error;

    if (err && ignoreMissingStash && err.code === 1) {
      err = null;
    }
    if (err) {
      if (progressbar) bosco.console.log('');
      bosco.error(orgPath.blue + ' >> ' + stderr);
    } else {
      if (!progressbar && stdout) bosco.log(orgPath.blue + ' >> ' + stdout);
    }
    next(err);
  });
}

function cmd(bosco, args) {
  var repoPattern = bosco.options.repo;
  var repoRegex = new RegExp(repoPattern);

  var repos = bosco.getRepos();
  if (!repos) return bosco.error('You are repo-less :( You need to initialise bosco first, try \'bosco clone\'.');

  bosco.log('Running git stash across all repos ...');

  function stashRepos(cb) {
    var progressbar = bosco.config.get('progress') === 'bar';
    var total = repos.length;

    var bar = progressbar ? new bosco.Progress('Doing git stash [:bar] :percent :etas', {
      complete: green,
      incomplete: red,
      width: 50,
      total: total,
    }) : null;

    async.mapSeries(repos, function repoStash(repo, repoCb) {
      if (!repo.match(repoRegex)) return repoCb();

      var repoPath = bosco.getRepoPath(repo);
      stash(bosco, args, progressbar, bar, repoPath, repoCb);
    }, function() {
      cb();
    });
  }

  stashRepos(function() {
    bosco.log('Complete');
  });
}

module.exports.cmd = cmd;


text:
include(AddFileDependencies)

  macro(polyhedron_demo_plugin plugin_name plugin_implementation_base_name)
    list_split(option ARGN_TAIL ${ARGN} )
    if(NOT ${option} STREQUAL "EXCLUDE_FROM_ALL")
      if(NOT ${option} STREQUAL "NO_MOC")
        set(other_sources ${ARGN})
        set(option "")
      else()
        set(other_sources ${ARGN_TAIL})
      endif()
    else()
      set(other_sources ${ARGN_TAIL})
    endif()
    if("${option}" STREQUAL "NO_MOC")
      set(option "")
      set(moc_file_name "")
    else()
      set(moc_file_name ${plugin_implementation_base_name}.moc )
      qt4_generate_moc( ${plugin_implementation_base_name}.cpp "${CMAKE_CURRENT_BINARY_DIR}/${moc_file_name}" )
      add_file_dependencies( ${moc_file_name} "${CMAKE_CURRENT_SOURCE_DIR}/${plugin_implementation_base_name}.cpp" )
    endif()

    add_library(${plugin_name} MODULE ${option} ${moc_file_name} ${plugin_implementation_base_name}.cpp ${other_sources})
    set_property(TARGET ${plugin_name}
      PROPERTY LIBRARY_OUTPUT_DIRECTORY
      "${CGAL_POLYHEDRON_DEMO_PLUGINS_DIR}")

    add_to_cached_list( CGAL_EXECUTABLE_TARGETS ${plugin_name} )
    # Link with Qt
    target_link_libraries( ${plugin_name} ${QT_LIBRARIES} )
    # Link with the demo_framework
    if(TARGET demo_framework)
      target_link_libraries( ${plugin_name} demo_framework)
    else()
      target_link_libraries( ${plugin_name} Polyhedron_demo_framework)
    endif()
    # Link with CGAL
    target_link_libraries( ${plugin_name} ${CGAL_LIBRARIES} ${CGAL_3RD_PARTY_LIBRARIES} )
    add_dependencies( ${plugin_name} Polyhedron_3 )
  endmacro(polyhedron_demo_plugin)


text:
'use strict';

describe('dep-copy', function () {
    var DepCopy = require('../dep-copy.js'),
        fs = require('fs'),
        path = require('path'),
        through = require('through2');

    var dependencyIndexFile = 'dependency-index.json';
    var packageName = 'testPackage';
    var deployDir = './tests/testDeployFolder';
    var basePath = 'tests/testInputs';
    var installer;

    beforeEach(function () {
        installer = new DepCopy(basePath, packageName, deployDir);
    });

    var writeToIndexFile = function (indexFileObject) {
        var filePath = installer.getIndexFilePath(dependencyIndexFile);
        var content = JSON.stringify(indexFileObject, null, 4);
        fs.writeFileSync(filePath, content);
    }

    describe('basic functionality', function () {

        it('getIndexFilePath should concatenate with basePath', function () {
            //Arrange

            //Act
            var result = installer.getIndexFilePath(dependencyIndexFile);

            //Assert
            expect(result).toEqual('tests\\testDeployFolder\\' + dependencyIndexFile);
        });

        it('registerDependency to undefined object', function () {
            //Arrange
            var indexObject;

            //Act
            var result = installer.registerDependency(indexObject, "somedll.dll");

            //Assert
            var expectedResult = {
                "somedll.dll": [packageName]
            };

            expect(result).toEqual(expectedResult);

        });

        it('registerDependency to empty object', function () {
            //Arrange
            var indexObject = {};
            //Act
            var result = installer.registerDependency(indexObject, "somedll.dll");

            //Assert
            var expectedResult = {
                "somedll.dll" : [packageName]
            };

            expect(result).toEqual(expectedResult);
        });

        it('registerDependency to object already containing some dependencies for this package', function () {
            //Arrange
            var indexObject = {
                "previouslyAddedDll.dll" : [packageName]
            };

            //Act
            var result = installer.registerDependency(indexObject, "somedll.dll");

            //Assert
            var expectedResult = {
                "previouslyAddedDll.dll": [packageName],
                "somedll.dll": [packageName]
            };
            expect(result).toEqual(expectedResult);
        });

        it('registerDependency should add another package to dependency from some other package', function () {
            //Arrange
            var indexObject = {
                "previouslyAddedDll.dll": ["PreviouslyAddedPackage"]
            };

            //Act
            var result = installer.registerDependency(indexObject, "previouslyAddedDll.dll");

            //Assert
            var expectedResult = {
                "previouslyAddedDll.dll": ["PreviouslyAddedPackage", packageName]
            };
            expect(result).toEqual(expectedResult);
        });

        it('registerDependency should not add duplicate', function () {
            //Arrange
            var indexObject = {
                "duplicatedll.dll" : [packageName]
            };

            //Act
            var result = installer.registerDependency(indexObject, "duplicatedll.dll");

            //Assert
            var expectedResult = {
                "duplicatedll.dll" : [packageName]
            };
            expect(result).toEqual(expectedResult);
        });

        it('unregisterDependency - only this package is dependent - should remove completely', function () {
            //Arrange

            var indexObject = {
                "bin\\somedll.dll": [packageName]
            }

            //Act
            installer.unregisterDependency(indexObject, "bin\\somedll.dll");

            //Assert
            expect(indexObject).toEqual({});
            expect(indexObject["bin\\somedll.dll"]).toBeUndefined();

        });

        it('unregisterDependency - more packages dependent - should remove package dependency', function () {
            //Arrange
            var indexObject = {
                "bin\\somedll.dll": [packageName, "otherPackage"]
            }

            //Act
            installer.unregisterDependency(indexObject, "bin\\somedll.dll");

            //Assert
            expect(indexObject).toEqual({ "bin\\somedll.dll": ["otherPackage"] });
            expect(indexObject["bin\\somedll.dll"].length).toEqual(1);
        });
    });

    describe('file misc functions', function () {
        beforeEach(function () {
            writeToIndexFile({});
        });

        var truncateFile = function () {
            writeToIndexFile({});
        };

        afterEach(function () {
            truncateFile();
        });

        it('indexFileExists should return true', function () {
            //Arrange

            //Act
            var result = installer.indexFileExists(dependencyIndexFile);

            //Assert
            expect(result).toEqual(true);
        });

        it('indexFileExists should return false if no such file exists', function () {
            //Arrange

            //Act
            var result = installer.indexFileExists("file.json");

            //Assert
            expect(result).toEqual(false);
        });

        it('getIndexFileContent shoudl return empty object if file is blank', function () {
            //Arrange
            var filePath = installer.getIndexFilePath(dependencyIndexFile);
            fs.writeFileSync(filePath, '');

            //Act
            var result = installer.getIndexFileContent(dependencyIndexFile);

            //Assert
            expect(result).toEqual({});
        });

        it('getIndexFileContent should return content of indexFile', function () {
            //Arrange

            //Act
            var result = installer.getIndexFileContent(dependencyIndexFile);

            //Assert
            expect(result).toEqual({});
        });

        it('getIndexFileContent should return null if no file', function () {
            //Arrange

            //Act
            var result = installer.getIndexFileContent("no-file.json");

            //Assert
            expect(result).toEqual(null);
        });

        it('setIndexFileContent should set new content to an existing file', function (done) {
            //Arrange
            var newContent = {};
            newContent["dependency1.dll"] = [packageName];
            newContent["dependency2.dll"] = [packageName];

            //Act
            installer.setIndexFileContent(dependencyIndexFile, newContent, function () {
                var content = installer.getIndexFileContent(dependencyIndexFile);
                expect(content).toEqual(newContent);
                done();
                truncateFile();
            });

			//Assert
        });

        it('setIndexFileContent should throw if file doesnt exist', function () {
            //Arrange
            var content = {};

            //Act

            expect(function () { installer.setIndexFileContent("new-file.json", content); }).toThrow(new Error("Index file new-file.json does not exist"));

			//Assert

        });
    });

    describe('addPackageDependency end-to-end tests', function () {
        beforeEach(function () {
            writeToIndexFile({});
        });

        afterEach(function () {
            writeToIndexFile({});
        });

        it('addPackageDependency should add dependency to existing file', function (done) {
            //Arrange

            //Act
            installer.addPackageDependency(dependencyIndexFile, "somedll.dll", function () {

                //Assert
                var content = installer.getIndexFileContent(dependencyIndexFile);
                var newContent = {
                    "somedll.dll": [packageName]
                };
                expect(content).toEqual(newContent);
                done();
            });
        });

        it('addPackageDependency should create new file if does not exist', function (done) {
            //Arrange
            var newFileName = "some-file-name.json";

            //Act
            installer.addPackageDependency(newFileName, "somedll.dll", function () {
                //Assert
                var content = installer.getIndexFileContent(newFileName);
                var newContent = {
                    "somedll.dll": [packageName]
                };
                expect(content).toEqual(newContent);
                done();
                cleanup();
            });

            var cleanup = function () {
                //cleanup
                var filePath = installer.getIndexFilePath(newFileName);
                fs.unlinkSync(filePath);
            }
        });

        it('addPackageDependency should add dependency when preserveTree is false', function (done) {
            //Arrange
            installer = new DepCopy(basePath, packageName, deployDir, { preserveTree: false });

            //Act
            installer.addPackageDependency(dependencyIndexFile, "App/Packages/somedll.dll", function () {

                //Assert
                var content = installer.getIndexFileContent(dependencyIndexFile);
                var newContent = {
                    "/somedll.dll": [packageName]
                };
                expect(content).toEqual(newContent);
                done();
            });

		    //Assert

        });
    });

    xdescribe('copyFiles end-to-end tests', function () {

        it('copyFiles should not fail', function () {
            //Arrange
            writeToIndexFile({});

            var stream = through({ objectMode: true });
            var filePath = 'App/Packages/someController.js';

            //Act
            stream.pipe(installer.copyFiles());
            stream.pipe(installer.addToIndexFile());

            stream.write({ relative: filePath });

            //Assert
            //TODO: No asserts yet. Feel free to fork and pull request. Need to figure out how to test presence of file after execution of ^^.
        });

        it('copyFiles - other than original file tree', function () {
            //Arrange
            writeToIndexFile({});

            var stream = through({ objectMode: true });
            var filePath = 'App/Packages/someController.js';
            installer = new DepCopy(basePath, packageName, deployDir, { preserveTree: false });

            //Act
            stream.pipe(installer.copyFiles());
            stream.pipe(installer.addToIndexFile());

            stream.write({ relative: filePath });

		    //Assert
            //TODO: No asserts yet. Feel free to fork and pull request. Need to figure out how to test presence of file after execution of ^^.
        });

        it('should copied according to index-file', function () {
            //Arrange
            installer = new DepCopy(basePath, packageName, deployDir, { preserveTree: false });

            //Act
            installer.readIndexFile()
			   .pipe(installer.removeFromIndexFile())
			   .pipe(installer.removeFile());
		   //Assert
           //TODO: No asserts yet. Just some integration testing.
        });
    });

    xdescribe('removeFromIndexFile end-to-end tests', function () {

        it('removeFromIndexFile should remove dependency from file', function () {
            //Arrange
            var indexFileObject = {
                "somedll.dll": [packageName]
            }
            writeToIndexFile(indexFileObject);

            //Act
            var stream = through({ objectMode: true });
            stream.pipe(installer.removeFromIndexFile());
            stream.pipe(function () {
                return through({ objectMode: true }, function (data, enc, callback) {
                });
            }());
            stream.write("somedll.dll");

            //Assert
            //TODO: No asserts yet. Feel free to fork and pull request. Need to figure out how to test this.
        });

        it('removeFromIndexFile should deregister dependency if more packages are dependent on file', function () {
            //Arrange
            var indexFileObject = {
                "somedll.dll": [packageName, "otherPackage"]
            }
            writeToIndexFile(indexFileObject);

            //Act
            var stream = through({ objectMode: true });
            stream.pipe(installer.removeFromIndexFile());
            stream.pipe(function () {
                return through({ objectMode: true }, function (data, enc, callback) {
                });
            }());
            stream.write("somedll.dll");

            //Assert
            //TODO: No asserts yet. Feel free to fork and pull request. Need to figure out how to test this.
        });

        it('removeFromIndexFile should remove and deregister dependency', function () {
            //Arrange
            var indexFileObject = {
                "somedll1.dll": [packageName, "otherPackage"],
                "somedll2.dll": [packageName]
            }
            writeToIndexFile(indexFileObject);

            //Act

            var stream = through({ objectMode: true });
            stream.pipe(installer.removeFromIndexFile());
            stream.pipe(function () {
                return through({ objectMode: true }, function (data, enc, callback) {
                });
            }());
            stream.write("somedll1.dll");

            //Assert
            //TODO: No asserts yet. Feel free to fork and pull request. Need to figure out how to test this.
        });
    });

});


text:
extract:
	${tooldir}/ecore2bgf EG.ecore grammar.bgf

include ../../Makefile.grammar


text:
{% extends "layout.html" %}
{% block page_title %}
Do you have an address for the land sold to the authority?
{% endblock %}
{% block content %}

BETA

        Land sold to the authority

      <form action="document-link" method="GET">
        <fieldset>
          <legend class="visually-hidden form-label">Do you have an address for the land sold to the authority?</legend>

                  Describe the land sold

                  For example, land on the north side of Smith Street.

                <textarea id="retainedLand" class="form-control form-control-3-4" name="textarea" rows="5"></textarea>

                  What work will the authority do on this land?

                  For example, for the construction of a bypass.

                <textarea id="retainedLand" class="form-control form-control-3-4" name="textarea" rows="5"></textarea>

        </fieldset>

      </form>

        Continue

        Back

{% endblock %}


text:
namespace mediapipe {

// Creates image to tensor (represented as OpenGL texture) converter.
// NOTE: mediapipe::GlCalculatorHelper::UpdateContract invocation must precede
// converter creation.
absl::StatusOr<std::unique_ptr<ImageToTensorConverter>>
CreateImageToGlTextureTensorConverter(CalculatorContext* cc,
                                      bool input_starts_at_bottom,
                                      BorderMode border_mode);

}  // namespace mediapipe

#endif  // MEDIAPIPE_OPENGL_ES_VERSION >= MEDIAPIPE_OPENGL_ES_30

#endif  // MEDIAPIPE_CALCULATORS_TENSOR_IMAGE_TO_TENSOR_CONVERTER_GL_TEXTURE_H_


text:
from django import forms

class TransactionDataFormGet(forms.Form):
    from_date = forms.CharField(label='From', required=True)
    to_date = forms.CharField(label='To', required=True)


text:
<?php
    // $Id: form_test.php 4 2006-04-25 02:08:26Z phpnut $

    require_once(dirname(__FILE__) . '/../form.php');
    require_once(dirname(__FILE__) . '/../encoding.php');

    class TestOfForm extends UnitTestCase {

        function testFormAttributes() {
            $tag = &new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php', 'id' => '33'));
            $form = &new SimpleForm($tag, new SimpleUrl('http://host/a/index.html'));
            $this->assertEqual($form->getMethod(), 'get');
            $this->assertEqual(
                    $form->getAction(),
                    new SimpleUrl('http://host/a/here.php'));
            $this->assertIdentical($form->getId(), '33');
            $this->assertNull($form->getValue(new SimpleByName('a')));
        }

        function testEmptyAction() {
            $tag = &new SimpleFormTag(array('method' => 'GET', 'action' => '', 'id' => '33'));
            $form = &new SimpleForm($tag, new SimpleUrl('http://host/a/index.html'));
            $this->assertEqual(
                    $form->getAction(),
                    new SimpleUrl('http://host/a/index.html'));
        }

        function testMissingAction() {
            $tag = &new SimpleFormTag(array('method' => 'GET', 'id' => '33'));
            $form = &new SimpleForm($tag, new SimpleUrl('http://host/a/index.html'));
            $this->assertEqual(
                    $form->getAction(),
                    new SimpleUrl('http://host/a/index.html'));
        }

        function testRootAction() {
            $tag = &new SimpleFormTag(array('method' => 'GET', 'action' => '/', 'id' => '33'));
            $form = &new SimpleForm($tag, new SimpleUrl('http://host/a/index.html'));
            $this->assertEqual(
                    $form->getAction(),
                    new SimpleUrl('http://host/'));
        }

        function testDefaultFrameTargetOnForm() {
            $tag = &new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php', 'id' => '33'));
            $form = &new SimpleForm($tag, new SimpleUrl('http://host/a/index.html'));
            $form->setDefaultTarget('frame');

            $expected = new SimpleUrl('http://host/a/here.php');
            $expected->setTarget('frame');
            $this->assertEqual($form->getAction(), $expected);
        }

        function testTextWidget() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('htp://host'));
            $form->addWidget(new SimpleTextTag(
                    array('name' => 'me', 'type' => 'text', 'value' => 'Myself')));
            $this->assertIdentical($form->getValue(new SimpleByName('me')), 'Myself');
            $this->assertTrue($form->setField(new SimpleByName('me'), 'Not me'));
            $this->assertFalse($form->setField(new SimpleByName('not_present'), 'Not me'));
            $this->assertIdentical($form->getValue(new SimpleByName('me')), 'Not me');
            $this->assertNull($form->getValue(new SimpleByName('not_present')));
        }

        function testTextWidgetById() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('htp://host'));
            $form->addWidget(new SimpleTextTag(
                    array('name' => 'me', 'type' => 'text', 'value' => 'Myself', 'id' => 50)));
            $this->assertIdentical($form->getValue(new SimpleById(50)), 'Myself');
            $this->assertTrue($form->setField(new SimpleById(50), 'Not me'));
            $this->assertIdentical($form->getValue(new SimpleById(50)), 'Not me');
        }

        function testTextWidgetByLabel() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('htp://host'));
            $widget = &new SimpleTextTag(array('name' => 'me', 'type' => 'text', 'value' => 'a'));
            $form->addWidget($widget);
            $widget->setLabel('thing');
            $this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'a');
            $this->assertTrue($form->setField(new SimpleByLabel('thing'), 'b'));
            $this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'b');
        }

        function testSubmitEmpty() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('htp://host'));
            $this->assertIdentical($form->submit(), new SimpleGetEncoding());
        }

        function testSubmitButton() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('http://host'));
            $form->addWidget(new SimpleSubmitTag(
                    array('type' => 'submit', 'name' => 'go', 'value' => 'Go!', 'id' => '9')));
            $this->assertTrue($form->hasSubmit(new SimpleByName('go')));
            $this->assertEqual($form->getValue(new SimpleByName('go')), 'Go!');
            $this->assertEqual($form->getValue(new SimpleById(9)), 'Go!');
            $this->assertEqual(
                    $form->submitButton(new SimpleByName('go')),
                    new SimpleGetEncoding(array('go' => 'Go!')));
            $this->assertEqual(
                    $form->submitButton(new SimpleByLabel('Go!')),
                    new SimpleGetEncoding(array('go' => 'Go!')));
            $this->assertEqual(
                    $form->submitButton(new SimpleById(9)),
                    new SimpleGetEncoding(array('go' => 'Go!')));
        }

        function testSubmitWithAdditionalParameters() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('http://host'));
            $form->addWidget(new SimpleSubmitTag(
                    array('type' => 'submit', 'name' => 'go', 'value' => 'Go!')));
            $this->assertEqual(
                    $form->submitButton(new SimpleByLabel('Go!'), array('a' => 'A')),
                    new SimpleGetEncoding(array('go' => 'Go!', 'a' => 'A')));
        }

        function testSubmitButtonWithLabelOfSubmit() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('http://host'));
            $form->addWidget(new SimpleSubmitTag(
                    array('type' => 'submit', 'name' => 'test', 'value' => 'Submit')));
            $this->assertEqual(
                    $form->submitButton(new SimpleByName('test')),
                    new SimpleGetEncoding(array('test' => 'Submit')));
            $this->assertEqual(
                    $form->submitButton(new SimpleByLabel('Submit')),
                    new SimpleGetEncoding(array('test' => 'Submit')));
        }

        function testSubmitButtonWithWhitespacePaddedLabelOfSubmit() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('http://host'));
            $form->addWidget(new SimpleSubmitTag(
                    array('type' => 'submit', 'name' => 'test', 'value' => ' Submit ')));
            $this->assertEqual(
                    $form->submitButton(new SimpleByLabel('Submit')),
                    new SimpleGetEncoding(array('test' => ' Submit ')));
        }

        function testImageSubmitButton() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('htp://host'));
            $form->addWidget(new SimpleImageSubmitTag(array(
                    'type' => 'image',
                    'src' => 'source.jpg',
                    'name' => 'go',
                    'alt' => 'Go!',
                    'id' => '9')));
            $this->assertTrue($form->hasImage(new SimpleByLabel('Go!')));
            $this->assertEqual(
                    $form->submitImage(new SimpleByLabel('Go!'), 100, 101),
                    new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101)));
            $this->assertTrue($form->hasImage(new SimpleByName('go')));
            $this->assertEqual(
                    $form->submitImage(new SimpleByName('go'), 100, 101),
                    new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101)));
            $this->assertTrue($form->hasImage(new SimpleById(9)));
            $this->assertEqual(
                    $form->submitImage(new SimpleById(9), 100, 101),
                    new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101)));
        }

        function testImageSubmitButtonWithAdditionalData() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('htp://host'));
            $form->addWidget(new SimpleImageSubmitTag(array(
                    'type' => 'image',
                    'src' => 'source.jpg',
                    'name' => 'go',
                    'alt' => 'Go!')));
            $this->assertEqual(
                    $form->submitImage(new SimpleByLabel('Go!'), 100, 101, array('a' => 'A')),
                    new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101, 'a' => 'A')));
        }

        function testButtonTag() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('http://host'));
            $widget = &new SimpleButtonTag(
                    array('type' => 'submit', 'name' => 'go', 'value' => 'Go', 'id' => '9'));
            $widget->addContent('Go!');
            $form->addWidget($widget);
            $this->assertTrue($form->hasSubmit(new SimpleByName('go')));
            $this->assertTrue($form->hasSubmit(new SimpleByLabel('Go!')));
            $this->assertEqual(
                    $form->submitButton(new SimpleByName('go')),
                    new SimpleGetEncoding(array('go' => 'Go')));
            $this->assertEqual(
                    $form->submitButton(new SimpleByLabel('Go!')),
                    new SimpleGetEncoding(array('go' => 'Go')));
            $this->assertEqual(
                    $form->submitButton(new SimpleById(9)),
                    new SimpleGetEncoding(array('go' => 'Go')));
        }

        function testSingleSelectFieldSubmitted() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('htp://host'));
            $select = &new SimpleSelectionTag(array('name' => 'a'));
            $select->addTag(new SimpleOptionTag(
                    array('value' => 'aaa', 'selected' => '')));
            $form->addWidget($select);
            $this->assertIdentical(
                    $form->submit(),
                    new SimpleGetEncoding(array('a' => 'aaa')));
        }

        function testSingleSelectFieldSubmittedWithPost() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array('method' => 'post')),
                    new SimpleUrl('htp://host'));
            $select = &new SimpleSelectionTag(array('name' => 'a'));
            $select->addTag(new SimpleOptionTag(
                    array('value' => 'aaa', 'selected' => '')));
            $form->addWidget($select);
            $this->assertIdentical(
                    $form->submit(),
                    new SimplePostEncoding(array('a' => 'aaa')));
        }

        function testUnchecked() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('htp://host'));
            $form->addWidget(new SimpleCheckboxTag(
                    array('name' => 'me', 'type' => 'checkbox')));
            $this->assertIdentical($form->getValue(new SimpleByName('me')), false);
            $this->assertTrue($form->setField(new SimpleByName('me'), 'on'));
            $this->assertEqual($form->getValue(new SimpleByName('me')), 'on');
            $this->assertFalse($form->setField(new SimpleByName('me'), 'other'));
            $this->assertEqual($form->getValue(new SimpleByName('me')), 'on');
        }

        function testChecked() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('htp://host'));
            $form->addWidget(new SimpleCheckboxTag(
                    array('name' => 'me', 'value' => 'a', 'type' => 'checkbox', 'checked' => '')));
            $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a');
            $this->assertTrue($form->setField(new SimpleByName('me'), 'a'));
            $this->assertEqual($form->getValue(new SimpleByName('me')), 'a');
            $this->assertTrue($form->setField(new SimpleByName('me'), false));
            $this->assertEqual($form->getValue(new SimpleByName('me')), false);
        }

        function testSingleUncheckedRadioButton() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('htp://host'));
            $form->addWidget(new SimpleRadioButtonTag(
                    array('name' => 'me', 'value' => 'a', 'type' => 'radio')));
            $this->assertIdentical($form->getValue(new SimpleByName('me')), false);
            $this->assertTrue($form->setField(new SimpleByName('me'), 'a'));
            $this->assertEqual($form->getValue(new SimpleByName('me')), 'a');
        }

        function testSingleCheckedRadioButton() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('htp://host'));
            $form->addWidget(new SimpleRadioButtonTag(
                    array('name' => 'me', 'value' => 'a', 'type' => 'radio', 'checked' => '')));
            $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a');
            $this->assertFalse($form->setField(new SimpleByName('me'), 'other'));
        }

        function testUncheckedRadioButtons() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('htp://host'));
            $form->addWidget(new SimpleRadioButtonTag(
                    array('name' => 'me', 'value' => 'a', 'type' => 'radio')));
            $form->addWidget(new SimpleRadioButtonTag(
                    array('name' => 'me', 'value' => 'b', 'type' => 'radio')));
            $this->assertIdentical($form->getValue(new SimpleByName('me')), false);
            $this->assertTrue($form->setField(new SimpleByName('me'), 'a'));
            $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a');
            $this->assertTrue($form->setField(new SimpleByName('me'), 'b'));
            $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b');
            $this->assertFalse($form->setField(new SimpleByName('me'), 'c'));
            $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b');
        }

        function testCheckedRadioButtons() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('htp://host'));
            $form->addWidget(new SimpleRadioButtonTag(
                    array('name' => 'me', 'value' => 'a', 'type' => 'radio')));
            $form->addWidget(new SimpleRadioButtonTag(
                    array('name' => 'me', 'value' => 'b', 'type' => 'radio', 'checked' => '')));
            $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b');
            $this->assertTrue($form->setField(new SimpleByName('me'), 'a'));
            $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a');
        }

        function testMultipleFieldsWithSameKey() {
            $form = &new SimpleForm(
                    new SimpleFormTag(array()),
                    new SimpleUrl('htp://host'));
            $form->addWidget(new SimpleCheckboxTag(
                    array('name' => 'a', 'type' => 'checkbox', 'value' => 'me')));
            $form->addWidget(new SimpleCheckboxTag(
                    array('name' => 'a', 'type' => 'checkbox', 'value' => 'you')));
            $this->assertIdentical($form->getValue(new SimpleByName('a')), false);
            $this->assertTrue($form->setField(new SimpleByName('a'), 'me'));
            $this->assertIdentical($form->getValue(new SimpleByName('a')), 'me');
        }
    }
?>