text:
"""
=========================================
Image denoising using dictionary learning
=========================================

An example comparing the effect of reconstructing noisy fragments
of the Lena image using firstly online :ref:`DictionaryLearning` and
various transform methods.

The dictionary is fitted on the distorted left half of the image, and
subsequently used to reconstruct the right half. Note that even better
performance could be achieved by fitting to an undistorted (i.e.
noiseless) image, but here we start from the assumption that it is not
available.

A common practice for evaluating the results of image denoising is by looking
at the difference between the reconstruction and the original image. If the
reconstruction is perfect this will look like gaussian noise.

It can be seen from the plots that the results of :ref:`omp` with two
non-zero coefficients is a bit less biased than when keeping only one
(the edges look less prominent). It is in addition closer from the ground
truth in Frobenius norm.

The result of :ref:`least_angle_regression` is much more strongly biased: the
difference is reminiscent of the local intensity value of the original image.

Thresholding is clearly not useful for denoising, but it is here to show that
it can produce a suggestive output with very high speed, and thus be useful
for other tasks such as object classification, where performance is not
necessarily related to visualisation.

"""
print(__doc__)

from time import time

import matplotlib.pyplot as plt
import numpy as np

from scipy.misc import lena

from sklearn.decomposition import MiniBatchDictionaryLearning
from sklearn.feature_extraction.image import extract_patches_2d
from sklearn.feature_extraction.image import reconstruct_from_patches_2d

###############################################################################
# Load Lena image and extract patches

lena = lena() / 256.0

# downsample for higher speed
lena = lena[::2, ::2] + lena[1::2, ::2] + lena[::2, 1::2] + lena[1::2, 1::2]
lena /= 4.0
height, width = lena.shape

# Distort the right half of the image
print('Distorting image...')
distorted = lena.copy()
distorted[:, height / 2:] += 0.075 * np.random.randn(width, height / 2)

# Extract all reference patches from the left half of the image
print('Extracting reference patches...')
t0 = time()
patch_size = (7, 7)
data = extract_patches_2d(distorted[:, :height / 2], patch_size)
data = data.reshape(data.shape[0], -1)
data -= np.mean(data, axis=0)
data /= np.std(data, axis=0)
print('done in %.2fs.' % (time() - t0))

###############################################################################
# Learn the dictionary from reference patches

print('Learning the dictionary...')
t0 = time()
dico = MiniBatchDictionaryLearning(n_components=100, alpha=1, n_iter=500)
V = dico.fit(data).components_
dt = time() - t0
print('done in %.2fs.' % dt)

plt.figure(figsize=(4.2, 4))
for i, comp in enumerate(V[:100]):
    plt.subplot(10, 10, i + 1)
    plt.imshow(comp.reshape(patch_size), cmap=plt.cm.gray_r,
               interpolation='nearest')
    plt.xticks(())
    plt.yticks(())
plt.suptitle('Dictionary learned from Lena patches\n' +
             'Train time %.1fs on %d patches' % (dt, len(data)),
             fontsize=16)
plt.subplots_adjust(0.08, 0.02, 0.92, 0.85, 0.08, 0.23)

###############################################################################
# Display the distorted image

def show_with_diff(image, reference, title):
    """Helper function to display denoising"""
    plt.figure(figsize=(5, 3.3))
    plt.subplot(1, 2, 1)
    plt.title('Image')
    plt.imshow(image, vmin=0, vmax=1, cmap=plt.cm.gray, interpolation='nearest')
    plt.xticks(())
    plt.yticks(())
    plt.subplot(1, 2, 2)
    difference = image - reference

    plt.title('Difference (norm: %.2f)' % np.sqrt(np.sum(difference ** 2)))
    plt.imshow(difference, vmin=-0.5, vmax=0.5, cmap=plt.cm.PuOr,
               interpolation='nearest')
    plt.xticks(())
    plt.yticks(())
    plt.suptitle(title, size=16)
    plt.subplots_adjust(0.02, 0.02, 0.98, 0.79, 0.02, 0.2)

show_with_diff(distorted, lena, 'Distorted image')

###############################################################################
# Extract noisy patches and reconstruct them using the dictionary

print('Extracting noisy patches... ')
t0 = time()
data = extract_patches_2d(distorted[:, height / 2:], patch_size)
data = data.reshape(data.shape[0], -1)
intercept = np.mean(data, axis=0)
data -= intercept
print('done in %.2fs.' % (time() - t0))

transform_algorithms = [
    ('Orthogonal Matching Pursuit\n1 atom', 'omp',
     {'transform_n_nonzero_coefs': 1}),
    ('Orthogonal Matching Pursuit\n2 atoms', 'omp',
     {'transform_n_nonzero_coefs': 2}),
    ('Least-angle regression\n5 atoms', 'lars',
     {'transform_n_nonzero_coefs': 5}),
    ('Thresholding\n alpha=0.1', 'threshold', {'transform_alpha': .1})]

reconstructions = {}
for title, transform_algorithm, kwargs in transform_algorithms:
    print(title + '...')
    reconstructions[title] = lena.copy()
    t0 = time()
    dico.set_params(transform_algorithm=transform_algorithm, **kwargs)
    code = dico.transform(data)
    patches = np.dot(code, V)

    if transform_algorithm == 'threshold':
        patches -= patches.min()
        patches /= patches.max()

    patches += intercept
    patches = patches.reshape(len(data), *patch_size)
    if transform_algorithm == 'threshold':
        patches -= patches.min()
        patches /= patches.max()
    reconstructions[title][:, height / 2:] = reconstruct_from_patches_2d(
        patches, (width, height / 2))
    dt = time() - t0
    print('done in %.2fs.' % dt)
    show_with_diff(reconstructions[title], lena,
                   title + ' (time: %.1fs)' % dt)

plt.show()


text:
""" Test suite for the the cmake module.

The script can be executed on its own or incorporated into a larger test suite.
The ANSIBLE_LIBRARY environment variable must include src/, and pytest must be
run with `--ansible-host-pattern=localhost`.

"""
from os.path import abspath
from os.path import dirname
from os.path import join
from subprocess import call

import pytest

@pytest.fixture(scope="module")
def tmpdir(tmpdir_factory):
    """ Generate a test directory.

    """
    # Can't use the predefined tmpdir fixture because module scope is needed.
    return tmpdir_factory.mktemp("test_module")

def test_build(tmpdir, ansible_module):
    """ Test a normal build.

    """
    params = {
        "executable": "cmake",
        "build_type": "Debug",
        "source_dir": dirname(abspath(__file__)),
        "binary_dir": tmpdir.strpath,
    }
    result = ansible_module.cmake(**params)
    assert not result["localhost"].get("failed", False)
    cmd = join(result["localhost"]["binary_dir"], "test_app")
    assert 0 == call([cmd])
    return

def test_creates(tmpdir, ansible_module):
    """ Test a build using the creates option.

    This depends on the existence of the executable created by test_build().

    """
    params = {
        "executable": "cmake",
        "build_type": "Debug",
        "source_dir": dirname(abspath(__file__)),
        "binary_dir": tmpdir.strpath,
        "creates": tmpdir.join("test_app").strpath
    }
    result = ansible_module.cmake(**params)
    assert not result["localhost"].get("failed", False)
    assert not result["localhost"]["changed"]
    return

def test_clean(tmpdir, ansible_module):
    """ Test a build with a target.

    """
    params = {
        "executable": "cmake",
        "build_type": "Debug",
        "binary_dir": tmpdir.strpath,
        "target": "clean",
    }
    result = ansible_module.cmake(**params)
    assert not result["localhost"].get("failed", False)
    assert not tmpdir.join("test_app").check()  # make sure file is removed
    return

# Make the module executable.

if __name__ == "__main__":
    raise exit(pytest.main([__file__]))

redpajama_set_name: RedPajamaGithub


text:
package org.security.crypt;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import org.security.crypt.digest.MD5;
import org.security.crypt.digest.SHA1;
import org.security.crypt.util.CryptReader;
import org.security.crypt.util.CryptWriter;
import org.security.crypt.util.HexConverter;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.Option;

/**
 * Command line interface for keystore operations.
 *
 * @author shivam
 *
 */
public class KeyStoreCli extends AbstractCli {

	/** Default key algorithm name. */
	public static final String DEFAULT_KEY_ALGORITHM = "RSA";

	/** Option for listing keystore contents. */
	protected static final String OPT_LIST = "list";

	/** Option for importing keypair into keystore. */
	protected static final String OPT_IMPORT = "import";

	/** Option for exporting keypair from keystore. */
	protected static final String OPT_EXPORT = "export";

	/** Option for specifying keystore file. */
	protected static final String OPT_STORE = "keystore";

	/** Option for specifying keystore type. */
	protected static final String OPT_TYPE = "storetype";

	/** Option for specifying keystore password. */
	protected static final String OPT_PASS = "storepass";

	/** Option for specifying alias for keystore entry to import/export. */
	protected static final String OPT_ALIAS = "alias";

	/** Option for specifying certificate file to import/export. */
	protected static final String OPT_CERT = "cert";

	/** Option for specifying key file to import/export. */
	protected static final String OPT_KEY = "key";

	/** Option for specifying key cipher algorithm. */
	protected static final String OPT_KEYALG = "keyalg";

	/** Name of operation provided by this class. */
	private static final String COMMAND_NAME = "keystore";

	/** For calculating MD5 cert fingerprints. */
	private final MD5 md5 = new MD5();

	/** For calculating SHA-1 cert fingerprints. */
	private final SHA1 sha1 = new SHA1();

	/** For pretty-printing cert signature fingerprint in HEX. */
	private final HexConverter hexConv = new HexConverter(true);

	/**
	 * CLI entry point method.
	 *
	 * @param args
	 *            Command line arguments.
	 */
	public static void main(final String[] args) {
		new KeyStoreCli().performAction(args);
	}

	/** {@inheritDoc} */
	protected void initOptions() {
		super.initOptions();

		final Option keystore = new Option(OPT_STORE, true, "keystore file");
		keystore.setArgName("filepath");
		keystore.setOptionalArg(false);

		final Option pass = new Option(OPT_PASS, true, "keystore password");
		pass.setArgName("password");
		pass.setOptionalArg(false);

		final Option type = new Option(OPT_TYPE, true,
				"keystore type, e.g. BKS (default), JKS");
		type.setArgName("name");
		type.setOptionalArg(false);

		final Option alias = new Option(OPT_ALIAS, true,
				"alias assigned to imported item or alias of item to export");
		alias.setArgName("name");
		alias.setOptionalArg(false);

		final Option cert = new Option(OPT_CERT, true,
				"X.509 certificate file; "
						+ "encoding determined by file extension (der|pem)");
		cert.setArgName("filepath");
		cert.setOptionalArg(false);

		final Option key = new Option(OPT_KEY, true,
				"DER-encoded PKCS#8 or PEM-encoded SSLeay private key; "
						+ "encoding determined by file extension (der|pem)");
		key.setArgName("filepath");
		key.setOptionalArg(false);

		final Option keyalg = new Option(OPT_KEYALG, true,
				"private key algorithm name; assumes RSA if not specified");
		keyalg.setArgName("algorithm");
		keyalg.setOptionalArg(false);

		options.addOption(keystore);
		options.addOption(pass);
		options.addOption(type);
		options.addOption(alias);
		options.addOption(cert);
		options.addOption(key);
		options.addOption(keyalg);
		options.addOption(new Option(OPT_LIST, "list keystore contents"));
		options.addOption(new Option(OPT_IMPORT, "import cert or cert/key pair"));
		options.addOption(new Option(OPT_EXPORT, "export cert or cert/key pair"));
	}

	/** {@inheritDoc} */
	protected void dispatch(final CommandLine line) throws Exception {
		if (line.hasOption(OPT_LIST)) {
			list(line);
		} else if (line.hasOption(OPT_IMPORT)) {
			doImport(line);
		} else if (line.hasOption(OPT_EXPORT)) {
			doExport(line);
		} else {
			printHelp();
		}
	}

	/**
	 * Lists keystore contents on STDOUT. Output is similar to keytool -list -v.
	 *
	 * @param line
	 *            Parsed command line arguments container.
	 *
	 * @throws Exception
	 *             On errors.
	 */
	protected void list(final CommandLine line) throws Exception {
		validateOptions(line);

		final KeyStore store = readKeyStore(line);
		final Enumeration<String> aliases = store.aliases();
		System.out.println("");
		while (aliases.hasMoreElements()) {
			final String alias = aliases.nextElement();
			System.out.println("Alias name: " + alias);
			System.out
					.println("Creation date: " + store.getCreationDate(alias));
			if (store.isKeyEntry(alias)) {
				System.out.println("Entry type: keyEntry");

				final Certificate[] chain = store.getCertificateChain(alias);
				System.out.println("Certificate chain length: " + chain.length);
				for (int i = 0; i < chain.length; i++) {
					System.out.println("===== Certificate [" + i + "] =====");
					printCertificate(chain[i]);
				}
			} else {
				System.out.println("Entry type: trustedCertEntry");
				System.out.println("Certificate details:");
				printCertificate(store.getCertificate(alias));
			}
			System.out.println("");
			System.out.println("");
		}
	}

	/**
	 * Imports a certificate or key pair into the keystore.
	 *
	 * @param line
	 *            Parsed command line arguments container.
	 *
	 * @throws Exception
	 *             On errors.
	 */
	protected void doImport(final CommandLine line) throws Exception {
		validateOptions(line);

		final KeyStore store = readKeyStore(line);
		final String alias = line.getOptionValue(OPT_ALIAS);
		final File certFile = new File(line.getOptionValue(OPT_CERT));
		if (line.hasOption(OPT_KEY)) {
			final File keyFile = new File(line.getOptionValue(OPT_KEY));
			final char[] passChars = line.getOptionValue(OPT_PASS)
					.toCharArray();
			final PrivateKey key = CryptReader.readPrivateKey(keyFile);
			final Certificate[] chain = CryptReader
					.readCertificateChain(certFile);
			System.err.println("Read certificate chain of length "
					+ chain.length + ":");
			for (int i = 0; i < chain.length; i++) {
				System.out.println("===== Certificate [" + i + "] =====");
				printCertificate(chain[i]);
			}
			store.setKeyEntry(alias, key, passChars, chain);
			System.err.println("Imported key entry " + alias);
		} else {
			final Certificate cert = CryptReader.readCertificate(certFile);
			System.err.println("Read certificate:");
			printCertificate(cert);
			store.setCertificateEntry(alias, cert);
			System.err.println("Imported trusted cert entry " + alias);
		}

		final OutputStream os = new FileOutputStream(new File(
				line.getOptionValue(OPT_STORE)));
		try {
			store.store(os, line.getOptionValue(OPT_PASS).toCharArray());
		} finally {
			os.close();
		}
	}

	/**
	 * Exports a certificate or key pair from the keystore.
	 *
	 * @param line
	 *            Parsed command line arguments container.
	 *
	 * @throws Exception
	 *             On errors.
	 */
	protected void doExport(final CommandLine line) throws Exception {
		validateOptions(line);

		final KeyStore store = readKeyStore(line);
		final String alias = line.getOptionValue(OPT_ALIAS);
		boolean wroteData = false;
		if (line.hasOption(OPT_CERT)) {
			final File certFile = new File(line.getOptionValue(OPT_CERT));
			final Certificate[] certs = store.getCertificateChain(alias);
			if (certs != null) {
				if (certFile.getName().endsWith(PEM_SUFFIX)) {
					CryptWriter.writePemCertificates(certs, certFile);
				} else {
					CryptWriter.writeEncodedCertificates(certs, certFile);
				}
			} else {
				// Null cert chain indicates trusted cert entry
				// with single cert
				final Certificate cert = store.getCertificate(alias);
				if (certFile.getName().endsWith(PEM_SUFFIX)) {
					CryptWriter.writePemCertificate(cert, certFile);
				} else {
					CryptWriter.writeEncodedCertificate(cert, certFile);
				}
			}
			System.err.println("Wrote certificate to " + certFile);
			wroteData = true;
		}
		if (line.hasOption(OPT_KEY)) {
			final File keyFile = new File(line.getOptionValue(OPT_KEY));
			final PrivateKey key = (PrivateKey) store.getKey(alias, line
					.getOptionValue(OPT_PASS).toCharArray());
			if (keyFile.getName().endsWith(PEM_SUFFIX)) {
				CryptWriter.writePemKey(key, null, null, keyFile);
			} else {
				CryptWriter.writeEncodedKey(key, keyFile);
			}
			System.err.println("Wrote key to " + keyFile);
			wroteData = true;
		}
		if (!wroteData) {
			System.err
					.println("No data was written because neither -cert nor -key was specified.");
		}
	}

	/** {@inheritDoc} */
	protected String getCommandName() {
		return COMMAND_NAME;
	}

	/**
	 * Reads a keystore from disk using command line arguments.
	 *
	 * @param line
	 *            Parsed command line arguments container.
	 *
	 * @return Initialized key store read from disk.
	 *
	 * @throws Exception
	 *             On errors.
	 */
	protected KeyStore readKeyStore(final CommandLine line) throws Exception {
		KeyStore store;
		if (line.hasOption(OPT_TYPE)) {
			store = CryptProvider.getKeyStore(line.getOptionValue(OPT_TYPE));
		} else {
			// Get a store of the default type
			store = CryptProvider.getKeyStore();
		}

		final File storeFile = new File(line.getOptionValue(OPT_STORE));
		final char[] passChars = line.getOptionValue(OPT_PASS).toCharArray();
		if (storeFile.exists()) {
			final InputStream in = new FileInputStream(storeFile);
			try {
				store.load(in, passChars);
			} finally {
				in.close();
			}
		} else {
			// An existing file is required for everything but import operation
			if (line.hasOption(OPT_IMPORT)) {
				// Initialize new keystore by passing null stream
				store.load(null, passChars);
			} else {
				throw new IllegalArgumentException(
						"Keystore does not exist at "
								+ storeFile
								+ ". "
								+ "An existing keystore is required for this operation.");
			}
		}
		return store;
	}

	/**
	 * Prints a string representation of the given certificate to STDOUT. For an
	 * X.509 certificate, prints important fields.
	 *
	 * @param cert
	 *            Certificate to print.
	 *
	 * @throws Exception
	 *             On print errors.
	 */
	protected void printCertificate(final Certificate cert) throws Exception {
		if (cert instanceof X509Certificate) {
			final X509Certificate xCert = (X509Certificate) cert;
			final byte[] encodedCert = xCert.getEncoded();
			System.out.println("Subject: " + xCert.getSubjectDN());
			System.out.println("Issuer: " + xCert.getIssuerDN());
			System.out.println("Serial: "
					+ hexConv.fromBytes(xCert.getSerialNumber().toByteArray()));
			System.out.println("Valid not before: " + xCert.getNotBefore());
			System.out.println("Valid not after: " + xCert.getNotAfter());
			System.out.println("MD5 fingerprint: "
					+ md5.digest(encodedCert, hexConv));
			System.out.println("SHA1 fingerprint: "
					+ sha1.digest(encodedCert, hexConv));
		} else {
			System.out.println(cert);
		}
	}

	/**
	 * Validates the existence of required options for an operation.
	 *
	 * @param line
	 *            Parsed command line arguments container.
	 */
	protected void validateOptions(final CommandLine line) {
		if (!line.hasOption(OPT_STORE)) {
			throw new IllegalArgumentException("keystore option is required.");
		}
		if (!line.hasOption(OPT_PASS)) {
			throw new IllegalArgumentException("storepass option is required.");
		}
		if (line.hasOption(OPT_IMPORT) || line.hasOption(OPT_EXPORT)) {
			if (!line.hasOption(OPT_ALIAS)) {
				throw new IllegalArgumentException("alias option is required.");
			}
		}
		if (line.hasOption(OPT_IMPORT)) {
			if (!line.hasOption(OPT_CERT)) {
				throw new IllegalArgumentException("cert option is required.");
			}
		}
	}
}


text:
import System.Console.ANSI

main = do
  setSGR [ SetConsoleIntensity BoldIntensity
         , SetColor Foreground Vivid Red
         ]
  putStr "Hello"

  setSGR [ SetConsoleIntensity NormalIntensity
         , SetColor Foreground Vivid White
         , SetColor Background Dull Blue
         ]
  putStrLn "World!"
  setSGR [Reset]


text:
var express = require('express');
var app = express();
var path = require('path');
var server = require('http').createServer(app);
var formidable = require('formidable');
var fs = require('fs');
var azure = require('azure-storage');

const storageAccount = 'azureappb4';
const storageAccessKey = 'M28H+AO14p6JiUDg6HeRQNPsYycCeLw4mMMSxNXSk5m5LjIt8jx11YULjXPDvGcgftjiGT089TDB3WLWhpkfJg==';
const containerName = 'azureappb4';

var blobClient = azure.createBlobService(storageAccount, storageAccessKey);
var blobSvc = azure.createBlobServiceAnonymous('https://azureappb4.blob.core.windows.net/');

try {
    server.listen(process.env.PORT || 1337);

    app.use(express.static(path.join(__dirname, 'public')));

    app.get('/', function (request, response) {
        if (request) {
            console.log(request);
        }
        response.sendFile(__dirname, 'index.html');
    });

    app.get('/sitemap.xml', function (request, response) {
        if (request) {
            console.log(request);
        }
        response.sendFile(__dirname, 'sitemap.xml');
    });

    app.get('/images', function (request, response) {
        if (request) {
            console.log(request);
        }

   blobClient.listBlobsSegmented('azureappb4', null, function(error, result, resp){
  if(!error){
     console.log(resp);
      back="";
      var arrayLength = result.entries.length;
for (var i = 0; i < arrayLength; i++) {
    back+="<img src='"+"https://azureappb4.blob.core.windows.net/azureappb4/"+result.entries[i].name+"'>";
    //Do something
}

      response.send(back);
      // result.entries contains the entries
      // If not all blobs were returned, result.continuationToken has the continuation token.
  }
});
    });

    app.get('/BingSiteAuth.xml', function (request, response) {
        if (request) {
            console.log(request);
        }
        response.sendFile(__dirname, 'BingSiteAuth.xml');
    });

    app.post('/upload', function (request, response) {
        console.log('Here');

        var form = new formidable.IncomingForm();

        form.on('error', function (error) {
            console.log('An error occurred: \n' + error);
        });

        form.on('end', function () {
            console.log('success')
        });

        form.parse(request, function (error, fields, files) {
            var itemID = new Date().getTime();
            var options = {
                contentType: 'image/jpeg',
                metadata: {
                    fileName: itemID
                }
            };

            blobClient.createBlockBlobFromLocalFile(containerName, itemID + '.jpeg', files['files'].path, options,
                function(error){
                    if(error !== null){
                        console.log('Azure full error: ', error);
                    }
                    else{
                        console.log('Azure full success.');
                    }
                });
        });

    });

} catch(err){
    console.log(err);
}


text:
"""
    pygments.lexers.tap
    ~~~~~~~~~~~~~~~~~~~

    Lexer for the Test Anything Protocol (TAP).

    :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

from pygments.lexer import bygroups, RegexLexer
from pygments.token import Comment, Generic, Keyword, Name, Number, Text

__all__ = ['TAPLexer']

class TAPLexer(RegexLexer):
    """
    For Test Anything Protocol (TAP) output.

    .. versionadded:: 2.1
    """
    name = 'TAP'
    aliases = ['tap']
    filenames = ['*.tap']

    tokens = {
        'root': [
            # A TAP version may be specified.
            (r'^TAP version \d+\n', Name.Namespace),

            # Specify a plan with a plan line.
            (r'^1..\d+', Keyword.Declaration, 'plan'),

            # A test failure
            (r'^(not ok)([^\S\n]*)(\d*)',
             bygroups(Generic.Error, Text, Number.Integer), 'test'),

            # A test success
            (r'^(ok)([^\S\n]*)(\d*)',
             bygroups(Keyword.Reserved, Text, Number.Integer), 'test'),

            # Diagnostics start with a hash.
            (r'^#.*\n', Comment),

            # TAP's version of an abort statement.
            (r'^Bail out!.*\n', Generic.Error),

            # TAP ignores any unrecognized lines.
            (r'^.*\n', Text),
        ],
        'plan': [
            # Consume whitespace (but not newline).
            (r'[^\S\n]+', Text),

            # A plan may have a directive with it.
            (r'#', Comment, 'directive'),

            # Or it could just end.
            (r'\n', Comment, '#pop'),

            # Anything else is wrong.
            (r'.*\n', Generic.Error, '#pop'),
        ],
        'test': [
            # Consume whitespace (but not newline).
            (r'[^\S\n]+', Text),

            # A test may have a directive with it.
            (r'#', Comment, 'directive'),

            (r'\S+', Text),

            (r'\n', Text, '#pop'),
        ],
        'directive': [
            # Consume whitespace (but not newline).
            (r'[^\S\n]+', Comment),

            # Extract todo items.
            (r'(?i)\bTODO\b', Comment.Preproc),

            # Extract skip items.
            (r'(?i)\bSKIP\S*', Comment.Preproc),

            (r'\S+', Comment),

            (r'\n', Comment, '#pop:2'),
        ],
    }


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:background="@color/colorPrimary"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/inspiremeText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="INSPIRE ME"
        android:fontFamily="serif-monospace"
        android:textSize="40dp"
        android:textStyle="bold"
        android:textColor="#3CB371"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>


text:
<?xml version="1.0" encoding="utf-8" ?>
<language xmlns:xs="http://www.w3.org/2001/XMLSchema-instance"
    xs:noNamespaceSchemaLocation="http://www.csphere.eu/xml/schemas/language.xsd">
    <translation type="plugin" name="news" version_min="0.1"
        short="de" />
    <vendor>acme</vendor>
    <version>0.1</version>
    <published>2007-04-17</published>
    <copyright>cSphere Team</copyright>
    <license>Simplified BSD License</license>
    <name>News</name>
    <info>Nachrichten anzeigen und verwalten</info>
    <engine name="csphere" version_min="2012.0" />
    <icon type="default">layout</icon>
    <authors>
        <current>cSphere Team</current>
        <past>cSphere Team</past>
    </authors>
    <contact>
        <email adress="contact@csphere.eu" />
        <web url="http://www.csphere.eu" />
    </contact>
    <definitions>
        <define name="category">Kategorie</define>
        <define name="no_news_found">Keine Nachricht vorhanden</define>
    </definitions>
</language>


text:
package com.magnet.mmx.server.plugin.mmxmgmt.api.tags;

import java.util.*;

/**
 */
public class TopicTagMap extends TagMap {
  public List<TopicTagInfo> getTagInfoList() {
    List<TopicTagInfo> topicTagInfoList = new ArrayList<TopicTagInfo>();
    Set<String> topicIdSet = map.keySet();
    for(String topicId : topicIdSet) {
      ArrayList<String> tagList = map.get(topicId);
      topicTagInfoList.add(new TopicTagInfo(topicId, tagList));
    }
    return topicTagInfoList;
  }
}


text:
RDPy is a python script for auditing the security of a Remote Desktop
configuration.

This project borrows heavily from two related works:

- http://labs.portcullis.co.uk/application/rdp-sec-check/
- http://troels.arvin.dk/code/nagios/check_x224

RDPy started life as an attempt to avoid wrapping rdp-sec-check so that multiple
hosts could be scanned without interaction. It appears that rdp-sec-check now
supports a hosts file that solves this issue. The second reason for creating
RDPy was to learn a little more about the Remote Desktop protocol and have a
tool written in Python. Both of these goals were met (as evidenced by the
extensive but highly unecessary comments in the source) and this project has
received little love since. It was originally written in 2013 but I've just now
gotten around to releasing it.

This project is being used for testing but is not guaranteed to be bug-free. If
you have any problems, feel free to open an issue.

# Example

~~~
# ./rdpy.py 192.0.2.1
Target:      192.0.2.1
Port:        3389 (default)
Host Status: UP

[+] Supported Protocols:
	Standard RDP Security
	TLS 1.0, 1.1 or 1.2 Security
	Hybrid (TLS + CredSSP) Security

[+] Supported Encryption Methods:
	40 Bit
	128 Bit
	56 Bit

[+] Supported Encryption Levels:
	Client Compatible

[+] Security Issues:
	NLA supported but not mandated DoS
	SSL supported but not mandated MitM
	Weak RDP encryption supported

[+] Server Messages:
	(None)

--------------------------------------------------

Total Hosts:     1
Listening Hosts: 1
~~~


text:
import numpy
import pytest

from qualipy.filters.blurred_context import *

BLURRED_CONTEXT = 'tests/images/blurred_context.jpg'
NON_BLURRED_CONTEXT = 'tests/images/exposure_sample_good.jpg'

def test_blurry_degree_works_for_all_zeroes():
    assert -0.001 < blurry_degree(numpy.array([0, 0, 0])) < 0.001

def test_blurry_degree_returns_first_values_ratio():
    assert round(blurry_degree(numpy.array([1, 1, 2])) - 1 / 4., 3) == 0

def test_blurmap_returns_correct_size_matrix():
    mat = numpy.eye(10)
    assert blurmap(mat).shape == (6, 6)

def test_input_vector_is_of_right_size():
    mat = numpy.eye(50)
    assert len(get_input_vector(mat)) == 101

def test_input_vector_is_of_right_type():
    mat = numpy.eye(50)
    assert get_input_vector(mat).dtype == numpy.float32

def test_recognizes_blurred_context():
    assert BlurredContext().predict(BLURRED_CONTEXT)

def test_doesnt_recognize_normal_image():
    assert not BlurredContext().predict(NON_BLURRED_CONTEXT)

def test_setting_threshold():
    assert not BlurredContext(threshold=1).predict(BLURRED_CONTEXT)

def test_inverting_threshold():
    assert BlurredContext(1.01, invert_threshold=True).predict(BLURRED_CONTEXT)

def test_can_return_float():
    assert type(BlurredContext().predict(BLURRED_CONTEXT,
                                         return_boolean=False)) == float

def test_wrong_path_type_raises_exception():
    with pytest.raises(TypeError):
        BlurredContext().predict(0)

def test_training_with_too_few_images_causes_exception():
    with pytest.raises(ValueError):
        BlurredContext().train([BLURRED_CONTEXT], [0])

def test_training_with_invalid_number_of_labels_causes_exception():
    with pytest.raises(ValueError):
        BlurredContext().train([BLURRED_CONTEXT], [])

def test_training_with_invalid_paths_causes_exception():
    with pytest.raises(IOError):
        BlurredContext().train(['fail'], [])

def test_invalid_svm_file_causes_exception():
    with pytest.raises(TypeError):
        BlurredContext(svm_file=0)

def test_invalid_load_path_causes_exception():
    with pytest.raises(TypeError):
        BlurredContext().load(0)

def test_svm_file_not_found_causes_exception():
    with pytest.raises(ValueError):
        BlurredContext().load('fail')

def test_invalid_save_path_causes_exception():
    with pytest.raises(TypeError):
        BlurredContext().save(0)


text:
package org.pwmgr.command;

import org.pwmgr.util.CConfig;
import org.pwmgr.util.CConsole;
import org.pwmgr.util.CPGPUtils;
import org.pwmgr.util.CDatabase;

import org.bouncycastle.openpgp.PGPKeyRingGenerator;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRing;

import org.jsonjava.JSONException;

import java.io.File;
import java.io.IOException;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;

import java.util.Arrays;
import java.util.Date;

public class CInit
{
    public static void execute(CConfig config)
        throws IOException, JSONException
    {
        // Check for various files we'll be writing.
        String root = config.getArgOption(CConfig.ArgOption.PUBLIC);
        String ppath = config.getArgOption(CConfig.ArgOption.PRIVATE);

        boolean done = false;
        while (!done) {
            while (!validateDbRoot(root)) {
                root = CConsole.readString
                    ("Create password directory",
                     System.getProperty("user.home")+
                     File.separator+"pwmgr"+File.separator+"db");
            }

            ppath = config.getArgOption(CConfig.ArgOption.PRIVATE);
            while (!validatePrivatePath(ppath)) {
                ppath = CConsole.readString
                    ("Create secret key",
                     System.getProperty("user.home")+
                     File.separator+"pwmgr"+File.separator+"private.pgp");
            }

            CConsole.message("");
            CConsole.message("  Passwords under  "+root);
            CConsole.message("  Secret key file  "+ppath);
            CConsole.message("");
            done = CConsole.isYes("Proceed", true);
            if (!done) {
                root = null;
                ppath = null;
            }
        }

        // use provided paths to do the rest.
        config
            .setArgOption(CConfig.ArgOption.PUBLIC, root)
            .setArgOption(CConfig.ArgOption.PRIVATE, ppath);

        char[] pw = CConsole.readPassword("Master passphrase", true);
        if (pw == null) { return; }

        init(CDatabase.newDatabase(), config, pw);
    }

    final static void init(CDatabase db, CConfig config, char[] pw)
        throws IOException, JSONException
    {
        File rootf =
            new File(config.getArgOption(CConfig.ArgOption.PUBLIC));
        if (!rootf.isDirectory()) {
            if (!rootf.mkdirs()) {
                throw new IOException("Unable to create directory "+rootf);
            }
        }

        // Now generate keypair.
        CConsole.message("Generating keys. This may take a while...");
        PGPKeyRingGenerator krgen = CPGPUtils.generateKeyRingGenerator
            ("pwmgr", pw, 0x60);

        // Write out files.

        // Secret file is re-encrypted with master pass-phrase.
        // TBD: allow separate pass-phrases.
        PGPSecretKeyRing skr = krgen.generateSecretKeyRing();

        boolean ok = false;
        BufferedOutputStream out = null;
        File privfile = ensureParent
            (config.getArgOption(CConfig.ArgOption.PRIVATE));
        try {
            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            skr.encode(bout);
            bout.close();

            out = new BufferedOutputStream(new FileOutputStream(privfile));
            CPGPUtils.symmetricEncryptAndSign
                (bout.toByteArray(), out, pw,
                 CPGPUtils.getSigningSecretKey(skr), pw,
                 "_CONSOLE", new Date());

            ok = true;
        }
        finally {
            if (out != null) {
                try { out.close(); } catch (Throwable ign){}
            }
            if (!ok) {
                Arrays.fill(pw, '.');
                privfile.delete();
            }
        }

        File pubfile = new File(rootf, CConfig.PUBKEY);
        PGPPublicKeyRing pkr = krgen.generatePublicKeyRing();

        out = null;
        ok = false;
        try {
            out = new BufferedOutputStream(new FileOutputStream(pubfile));
            pkr.encode(out);
            ok = true;
        }
        finally {
            if (out != null) {
                try { out.close(); } catch (Throwable ign){}
            }
            if (!ok) {
                Arrays.fill(pw, '.');
                privfile.delete();
                pubfile.delete();
            }
        }

        ok = false;
        File pwdb = new File(rootf, CConfig.PWDB);
        try {
            db.save(config, skr, pw);
            ok = true;
        }
        finally {
            Arrays.fill(pw, '.');
            if (!ok) {
                privfile.delete();
                pubfile.delete();
                pwdb.delete();
            }
        }

        boolean write_config;
        File conffile = CConfig.getDefaultLocation();
        if (conffile.canRead()) {
            write_config = CConsole.isYes
                ("Update file path options under "+conffile, false);
        }
        else {
            write_config = CConsole.isYes
                ("Save file path options to "+conffile, true);
        }
        if (write_config) {
            ok = false;
            try {
                config.saveOptions(conffile);
                ok = true;
            }
            finally {
                if (!ok) {
                    privfile.delete();
                    pubfile.delete();
                    pwdb.delete();
                }
            }
        }

        CConsole.message("");
        CConsole.message("Files generated successfully.");
        CConsole.message("  Passwords under: "+rootf);
        CConsole.message("  Private key file: "+privfile);
        CConsole.message("");
        CConsole.message("Please backup these files.");
        if (write_config) {
            CConsole.message
                ("If you move these files around, also update your config file:");
            CConsole.message
                ("  "+conffile);
        }
    }

    private final static File ensureParent(String path)
    {
        File ret = new File(path);
        File p = ret.getParentFile();
        if ((p != null) && !(p.isDirectory())) {
            p.mkdirs();
        }
        return ret;
    }

    final static boolean validatePrivatePath(String p)
    {
        if (p == null) { return false; }
        File f = new File(p);

        // nothing here -- that's fine.
        if (!f.exists()) {
            return true;
        }
        CConsole.error("Will not overwrite existing file: "+p);
        return false;
    }

    final static boolean validateDbRoot(String rootS)
    {
        if (rootS == null) { return false; }
        File root = new File(rootS);

        // nothing here -- that's fine.
        if (!root.exists()) {
            return true;
        }
        // Check we don't have stuff underneath it already.
        if (!root.isDirectory()) {
            CConsole.error(rootS + " is not a directory");
            return false;
        }

        File pw = new File(root, CConfig.PWDB);
        if (pw.exists()) {
            CConsole.error("Will not overwrite existing file: "+pw);
            return false;
        }
        File pk = new File(root, CConfig.PUBKEY);
        if (pk.exists()) {
            CConsole.error("Will not overwrite existing file: "+pk);
            return false;
        }
        return true;
    }
}


text:
<?php

namespace FivePercent\Component\Reflection;

use Doctrine\Common\Annotations\Reader;

/**
 * Reflection helper
 *
 * @author Vitaliy Zhuk <zhuk2205@gmail.com>
 */
final class Reflection
{
    const TYPE_CLASS        = 0b00000001;
    const TYPE_OBJECT       = 0b00000010;

    /**
     * @var array|\ReflectionClass[]
     */
    private static $classReflections = array();

    /**
     * @var array|\ReflectionObject[]
     */
    private static $objectReflections = array();

    /**
     * Disable constructor
     */
    private function __construct()
    {
    }

    /**
     * Load class reflection
     *
     * @param string|object $class
     *
     * @return \ReflectionClass
     */
    public static function loadClassReflection($class)
    {
        if (is_object($class)) {
            $class = get_class($class);
        }

        if (isset(self::$classReflections[$class])) {
            return self::$classReflections[$class];
        }

        $reflection = new \ReflectionClass($class);

        self::$classReflections[$class] = $reflection;

        return $reflection;
    }

    /**
     * Load method reflection
     *
     * @param string|object $class
     * @param string        $method
     *
     * @return \ReflectionMethod
     */
    public static function loadMethodReflection($class, $method)
    {
        $reflectionClass = self::loadClassReflection($class);

        return $reflectionClass->getMethod($method);
    }

    /**
     * Load object reflection
     *
     * @param object $object
     *
     * @return \ReflectionObject
     */
    public static function loadObjectReflection($object)
    {
        if (!is_object($object)) {
            throw new \InvalidArgumentException(sprintf(
                'Could not load reflection for non object. Given: "%s".',
                gettype($object)
            ));
        }

        $hash = spl_object_hash($object);

        if (isset(self::$objectReflections[$hash])) {
            return self::$objectReflections[$hash];
        }

        $reflection = new \ReflectionObject($object);

        self::$objectReflections[$hash] = $reflection;

        return $reflection;
    }

    /**
     * Get called method from abstract reflection function
     *
     * @param \ReflectionFunctionAbstract $method
     * @param bool                        $closureInfo
     *
     * @return string
     */
    public static function getCalledMethod(\ReflectionFunctionAbstract $method, $closureInfo = true)
    {
        if ($method->isClosure()) {
            if ($closureInfo) {
                return sprintf(
                    'Closure [%s:%d]',
                    $method->getFileName(),
                    $method->getStartLine()
                );
            }

            return 'Closure';
        }

        if ($method instanceof \ReflectionMethod) {
            return sprintf(
                '%s::%s',
                $method->getDeclaringClass()->getName(),
                $method->getName()
            );
        }

        return $method->getName();
    }

    /**
     * Get class properties
     *
     * @param string $class
     * @param bool   $inParents
     * @param int    $filter
     *
     * @return \ReflectionProperty[]
     */
    public static function getClassProperties($class, $inParents = false, $filter = null)
    {
        if ($filter === null) {
            $filter = \ReflectionProperty::IS_PRIVATE
                | \ReflectionProperty::IS_PROTECTED
                | \ReflectionProperty::IS_PUBLIC;
        }

        $reflection = self::loadClassReflection($class);

        if (!$inParents) {
            return $reflection->getProperties($filter);
        }

        $properties = [];

        do {
            $properties = array_merge(
                $reflection->getProperties($filter),
                $properties
            );
        } while ($reflection = $reflection->getParentClass());

        return $properties;
    }

    /**
     * Set value to property
     *
     * @param object|string $object
     * @param string        $property
     * @param mixed  $value
     */
    public static function setPropertyValue($object, $property, $value)
    {
        $ref = self::loadClassReflection($object);

        $refProperty = $ref->getProperty($property);

        if (!$refProperty->isPublic()) {
            $refProperty->setAccessible(true);
        }

        if ($refProperty->isStatic()) {
            $refProperty->setValue($value);
        } else {
            $refProperty->setValue($object, $value);
        }
    }

    /**
     * Set value to properties
     *
     * @param object|string $object
     * @param array         $properties
     */
    public static function setPropertiesValue($object, array $properties)
    {
        foreach ($properties as $name => $value) {
            self::setPropertyValue($object, $name, $value);
        }
    }

    /**
     * Get property value
     *
     * @param object|string $object
     * @param string        $property
     *
     * @return mixed
     */
    public static function getPropertyValue($object, $property)
    {
        $ref = self::loadClassReflection($object);

        $refProperty = $ref->getProperty($property);

        if (!$refProperty->isPublic()) {
            $refProperty->setAccessible(true);
        }

        if ($refProperty->isStatic()) {
            $value = $refProperty->getValue();
        } else {
            $value = $refProperty->getValue($object);
        }

        return $value;
    }

    /**
     * Load class annotations
     *
     * @param Reader        $reader
     * @param string|object $class
     * @param bool          $inParents
     *
     * @return array
     */
    public static function loadClassAnnotations(Reader $reader, $class, $inParents = false)
    {
        $reflection = self::loadClassReflection($class);

        if (!$inParents) {
            return $reader->getClassAnnotations($reflection);
        }

        $annotations = [];

        do {
            $classAnnotations = $reader->getClassAnnotations($reflection);

            foreach ($classAnnotations as $classAnnotation) {
                if (!isset($annotations[get_class($classAnnotation)])) {
                    $annotations[get_class($classAnnotation)] = $classAnnotation;
                }
            }
        } while ($reflection = $reflection->getParentClass());

        return array_values($annotations);
    }

    /**
     * Clear internal storage
     *
     * @param int $mode
     */
    public static function clear($mode = null)
    {
        if (is_numeric($mode)) {
            $mode = self::TYPE_CLASS | self::TYPE_OBJECT;
        }

        if ($mode & self::TYPE_CLASS) {
            self::$classReflections = array();
        }

        if ($mode & self::TYPE_OBJECT) {
            self::$objectReflections = array();
        }
    }
}


text:
#ifndef BOOST_ASIO_DETAIL_ATOMIC_COUNT_HPP
#define BOOST_ASIO_DETAIL_ATOMIC_COUNT_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/config.hpp>

#if !defined(BOOST_ASIO_HAS_THREADS)
// Nothing to include.
#elif defined(BOOST_ASIO_HAS_STD_ATOMIC)
# include <atomic>
#else // defined(BOOST_ASIO_HAS_STD_ATOMIC)
# include <boost/detail/atomic_count.hpp>
#endif // defined(BOOST_ASIO_HAS_STD_ATOMIC)

namespace boost {
namespace asio {
namespace detail {

#if !defined(BOOST_ASIO_HAS_THREADS)
typedef long atomic_count;
inline void increment(atomic_count& a, long b) { a += b; }
#elif defined(BOOST_ASIO_HAS_STD_ATOMIC)
typedef std::atomic<long> atomic_count;
inline void increment(atomic_count& a, long b) { a += b; }
#else // defined(BOOST_ASIO_HAS_STD_ATOMIC)
typedef boost::detail::atomic_count atomic_count;
inline void increment(atomic_count& a, long b) { while (b > 0) ++a, --b; }
#endif // defined(BOOST_ASIO_HAS_STD_ATOMIC)

} // namespace detail
} // namespace asio
} // namespace boost

#endif // BOOST_ASIO_DETAIL_ATOMIC_COUNT_HPP


text:
CFLAGS += -Wall -Wextra -Werror -Os
APPCFLAGS = $(CFLAGS) -Wno-unused-parameter

all: dmapprint test

test: testapp
	@ ./testapp

checkcodes: checkapp
	@echo "iTunes: "
	curl --silent --header "Viewer-Only-Client: 1" http://127.0.0.1:3689/content-codes | ./checkapp | LC_ALL=C sort
	@echo "\niPhoto (note: remaps containers): "
	curl --silent --header "Viewer-Only-Client: 1" http://127.0.0.1:8770/content-codes | ./checkapp | LC_ALL=C sort

dmap_parser.o: dmap_parser.c dmap_parser.h Makefile
	$(CC) $(CFLAGS) -c dmap_parser.c -o $@

testapp: dmap_parser.o test.c
	$(CC) $(APPCFLAGS) -o testapp dmap_parser.o test.c

checkapp: dmap_parser.o checkcodes.c
	$(CC) $(APPCFLAGS) -o checkapp dmap_parser.o checkcodes.c

dmapprint: dmap_parser.o dmapprint.c
	$(CC) $(APPCFLAGS) -o dmapprint dmap_parser.o dmapprint.c

clean:
	rm -f *.o checkapp testapp dmapprint

.PHONY: checkcodes clean test


text:
package com.intellij.codeInsight.intention.impl;

import javax.annotation.Nonnull;

import com.intellij.codeInsight.CodeInsightBundle;
import com.intellij.codeInsight.intention.PsiElementBaseIntentionAction;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.text.LiteralFormatUtil;

public class RemoveLiteralUnderscoresAction extends PsiElementBaseIntentionAction {
  @Override
  public boolean isAvailable(@Nonnull final Project project, final Editor editor, @Nonnull final PsiElement element) {
    final PsiLiteralExpression literalExpression = PsiTreeUtil.getParentOfType(element, PsiLiteralExpression.class, false);
    if (literalExpression == null) return false;

    final PsiType type = literalExpression.getType();
    if (!PsiType.INT.equals(type) && !PsiType.LONG.equals(type) &&
        !PsiType.FLOAT.equals(type) && !PsiType.DOUBLE.equals(type)) return false;

    final String text = literalExpression.getText();
    return text != null && text.contains("_");
  }

  @Override
  public void invoke(@Nonnull final Project project, final Editor editor, @Nonnull final PsiElement element) throws IncorrectOperationException {
    final PsiLiteralExpression literalExpression = PsiTreeUtil.getParentOfType(element, PsiLiteralExpression.class, false);
    if (literalExpression == null) return;

    final String text = literalExpression.getText();
    final String converted = LiteralFormatUtil.removeUnderscores(text);
    if (converted.length() == text.length()) return;

    final PsiExpression replacement = JavaPsiFacade.getElementFactory(project).createExpressionFromText(converted, null);
    literalExpression.replace(replacement);
  }

  @Nonnull
  @Override
  public String getFamilyName() {
    return CodeInsightBundle.message("intention.underscores.in.literals.family");
  }

  @Nonnull
  @Override
  public String getText() {
    return CodeInsightBundle.message("intention.remove.literal.underscores");
  }
}


text:
package nu.xom;

import java.util.ArrayList;
import java.util.List;

/**
 *
 *

 * A read-only list of elements for traversal purposes.
 * Changes to the document from which this list was generated
 * are not reflected in this list. Changes to the individual
 * Element objects in the list are reflected.
 *

 *
 * @author Elliotte Rusty Harold
 * @version 1.0
 *
 *
 */
public final class Elements {

    private List elements = new ArrayList(1);

    // non-public constructor to prevent instantiation
    Elements() {}

    /**
     *

     * Returns the number of elements in the list.
     * This is guaranteed non-negative.
     *

     *
     * @return the number of elements in the list
     */
    public int size() {
        return elements.size();
    }

    /**
     *

     * Returns the indexth element in the list.
     * The first element has index 0. The last element
     * has index size()-1.
     *

     *
     * @param index the element to return
     *
     * @return the element at the specified position
     *
     * @throws IndexOutOfBoundsException if index is negative
     *     or greater than or equal to the size of the list
     */
    public Element get(int index) {
        return (Element) elements.get(index);
    }

    // Add the specified Element object to the list
    void add(Element element) {
        elements.add(element);
    }

}