text:
<?php
/*
Plugin Name: SimpleModal Login
Plugin URI: http://www.studiofuel.com/simplemodal-login/
Description: A modal Ajax login, registration, and password reset feature for WordPress which utilizes jQuery and the SimpleModal jQuery plugin.
Version: 1.1
Author: Noah Cinquini
Author URI: http://www.studiofuel.com
*/

/*  Copyright 2014 Studio Fuel (http://www.studiofuel.com)

    Plugin originally created by Eric Martin (http://www.ericmmartin.com)

	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/

/**
 * Set the wp-content and plugin urls/paths
 */
if (!defined('WP_CONTENT_URL'))
	define('WP_CONTENT_URL', get_option('siteurl') . '/wp-content');
if (!defined('WP_CONTENT_DIR'))
	define('WP_CONTENT_DIR', ABSPATH . 'wp-content');
if (!defined('WP_PLUGIN_URL') )
	define('WP_PLUGIN_URL', WP_CONTENT_URL. '/plugins');
if (!defined('WP_PLUGIN_DIR') )
	define('WP_PLUGIN_DIR', WP_CONTENT_DIR . '/plugins');

if (!class_exists('SimpleModalLogin')) {
	class SimpleModalLogin {
		/**
		 * @var string The plugin version
		 */
		var $version = '1.1';

		/**
		 * @var string The plugin version
		 */
		var $simplemodalVersion = '1.4.3';

		/**
		 * @var string The options string name for this plugin
		 */
		var $optionsName = 'simplemodal_login_options';

		/**
		 * @var string $nonce String used for nonce security
		 */
		var $nonce = 'simplemodal-login-update-options';

		/**
		 * @var string $pluginurl The url to this plugin
		 */
		var $pluginurl = '';

		/**
		 * @var string $pluginpath The path to this plugin
		 */
		var $pluginpath = '';

		/**
		 * @var array $options Stores the options for this plugin
		 */
		var $options = array();

		/**
		 * @var boolean $users_can_register Stores the option for this plugin
		 */
		var $users_can_register = null;

		/**
		 * PHP 4 Compatible Constructor
		 */
		function SimpleModalLogin() {$this->__construct();}

		/**
		 * PHP 5 Constructor
		 */
		function __construct() {
			$name = dirname(plugin_basename(__FILE__));

			//Language Setup
			load_plugin_textdomain('simplemodal-login', false, "$name/I18n/");

			//"Constants" setup
			$this->pluginurl = WP_PLUGIN_URL . "/$name/";
			$this->pluginpath = WP_PLUGIN_DIR . "/$name/";

			//Initialize the options
			$this->get_options();

			//Actions
			add_action('admin_menu', array(&$this, 'admin_menu_link'));

			if (!is_admin()) {
				// attempt to set the test cookie so that the user does not receive the WP cookie error
				$secure = ( 'https' === parse_url( site_url(), PHP_URL_SCHEME ) && 'https' === parse_url( home_url(), PHP_URL_SCHEME ) );
				setcookie( TEST_COOKIE, 'WP Cookie check', 0, COOKIEPATH, COOKIE_DOMAIN, $secure );
				if ( SITECOOKIEPATH != COOKIEPATH )
					setcookie( TEST_COOKIE, 'WP Cookie check', 0, SITECOOKIEPATH, COOKIE_DOMAIN, $secure );

				add_filter('login_redirect', array(&$this, 'login_redirect'), 5, 3);
				add_filter('register', array(&$this, 'register'));
				add_filter('loginout', array(&$this, 'login_loginout'));
				add_action('wp_footer', array($this, 'login_footer'));
				add_action('wp_print_styles', array(&$this, 'login_css'));
				add_action('wp_print_scripts', array(&$this, 'login_js'));
			}
		}

		/**
		 * @desc Adds the options subpanel
		 */
		function admin_menu_link() {
			add_options_page('SimpleModal Login', 'SimpleModal Login', 'manage_options', basename(__FILE__), array(&$this, 'admin_options_page'));
			add_filter('plugin_action_links_' . plugin_basename(__FILE__), array(&$this, 'filter_plugin_actions'), 10, 2 );
		}

		/**
		 * @desc Adds settings/options page
		 */
		function admin_options_page() {
			if (isset($_POST['simplemodal_login_save'])) {
				check_admin_referer($this->nonce);

				$this->options['theme'] = $_POST['theme'];
				$this->options['shortcut'] = (isset($_POST['shortcut']) && $_POST['shortcut'] === 'on') ? true : false;
				$this->options['registration'] = (isset($_POST['registration']) && $_POST['registration'] === 'on') ? true : false;
				$this->options['reset'] = (isset($_POST['reset']) && $_POST['reset'] === 'on') ? true : false;

				$this->save_admin_options();

				echo '

' . __('Success! Your changes were successfully saved!', 'simplemodal-login') . '

';
			}
?>

SimpleModal Login v<?php echo $this->version; ?>

<form method='post' id='simplemodal_login_options'>
<?php wp_nonce_field($this->nonce); ?>

			<?php _e('Theme:', 'simplemodal-login'); ?>

				<select name='theme' id='theme'>
				<?php foreach (glob($this->pluginpath . 'css/*.css') as $cssfile) :
					$cssfile = basename($cssfile);
					$theme = str_replace('.css', '', $cssfile);

					if (false === @file_exists($this->pluginpath . "js/{$theme}.js")) {
						continue;
					}
				?>
					<option value='<?php echo $theme; ?>' <?php echo ($theme == $this->options['theme']) ? "selected='selected'" : ''; ?>><?php echo $theme; ?></option>
				<?php endforeach; ?>
				</select>
				<?php _e('The theme to use.', 'simplemodal-login'); ?>

			<?php _e('User Registration:', 'simplemodal-login'); ?>

				<input type="checkbox" id="registration" name="registration" <?php echo ($this->options['registration'] === true) ? "checked='checked'" : ""; ?>/> <?php _e('Enable', 'simplemodal-login'); ?>

				<?php _e('Select this option to enable the user registration feature in SimpleModal Login. This requires the "Anyone can register" Membership option to be selected on your WordPress General Settings page.', 'simplemodal-login'); ?>

			<?php _e('Password Reset:', 'simplemodal-login'); ?>

				<input type="checkbox" id="reset" name="reset" <?php echo ($this->options['reset'] === true) ? "checked='checked'" : ""; ?>/> <?php _e('Enable', 'simplemodal-login'); ?>

				<?php _e('Select this option to enable the password reset feature in SimpleModal Login.', 'simplemodal-login'); ?>

			<?php _e('Keystroke Shortcut:', 'simplemodal-login'); ?>

				<input type="checkbox" id="shortcut" name="shortcut" <?php echo ($this->options['shortcut'] === true) ? "checked='checked'" : ""; ?>/> <?php _e('Enable', 'simplemodal-login'); ?>

				<?php _e('Select this option to enable the keystroke shortcut of Ctrl+Alt+L to display the log in form. Allows you to invoke the log in form without displaying a "Log In" link.', 'simplemodal-login'); ?>

		<input type='submit' value='Save Changes' name='simplemodal_login_save' class='button-primary' />

</form>

<?php _e('Themes', 'simplemodal-login'); ?>

<?php _e('SimpleModal Login allows you to create your own themes.', 'simplemodal-login'); ?>

<?php _e('To create a new theme you\'ll need to add two files under the simplemodal-login plugin directory: css/THEME.css and js/THEME.js. Replace THEME with the name you would like to use. I suggest using one of the existing themes as a template.', 'simplemodal-login'); ?>

<?php _e('Need Support?', 'simplemodal-login'); ?>

<?php printf(__('For questions, issues or feature requests, please post them in the %s and make sure to tag the post with simplemodal-login.', 'simplemodal-login'), 'WordPress Forum'); ?>

<?php _e('Want To Contribute?', 'simplemodal-login'); ?>

<?php _e('If you would like to contribute, the following is a list of ways you can help:', 'simplemodal-login'); ?>

» <?php _e('Translate SimpleModal Login into your language', 'simplemodal-login'); ?>

» <?php _e('Blog about or link to SimpleModal Login so others can find out about it', 'simplemodal-login'); ?>

» <?php _e('Report issues, provide feedback, request features, etc.', 'simplemodal-login'); ?>

» <?php _e('Review SimpleModal Login on the WordPress Plugins Page', 'simplemodal-login'); ?>

<?php _e('Other Links', 'simplemodal-login'); ?>

» SimpleModal Login on GitHub

» SimpleModal Contact Form (SMCF) - WordPress Plugin

» WP-Paginate - a simple and flexible pagination plugin for posts and comments

<?php
		}

		/**
		 * @desc Loads the SimpleModal Login options. Responsible for
		 * handling upgrades and default option values.
		 * @return array
		 */
		function check_options() {
			$options = null;
			if (!$options = get_option($this->optionsName)) {
				// default options for a clean install
				$options = array(
					'shortcut' => true,
					'theme' => 'default',
					'version' => $this->version,
					'registration' => $this->users_can_register,
					'reset' => true
				);
				update_option($this->optionsName, $options);
			}
			else {
				// check for upgrades
				if (isset($options['version'])) {
					if ($options['version'] < $this->version) {
						// post v1.0 upgrade logic goes here
					}
				}
				else {
					// pre v1.0 updates
					if (isset($options['admin'])) {
						unset($options['admin']);
						$options['shortcut'] = true;
						$options['version'] = $this->version;
						$options['registration'] = $this->users_can_register;
						$options['reset'] = true;
						update_option($this->optionsName, $options);
					}
				}
			}

			return $options;
		}

		/**
		 * @desc Adds the Settings link to the plugin activate/deactivate page
		 * @return string
		 */
		function filter_plugin_actions($links, $file) {
			$settings_link = '' . __('Settings', 'simplemodal-login') . '';
			array_unshift($links, $settings_link); // before other links

			return $links;
		}

		/**
		 * @desc Retrieves the plugin options from the database.
		 */
		function get_options() {
			$options = $this->check_options();
			$this->options = $options;
		}

		/**
		 * @desc Determines if request is an AJAX call
		 * @return boolean
		 */
		function is_ajax() {
			return isset($_SERVER['HTTP_X_REQUESTED_WITH'])
					&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';
		}

		/**
		 * @desc Checks to see if the given plugin is active.
		 * @return boolean
		 */
		function is_plugin_active($plugin) {
			return in_array($plugin, (array) get_option('active_plugins', array()));
		}

		/**
		 * @desc Enqueue's the CSS for the specified theme.
		 */
		function login_css() {
			$style = sprintf('%s.css', $this->options['theme']);
			wp_enqueue_style('simplemodal-login', $this->pluginurl . "css/$style", false, $this->version, 'screen');
			if (false !== @file_exists(TEMPLATEPATH . "simplemodal-login-$style")) {
				wp_enqueue_style('simplemodal-login-form', get_template_directory_uri() . $style, false, $this->version, 'screen');
			}
		}

		/**
		 * @desc Builds the login, registration, and password reset form HTML.
		 * Calls filters for each form, then echo's the output.
		 */
		function login_footer() {
			$output = '
';

			$login_form = $this->login_form();
			$output .= apply_filters('simplemodal_login_form', $login_form);

			if ($this->users_can_register && $this->options['registration']) {
				$registration_form = $this->registration_form();
				$output .= apply_filters('simplemodal_registration_form', $registration_form);
			}

			if ($this->options['reset']) {
				$reset_form = $this->reset_form();
				$output .= apply_filters('simplemodal_reset_form', $reset_form);
			}
			$output .= '
';

			echo $output;
		}

		/**
		 * @desc Builds the login form HTML.
		 * If using the simplemodal_login_form filter, copy and modify this code
		 * into your function.
		 * @return string
		 */
		function login_form() {
			$output = sprintf('
	<form name="loginform" id="loginform" action="%s" method="post">

%s

			%s

			<input type="text" name="log" class="user_login input" value="" size="20" tabindex="10" />

			%s

			<input type="password" name="pwd" class="user_pass input" value="" size="20" tabindex="20" />

',
				site_url('wp-login.php', 'login_post'),
				__('Login', 'simplemodal-login'),
				__('Username', 'simplemodal-login'),
				__('Password', 'simplemodal-login')
			);

			ob_start();
			do_action('login_form');
			$output .= ob_get_clean();

			$output .= sprintf('

<input name="rememberme" type="checkbox" id="rememberme" class="rememberme" value="forever" tabindex="90" /> %s

			<input type="submit" name="wp-submit" value="%s" tabindex="100" />
			<input type="button" class="simplemodal-close" value="%s" tabindex="101" />
			<input type="hidden" name="testcookie" value="1" />

',
				__('Remember Me', 'simplemodal-login'),
				__('Log In', 'simplemodal-login'),
				__('Cancel', 'simplemodal-login')
			);

			if ($this->users_can_register && $this->options['registration']) {
				$output .= sprintf('%s',
					site_url('wp-login.php?action=register', 'login'),
					__('Register', 'simplemodal-login')
				);
			}

			if (($this->users_can_register && $this->options['registration']) && $this->options['reset']) {
				$output .= ' | ';
			}

			if ($this->options['reset']) {
				$output .= sprintf('%s',
					site_url('wp-login.php?action=lostpassword', 'login'),
					__('Password Lost and Found', 'simplemodal-login'),
					__('Lost your password?', 'simplemodal-login')
				);
			}

			$output .= '

		</form>';

			return $output;
		}

		/**
		 * @desc Responsible for loading the necessary scripts and localizing JavaScript messages
		 */
		function login_js() {
			global $wp_scripts;

			if (isset($wp_scripts->registered['jquery-simplemodal'])
					&& version_compare($wp_scripts->registered['jquery-simplemodal']->ver, $this->simplemodalVersion) === -1) {
				wp_deregister_script('jquery-simplemodal'); // remove older versions
			}
			wp_enqueue_script('jquery-simplemodal', $this->pluginurl . 'js/jquery.simplemodal.js', array('jquery'), $this->simplemodalVersion, true);

			$script = sprintf('js/%s.js', $this->options['theme']);
			wp_enqueue_script('simplemodal-login', $this->pluginurl . $script, null, $this->version, true);
			wp_localize_script('simplemodal-login', 'SimpleModalLoginL10n', array(
				'shortcut' => $this->options['shortcut'] ? 'true' : 'false',
				'logged_in' => is_user_logged_in() ? 'true' : 'false',
				'admin_url' => get_admin_url(),
				'empty_username' => __('ERROR: The username field is empty.', 'simplemodal-login'),
				'empty_password' => __('ERROR: The password field is empty.', 'simplemodal-login'),
				'empty_email' => __('ERROR: The email field is empty.', 'simplemodal-login'),
				'empty_all' => __('ERROR: All fields are required.', 'simplemodal-login')
			));

		}

		/**
		 * @desc loginout filter that adds the simplemodal-login class to the "Log In" link
		 * @return string
		 */
		function login_loginout($link) {
			if (!is_user_logged_in()) {
				$link = str_replace('href=', 'class="simplemodal-login" href=', $link);
			}
			return $link;
		}

		/**
		 * @desc login_redirect filter that determines where to redirect the user.
		 * Supports Peter's Login Redirect plugin, if enabled.
		 * @return string
		 */
		function login_redirect($redirect_to, $req_redirect_to, $user) {
			if (!isset($user->user_login) || !$this->is_ajax()) {
				return $redirect_to;
			}
			if ($this->is_plugin_active('peters-login-redirect/wplogin_redirect.php')
					&& function_exists('redirect_to_front_page')) {
				$redirect_to = redirect_to_front_page($redirect_to, $req_redirect_to, $user);
			}
			echo "
$redirect_to
";
			exit();
		}

		/**
		 * @desc register filter that adds the simplemodal-register class to the "Register" link
		 * @return string
		 */
		function register($link) {
			if ($this->users_can_register && $this->options['registration']) {
				if (!is_user_logged_in()) {
					$link = str_replace('href=', 'class="simplemodal-register" href=', $link);
				}
			}
			return $link;
		}

		/**
		 * @desc Builds the registration form HTML.
		 * If using the simplemodal_registration_form filter, copy and modify this code
		 * into your function.
		 * @return string
		 */
		function registration_form() {
			$output = sprintf('
<form name="registerform" id="registerform" action="%s" method="post">

%s

		%s

		<input type="text" name="user_login" class="user_login input" value="" size="20" tabindex="10" />

		%s

		<input type="text" name="user_email" class="user_email input" value="" size="25" tabindex="20" />

',
				site_url('wp-login.php?action=register', 'login_post'),
				__('Register', 'simplemodal-login'),
				__('Username', 'simplemodal-login'),
				__('E-mail', 'simplemodal-login')
			);

			ob_start();
			do_action('register_form');
			$output .= ob_get_clean();

			$output .= sprintf('

%s

		<input type="submit" name="wp-submit" value="%s" tabindex="100" />
		<input type="button" class="simplemodal-close" value="%s" tabindex="101" />

		%s',
				__('A password will be e-mailed to you.', 'simplemodal-login'),
				__('Register', 'simplemodal-login'),
				__('Cancel', 'simplemodal-login'),
				site_url('wp-login.php', 'login'),
				__('Log in', 'simplemodal-login')
			);

			if ($this->options['reset']) {
				$output .= sprintf(' | %s',
					site_url('wp-login.php?action=lostpassword', 'login'),
					__('Password Lost and Found', 'simplemodal-login'),
					__('Lost your password?', 'simplemodal-login')
				);
			}

			$output .= '

</form>';

			return $output;
		}

		/**
		 * @desc Builds the reset password form HTML.
		 * If using the simplemodal_reset_form filter, copy and modify this code
		 * into your function.
		 * @return string
		 */
		function reset_form() {
			$output = sprintf('
	<form name="lostpasswordform" id="lostpasswordform" action="%s" method="post">

%s

			%s

			<input type="text" name="user_login" class="user_login input" value="" size="20" tabindex="10" />

',
				site_url('wp-login.php?action=lostpassword', 'login_post'),
				__('Reset Password', 'simplemodal-login'),
				__('Username or E-mail:', 'simplemodal-login')
			);

			ob_start();
			do_action('lostpassword_form');
			$output .= ob_get_clean();

			$output .= sprintf('

			<input type="submit" name="wp-submit" value="%s" tabindex="100" />
			<input type="button" class="simplemodal-close" value="%s" tabindex="101" />

			%s',
				__('Get New Password', 'simplemodal-login'),
				__('Cancel', 'simplemodal-login'),
				site_url('wp-login.php', 'login'),
				__('Log in', 'simplemodal-login')
			);

			if ($this->users_can_register && $this->options['registration']) {
				$output .= sprintf('| %s', site_url('wp-login.php?action=register', 'login'), __('Register', 'simplemodal-login'));
			}

			$output .= '

	</form>';

			return $output;
		}

		/**
		 * Saves the admin options to the database.
		 */
		function save_admin_options(){
			return update_option($this->optionsName, $this->options);
		}
	}
}

// instantiate the class
if (class_exists('SimpleModalLogin')) {
	$simplemodal_login = new SimpleModalLogin();
	$simplemodal_login->users_can_register = get_option('users_can_register') ? true : false;
}

/*
 * The format of this plugin is based on the following plugin template:
 * http://pressography.com/plugins/wordpress-plugin-template/
 */


text:
set -o errexit
set -x

# create a cache directory
mkdir -p .cache/bare
cd .cache/bare

# create the project using the default settings in cookiecutter.json
cookiecutter ../../ --no-input --overwrite-if-exists use_docker=n "$@"
cd my_awesome_project

# Install OS deps
sudo utility/install_os_dependencies.sh install

# Install Python deps
pip install -r requirements/local.txt

# Lint by running pre-commit on all files
# Needs a git repo to find the project root
git init
git add .
pre-commit run --show-diff-on-failure -a

# run the project's tests
pytest

# Make sure the check doesn't raise any warnings
python manage.py check --fail-level WARNING

if [ -f "package.json" ]
then
    npm install
    if [ -f "gulpfile.js" ]
    then
        npm run build
    fi
fi

# Generate the HTML for the documentation
cd docs && make html

redpajama_set_name: RedPajamaGithub


text:
package reggensc.poschtiapp.persistence;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Random;

import org.dbunit.DatabaseUnitException;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextTestExecutionListener;

import reggensc.poschtiapp.domain.User;
import reggensc.poschtiapp.persistence.config.SpringApplicationConfig;
import reggensc.poschtiapp.testutils.SpringTestDbUnitFlatXmlDataSetLoader;

import com.github.springtestdbunit.TransactionDbUnitTestExecutionListener;
import com.github.springtestdbunit.annotation.DatabaseSetup;
import com.github.springtestdbunit.annotation.DatabaseTearDown;
import com.github.springtestdbunit.annotation.DbUnitConfiguration;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = { SpringApplicationConfig.class })
@TestExecutionListeners({ DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
        TransactionDbUnitTestExecutionListener.class })
@DbUnitConfiguration(dataSetLoader = SpringTestDbUnitFlatXmlDataSetLoader.class)
public class UserDaoIT {

    private static final String DBUNIT_DATASET_LOCATION = "classpath:/dbunit/reference_db.dbunit.xml";

    @Autowired
    private UserDao userDao;

    private static Random random;
    private Long testIdentifier;

    @BeforeClass
    public static void setUpBeforeClass() {
        random = new Random();
    }

    @Before
    public void setUp() {
        testIdentifier = random.nextLong();
    }

    // TODO test validation constraints

    @Test
    @DatabaseSetup(DBUNIT_DATASET_LOCATION)
    @DatabaseTearDown(DBUNIT_DATASET_LOCATION)
    public void testCreate() throws DatabaseUnitException, SQLException, IOException {
        User user = new User();
        user.setEmail(testIdentifier + ".email@testdata.org");
        user.setFirstName(testIdentifier + " firstName");
        user.setLastName(testIdentifier + " lastName");

        userDao.create(user);
    }

    @Test
    @DatabaseSetup(DBUNIT_DATASET_LOCATION)
    @DatabaseTearDown(DBUNIT_DATASET_LOCATION)
    public void testDelete() {
        userDao.deleteById(1L);
    }

}


text:
/**
 * @file NetGraphNode.h
 * @class NetGraphNode
 * @brief Represents a node in the NetGraph
 *
 * @author Clemens-Alexander Brust (ikosa dot de at gmail dot com)
 */

#ifndef CONV_NETGRAPHNODE_H
#define CONV_NETGRAPHNODE_H

#include "Layer.h"
#include "../util/CombinedTensor.h"
#include "NetStatus.h"
#include "../util/TensorViewer.h"

#include "StatLayer.h"
#include "NetGraph.h"

#include <vector>
#include <string>

namespace Conv {

class NetGraphNode {
public:
	explicit NetGraphNode(Layer* layer) : layer(layer) {
		layer->CreateBufferDescriptors(output_buffers);
	}
  explicit NetGraphNode(std::string);

	NetGraphNode(Layer* layer, NetGraphConnection first_connection) : layer(layer) {
		input_connections.push_back(first_connection);
		layer->CreateBufferDescriptors(output_buffers);
	}

  NetGraphNode(std::string configuration, NetGraphConnection first_connection) {

  }

	Layer* layer;
	std::vector<NetGraphConnection> input_connections;
	std::vector<NetGraphBackpropConnection> backprop_connections;
	std::vector<NetGraphBuffer> output_buffers;

	//int unique_id = -1;
  std::string unique_name = "";
	bool is_output = false;
	bool is_input = false;

	// Status
	bool initialized = false;

	// Flags used by NetGraph functions
	bool flag_ff_visited = false;
	bool flag_bp_visited = false;
};

}
#endif


text:
class << ActiveRecord::Base
  def belongs_to_with_deleted(association_id, options = {})
    with_deleted = options.delete :with_deleted
    belongs_to_without_deleted(association_id, options).tap do
      if with_deleted
        reflection = reflect_on_association(association_id)
        association_accessor_methods(reflection,            Caboose::Acts::BelongsToWithDeletedAssociation)
        association_constructor_method(:build,  reflection, Caboose::Acts::BelongsToWithDeletedAssociation)
        association_constructor_method(:create, reflection, Caboose::Acts::BelongsToWithDeletedAssociation)
      end
    end
  end

  def has_many_without_deleted(association_id, options = {}, &extension)
    with_deleted = options.delete :with_deleted
    has_many_with_deleted(association_id, options, &extension).tap do
      if options[:through] && !with_deleted
        reflection = reflect_on_association(association_id)
        collection_reader_method(reflection, Caboose::Acts::HasManyThroughWithoutDeletedAssociation)
        collection_accessor_methods(reflection, Caboose::Acts::HasManyThroughWithoutDeletedAssociation, false)
      end
    end
  end

  alias_method_chain :belongs_to, :deleted
  alias_method :has_many_with_deleted, :has_many
  alias_method :has_many, :has_many_without_deleted
  alias_method :exists_with_deleted?, :exists?
end
ActiveRecord::Base.send :include, Caboose::Acts::Paranoid
ActiveRecord::Base.send :include, Caboose::Acts::ParanoidFindWrapper
class << ActiveRecord::Base
  alias_method_chain :acts_as_paranoid, :find_wrapper
end


text:
<link rel="import" href="../../bower_components/polymer-ts/polymer-ts.html">

<dom-module id="browsix-terminal">
    <template>
        <style>
        #term {
          background: #171a1b;
          font-size: 24px;
          font-family: 'Hack', 'Roboto', 'Helvetica Neue', Helvetica, Arial, sans-serif;
          color: #eeeeec;
          resize:  none;
          padding: 24px;
          outline: 0px solid transparent;
          border: 0px;
          -webkit-box-sizing: border-box;
          -moz-box-sizing: border-box;
          box-sizing: border-box;
          width: 100%;
          height: 100%;
          margin: 0px;
        }
        #term:focus {
          outline: 0px solid transparent;
        }
        </style>

        <textarea
            class="fit" id="term" disabled="[[!editable]]"
            spellcheck="false" autocorrect="off" autocapitalize="off"></textarea>
    </template>
</dom-module>

<script type="text/javascript" src="browsix-terminal.js"></script>


text:
<?php
/*
Template Name: acf test
*/
acf_form_head();
get_header(); ?>

	<?php do_action('foundationPress_before_content'); ?>

	<?php /* The loop */ ?>
			<?php while ( have_posts() ) : the_post(); ?>
                <form id="post" class="acf-form" action="" method="post" >
                	<input type=text length=10>
				<?php acf_form(array(
					'post_id'	=> 'new',
					'field_groups'	=> array( 123 ),
					'form' => false,
					'submit_value'	=> 'Create a new event'
				)); ?>

						<input type="submit" value="Create a new event" />

				</form>

			<?php endwhile; ?>

	<?php do_action('foundationPress_after_content'); ?>

	<?php get_sidebar(); ?>

<?php get_footer(); ?>


text:
Zstandard library files
================================

The __lib__ directory contains several directories.
Depending on target use case, it's enough to include only files from relevant directories.

#### API

Zstandard's stable API is exposed within [zstd.h](zstd.h),
at the root of `lib` directory.

#### Advanced API

Some additional API may be useful if you're looking into advanced features :
- common/error_public.h : transforms `size_t` function results into an `enum`,
                          for precise error handling.
- ZSTD_STATIC_LINKING_ONLY : if you define this macro _before_ including `zstd.h`,
                          it will give access to advanced and experimental API.
                          These APIs shall ___never be used with dynamic library___ !
                          They are not "stable", their definition may change in the future.
                          Only static linking is allowed.

#### ZSTDMT API

To enable multithreaded compression within the library, invoke `make lib-mt` target.
Prototypes are defined in header file `compress/zstdmt_compress.h`.
When linking a program that uses ZSTDMT API against libzstd.a on a POSIX system,
`-pthread` flag must be provided to the compiler and linker.
Note : ZSTDMT prototypes can still be used with a library built without multithread support,
but in this case, they will be single threaded only.

#### Modular build

Directory `common/` is required in all circumstances.
You can select to support compression only, by just adding files from the `compress/` directory,
In a similar way, you can build a decompressor-only library with the `decompress/` directory.

Other optional functionalities provided are :

- `dictBuilder/`  : source files to create dictionaries.
                    The API can be consulted in `dictBuilder/zdict.h`.
                    This module also depends on `common/` and `compress/` .

- `legacy/` : source code to decompress previous versions of zstd, starting from `v0.1`.
              This module also depends on `common/` and `decompress/` .
              Library compilation must include directive `ZSTD_LEGACY_SUPPORT = 1` .
              The main API can be consulted in `legacy/zstd_legacy.h`.
              Advanced API from each version can be found in their relevant header file.
              For example, advanced API for version `v0.4` is in `legacy/zstd_v04.h` .

#### Using MinGW+MSYS to create DLL

DLL can be created using MinGW+MSYS with the `make libzstd` command.
This command creates `dll\libzstd.dll` and the import library `dll\libzstd.lib`.
The import library is only required with Visual C++.
The header file `zstd.h` and the dynamic library `dll\libzstd.dll` are required to
compile a project using gcc/MinGW.
The dynamic library has to be added to linking options.
It means that if a project that uses ZSTD consists of a single `test-dll.c`
file it should be linked with `dll\libzstd.dll`. For example:
```
    gcc $(CFLAGS) -Iinclude/ test-dll.c -o test-dll dll\libzstd.dll
```
The compiled executable will require ZSTD DLL which is available at `dll\libzstd.dll`.

#### Obsolete streaming API

Streaming is now provided within `zstd.h`.
Older streaming API is still available within `deprecated/zbuff.h`.
It will be removed in a future version.
Consider migrating code towards newer streaming API in `zstd.h`.

#### Miscellaneous

The other files are not source code. There are :

 - LICENSE : contains the BSD license text
 - Makefile : script to compile or install zstd library (static and dynamic)
 - libzstd.pc.in : for pkg-config (`make install`)
 - README.md : this file


text:
using System;
using SharpBox2D.Callbacks;
using SharpBox2D.Collision;
using SharpBox2D.Collision.Shapes;
using SharpBox2D.Common;
using SharpBox2D.Dynamics;
using SharpBox2D.Dynamics.Contacts;
using SharpBox2D.Dynamics.Joints;
using SharpBox2D.TestBed.Framework;

namespace SharpBox2D.TestBed.Tests
{

    public class Tumbler : TestbedTest
    {
        private static int MAX_NUM = 800;
        private RevoluteJoint m_joint;
        private int m_count;
        private object _stepLock = new object();

        public override void initTest(bool deserialized)
        {
            {
                BodyDef bd = new BodyDef();
                bd.type = BodyType.DYNAMIC;
                bd.allowSleep = false;
                bd.position.set(0.0f, 10.0f);
                Body body = m_world.createBody(bd);

                PolygonShape shape = new PolygonShape();
                shape.setAsBox(0.5f, 10.0f, new Vec2(10.0f, 0.0f), 0.0f);
                body.createFixture(shape, 5.0f);
                shape.setAsBox(0.5f, 10.0f, new Vec2(-10.0f, 0.0f), 0.0f);
                body.createFixture(shape, 5.0f);
                shape.setAsBox(10.0f, 0.5f, new Vec2(0.0f, 10.0f), 0.0f);
                body.createFixture(shape, 5.0f);
                shape.setAsBox(10.0f, 0.5f, new Vec2(0.0f, -10.0f), 0.0f);
                body.createFixture(shape, 5.0f);

                RevoluteJointDef jd = new RevoluteJointDef();
                jd.bodyA = getGroundBody();
                jd.bodyB = body;
                jd.localAnchorA.set(0.0f, 10.0f);
                jd.localAnchorB.set(0.0f, 0.0f);
                jd.referenceAngle = 0.0f;
                jd.motorSpeed = 0.05f*MathUtils.PI;
                jd.maxMotorTorque = 1e8f;
                jd.enableMotor = true;
                m_joint = (RevoluteJoint) m_world.createJoint(jd);
            }
            m_count = 0;
        }

        public override void step(TestbedSettings settings)
        {
            lock (_stepLock)
            {
                base.step(settings);

                if (m_count < MAX_NUM)
                {
                    BodyDef bd = new BodyDef();
                    bd.type = BodyType.DYNAMIC;
                    bd.position.set(0.0f, 10.0f);
                    Body body = m_world.createBody(bd);

                    PolygonShape shape = new PolygonShape();
                    shape.setAsBox(0.125f, 0.125f);
                    body.createFixture(shape, 1.0f);

                    ++m_count;
                }
            }
        }

        public override string getTestName()
        {
            return "Tumbler";
        }
    }
}


text:
use std::{io, result};

#[derive(Debug)]
pub struct EofError;

pub type Result<T> = result::Result<T, EofError>;

#[derive(Debug)]
pub enum ParseError {
    Eof,
    Invalid,
}

pub type ParseResult<T> = result::Result<T, ParseError>;

impl From<io::Error> for EofError {
    fn from(val: io::Error) -> EofError {
        assert_eq!(val.kind(), io::ErrorKind::UnexpectedEof);
        EofError
    }
}

impl From<io::Error> for ParseError {
    fn from(val: io::Error) -> ParseError {
        assert_eq!(val.kind(), io::ErrorKind::UnexpectedEof);
        ParseError::Eof
    }
}

impl From<EofError> for ParseError {
    fn from(_: EofError) -> ParseError {
        ParseError::Eof
    }
}


text:
<?php

// @TODO two functions that do the exact same thing
if ( ! function_exists( 'tribe_get_single_ical_link' ) ) {
	/**
	 * iCal Link (Single)
	 *
	 * Returns an ical feed for a single event. Must be used in the loop.
	 *
	 * @return string URL for ical for single event.
	 */
	function tribe_get_single_ical_link() {
		return tribe_get_ical_link();
	}
}

if ( ! function_exists( 'tribe_get_ical_link' ) ) {
	/**
	 * iCal Link
	 *
	 * Returns a sitewide ical link
	 *
	 * @return string URL for ical dump.
	 */
	function tribe_get_ical_link() {
		$output = Tribe__Events__iCal::get_ical_link();

		return apply_filters( 'tribe_get_ical_link', $output );
	}

}

if ( ! function_exists( 'tribe_get_gcal_link' ) ) {
	/**
	 * Google Calendar Link
	 *
	 * Returns an "add to Google Calendar link for a single event. Must be used in the loop
	 *
	 * @param int $postId (optional)
	 *
	 * @return string URL for google calendar.
	 */
	function tribe_get_gcal_link( $postId = null ) {
		$postId    = Tribe__Events__Main::postIdHelper( $postId );
		$output    = Tribe__Events__Main::instance()->googleCalendarLink( $postId );

		/**
		 * Filters the Google Calendar gcal link
		 *
		 * @param string $output Gcal link
		 * @param int $postId WP Post ID of an event
		 */
		return apply_filters( 'tribe_get_gcal_link', $output, $postId );
	}
}


text:
import Datastore from 'nedb'

import { error } from 'quiver/error'

import {
  async, promisifyMethods
} from 'quiver/promise'

import {
  configMiddleware
} from 'quiver/component'

const createDb = dbPath => {
  const db = new Datastore({ filename: dbPath })

  return promisifyMethods(db,
    ['loadDatabase', 'find', 'findOne'])
}

export const databaseMiddleware = configMiddleware(
  async(function*(config) {
    if(config.db) return

    const { dbPath } = config

    const db = createDb(dbPath)
    yield db.loadDatabase()

    config.db = db
  }))


text:
const test = require('ava');
const env = require('./setup/environment');
const OBSWebSocket = require('..');
const SHA256 = require('sha.js/sha256');
const WebSocket = require('ws');

let unauthServer;
let authServer;

const password = 'supersecretpassword';

test.before(() => {
  unauthServer = env.makeServer(4444);
  authServer = env.makeServer(4443);

  const salt = 'PZVbYpvAnZut2SS6JNJytDm9';
  const challenge = 'ztTBnnuqrqaKDzRM3xcVdbYm';
  const secret = new SHA256().update(password).update(salt).digest('base64');
  const expectedAuthResponse = new SHA256().update(secret).update(challenge).digest('base64');

  authServer.storedResponses.GetAuthRequired = () => {
    return {
      authRequired: true,
      salt,
      challenge
    };
  };

  authServer.storedResponses.Authenticate = data => {
    return data.auth === expectedAuthResponse ? {} : {status: 'error', error: 'authentication failed'};
  };
});

test.after.always('cleanup', () => {
  authServer.close();
  unauthServer.close();
});

test('connects when auth is not required', async t => {
  const obs = new OBSWebSocket();
  await t.notThrowsAsync(obs.connect({
    address: 'localhost:4444'
  }));
});

test('connects when auth is required', async t => {
  const obs = new OBSWebSocket();
  await t.notThrowsAsync(obs.connect({
    address: 'localhost:4443',
    password
  }));
});

test('fails to connect when an incorrect url is provided', async t => {
  const obs = new OBSWebSocket();
  try {
    await obs.connect({
      address: 'localhost:4442'
    });
    t.fail('expected promise rejection');
  } catch (e) {
    t.is(e.status, 'error');
    t.is(e.code, 'CONNECTION_ERROR');
    t.is(e.error, 'Connection error.');
  }
});

test.cb('rejects a promise when a connection fails', t => {
  const obs = new OBSWebSocket();
  obs.connect({
    address: 'localhost:4442'
  }).then(() => {
    t.fail('Expected a promise rejection when a connection cannot be established.');
  }).catch(err => {
    t.is(err.status, 'error');
    t.is(err.code, 'CONNECTION_ERROR');
    t.is(err.error, 'Connection error.');
    t.end();
  });
});

test('fails to connect when the wrong password is provided', async t => {
  const obs = new OBSWebSocket();
  try {
    await obs.connect({
      address: 'localhost:4443',
      password: 'wrong_password'
    });
    t.fail('expected promise rejection');
  } catch (e) {
    t.is(e.error, 'authentication failed');
  }
});

test.cb('emits ConnectionOpened', t => {
  const obs2 = new OBSWebSocket();
  obs2.on('ConnectionOpened', () => {
    t.end();
  });

  obs2.connect({
    address: 'localhost:4444'
  });
});

test.cb('emits ConnectionClosed', t => {
  const obs2 = new OBSWebSocket();
  obs2.on('ConnectionClosed', () => {
    t.end();
  });

  obs2.connect({
    address: 'localhost:4444'
  }).then(() => {
    obs2.disconnect();
  });
});

test.cb('emits AuthenticationSuccess', t => {
  const obs2 = new OBSWebSocket();
  obs2.on('AuthenticationSuccess', () => {
    t.end();
  });

  obs2.connect({
    address: 'localhost:4443',
    password: 'supersecretpassword'
  });
});

test.cb('emits AuthenticationFailure', t => {
  const obs2 = new OBSWebSocket();
  obs2.on('AuthenticationFailure', () => {
    t.end();
  });

  obs2.connect({
    address: 'localhost:4443',
    password: 'wrong_password'
  }).catch(() => {});
});

test.cb('throws AuthenticationFailure', t => {
  const obs2 = new OBSWebSocket();
  obs2.connect({
    address: 'localhost:4443',
    password: 'wrong_password'
  }).catch(() => {
    t.end();
  });
});

test.cb('emits error when an unhandled socket error occurs', t => {
  const obs2 = new OBSWebSocket();
  obs2.on('ConnectionOpened', () => {
    obs2._socket.onerror('first error message');
    obs2._socket.onerror('second error message');
    t.end();
  });

  let errorCount = 0;

  obs2.on('error', error => {
    errorCount += 1;
    switch (errorCount) {
      case 1:
        t.is(error, 'first error message');
        break;
      case 2:
        t.is(error, 'second error message');
        t.end();
        break;
      default:
        t.fail();
    }
  });

  obs2.connect({
    address: 'localhost:4444'
  });
});

// eslint-disable-next-line quotes
test.cb(`emits 'message' when an unrecognized socket message is received`, t => {
  const obs2 = new OBSWebSocket();
  obs2.on('ConnectionOpened', () => {
    obs2.send('echo', {
      emitMessage: {
        message: 'message'
      }
    });
  });

  obs2.on('message', msg => {
    t.is(msg.message, 'message');
    t.end();
  });

  obs2.connect({
    address: 'localhost:4444'
  });
});

test('closes an existing connection when `connect` is called again', async t => {
  const obs = new OBSWebSocket();

  let open = false;

  // Verify that the previous connection was closed.
  obs.on('ConnectionOpened', () => {
    t.false(open);
    open = true;
  });

  obs.on('ConnectionClosed', () => {
    open = false;
  });

  await t.notThrowsAsync(obs.connect({
    address: 'localhost:4444'
  }));

  t.true(open);

  await t.notThrowsAsync(obs.connect({
    address: 'localhost:4444'
  }));

  t.true(open);
});

test('closes in-flight sockets when `connect` is called', async t => {
  const obs = new OBSWebSocket();
  obs._connected = false;

  // A minimal stub of a socket that is currently connecting.
  let closeCalled = 0;
  obs._socket = {
    readyState: WebSocket.CONNECTING,
    close() {
      closeCalled++;
    }
  };

  await t.notThrowsAsync(obs.connect({
    address: 'localhost:4444'
  }));

  t.is(closeCalled, 1);
});


text:
package com.danielkueffer.filehosting.desktop.repository.client;

import java.io.File;
import java.io.InputStream;

/**
 * The file client
 *
 * @author dkueffer
 *
 */
public interface FileClient {
	String uploadFile(String url, File file, String fileName, int parent,
			String authToken);

	String createFolder(String url, String folderName, int parent,
			String authToken);

	InputStream getFileByPath(String url, String authToken);

	String getFilesByUser(String url, String authToken);

	String deleteFile(String url, String authToken);

	String getDeletedFilesByUser(String url, String authToken);

	String updateDeletedFiles(String url, String authToken);
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Z. Mykol. 58(2): 197 (1992)

#### Original name
Conocybe cettoiana Hauskn. & Enderle

### Remarks
null


text:
package db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class MyWeatherDBHelper extends SQLiteOpenHelper
{
	private static final String CREATE_T_PROVINCE = "create table t_province (" +
			"id integer primary key autoincrement," +
			"name text not NULL," +
			"code text not NULL)";

	private static final String CREATE_T_CITY = "create table t_city (" +
			"id integer primary key autoincrement," +
			"name text not NULL," +
			"code text not NULL," +
			"province_code text not NULL)";

	private static final String CREATE_T_COUNTY = "create table t_county (" +
			"id integer primary key autoincrement," +
			"name text not NULL," +
			"code text not NULL," +
			"city_code text not NULL)";

	public MyWeatherDBHelper(Context context,String strName,CursorFactory factory,int nVersion)
	{
		super(context,strName,factory,nVersion);
	}

	@Override
	public void onCreate(SQLiteDatabase db)
	{
		db.execSQL(CREATE_T_PROVINCE);
		db.execSQL(CREATE_T_CITY);
		db.execSQL(CREATE_T_COUNTY);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db,int nOldVersion,int nNewVersion)
	{
	}
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Boletim da Chácara Botânica de Itu 1: 32 (1994)

#### Original name
Polyporus skamanius (Murrill) Murrill, 1946

### Remarks
null


text:
//  (C) Copyright Edward Diener 2011,2012,2013
//  Use, modification and distribution are subject to the Boost Software License,
//  Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt).

#if !defined(BOOST_TTI_DETAIL_TEMPLATE_HPP)
#define BOOST_TTI_DETAIL_TEMPLATE_HPP

#include <boost/config.hpp>
#include <boost/mpl/has_xxx.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/debug/assert.hpp>
#include <boost/preprocessor/facilities/is_empty.hpp>

#define BOOST_TTI_DETAIL_IS_HELPER_BOOST_PP_NIL

#define BOOST_TTI_DETAIL_IS_NIL(param) \
  BOOST_PP_IS_EMPTY \
    ( \
    BOOST_PP_CAT(BOOST_TTI_DETAIL_IS_HELPER_,param) \
    ) \
/**/

#define BOOST_TTI_DETAIL_TRAIT_ASSERT_NOT_NIL(trait,name,params) \
  BOOST_PP_ASSERT_MSG(0, "The parameter must be BOOST_PP_NIL") \
/**/

#define BOOST_TTI_DETAIL_TRAIT_CHECK_IS_NIL(trait,name,params) \
  BOOST_PP_IIF \
    ( \
    BOOST_TTI_DETAIL_IS_NIL(params), \
    BOOST_TTI_DETAIL_TRAIT_HAS_TEMPLATE, \
    BOOST_TTI_DETAIL_TRAIT_ASSERT_NOT_NIL \
    ) \
    (trait,name,params) \
/**/

#define BOOST_TTI_DETAIL_TRAIT_HAS_TEMPLATE(trait,name,params) \
  BOOST_MPL_HAS_XXX_TEMPLATE_NAMED_DEF(BOOST_PP_CAT(trait,_detail_mpl), name, false) \
  template<class BOOST_TTI_DETAIL_TP_T> \
  struct trait : \
    BOOST_PP_CAT(trait,_detail_mpl)<BOOST_TTI_DETAIL_TP_T> \
    { \
    }; \
/**/

#endif // !BOOST_TTI_DETAIL_TEMPLATE_HPP


text:
using System;
using System.Buffers;
using System.Diagnostics.Contracts;
using System.Text;

namespace Benchmarks.Utilities
{
    public class ClassSingleSegmentBuffer : IBufferWriter<byte>
    {
        private readonly byte[] _buffer;
        private int _written;

        public ClassSingleSegmentBuffer(byte[] buffer)
        {
            _buffer = buffer;
            _written = 0;
        }

        public void Advance(int bytes) => _written += bytes;

        [Pure]
        public Memory<byte> GetMemory(int sizeHint = 0) => _buffer.AsMemory(_written);

        [Pure]
        public Span<byte> GetSpan(int sizeHint) => _buffer.AsSpan(_written);

        public byte[] ToArray() => _buffer.AsSpan(0, _written).ToArray();

        public void Reset() => _written = 0;

        [Pure]
        public int Length => _written;

        [Pure]
        public ReadOnlySequence<byte> GetReadOnlySequence() => new(_buffer, 0, _written);

        public override string ToString() => Encoding.UTF8.GetString(_buffer.AsSpan(0, _written).ToArray());
    }
}


text:
from project.settings.base import *
import dj_database_url

DEBUG = False

DATABASES['default'] = dj_database_url.config()

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
# SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Allow all host headers
ALLOWED_HOSTS = ['*']


text:
/*
 * Problem 5. Generic class
 * Write a generic class GenericList<T> that keeps a list of elements of some parametric type T.
 * Keep the elements of the list in an array with fixed capacity which is given as parameter in the class constructor.
 * Implement methods for adding element, accessing element by index, removing element by index, inserting element at given position, clearing the list, finding element by its value and ToString().
 * Check all input parameters to avoid accessing elements at invalid positions.
*/
namespace _02.GenericClassProject
{
    using System;
    using System.Text;
    class GenericList<T>
        where T : IComparable // Generic constraints
    {
        private T[] elements;
        private int count = 0;
        private int capacity;

        // you can not create a GenericList without giving an initial capacity
        public GenericList(int capacity)
        {
            this.Capacity = capacity;
            elements = new T[capacity];
        }

        public int Capacity
        {
            get
            {
                return this.capacity;
            }
            private set
            {
                this.capacity = value;
            }
        }
        public int Count
        {
            get
            {
                return this.count;
            }
        }
        // this method will add the element at the end of the array
        public void Add(T addElement)
        {
            // check if there is enough free space in the array
            if (count >= Capacity)
            {
                AutoGrow();
            }
            this.elements[count] = addElement;
            this.count++;
        }

        // removing element by index
        public void RemoveAt(int index)
        {
            if (index >= count || index < 0)
            {
                throw new IndexOutOfRangeException(String.Format(
                        "Invalid index: {0}.", index));
            }
            //re-write all elements with one positon forward
            for (int i = index; i < this.count - 1; i++)
            {
                elements[i] = elements[i + 1];
            }
            this.count--;
        }

        // inserting element at given position
        public void InsertAt(int index, T addElement)
        {
            if (index > count || index < 0)
            {
                throw new IndexOutOfRangeException(String.Format(
                        "Invalid index: {0}.", index));
            }

            if ((count + 1) >= elements.Length)
            {
                AutoGrow();
            }

            if (index == count)
            {
                elements[index] = addElement;
                count++;
                return;
            }

            //re-write all elements with one positon backwards, and only after that operation adding the new one
            for (int i = count - 1; i >= index; i--)
            {
                elements[i + 1] = elements[i];
            }

            elements[index] = addElement;
            count++;
        }

        public void ClearList()
        {
            // this will save the elements, but they can not be accessed
            count = 0;
        }

        // finding element by its value
        public int FindElementIndex(T findElement)
        {
            for (int i = 0; i < this.count; i++)
            {
                if (this.elements[i].Equals(findElement))
                {
                    return i; // this will return the index of the element
                }
            }
            return -1;
        }
        public T this[int index]
        {
            get
            {
                if (index >= count || index < 0)
                {
                    throw new IndexOutOfRangeException(String.Format(
                        "Invalid index: {0}.", index));
                }
                T result = elements[index];
                return result;
            }
        }
        public override string ToString()
        {
            StringBuilder result = new StringBuilder();
            if (count > 0)
            {
                for (int i = 0; i < this.count; i++)
                {
                    result.AppendFormat("{0}", this.elements[i]);
                    if (i + 1 < this.count)
                    {
                        result.Append(", ");
                    }
                }

                return result.ToString();
            }
            else
            {
                return "The Generic List is empty";
            }
        }

        // Problem 6. Auto-grow
        // Implement auto-grow functionality: when the internal array is full, create a new array of double size and move all elements to it.
        private void AutoGrow()
        {
            T[] newArr = new T[this.Capacity * 2];

            Array.Copy(this.elements, newArr, count);

            this.elements = newArr;
            this.Capacity *= 2;
        }

        /*
         * Problem 7. Min and Max
         * Create generic methods Min<T>() and Max<T>() for finding the minimal and maximal element in the GenericList<T>.
         * You may need to add a generic constraints for the type T.
        */
        public T MinT()
        {
            if (this.count == 0)
            {
                throw new ApplicationException("Searching min value in an empty Generic List!");
            }

            // setting initial value and than comparing all elements of the array
            T min = elements[0];

            for (int i = 1; i < this.count; i++)
            {
                if (min.CompareTo(elements[i]) > 0)
                {
                    min = elements[i];
                }
            }

            return min;
        }

        public T MaxT()
        {
            if (this.count == 0)
            {
                throw new ApplicationException("Searching max value in an empty Generic List!");
            }

            T max = elements[0];

            for (int i = 1; i < this.count; i++)
            {
                if (max.CompareTo(elements[i]) < 0)
                {
                    max = elements[i];
                }
            }

            return max;
        }
    }
}


text:
package org.sleuthkit.autopsy.keywordsearch;

import java.awt.Component;
import java.io.File;
import org.sleuthkit.autopsy.coreutils.Logger;
import javax.swing.JOptionPane;
import org.openide.windows.WindowManager;

class KeywordSearchUtil {

    public enum DIALOG_MESSAGE_TYPE {

        ERROR, WARN, INFO
    };
    private static final Logger logger = Logger.getLogger(KeywordSearchUtil.class.getName());

    /**
     * Return a quoted version of the query if the original query is not quoted
     *
     * @param query the query to check if it is quoted
     *
     * @return quoted query
     */
    public static String quoteQuery(String query) {
        //ensure a single pair of quotes around the query
        final int length = query.length();
        if (length > 1 && query.charAt(0) == '"'
                && query.charAt(length - 1) == '"') {
            return query;
        }

        return "\""+query+"\"";
    }

    /**
     * Perform standard escaping of Solr chars such as /+-&|!(){}[]^"~*?:\
     * before sending over net does not escape the outter enclosing double
     * quotes, if present
     *
     * @param query to be encoded
     *
     * @return encoded query
     */
    public static String escapeLuceneQuery(String query) {
        String queryEscaped = null;
        String inputString = query.trim();

        if (inputString.length() == 0) {
            return inputString;
        }

        final String ESCAPE_CHARS = "/+-&|!(){}[]^\"~*?:\\";
        StringBuilder sb = new StringBuilder();
        final int length = inputString.length();

        //see if the quoery is quoted
        boolean quotedQuery = false;
        if (length > 1 && inputString.charAt(0) == '"' && inputString.charAt(length - 1) == '"') {
            quotedQuery = true;
        }

        for (int i = 0; i < length; ++i) {
            final char c = inputString.charAt(i);

            if (ESCAPE_CHARS.contains(Character.toString(c))) {
                //escape if not outter quotes
                if (quotedQuery == false || (i > 0 && i < length - 1)) {
                    sb.append("\\");
                }
            }
            sb.append(c);
        }
        queryEscaped = inputString = sb.toString();

        return queryEscaped;
    }

    public static void displayDialog(final String title, final String message, final DIALOG_MESSAGE_TYPE type) {
        int messageType;
        if (type == DIALOG_MESSAGE_TYPE.ERROR) {
            messageType = JOptionPane.ERROR_MESSAGE;
        } else if (type == DIALOG_MESSAGE_TYPE.WARN) {
            messageType = JOptionPane.WARNING_MESSAGE;
        } else {
            messageType = JOptionPane.INFORMATION_MESSAGE;
        }

        final Component parentComponent = WindowManager.getDefault().getMainWindow();
        JOptionPane.showMessageDialog(
                parentComponent,
                message,
                title,
                messageType);
    }

    public static boolean displayConfirmDialog(final String title, final String message, final DIALOG_MESSAGE_TYPE type) {
        int messageType;
        if (type == DIALOG_MESSAGE_TYPE.ERROR) {
            messageType = JOptionPane.ERROR_MESSAGE;
        } else if (type == DIALOG_MESSAGE_TYPE.WARN) {
            messageType = JOptionPane.WARNING_MESSAGE;
        } else {
            messageType = JOptionPane.INFORMATION_MESSAGE;
        }
        if (JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION, messageType) == JOptionPane.YES_OPTION) {
            return true;
        } else {
            return false;
        }
    }

    static KeywordSearchQuery getQueryForKeyword(Keyword keyword, KeywordList keywordList) {
        KeywordSearchQuery query = null;
        if (keyword.searchTermIsLiteral()) {
            // literal, exact match
            if (keyword.searchTermIsWholeWord()) {
                query = new LuceneQuery(keywordList, keyword);
                query.escape();
            } // literal, substring match
            else {
                query = new TermsComponentQuery(keywordList, keyword);
                query.escape();
                query.setSubstringQuery();
            }
        } // regexp
        else {
            query = new RegexQuery(keywordList, keyword);
        }
        return query;
    }

    /**
     * Is the Keyword Search list at absPath an XML list?
     *
     * @param absPath
     *
     * @return yes or no
     */
    static boolean isXMLList(String absPath) {
        //TODO: make this more robust, if necessary
        return new File(absPath).getName().endsWith(".xml"); //NON-NLS
    }
}