text:
package com.palantir.atlasdb.util;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

import com.google.common.collect.ImmutableMap;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import org.junit.Test;

public class MetricNameUtilsTest {
    private static final String TAG_KEY_1 = "tag1";
    private static final String TAG_VALUE_1 = "tagVal1";
    private static final String METRIC_NAME = "metricName";
    private static final String TAG_VALUE_2 = "tagVal2";
    private static final String TAG_KEY_2 = "tag2";

    @Test
    public void shouldReturnNameWithSingleTag() throws Exception {
        String metricName = MetricNameUtils.getMetricName(METRIC_NAME, ImmutableMap.of(TAG_KEY_1, TAG_VALUE_1));
        assertThat(metricName).isEqualTo("metricName;tag1=tagVal1");
    }

    @Test
    public void shouldReturnNameWithMultipleTags() throws Exception {
        String metricName = MetricNameUtils.getMetricName(
                METRIC_NAME, ImmutableMap.of(TAG_KEY_2, TAG_VALUE_2, TAG_KEY_1, TAG_VALUE_1));
        assertThat(metricName).isIn("metricName;tag1=tagVal1;tag2=tagVal2", "metricName;tag2=tagVal2;tag1=tagVal1");
    }

    @Test
    public void shouldThrowIfMetricNameContainsSemiColon() throws Exception {
        assertThatThrownBy(() -> MetricNameUtils.getMetricName(
                        "metric;Name", ImmutableMap.of(TAG_KEY_1, TAG_VALUE_1, TAG_KEY_2, TAG_VALUE_2)))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessage("The metric name: metric;Name contains the forbidden character: ;");
    }

    @Test
    public void shouldThrowIfMetricNameContainsEqualSign() throws Exception {
        assertThatThrownBy(() -> MetricNameUtils.getMetricName(
                        "metric=Name", ImmutableMap.of(TAG_KEY_1, TAG_VALUE_1, TAG_KEY_2, TAG_VALUE_2)))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessage("The metric name: metric=Name contains the forbidden character: =");
    }

    @Test
    public void shouldThrowIfFirstMetricTagKeyContainsSemiColon() throws Exception {
        assertThatThrownBy(() -> MetricNameUtils.getMetricName(
                        METRIC_NAME, ImmutableMap.of("tag;1", TAG_VALUE_1, TAG_KEY_2, TAG_VALUE_2)))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessage("The tag key name: tag;1 contains the forbidden character: ;");
    }

    @Test
    public void shouldThrowIfFirstMetricTagValueContainsSemiColon() throws Exception {
        assertThatThrownBy(() -> MetricNameUtils.getMetricName(
                        METRIC_NAME, ImmutableMap.of(TAG_KEY_1, "tag;Val1", TAG_KEY_2, TAG_VALUE_2)))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessage("The tag value name: tag;Val1 contains the forbidden character: ;");
    }

    @Test
    public void shouldThrowIfFirstMetricTagKeyContainsEquals() throws Exception {
        assertThatThrownBy(() -> MetricNameUtils.getMetricName(
                        METRIC_NAME, ImmutableMap.of("tag=1", TAG_VALUE_1, TAG_KEY_2, TAG_VALUE_2)))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessage("The tag key name: tag=1 contains the forbidden character: =");
    }

    @Test
    public void shouldThrowIfFirstMetricTagValueContainsEquals() throws Exception {
        assertThatThrownBy(() -> MetricNameUtils.getMetricName(
                        METRIC_NAME, ImmutableMap.of(TAG_KEY_1, "tag=Val1", TAG_KEY_2, TAG_VALUE_2)))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessage("The tag value name: tag=Val1 contains the forbidden character: =");
    }

    @Test
    public void shouldThrowIfSecondMetricTagValueContainsEquals() throws Exception {
        assertThatThrownBy(() -> MetricNameUtils.getMetricName(
                        METRIC_NAME, ImmutableMap.of(TAG_KEY_1, TAG_VALUE_1, TAG_KEY_2, "tagVal=2")))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessage("The tag value name: tagVal=2 contains the forbidden character: =");
    }

    @Test
    public void shouldThrowForFirstEncounteredErrorMultipleMetricArgsContainInvalidCharacters() throws Exception {
        assertThatThrownBy(() -> MetricNameUtils.getMetricName(
                        "metric;Name", ImmutableMap.of("tag;1", TAG_VALUE_1, TAG_KEY_2, "tagVal=2")))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessage("The metric name: metric;Name contains the forbidden character: ;");
    }

    @Test
    public void shouldReturnANameIfTryingToRegisterMetricWithExactlyTenTags() throws Exception {
        Map<String, String> tags =
                IntStream.range(0, 10).boxed().collect(Collectors.toMap(i -> "tag" + i, i -> "tagVal" + i));
        assertThat(tags).hasSize(10);
        assertThat(MetricNameUtils.getMetricName(METRIC_NAME, tags)).contains(METRIC_NAME);
    }

    @Test
    public void shouldThrowIfTryingToRegisterMetricWithMoreThanTenTags() throws Exception {
        Map<String, String> tags =
                IntStream.range(0, 11).boxed().collect(Collectors.toMap(i -> "tag" + i, i -> "tagVal" + i));
        assertThat(tags).hasSize(11);
        assertThatThrownBy(() -> MetricNameUtils.getMetricName(METRIC_NAME, tags))
                .isInstanceOf(IllegalArgumentException.class)
                .hasMessage("Too many tags set on the metric metricName. "
                        + "Maximum allowed number of tags is 10, found 11.");
    }
}


text:
<?php
function testAssignmentExpressionFromMethodInvocation($object)
{
    $foo = $object->bar();
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/**
 * Provides an API for managing common file operations such as listing directory
 * contents, renaming, and deleting files. Using this class, extended file
 * properties will be correctly re-linked to files that are renamed or moved,
 * and file and folder names and paths will be verified to be correct.
 *
 * Also note that file and folder paths are specified relative to `FileManager::root()`.
 *
 * Usage:
 *
 *     <?php
 *
 *     // Get listing of files/homepage directory
 *     $list = FileManager::dir ('homepage');
 *
 *     // Delete files/homepage/photo1.jpg
 *     $res = FileManager::unlink ('homepage/photo1.jpg');
 *
 *     ?>
 */
class FileManager {
	/**
	 * The path to the root directory to store files.
	 */
	public static $root = null;

	/**
	 * The web path to the root directory.
	 */
	public static $webroot = null;

	/**
	 * The error message if an error occurs in one of the static methods.
	 */
	public static $error;

	/**
	 * Returns the $root. Sets $root if not yet set.
	 */
	public static function root () {
                self::$webroot = self::$webroot ? self::$webroot : '/' . conf('Paths','filemanager_path') . '/';
		if (self::$root === null) {
			self::$root = getcwd () . '/' . conf('Paths','filemanager_path') . '/';
		}
		return self::$root;
	}

	/**
	 * Adds the $webroot to a file/folder path, if not present.
	 * Examples:
	 *
	 *     foo.txt  -> /files/foo.txt
	 *     /foo.txt -> /files/foo.txt
	 */
	public static function add_webroot ($path) {
                self::$webroot = self::$webroot ? self::$webroot : '/' . conf('Paths','filemanager_path') . '/';
		$path = (strpos ($path, '/') === 0) ? $path : '/' . $path;
		if (! preg_match ('/^' . preg_quote (self::$webroot, '/') . '/', $path)) {
			$path = self::$webroot . ltrim ($path, '/');
		}
		return $path;
	}

	/**
	 * Removes the $webroot from a file/folder path.
	 * Examples:
	 *
	 *     /files/foo.txt -> foo.txt
	 *     files/foo.txt  -> foo.txt
	 */
	public static function strip_webroot ($path) {
                self::$webroot = self::$webroot ? self::$webroot : '/' . conf('Paths','filemanager_path') . '/';
		$root = preg_quote (self::$webroot, '/');
		$root = preg_replace ('|^\\\/|', '\\/?', $root);
		return preg_replace ('/^' . $root . '/', '', $path);
	}

	/**
	 * Returns the last error message.
	 */
	public static function error () {
		return self::$error;
	}

	/**
	 * List all directories and files in a directory. Returns an array
	 * with 'dirs' and 'files'. Each directory has a 'name', 'path',
	 * and 'mtime'. Each file also has 'fsize'.
	 */
	public static function dir ($path = '') {
		if (! self::verify_folder ($path)) {
			self::$error = __ ('Invalid folder name');
			return false;
		}

		$d = dir (self::root () . $path);
		if (! $d) {
			self::$error = __ ('Unable to read folder');
			return false;
		}

		$out = array ('dirs' => array (), 'files' => array ());
		while (false !=  ($entry = $d->read ())) {
			if (preg_match ('/^\./', $entry)) {
				continue;
			} elseif (is_dir (self::root () . $path . '/' . $entry)) {
				$out['dirs'][] = array (
					'name' => $entry,
					'path' => ltrim ($path . '/' . $entry, '/'),
					'mtime' => filemtime (self::root () . $path . '/' . $entry)
				);
			} else {
				$out['files'][] = array (
					'name' => $entry,
					'path' => ltrim ($path . '/' . $entry, '/'),
					'mtime' => filemtime (self::root () . $path . '/' . $entry),
					'fsize' => filesize (self::root () . $path . '/' . $entry)
				);
			}
		}
		$d->close ();
		usort ($out['dirs'], array ('FileManager', 'fsort'));
		usort ($out['files'], array ('FileManager', 'fsort'));
		return $out;
	}

	/**
	 * Search for all directories and files that match a query. Returns an
	 * array with 'dirs' and 'files'. Each directory has a 'name', 'path',
	 * and 'mtime'. Each file also has 'fsize'.
	 */
	public static function search ($query) {
		$d = dir (self::root ());

		$out = ['dirs' => [], 'files' => []];

		self::match_recursive ('', $query, $out);

		return $out;
	}

	private static function match_recursive ($path, $query, &$out) {
		$current = rtrim (self::root () . $path, '/');
		$list = scandir ($current);

		$query = strtolower ($query);

		foreach ($list as $entry) {
			if (preg_match ('/^\./', $entry)) {
				continue;
			}

			$lower = strtolower ($entry);

			if (is_dir ($current . '/' . $entry)) {
				if (strpos ($lower, $query) !== false) {
					$out['dirs'][] = [
						'name' => $entry,
						'path' => ltrim ($path . '/' . $entry, '/'),
						'mtime' => filemtime ($current . '/' . $entry)
					];
				}

				self::match_recursive ($path . '/' . $entry, $query, $out);
			} elseif (strpos ($lower, $query) !== false) {
				$out['files'][] = [
					'name' => $entry,
					'path' => ltrim ($path . '/' . $entry, '/'),
					'mtime' => filemtime ($current . '/' . $entry),
					'fsize' => filesize ($current . '/' . $entry)
				];
			}
		}
	}

	/**
	 * Delete a file.
	 */
	public static function unlink ($file) {
		if (self::verify_folder ($file)) {
			self::$error = __ ('Unable to delete folders');
			return false;
		} elseif (! self::verify_file ($file)) {
			self::$error = __ ('File not found');
			return false;
		} elseif (! self::verify_file_name (basename ($file))) {
			self::$error = __ ('Invalid file name');
			return false;
		} elseif (! unlink (self::root () . $file)) {
			self::$error = __ ('Unable to delete') . ' ' . $file;
			return false;
		}
		self::prop_delete ($file);
		return true;
	}

	/**
	 * Rename a file or folder.
	 */
	public static function rename ($file, $new_name) {
		if (self::verify_folder ($file)) {
			if (! self::verify_folder_name ($new_name)) {
				self::$error = __ ('Invalid folder name');
				return false;
			}
			$parts = explode ('/', $file);
			$old = array_pop ($parts);
			$new = preg_replace ('/' . preg_quote ($old) . '$/', $new_name, $file);
			if (! rename (self::root () . $file, self::root () . $new)) {
				self::$error = __ ('Unable to rename') . ' ' . $file;
				return false;
			}
			self::prop_rename ($file, $new, true);
			return true;
		} elseif (self::verify_file ($file)) {
			if (! self::verify_file_name ($new_name)) {
				self::$error = __ ('Invalid file name');
				return false;
			}
			$parts = explode ('/', $file);
			$old = array_pop ($parts);
			$new = preg_replace ('/' . preg_quote ($old) . '$/', $new_name, $file);
			if (! rename (self::root () . $file, self::root () . $new)) {
				self::$error = __ ('Unable to rename') . ' ' . $file;
				return false;
			}
			FileManager::prop_rename ($file, $new);
			return true;
		}
		self::$error = __ ('File not found');
		return false;
	}

	/**
	 * Move a file to a new folder.
	 */
	public static function move ($file, $folder) {
		if (! self::verify_file ($file)) {
			self::$error = __ ('File not found');
			return false;
		}

		if (! self::verify_folder ($folder)) {
			self::$error = __ ('Invalid folder');
			return false;
		}

		$new = $folder . '/' . basename ($file);
		$new = ltrim ($new, '/');
		if (! rename (self::root () . $file, self::root () . $new)) {
			self::$error = __ ('Unable to move') . ' ' . $file;
			return false;
		}

		self::prop_rename ($file, $new);
		return true;
	}

	/**
	 * Touch a file. If it exists, updates its modification
	 * time. If not, creates a blank file.
	 */
	public static function touch ($file) {
		if (! self::verify_file ($file)) {
			$basename = basename ($file);
			$path = pathinfo ($file, PATHINFO_DIRNAME);
			if (! self::verify_folder ($path)) {
				self::$error = __ ('Invalid folder');
				return false;
			}
			if (! self::verify_file_name ($basename)) {
				self::$error = __ ('Invalid file name');
				return false;
			}
		}

		return touch (self::root () . $file);
	}

	/**
	 * Make a new folder.
	 */
	public static function mkdir ($folder) {
		$parts = explode ('/', $folder);
		$newdir = array_pop ($parts);
		$path = preg_replace ('/\/?' . preg_quote ($newdir) . '$/', '', $folder);
		if (! self::verify_folder ($path)) {
			self::$error = __ ('Invalid location');
			return false;
		} elseif (! self::verify_folder_name ($newdir)) {
			self::$error = __ ('Invalid folder name');
			return false;
		} elseif (is_dir (self::root () . $folder)) {
			self::$error = __ ('Folder already exists') . ' ' . $folder;
			return false;
		} elseif (! mkdir (self::root () . $folder)) {
			self::$error = __ ('Unable to create folder') . ' ' . $folder;
			return false;
		}
		chmod (self::root () . $folder, 0777);
		return true;
	}

	/**
	 * Remove a folder. The folder must be empty, or recursive
	 * must be set to true to remove non-empty folders.
	 */
	public static function rmdir ($folder, $recursive = false) {
		if (! self::verify_folder ($folder)) {
			self::$error = __ ('Invalid folder name');
			return false;
		}

		$list = self::dir ($folder);
		if (! $list) {
			self::$error = __ ('Unable to verify folder');
			return false;
		}

		if (! $recursive) {
			if (count ($list['dirs']) > 0 || count ($list['files']) > 0) {
				self::$error = __ ('Folder must be empty');
				return false;
			}
			if (! rmdir (self::root () . $folder)) {
				self::$error = __ ('Unable to delete folder');
				return false;
			}
			return true;
		}

		return self::rmdir_recursive (self::root () . $folder);
	}

	/**
	 * Handles recursively deleting folders for `FileManager::rmdir()`.
	 */
	private static function rmdir_recursive ($path) {
		if (preg_match ('|/\.+$|', $path)) {
			return;
		}
		return is_file ($path)
			? unlink ($path)
			: array_map (array ('FileManager', 'rmdir_recursive'), glob ($path . '/{,.}*', GLOB_BRACE)) == rmdir ($path);
	}

	/**
	 * Returns a list of folders recursively under the specified
	 * folder path.
	 */
	public static function list_folders ($path = '') {
		$folders = array ();
                $root = conf('Paths','filemanager_path');
		if (! empty ($path)) {
			$rpath = $root . "/" . $path;
			$epath = $path . '/';
		} else {
			$rpath = $root;
			$epath = '';
		}
		$d = dir ($rpath);
		if (! $d) {
			return array ();
		}
		while (false !== ($file = $d->read ())) {
			$files[] = $file;
		}
		$d->close ();

		foreach ($files as $file) {
			if (strpos ($file, '.') === 0 || ! @is_dir ($rpath . '/' . $file)) {
				continue;
			}
			$folders[] = $epath . $file;
			$subs = self::list_folders ($epath . $file);
			foreach ($subs as $sub) {
				$folders[] = $sub;
			}
		}
		return $folders;
	}

	/**
	 * Verify that the specified folder is valid, and exists
	 * inside a certain root folder.
	 */
	public static function verify_folder ($path, $root = false) {
		$root = ($root) ? rtrim ($root) : rtrim (self::root ());
		$path = trim ($path, '/');
		if (strpos ($path, '..') !== false) {
			return false;
		}
		if (! @is_dir ($root . '/' . $path)) {
			return false;
		}
		return true;
	}

	/**
	 * Verify that the specified file is valid, and exists
	 * inside a certain root folder.
	 */
	public static function verify_file ($path, $root = false) {
		$root = ($root) ? rtrim ($root) : rtrim (self::root ());
		$path = trim ($path, '/');
		if (strpos ($path, '..') !== false) {
			return false;
		}
		if (! @file_exists ($root . '/' . $path)) {
			return false;
		}
		return true;
	}

	/**
	 * Verify that a folder name contains only a-z, A-Z, 0-9,
	 * underscores, and dashes.
	 */
	public static function verify_folder_name ($name) {
		if (! preg_match ('/^[a-zA-Z0-9 _-]+$/', $name)) {
			return false;
		}
		return true;
	}

	/**
	 * Verify that a file name contains only a-z, A-Z, 0-9,
	 * underscores, dashes, and at least one dot plus a file
	 * extension.
	 */
	public static function verify_file_name ($name) {
		if (! preg_match ('/^([a-zA-Z0-9 @_-]+\.)+[a-zA-Z0-9_-]+$/', $name)) {
			return false;
		}
		if (preg_match ('/\.(php|phtml|pht|php3|php4|php5|phar|js|rb|py|pl|sh|bash|exe|htaccess|htpasswd)$/i', $name)) {
			return false;
		}
		return true;
	}

	/**
	 * Helper for sorting files by name. For use with `usort()`.
	 */
	public static function fsort ($a, $b) {
		return strcmp ($a['name'], $b['name']);
	}

	/**
	 * Fetch all of the properties for the specified file.
	 */
	public static function props ($file) {
		return DB::pairs ('select prop, value from #prefix#filemanager_prop where file = ?', $file);
	}

	/**
	 * Get or set a property for the specified file.
	 * Can also retrieve an array of a property for a
	 * list of files if `$file` is an array.
	 */
	public static function prop ($file, $prop, $value = null) {
		if ($value !== null) {
			// takes an extra select query, but works cross-database
			$res = self::prop ($file, $prop);
			if ($res === $value) {
				return $value;
			} elseif ($res === false || $res === null) {
				// doesn't exist yet
				if (! DB::execute (
					'insert into #prefix#filemanager_prop (file, prop, value) values (?, ?, ?)',
					$file,
					$prop,
					$value
				)) {
					self::$error = DB::error ();
					return false;
				}
			} else {
				// already exists, update
				if (! DB::execute (
					'update #prefix#filemanager_prop set value = ? where file = ? and prop = ?',
					$value,
					$file,
					$prop
				)) {
					self::$error = DB::error ();
					return false;
				}
			}
			return $value;
		}
		if (is_array ($file)) {
			// get as a list
			$qmarks = array_fill (0, count ($file), '?');
			$file[] = $prop;
			return DB::pairs (
				'select file, value from #prefix#filemanager_prop where file in(' . join (', ', $qmarks) . ') and prop = ?',
				$file
			);
		}
		// get a single value
		return DB::shift (
			'select value from #prefix#filemanager_prop where file = ? and prop = ?',
			$file,
			$prop
		);
	}

	/**
	 * Rename the properties for a file that has been renamed.
	 */
	public static function prop_rename ($file, $new_name, $folder = false) {
		if ($folder) {
			if (! DB::execute (
				'update #prefix#filemanager_prop set file = replace(file, ?, ?) where file like ?',
				$file . '/',
				$new_name . '/',
				$file . '/%'
			)) {
				self::$error = DB::error ();
				return false;
			}
			return true;
		}
		if (! DB::execute (
			'update #prefix#filemanager_prop set file = ? where file = ?',
			$new_name,
			$file
		)) {
			self::$error = DB::error ();
			return false;
		}
		return true;
	}

	/**
	 * Delete the properties for a file that has been deleted.
	 */
	public static function prop_delete ($file) {
		if (! DB::execute (
			'delete from #prefix#filemanager_prop where file = ?',
			$file
		)) {
			self::$error = DB::error ();
			return false;
		}
		return true;
	}
}


text:
'use strict';

var mongoose = require('mongoose');

var ScoreSchema = new mongoose.Schema({
  serverId: String,
  gameId: String,
  gameDate: {type: Date, default: Date.now},
  playerName: String,
  score: {type: Number, min: 0, max: 99999999999}
});

module.exports = mongoose.model('Score', ScoreSchema);


text:
My Playground;
====

Smaller ruby scripts which don't need their own repository.
Here I explore ideas I find fun / interesting.
Also plausability tests / unfinished implementations, etc...

Feel free to play around, discover, contribute =)

/ ZirconCode

Changes
---
agile_scraper.rb script is now a gem at https://github.com/ZirconCode/Scrapah


text:
set -euo pipefail

image=build
ver=1.2.5

docker build -t davetang/${image}:${ver} .

>&2 echo Build complete
>&2 echo -e "Run the following to push to Docker Hub:\n"
>&2 echo docker login
>&2 echo docker push davetang/${image}:${ver}

exit 0


text:
> Generator for JSE

Currently, it can generate the module class file, the test spec for
jasmine and the import for the test

## Getting Started
This plugin requires Grunt `~0.4.1`

If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:

```shell
npm install grunt-jse --save-dev
```

One the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

```js
grunt.loadNpmTasks('grunt-jse');
```

## The "jse" task

### Overview
In your project's Gruntfile, add a section named `jse` to the data object passed into `grunt.initConfig()`.

```js
grunt.initConfig({
  jse: {
    options: {
			srcDir: 'Web Content/maf/jse',
			specDir: 'test/spec'
    },
    default: {}
  },
})
```

### Options

#### options.srcDir
Type: `String`
Default value: `'src'`

A string value that is used as a base path for the src directory of the
JSE modules.

#### options.specDir
Type: `String`
Default value: `'test/spec'`

A string value that is used as a base path for the jasmine spec directory of the JSE modules.

## Usage Examples

### Default Options
In this exemple, we generate files for the class named `Awesome.Module`

- Add this configuration in your Gruntfile.js (inside the `grunt.initConfig` block)

```js
grunt.initConfig({
  jse: {
    options: {
			srcDir: 'Web Content/maf/jse',
			specDir: 'test/spec'
    },
    default: {}
  },
})
```

- Type in the following command

```js
grunt jse --class=Awesome.Module
```

### Command line options

All those options are boolean, you should use `--singleton=true` instead
of `--singleton` as long as there is a bug with the `nopt` module
version (< 0.2) in `grunt`.

#### Generate a singleton module

```js
grunt jse --class=Awesome.Module --singleton=true
```

#### Skip the module file (only generate test files)

```js
grunt jse --class=Awesome.Module --skip-src=true
```

#### Skip the test files (only generate the class file)

```js
grunt jse --class=Awesome.Module --skip-test=true
```


text:
(function() {
    'use strict';

    angular
        .module('webmanager')
        .directive('wmFooter', wmFooter);

    /** @ngInject */
    function wmFooter() {
        var directive = {
            restrict: 'E',
            templateUrl: 'app/components/footer/footer.html',
            scope: {
            },
            controller: FooterController,
            controllerAs: 'vm',
            bindToController: true
        };

        return directive;

        /** @ngInject */
        function FooterController() {
            // TODO
        }
    }
})();


text:
package gui;

import java.awt.*;
import agent.*;

public class AgentGui implements Gui{
	Agent myAgent;
	MainFrameGui mainframe;
	private int xsize = 20, ysize = 20;
	private int xloc, yloc;
	Rectangle rectangle;

	/* Declarator, input: corresponding agent
	 * */
	public AgentGui (Agent theAgent, MainFrameGui main, int x, int y){
		myAgent = theAgent;
		mainframe = main;
		this.xloc = x;
		this.yloc = y;
		rectangle = new Rectangle(xloc,yloc,xsize,ysize);

	}

	/* Moving function for Gui image, input: movement in 2 axis
	 * */
	public void move(int x, int y){
		xloc += x;
		yloc += y;
	}

	public void paint(Graphics2D g){
		g.draw(rectangle);
		g.drawString(myAgent.getAgentName(), xloc, yloc);
	}

	@Override
	public void updatePosition() {
		// TODO Auto-generated method stub

	}

}


text:
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */

import 'babel/polyfill';
import React from 'react';
import FastClick from 'fastclick';
import emptyFunction from 'react/lib/emptyFunction';
import App from './components/App';
import Dispatcher from './core/Dispatcher';
import AppActions from './actions/AppActions';
import { ActionTypes } from './core/Constants';

let path = decodeURI(window.location.pathname);
let setMetaTag = (name, content) => {
  // Remove and create a new <meta /> tag in order to make it work
  // with bookmarks in Safari
  let elements = document.getElementsByTagName('meta');
  [].slice.call(elements).forEach((element) => {
    if (element.getAttribute('name') === name) {
      element.parentNode.removeChild(element);
    }
  });
  let meta = document.createElement('meta');
  meta.setAttribute('name', name);
  meta.setAttribute('content', content);
  document.getElementsByTagName('head')[0].appendChild(meta);
};

function run() {
  // Render the top-level React component
  let props = {
    path: path,
    onSetTitle: (title) => document.title = title,
    onSetMeta: setMetaTag,
    onPageNotFound: emptyFunction
  };
  let element = React.createElement(App, props);
  React.render(element, document.getElementById('app'));

  // Update `Application.path` prop when `window.location` is changed
  Dispatcher.register((action) => {
    if (action.type === ActionTypes.CHANGE_LOCATION) {
      element = React.cloneElement(element, {path: action.path});
      React.render(element, document.getElementById('app'));
    }
  });
}

// Run the application when both DOM is ready
// and page content is loaded
Promise.all([
  new Promise((resolve) => {
    if (window.addEventListener) {
      window.addEventListener('DOMContentLoaded', resolve);
    } else {
      window.attachEvent('onload', resolve);
    }
  }).then(() => FastClick.attach(document.body)),
  new Promise((resolve) => AppActions.loadPage(path, resolve))
]).then(run);


text:
#include "smbftpd.h"

extern smbftpd_session_t smbftpd_session;

void cmd_pbsz()
{
#ifdef WITH_SSL
	if (smbftpd_session.ssl_ctrl.ssl_active_flag) {
		reply_noformat(200, "PBSZ command successful (PBSZ=0).");
		smbftpd_session.ssl_ctrl.PBSZ_used_flag = 1;
	} else {
		reply_noformat(503, "Use AUTH command first.");
	}
#endif /* WITH_SSL */
}


text:
// Copyright 2012 Mark Cavage, Inc.  All rights reserved.

var crypto = require('crypto');
var EventEmitter = require('events').EventEmitter;
var fs = require('fs');
var http = require('http');
var https = require('https');
var os = require('os');
var querystring = require('querystring');
var url = require('url');
var util = require('util');
var zlib = require('zlib');

var assert = require('assert-plus');
var backoff = require('backoff');
var KeepAliveAgent = require('keep-alive-agent');
var mime = require('mime');
var once = require('once');
var semver = require('semver');
var uuid = require('node-uuid');

var errors = require('../errors');

///--- Globals

/* JSSTYLED */
var VERSION = JSON.parse(fs.readFileSync(require('path').normalize(__dirname + '/../../package.json'), 'utf8')).version;

///--- Helpers

function cloneRetryOptions(options, defaults) {
        if (options === false) {
                return ({
                        minTimeout: 1,
                        maxTimeout: 2,
                        retries: 1
                });
        }

        assert.optionalObject(options, 'options.retry');
        var r = options || {};
        assert.optionalNumber(r.minTimeout, 'options.retry.minTimeout');
        assert.optionalNumber(r.maxTimeout, 'options.retry.maxTimeout');
        assert.optionalNumber(r.retries, 'options.retry.retries');
        assert.optionalObject(defaults, 'defaults');
        defaults = defaults || {};

        return ({
                minTimeout: r.minTimeout || defaults.minTimeout || 1000,
                maxTimeout: r.maxTimeout || defaults.maxTimeout || Infinity,
                retries: r.retries || defaults.retries || 4
        });
}

function defaultUserAgent() {
        var UA = 'restify/' + VERSION +
                ' (' + os.arch() + '-' + os.platform() + '; ' +
                'v8/' + process.versions.v8 + '; ' +
                'OpenSSL/' + process.versions.openssl + ') ' +
                'node/' + process.versions.node;

        return (UA);
}

function ConnectTimeoutError(ms) {
        if (Error.captureStackTrace)
                Error.captureStackTrace(this, ConnectTimeoutError);

        this.message = 'connect timeout after ' + ms + 'ms';
        this.name = 'ConnectTimeoutError';
}
util.inherits(ConnectTimeoutError, Error);

function rawRequest(opts, cb) {
        assert.object(opts, 'options');
        assert.object(opts.log, 'options.log');
        assert.func(cb, 'callback');

        cb = once(cb);

        var log = opts.log;
        var proto = opts.protocol === 'https:' ? https : http;
        var timer;

        if (opts.cert && opts.key)
                opts.agent = false;

        if (opts.connectTimeout) {
                timer = setTimeout(function connectTimeout() {
                        timer = null;
                        if (req) {
                                req.abort();
                        }

                        cb(new ConnectTimeoutError(opts.connectTimeout), req);
                }, opts.connectTimeout);
        }

        var req = proto.request(opts, function onResponse(res) {
                clearTimeout(timer);
                log.trace({client_res: res}, 'Response received');

                res.log = log;

                var err;
                if (res.statusCode >= 400)
                        err = errors.codeToHttpError(res.statusCode);

                req.removeAllListeners('error');
                req.removeAllListeners('socket');
                req.emit('result', (err || null), res);
        });
        req.log = log;

        req.on('error', function onError(err) {
                log.trace({err: err}, 'Request failed');
                clearTimeout(timer);

                cb(err, req);
                if (req) {
                        process.nextTick(function () {
                                req.emit('result', err, null);
                        });
                }
        });

        req.once('socket', function onSocket(socket) {
                if (socket.writable && !socket._connecting) {
                        clearTimeout(timer);
                        cb(null, req);
                        return;
                }

                socket.once('connect', function onConnect() {
                        clearTimeout(timer);
                        cb(null, req);
                });
        });

        if (opts.signRequest)
                opts.signRequest(req);
} // end `rawRequest`

///--- API

function HttpClient(options) {
        assert.object(options, 'options');
        assert.optionalObject(options.headers, 'options.headers');
        assert.object(options.log, 'options.log');
        assert.optionalFunc(options.signRequest, 'options.signRequest');
        assert.optionalString(options.socketPath, 'options.socketPath');
        assert.optionalString(options.url, 'options.url');

        EventEmitter.call(this);

        this.agent = options.agent;
        this.cert = options.cert;
        this.connectTimeout = options.connectTimeout || false;
        this.headers = options.headers || {};
        this.log = options.log;
        this.key = options.key;
        this.name = options.name || 'HttpClient';
        this.retry = cloneRetryOptions(options.retry);
        this.signRequest = options.signRequest || false;
        this.socketPath = options.socketPath || false;
        this.url = options.url ? url.parse(options.url) : {};

        if (options.accept) {
                if (options.accept.indexOf('/') === -1)
                        options.accept = mime.lookup(options.accept);

                this.headers.accept = options.accept;
        }

        if (options.contentType) {
                if (options.contentType.indexOf('/') === -1)
                        options.type = mime.lookup(options.contentType);

                this.headers['content-type'] = options.contentType;
        }

        if (options.userAgent !== false) {
                this.headers['user-agent'] = options.userAgent ||
                        defaultUserAgent();
        }

        if (options.version)
                this.headers['accept-version'] = options.version;

        if (this.agent === undefined) {
                var Agent;
                var maxSockets;

                if (this.url.protocol === 'https:') {
                        Agent = KeepAliveAgent.Secure;
                        maxSockets = https.globalAgent.maxSockets;
                } else {
                        Agent = KeepAliveAgent;
                        maxSockets = http.globalAgent.maxSockets;
                }

                this.agent = new Agent({
                        maxSockets: maxSockets,
                        maxKeepAliveRequests: 0,
                        maxKeepAliveTime: 0
                });
        }
}
util.inherits(HttpClient, EventEmitter);
module.exports = HttpClient;

HttpClient.prototype.close = function close() {
        var sockets = this.agent.sockets;
        Object.keys((sockets || {})).forEach(function (k) {
                sockets[k].forEach(function (s) {
                        s.end();
                });
        });

        sockets = this.agent.idleSockets;
        Object.keys((sockets || {})).forEach(function (k) {
                sockets[k].forEach(function (s) {
                        s.end();
                });
        });
};

HttpClient.prototype.del = function del(options, callback) {
        var opts = this._options('DELETE', options);

        return (this.read(opts, callback));
};

HttpClient.prototype.get = function get(options, callback) {
        var opts = this._options('GET', options);

        return (this.read(opts, callback));
};

HttpClient.prototype.head = function head(options, callback) {
        var opts = this._options('HEAD', options);

        return (this.read(opts, callback));
};

HttpClient.prototype.opts = function http_options(options, callback) {
        var _opts = this._options('OPTIONS', options);

        return (this.read(_opts, callback));
};

HttpClient.prototype.post = function post(options, callback) {
        var opts = this._options('POST', options);

        return (this.request(opts, callback));
};

HttpClient.prototype.put = function put(options, callback) {
        var opts = this._options('PUT', options);

        return (this.request(opts, callback));
};

HttpClient.prototype.read = function read(options, callback) {
        var r = this.request(options, function readRequestCallback(err, req) {
                if (!err)
                        req.end();

                return (callback(err, req));
        });
        return (r);
};

HttpClient.prototype.basicAuth = function basicAuth(username, password) {
        if (username === false) {
                delete this.headers.authorization;
        } else {
                assert.string(username, 'username');
                assert.string(password, 'password');

                var buffer = new Buffer(username + ':' + password, 'utf8');
                this.headers.authorization = 'Basic ' +
                        buffer.toString('base64');
        }

        return (this);
};

HttpClient.prototype.request = function request(opts, cb) {
        assert.object(opts, 'options');
        assert.func(cb, 'callback');

        cb = once(cb);

        var call;
        var retry = cloneRetryOptions(opts.retry);

        call = backoff.call(rawRequest, opts, cb);
        call.setStrategy(new backoff.ExponentialStrategy({
                initialDelay: retry.minTimeout,
                maxDelay: retry.maxTimeout
        }));
        call.failAfter(retry.retries);
        call.on('backoff', this.emit.bind(this, 'attempt'));

        call.start();
};

HttpClient.prototype._options = function (method, options) {
        if (typeof (options) !== 'object')
                options = { path: options };

        var self = this;
        var opts = {
                agent: options.agent || self.agent,
                cert: options.cert || self.cert,
                connectTimeout: options.connectTimeout || self.connectTimeout,
                headers: options.headers || {},
                key: options.key || self.key,
                log: options.log || self.log,
                method: method,
                path: options.path || self.path,
                retry: options.retry || self.retry,
                signRequest: options.signRequest || self.signRequest
        };

        // Backwards compatibility with restify < 1.0
        if (options.query &&
            Object.keys(options.query).length &&
            opts.path.indexOf('?') === -1) {
                opts.path += '?' + querystring.stringify(options.query);
        }

        if (this.socketPath)
                opts.socketPath = this.socketPath;

        Object.keys(self.url).forEach(function (k) {
                if (!opts[k])
                        opts[k] = self.url[k];
        });

        Object.keys(self.headers).forEach(function (k) {
                if (!opts.headers[k])
                        opts.headers[k] = self.headers[k];
        });

        if (!opts.headers.date)
                opts.headers.date = new Date().toUTCString();

        if (method === 'GET' || method === 'HEAD' || method === 'DELETE') {
                if (opts.headers['content-type'])
                        delete opts.headers['content-type'];
                if (opts.headers['content-md5'])
                        delete opts.headers['content-md5'];
                if (opts.headers['content-length'])
                        delete opts.headers['content-length'];
                if (opts.headers['transfer-encoding'])
                        delete opts.headers['transfer-encoding'];
        }

        return (opts);
};


text:
\documentclass[letter]{article}
\usepackage{graphicx,amsmath,amssymb,amsthm,subfigure,color,url,multirow,rotating,comment}
%\usepackage{tikz}
\usepackage[normalem]{ulem}
\usepackage[np,autolanguage]{numprint}

\usepackage[]{hyperref}
\hypersetup{
    unicode=false,          % non-Latin characters in Acrobat's bookmarks
    pdftoolbar=true,        % show Acrobat's toolbar?
    pdfmenubar=true,        % show Acrobat's menu?
    pdffitwindow=true,      % window fit to page when opened
    pdfstartview={FitV},    % fits the width of the page to the window
    pdftitle={SystemML Algorithms Reference},    % title
    pdfauthor={SystemML Team}, % author
    pdfsubject={Documentation},   % subject of the document
    pdfkeywords={},         % list of keywords
    pdfnewwindow=true,      % links in new window
    bookmarksnumbered=true, % put section numbers in bookmarks
    bookmarksopen=true,     % open up bookmark tree
    bookmarksopenlevel=1,   % \maxdimen level to which bookmarks are open
    colorlinks=true,        % false: boxed links; true: colored links
    linkcolor=black,        % color of internal links
    citecolor=blue,         % color of links to bibliography
    filecolor=black,        % color of file links
    urlcolor=black          % color of external links
}

\newtheorem{definition}{Definition}
\newtheorem{example}{Example}

\newcommand{\Paragraph}[1]{\vspace*{1ex} \noindent {\bf #1} \hspace*{1ex}}
\newenvironment{Itemize}{\vspace{-0.5ex}\begin{itemize}\setlength{\itemsep}{-0.2ex}
}{\end{itemize}\vspace{-0.5ex}}
\newenvironment{Enumerate}{\vspace{-0.5ex}\begin{enumerate}\setlength{\itemsep}{-0.2ex}
}{\end{enumerate}\vspace{-0.5ex}}
\newenvironment{Description}{\vspace{-0.5ex}\begin{description}\setlength{\itemsep}{-0.2ex}
}{\end{description}\vspace{-0.5ex}}

\newcommand{\SystemML}{\texttt{SystemML} }
\newcommand{\hml}{\texttt{hadoop jar SystemML.jar} }
\newcommand{\pxp}{\mathbin{\texttt{\%\textasteriskcentered\%}}}
\newcommand{\todo}[1]{{{\color{red}TODO: #1}}}
\newcommand{\Normal}{\ensuremath{\mathop{\mathrm{Normal}}\nolimits}}
\newcommand{\Prob}{\ensuremath{\mathop{\mathrm{Prob}\hspace{0.5pt}}\nolimits}}
\newcommand{\E}{\ensuremath{\mathop{\mathrm{E}}\nolimits}}
\newcommand{\mean}{\ensuremath{\mathop{\mathrm{mean}}\nolimits}}
\newcommand{\Var}{\ensuremath{\mathop{\mathrm{Var}}\nolimits}}
\newcommand{\Cov}{\ensuremath{\mathop{\mathrm{Cov}}\nolimits}}
\newcommand{\stdev}{\ensuremath{\mathop{\mathrm{st.dev}}\nolimits}}
\newcommand{\atan}{\ensuremath{\mathop{\mathrm{arctan}}\nolimits}}
\newcommand{\diag}{\ensuremath{\mathop{\mathrm{diag}}\nolimits}}
\newcommand{\const}{\ensuremath{\mathop{\mathrm{const}}\nolimits}}
\newcommand{\eps}{\varepsilon}

\sloppy

%%%%%%%%%%%%%%%%%%%%%
% header
%%%%%%%%%%%%%%%%%%%%%

\title{\LARGE{{\SystemML Algorithms Reference}}}
\date{\today}

%%%%%%%%%%%%%%%%%%%%%
% document start
%%%%%%%%%%%%%%%%%%%%%
\begin{document}

%\pagenumbering{roman}
\maketitle

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Descriptive Statistics}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\input{DescriptiveStats}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Classification}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\input{LogReg}

\subsection{Support Vector Machines}

\input{BinarySVM}

\input{MultiSVM}

\input{NaiveBayes}

%\input{DecisionTrees}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Clustering}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\input{Kmeans}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Regression}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\input{LinReg}

\newpage

\input{GLM}

\newpage

\input{GLMpredict.tex}

\newpage

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Matrix Factorization}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\input{pca}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%{\color{red}\section{Sequence Mining}}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%\section{Matrix Factorization}

%%{\color{red}\subsection{GNMF}}

\bibliographystyle{abbrv}

\bibliography{SystemML_ALgorithms_Reference}

%%%%%%%%%%%%%%%%%%%%%
% document end
%%%%%%%%%%%%%%%%%%%%%
\end{document}


text:
FROM python:2.7.10

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY . /usr/src/app

RUN pip install -r requirements.txt

EXPOSE 3000

CMD [ "python","application.py"]


text:
export*from'../../lit-html/directives/ref.js';
//# sourceMappingURL=ref.js.map


text:
package io.crate.sql.tree;

public abstract class JoinCriteria {
    // Force subclasses to have a proper equals and hashcode implementation
    @Override
    public abstract boolean equals(Object obj);

    @Override
    public abstract int hashCode();

    @Override
    public abstract String toString();
}


text:
#pragma once
#include <aws/cognito-idp/CognitoIdentityProvider_EXPORTS.h>
#include <aws/cognito-idp/CognitoIdentityProviderRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <utility>

namespace Aws
{
namespace CognitoIdentityProvider
{
namespace Model
{

  /**
   *
Represents the request to get information about the user.

See
   * Also:
   AWS
   * API Reference

   */
  class AWS_COGNITOIDENTITYPROVIDER_API GetUserRequest : public CognitoIdentityProviderRequest
  {
  public:
    GetUserRequest();

    // Service request name is the Operation name which will send this request out,
    // each operation should has unique request name, so that we can get operation's name from this request.
    // Note: this is not true for response, multiple operations may have the same response name,
    // so we can not get operation's name from response.
    inline virtual const char* GetServiceRequestName() const override { return "GetUser"; }

    Aws::String SerializePayload() const override;

    Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;

    /**
     *
The access token returned by the server response to get information about the
     * user.

     */
    inline const Aws::String& GetAccessToken() const{ return m_accessToken; }

    /**
     *
The access token returned by the server response to get information about the
     * user.

     */
    inline bool AccessTokenHasBeenSet() const { return m_accessTokenHasBeenSet; }

    /**
     *
The access token returned by the server response to get information about the
     * user.

     */
    inline void SetAccessToken(const Aws::String& value) { m_accessTokenHasBeenSet = true; m_accessToken = value; }

    /**
     *
The access token returned by the server response to get information about the
     * user.

     */
    inline void SetAccessToken(Aws::String&& value) { m_accessTokenHasBeenSet = true; m_accessToken = std::move(value); }

    /**
     *
The access token returned by the server response to get information about the
     * user.

     */
    inline void SetAccessToken(const char* value) { m_accessTokenHasBeenSet = true; m_accessToken.assign(value); }

    /**
     *
The access token returned by the server response to get information about the
     * user.

     */
    inline GetUserRequest& WithAccessToken(const Aws::String& value) { SetAccessToken(value); return *this;}

    /**
     *
The access token returned by the server response to get information about the
     * user.

     */
    inline GetUserRequest& WithAccessToken(Aws::String&& value) { SetAccessToken(std::move(value)); return *this;}

    /**
     *
The access token returned by the server response to get information about the
     * user.

     */
    inline GetUserRequest& WithAccessToken(const char* value) { SetAccessToken(value); return *this;}

  private:

    Aws::String m_accessToken;
    bool m_accessTokenHasBeenSet;
  };

} // namespace Model
} // namespace CognitoIdentityProvider
} // namespace Aws


text:
<?php
/**
 * The template for displaying all single posts.
 *
 * @package neckbeard
 */

get_header(); ?>

				<?php while ( have_posts() ) : the_post(); ?>

					<?php
					do_action( 'neckbeard_single_post_before' );

					get_template_part( 'content', 'single' );

					/**
			 		* @hooked neckbeard_post_nav - 10
			 		* @hooked neckbeard_display_comments - 20
			 		*/
					do_action( 'neckbeard_single_post_after' );
					?>

				<?php endwhile; // end of the loop. ?>

<?php get_footer(); ?>


text:
<?

namespace MediaCore\Lib\Helpers;

class HArray {

	/**
	 * Get multilevel array from string, ignore nulls
	 *
	 * Example:
	 * expression
	 * <? print_r(HArray::createFromString('1,2,3,4,5|6,7,8,9,0,,,', array('|', ','))) ?>
	 * will return
	 * Array
	 * (
	 *      [0] => Array
	 *          (
	 *              [0] => 1
	 *              [1] => 2
	 *              [2] => 3
	 *              [3] => 4
	 *              [4] => 5
	 *          )
	 * 	    [1] => Array
	 *          (
	 *              [0] => 6
	 *              [1] => 7
	 *              [2] => 8
	 *              [3] => 9
	 *              [4] => 0
	 *          )
	 * )
	 *
	 * @static
	 * @access public
	 * @param string $string input string
	 * @param array/string $separators array/string of separator(s)
	 *
	 * @return array output array
	 */
	public static function createFromString($string, $separators = array(',')) {
		if (!is_string($string)) {
			return array();
		}

		$separators = (array)$separators;
		$separator = array_shift($separators);

		$array = array();
		foreach (array_map('trim', explode($separator, $string)) as $item) {
			if ($item !== '') {
				if (count($separators)) {
					$array[] = self::createFromString($item, $separators);
				} else {
					$array[] = $item;
				}
			}
		}

		return $array;
    }

	/**
	 * Create array with necessary structure
	 *
	 * Very useful to create multilevel array structures from database table data
	 *
	 * @static
	 * @access public
	 * @param string|array $key array/string of serial array keys
	 * @param array $array input data
	 * @param string|null $value array key of output array values (if needed)
	 *
	 * @return array output structure
	 */
	public static function createByKey($key, array $array, $value = null) {
		$result = array();

		if ($key === null) {
			$key = array(null);
		}
		$key = (array)$key;

		foreach ($array as $item) {
			if ($value === null) $tmp = $item;
			else $tmp = $item[$value];

			$counter_path = '';
			foreach ($key as $n => $k) {
				if ($k !== null) {
					$counter_path .= $item[$k];
				} else {
					$counter_path .= $n;
				}
			}

			foreach (array_reverse($key) as $k) {
				if ($k !== null) {
					$tmp = array($item[$k] => $tmp);
				} else {
					if (!isset($counter[$counter_path])) {
						$counter[$counter_path] = 0;
					}
					$tmp = array($counter[$counter_path]++ => $tmp);
				}
			}
			$result = self::mergeReplace($result, $tmp);
		}

		return $result;
	}

	/**
	 * Recursive merge and replace values in arrays
	 *
	 * @static
	 * @access public
	 * @param array $data main array
	 * @param array $data1 [, $data2, ... ] replacment array(s)
	 *
	 * @return merged array
	 */
	public static function mergeReplace() {
		$args = func_get_args();

		$array = $args[0];
		for ($i = 1; $i < count($args); $i++) {
			foreach ($args[$i] as $key => $value) {
				if (is_array($value) && isset($array[$key])) {
					$array[$key] = self::mergeReplace($array[$key], $value);
				} else {
					$array[$key] = $value;
				}
			}
		}

		return $array;
	}

	/**
	 * Recursive call to each array value
	 *
	 * @static
	 * @access public
	 * @param callback $callback callback
	 * @param array $element input data
	 *
	 * @return array output array
	 */
	public static function mapRecursive($callback, array $data) {

		if (is_array($data)) {
			$array = array();
			foreach ($data as $k => $e) {
				$array[$k] = self::mapRecursive($callback, $e);
			}
			return $array;
		}

		return $callback($data);
	}

	/**
	 * Escape array values with addslashes
	 *
	 * @static
	 * @access public
	 * @param array &$variable input array
	 *
	 * @return void
	 */
	public static function addSlashes(array &$variable) {
		foreach ($variable as $key => $value) {
			if (is_array($variable[$key])) {
				self::addSlashes($variable[$key]);
			} else {
				$variable[$key] = addslashes($variable[$key]);
			}
		}
	}

	/**
	 * Unescape array values with stripslashes
	 *
	 * @static
	 * @access public
	 * @param array &$variable input array
	 *
	 * @return void
	 */
	public static function stripSlashes(array &$variable) {
		foreach ($variable as $key => $value) {
			if (is_array($variable[$key])) {
				self::stripSlashes($variable[$key]);
			} else {
				$variable[$key] = stripslashes($variable[$key]);
			}
		}
	}
}


text:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LoginComponent } from './login.component';
import { LoginService } from "app/login/login.service";

@NgModule({
  imports: [
    CommonModule
  ],
  declarations: [LoginComponent],
  providers:[LoginService],
  exports:[LoginComponent]
})
export class LoginModule { }


text:
package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"sync/atomic"

	"github.com/olivere/elastic/v7"
)

// CountingTransport will count requests.
type CountingTransport struct {
	N    int64             // number of requests passing this transport
	next http.RoundTripper // next round-tripper or http.DefaultTransport if nil
}

// RoundTrip implements a transport that will count requests.
func (tr *CountingTransport) RoundTrip(r *http.Request) (*http.Response, error) {
	atomic.AddInt64(&tr.N, 1)
	if tr.next != nil {
		return tr.next.RoundTrip(r)
	}
	return http.DefaultTransport.RoundTrip(r)
}

func main() {
	var (
		url   = flag.String("url", "http://localhost:9200", "Elasticsearch URL")
		sniff = flag.Bool("sniff", true, "Enable or disable sniffing")
	)
	flag.Parse()
	log.SetFlags(0)

	if *url == "" {
		*url = "http://127.0.0.1:9200"
	}

	tr := &CountingTransport{}

	// Create an Elasticsearch client
	client, err := elastic.NewClient(
		elastic.SetURL(*url),
		elastic.SetSniff(*sniff),
		elastic.SetHttpClient(&http.Client{
			Transport: tr,
		}),
	)
	if err != nil {
		log.Fatal(err)
	}

	// Get ES version
	indices, err := client.IndexNames()
	if err != nil {
		log.Fatal(err)
	}
	for _, index := range indices {
		fmt.Println(index)
	}

	// Just a status message
	fmt.Printf("%d requests executed.\n", tr.N)
}


text:
#include "tiler.h"
#include <SDL2_image/SDL_image.h>

/*
 * A library for drawing 2D tilemaps using SDL
 */

namespace tiler {
    Map::Map(){
        this->map = nullptr;
        this->renderer = nullptr;
    }
    Map::~Map(){

    }
    int Map::numImages() {
        return images.size();
    }
    void Map::loadFromFile(const std::string filename){
        this->map = new Tmx::Map();
        this->map->ParseFile(filename);

        if(map->HasError() == true) { throw map->GetErrorText(); }
        if(this->renderer == nullptr) { throw new ExNoRenderer(); }

        // Load image files
        const std::vector<Tmx::Tileset*>& tileSets = map->GetTilesets();
        for(int i = 0; i < tileSets.size(); ++i) {
            const Tmx::Tileset * tileSet = tileSets[i];
            const Tmx::Image * image = tileSet->GetImage();
            const std::string source = image->GetSource();
            SDL_RWops * rwop = SDL_RWFromFile(source.c_str(),"r");
            SDL_Surface * surf = IMG_LoadPNG_RW(rwop);
            SDL_Texture * tex = SDL_CreateTextureFromSurface(this->renderer, surf);
            this->images.push_back(tex);
        }
    }
    void Map::setRenderer(SDL_Renderer * r){
        this->renderer = r;
    }
    void Map::drawTile(int guid, int tileset_i, int x, int y) {
        SDL_Rect dst, src;
        int tile_w = this->map->GetTileWidth();
        int tile_h = this->map->GetTileHeight();

        const Tmx::Tileset* ts = this->map->GetTileset(tileset_i);
        int img_w_tiles = ts->GetImage()->GetWidth() / tile_w;

        int spacing = ts->GetSpacing();
        int tile_pos = guid - ts->GetFirstGid() + 1; // first GUID is 1, not 0

        // Get pixel boundaries of this tile adjusting for tile borders
        src.x = (tile_pos % img_w_tiles) * (tile_w + spacing) + spacing;
        src.y = (tile_pos / img_w_tiles) * (tile_h + spacing) + spacing;

        src.w = dst.w = tile_w;
        src.h = dst.h = tile_h;

        dst.x = x;
        dst.y = y;

        SDL_RenderCopy(this->renderer, this->images[tileset_i], &src, &dst);
    }
    void Map::drawMap(int x_offset, int y_offset, int scr_width, int scr_height) {
        const std::vector<Tmx::Layer*> &layers = this->map->GetLayers();
        int tile_id = 0;
        int tileset_i = -1;
        int tile_w = this->map->GetTileWidth();
        int tile_h = this->map->GetTileHeight();
        Tmx::Layer* layer;

        // Draw all layers from bottom to top.
        for(int i = 0; i < layers.size(); ++i){
            layer = layers[i];

            // Set tile edges of the layer portion to be drawn.
            int start_x = 0;
            int end_x = layer->GetWidth() - 1;
            int start_y = 0;
            int end_y = layer->GetHeight() - 1;

            // Clip off-screen map tiles.
            if(x_offset + scr_width < (layer->GetWidth() - 1) * tile_w) {
                end_x = (x_offset + scr_width) / tile_w;
            }
            if(y_offset + scr_height < (layer->GetHeight() - 1) * tile_h) {
                end_y = (y_offset + scr_height) / tile_h;
            }
            if(x_offset > tile_w) {
                start_x = x_offset / tile_w;
            }
            if(y_offset > tile_h) {
                start_y = y_offset / tile_h;
            }

            // Draw all tiles in this layer after clipping.
            for(int y = start_y; y <= end_y; ++y){
                for(int x = start_x; x <= end_x; ++x){
                    tile_id = layer->GetTile(x, y).id;
                    tileset_i = layer->GetTile(x,y).tilesetId;
                    int x_pos = x * tile_w - x_offset;
                    int y_pos = y * tile_h - y_offset;
                    if(tileset_i != -1){
                        this->drawTile(tile_id, tileset_i, x_pos, y_pos);
                    }
                }
            }
        }
    }

    /*
     * Exception Classes
     */

    const char* ExNoRenderer::what() const _NOEXCEPT {
        return "Renderer has not been set";
    }
}


text:
{-# OPTIONS -O2 -Wall #-}

module Drool.UI.GLWindow (
    initComponent
) where

import Debug.Trace

import Data.IORef(IORef, readIORef, newIORef, modifyIORef, writeIORef )
import Data.Array.IO

import Control.Monad.Trans ( liftIO )

import qualified Graphics.UI.Gtk.Builder as GtkBuilder
import Graphics.Rendering.OpenGL as GL
import qualified Graphics.Rendering.FTGL as FTGL

import Graphics.UI.Gtk as Gtk
import qualified Graphics.UI.GLUT as GLUT ( initialize )
import qualified Graphics.UI.Gtk.OpenGL as GtkGL

import qualified Drool.Utils.SigGen as SigGen ( SignalGenerator(..) )
import qualified Drool.Utils.Conversions as Conv
import qualified Drool.Utils.RenderHelpers as RH
import qualified Drool.Utils.FeatureExtraction as FE ( SignalFeaturesList(..), FeatureTarget(..) )
import qualified Drool.Types as DT
import qualified Drool.ApplicationContext as AC
import qualified Drool.ContextObjects as AC

import qualified Control.Monad as M ( forever, forM )
import qualified Control.Concurrent as C
import qualified Control.Concurrent.MVar as MV ( MVar, swapMVar, takeMVar, putMVar )
import qualified Control.Concurrent.Chan as CC ( readChan )

import qualified Drool.UI.Visuals as Visuals

import Graphics.UI.GLUT ( Object(Sphere'), renderObject, Flavour(..) )

display :: IORef AC.ContextSettings -> IORef RH.RenderSettings -> [ IORef (Visuals.Visual) ] -> IO ()
display contextSettingsIORef renderSettingsIORef visualIORefs = do

  contextSettings <- readIORef contextSettingsIORef

  let blendModeFMSource      = Conv.blendModeSourceFromIndex $ AC.blendModeFMSourceIdx contextSettings
      blendModeFMFrameBuffer = Conv.blendModeFrameBufferFromIndex $ AC.blendModeFMFrameBufferIdx contextSettings
      blendModeMBSource      = Conv.blendModeSourceFromIndex $ AC.blendModeMBSourceIdx contextSettings
      blendModeMBFrameBuffer = Conv.blendModeFrameBufferFromIndex $ AC.blendModeMBFrameBufferIdx contextSettings

  clear [ColorBuffer, DepthBuffer]

  preservingMatrix $ do
    -- Render foreground model:
    displayModel contextSettingsIORef renderSettingsIORef (visualIORefs !! 0)
    blendFunc $= (blendModeMBSource, blendModeMBFrameBuffer)

  preservingMatrix $ do
    -- Render middleground model:
    displayModel contextSettingsIORef renderSettingsIORef (visualIORefs !! 1)
    blendFunc $= (blendModeFMSource, blendModeFMFrameBuffer)

  preservingMatrix $ do
    -- Render middleground model:
    displayModel contextSettingsIORef renderSettingsIORef (visualIORefs !! 2)

  return ()

displayModel :: IORef AC.ContextSettings -> IORef RH.RenderSettings -> IORef (Visuals.Visual) -> IO ()
displayModel contextSettingsIORef renderSettingsIORef visualIORef = do
-- {{{
--  renderSettingsPrev <- readIORef renderSettingsIORef
  contextSettings    <- readIORef contextSettingsIORef
  renderSettingsPrev <- readIORef renderSettingsIORef

  visual <- readIORef visualIORef

  let timeoutMs = (Conv.freqToMs $ AC.renderingFrequency contextSettings)
  let tick      = RH.tick renderSettingsPrev
  let tickMs    = tick * timeoutMs

  let renderSettingsCurr = renderSettingsPrev { RH.tick = (tick+1) `mod` 1000 }

  let samplingSem  = RH.samplingSem renderSettingsCurr

  signalBuf   <- readIORef (RH.signalBuf renderSettingsCurr)
  featuresBuf <- readIORef (RH.featuresBuf renderSettingsCurr)

  let featuresCurr = head (FE.signalFeaturesList featuresBuf)

  -- Wait until there is at least one signal ready for rendering.
  let nNewSignals = RH.numNewSignals renderSettingsCurr

  -- Load most recent signal from buffer (last signal in list):
  let recentSignal = DT.getRecentSignal signalBuf
  let lastSignal   = DT.getLastSignal signalBuf
  -- Get length of most recent signal (= number of samples per signal):
  numSamplesCurr <- case recentSignal of
                         Just s  -> do signalBounds <- getBounds $ DT.signalArray s
                                       return $ rangeSize signalBounds
                         Nothing -> return 0
  numSamplesLast <- case lastSignal of
                         Just s  -> do signalBounds <- getBounds $ DT.signalArray s
                                       return $ rangeSize signalBounds
                         Nothing -> return 0

  let nSamples = min numSamplesCurr numSamplesLast
  let nSignals = length $ DT.signalList signalBuf

  modifyIORef renderSettingsIORef ( \_ -> renderSettingsCurr { RH.numSignals    = nSignals,
                                                               RH.numNewSignals = nNewSignals,
                                                               RH.numSamples    = nSamples } )
  renderSettings <- readIORef renderSettingsIORef

  let accIncRotation  = (AC.incRotationAccum contextSettings)
  let incRotationStep = (AC.incRotation contextSettings)
  let nextIncRotation = DT.CRotationVector { DT.rotY = (DT.rotY accIncRotation + DT.rotY incRotationStep),
                                             DT.rotX = (DT.rotX accIncRotation + DT.rotX incRotationStep),
                                             DT.rotZ = (DT.rotZ accIncRotation + DT.rotZ incRotationStep) }
  modifyIORef contextSettingsIORef (\settings -> settings { AC.incRotationAccum = nextIncRotation } )

  -- Push new signal(s) to visual:

  (Visuals.update visual) renderSettings tick
  visualUpdated <- readIORef visualIORef

  matrixMode $= Projection
  loadIdentity
  perspective (realToFrac (AC.viewAngle contextSettings)) (fromIntegral canvasInitWidth / fromIntegral canvasInitHeight) 0.1 100

  matrixMode $= Modelview 0
  loadIdentity

  let hScale         = (AC.scaling contextSettings) / (100.0::Float)
      surfOpacity    = (AC.surfaceOpacity contextSettings) / (100.0::GLfloat)
      fixedRotation  = AC.fixedRotation contextSettings
      accIncRotation = AC.incRotationAccum contextSettings
      viewDistance   = AC.viewDistance contextSettings
      maxNumSignals  = AC.signalBufferSize contextSettings
      lightPos0      = RH.lightPos0 renderSettingsCurr
      lightPos1      = RH.lightPos1 renderSettingsCurr
      vPerspective   = AC.renderPerspective contextSettings

  let updatePerspective p = if AC.autoPerspectiveSwitch contextSettings && tickMs >= AC.autoPerspectiveSwitchInterval contextSettings then ( do
                                let nextPerspective = RH.nextPerspective p
                                modifyIORef contextSettingsIORef ( \_ -> contextSettings { AC.renderPerspective = nextPerspective } )
                                modifyIORef renderSettingsIORef ( \_ -> renderSettingsCurr { RH.tick = 0 } )
                                return nextPerspective )
                            else return p
  curPerspective <- updatePerspective vPerspective

  let blendModeSource      = Conv.blendModeSourceFromIndex $ AC.blendModeSourceIdx contextSettings
  let blendModeFrameBuffer = Conv.blendModeFrameBufferFromIndex $ AC.blendModeFrameBufferIdx contextSettings

  -- blendFunc $= (blendModeSource, blendModeFrameBuffer)

  clear [DepthBuffer]

  preservingMatrix $ do

    let lightIntensity = lCoeff + bCoeff
          where (lCoeff,bCoeff) = RH.featuresToIntensity featuresCurr FE.GlobalTarget contextSettings

    RH.useLight $ (AC.light0 contextSettings) { AC.lightIntensity = lightIntensity }
    RH.useLight $ (AC.light1 contextSettings) { AC.lightIntensity = lightIntensity }
    GL.position (Light 0) $= lightPos0
    GL.position (Light 1) $= lightPos1

    ---------------------------------------------------------------------------------------------------
    -- Perspective transformations
    ---------------------------------------------------------------------------------------------------

    GL.translate $ Vector3 0 0 viewDistance

    RH.applyPerspective curPerspective
    RH.applyGlobalRotation fixedRotation accIncRotation

    ---------------------------------------------------------------------------------------------------
    -- End of perspective transformations
    ---------------------------------------------------------------------------------------------------

    -- (visWidth,visHeight,visDepth) <- (Visuals.dimensions visualUpdated)

    -- fogMode  $= Linear 0.0 (visDepth * 20.0)
    -- fogColor $= (Color4 0.0 0.0 0.0 1.0)

    -- GL.translate $ Vector3 (-0.5 * visWidth) 0 0
    -- GL.translate $ Vector3 0 0 (-0.5 * visDepth)

    Visuals.render visualUpdated

-- }}}

reshape :: IORef AC.ContextSettings -> Gtk.Rectangle -> IO ()
reshape settingsIORef allocation = do
  let rectangleWidthHeight (Gtk.Rectangle _ _ w' h') = (w',h')
  let (w,h) = rectangleWidthHeight allocation
  settings <- readIORef settingsIORef
  let viewAngle = AC.viewAngle settings
  matrixMode $= Projection
  viewport $= (Position 0 0, Size (fromIntegral w) (fromIntegral h))
  perspective (realToFrac viewAngle) (fromIntegral w / fromIntegral h) 0.1 100
  matrixMode $= Modelview 0
  return ()

-- Component init interface for main UI.
initComponent :: GtkBuilder.Builder -> IORef AC.ContextSettings -> IORef AC.ContextObjects -> IO ()
initComponent _ contextSettingsIORef contextObjectsIORef = do
-- {{{
  window <- Gtk.windowNew

  _ <- GLUT.initialize "drool visualizer" []

  Gtk.set window [ Gtk.containerBorderWidth := 0,
                   Gtk.windowTitle := "drool visualizer" ]

  putStrLn "Initializing OpenGL viewport"

  glConfig <- GtkGL.glConfigNew [GtkGL.GLModeRGBA, GtkGL.GLModeMultiSample, GtkGL.GLModeStencil,
                                 GtkGL.GLModeDouble, GtkGL.GLModeDepth, GtkGL.GLModeAlpha]
  _ <- GtkGL.initGL

  canvas <- GtkGL.glDrawingAreaNew glConfig

  cObjects   <- readIORef contextObjectsIORef
  cSettings  <- readIORef contextSettingsIORef
  let sigGen  = AC.signalGenerator cObjects

  let renderSettings = RH.RenderSettings { RH.signalGenerator   = sigGen,
                                           RH.samplingSem       = AC.samplingSem cObjects,
                                           RH.numNewSignalsChan = AC.numNewSignalsChan cObjects,
                                           RH.signalBuf         = AC.signalBuf cObjects,
                                           RH.featuresBuf       = AC.featuresBuf cObjects,
                                           RH.lightPos0         = (Vertex4 (-1.0) 3.0 (-2.0) 0.0),
                                           RH.lightPos1         = (Vertex4 1.0 3.0 2.0 0.0),
                                           RH.numSignals        = 0,
                                           RH.numNewSignals     = 0,
                                           RH.numSamples        = SigGen.numSamples sigGen,
                                           RH.tick              = 0 }

  renderSettingsIORef <- newIORef renderSettings

  let visualForegroundIORef   = AC.visualForeground cObjects
      visualMiddlegroundIORef = AC.visualMiddleground cObjects
      visualBackgroundIORef   = AC.visualBackground cObjects

  -- Initialise some GL setting just before the canvas first gets shown
  -- (We can't initialise these things earlier since the GL resources that
  -- we are using wouldn't have been setup yet)

  _ <- Gtk.onRealize canvas $ GtkGL.withGLDrawingArea canvas $ \_ -> do
    -- {{{

    -- depthMask $= Disabled
    -- dither $= Enabled
    normalize $= Enabled -- Automatically normaliye normal vectors to (-1.0,1.0)
    shadeModel $= Smooth
    depthFunc $= Just Less
    -- polygonSmooth $= Enabled
    -- lineSmooth $= Enabled
    lighting $= Enabled
    light (Light 0) $= Enabled
    light (Light 1) $= Enabled
    frontFace $= CCW
    blend $= Enabled
    multisample $= Enabled
    sampleAlphaToCoverage $= Enabled
    -- fog $= Enabled

    lineWidthRange <- GL.get smoothLineWidthRange
    lineWidth $= fst lineWidthRange -- use thinnest possible lines

    colorMaterial $= Just (FrontAndBack, AmbientAndDiffuse)

    let blendModeSource = Conv.blendModeSourceFromIndex $ AC.blendModeSourceIdx cSettings
    let blendModeFrameBuffer = Conv.blendModeFrameBufferFromIndex $ AC.blendModeFrameBufferIdx cSettings
    blendFunc $= (blendModeSource, blendModeFrameBuffer)

    hint PerspectiveCorrection $= Nicest
    -- hint PolygonSmooth $= Nicest
    -- hint LineSmooth $= Nicest

    matrixMode $= Projection
    loadIdentity
    viewport $= (Position 0 0, Size (fromIntegral canvasInitWidth) (fromIntegral canvasInitHeight))
    perspective (realToFrac $ AC.viewAngle cSettings) (fromIntegral canvasInitWidth / fromIntegral canvasInitHeight) 0.1 10

    matrixMode $= Modelview 0
    loadIdentity

    return ()
    -- }}}

  -- OnShow handler for GL canvas:
  _ <- Gtk.onExpose canvas $ \_ -> do
    GtkGL.withGLDrawingArea canvas $ \glwindow -> do
      let visualModels = [ visualBackgroundIORef, visualMiddlegroundIORef, visualForegroundIORef ]
      display contextSettingsIORef renderSettingsIORef visualModels
      GtkGL.glDrawableSwapBuffers glwindow
    return True

  -- Resize handler:
  _ <- Gtk.onSizeAllocate canvas (reshape contextSettingsIORef)

  -- Add canvas (OpenGL drawing area) to GUI:
  Gtk.widgetSetSizeRequest canvas canvasInitWidth canvasInitHeight

  Gtk.set window [ Gtk.containerChild := canvas ]

  -- Fullscreen mode:
  _ <- Gtk.on window Gtk.keyPressEvent $ Gtk.tryEvent $ do
    [Gtk.Control] <- Gtk.eventModifier
    "f" <- Gtk.eventKeyName
    liftIO $ Gtk.windowSetKeepAbove window True
    liftIO $ Gtk.windowFullscreen window

  _ <- Gtk.on window Gtk.keyPressEvent $ Gtk.tryEvent $ do
    "Escape" <- Gtk.eventKeyName
    liftIO $ Gtk.windowUnfullscreen window
    liftIO $ Gtk.windowSetKeepAbove window False

  let timeoutMs = (Conv.freqToMs $ AC.renderingFrequency cSettings)

{-
  -- Redraw canvas according to rendering frequency:
  updateCanvasTimer <- Gtk.timeoutAddFull (do
      Gtk.widgetQueueDraw canvas
      return True)
    Gtk.priorityDefaultIdle timeoutMs
  -- Remove timer for redrawing canvas when closing window:
  _ <- Gtk.onDestroy window (Gtk.timeoutRemove updateCanvasTimer)
-}

  -- Try to redraw canvas on every new signal:
  sampleThread <- C.forkOS . M.forever $ do nNewSignals <- MV.takeMVar $ AC.samplingSem cObjects
                                            modifyIORef renderSettingsIORef ( \rs -> rs { RH.numNewSignals = nNewSignals } )
                                            Gtk.postGUISync $ Gtk.widgetQueueDraw canvas

  Gtk.widgetShowAll window
-- }}}

canvasInitWidth :: Int
canvasInitWidth = 800
canvasInitHeight :: Int
canvasInitHeight = 600

mulColor4Value :: Color4 GLfloat -> GLfloat -> Color4 GLfloat
mulColor4Value (Color4 r g b a) value = Color4 r' g' b' a'
  where r' = r * value
        g' = g * value
        b' = b * value
        a' = a * value


text:
Text2Gear
=========

Sends text to Tizen Wearable from your phone and display this text like running line which positioned according device rotation


text:
// *********************************************************************
// Copyright 2000-2004, Princeton University.  All rights reserved.
// By using this software the USER indicates that he or she has read,
// understood and will comply with the following:
//
// --- Princeton University hereby grants USER nonexclusive permission
// to use, copy and/or modify this software for internal, noncommercial,
// research purposes only. Any distribution, including commercial sale
// or license, of this software, copies of the software, its associated
// documentation and/or modifications of either is strictly prohibited
// without the prior consent of Princeton University.  Title to copyright
// to this software and its associated documentation shall at all times
// remain with Princeton University.  Appropriate copyright notice shall
// be placed on all software copies, and a complete copy of this notice
// shall be included in all copies of the associated documentation.
// No right is  granted to use in advertising, publicity or otherwise
// any trademark,  service mark, or the name of Princeton University.
//
//
// --- This software and any associated documentation is provided "as is"
//
// PRINCETON UNIVERSITY MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS
// OR IMPLIED, INCLUDING THOSE OF MERCHANTABILITY OR FITNESS FOR A
// PARTICULAR PURPOSE, OR THAT  USE OF THE SOFTWARE, MODIFICATIONS, OR
// ASSOCIATED DOCUMENTATION WILL NOT INFRINGE ANY PATENTS, COPYRIGHTS,
// TRADEMARKS OR OTHER INTELLECTUAL PROPERTY RIGHTS OF A THIRD PARTY.
//
// Princeton University shall not be liable under any circumstances for
// any direct, indirect, special, incidental, or consequential damages
// with respect to any claim by USER or any third party on account of
// or arising from the use, or inability to use, this software or its
// associated documentation, even if Princeton University has been advised
// of the possibility of those damages.
// ********************************************************************/

#include <stdlib.h>
#include <iostream>
#include <vector>
#include <set>

//AARON -- for INT_MAX
#include <limits.h>

using namespace std;

#include "zchaff_dbase.h"

CDatabase::CDatabase(void) {
  _stats.mem_used_up                 = false;
  _stats.init_num_clauses            = 0;
  _stats.init_num_literals           = 0;
  _stats.num_added_clauses           = 0;
  _stats.num_added_literals          = 0;
  _stats.num_deleted_clauses         = 0;
  _stats.num_del_orig_cls            = 0;
  _stats.num_deleted_literals        = 0;
  _stats.num_enlarge                 = 0;
  _stats.num_compact                 = 0;
  _lit_pool_start = (CLitPoolElement *) malloc(sizeof(CLitPoolElement) *
                                               STARTUP_LIT_POOL_SIZE);
  _lit_pool_finish = _lit_pool_start;
  _lit_pool_end_storage = _lit_pool_start + STARTUP_LIT_POOL_SIZE;
  lit_pool_push_back(0);  // set the first element as a dummy element
  _params.mem_limit = 1024 * 1024 * 1024;  // that's 1 G
  variables()->resize(1);                  // var_id == 0 is never used.
  _allocated_gid                    = 0;

  //AARON
  _min_unit_idx = INT_MAX;
  _last_sz = 0;
}

CDatabase::~CDatabase(void) {
  free(_lit_pool_start);
}

unsigned CDatabase::estimate_mem_usage(void) {
  unsigned mem_lit_pool = sizeof(CLitPoolElement) * (lit_pool_size() +
                                                     lit_pool_free_space());
  unsigned mem_vars = sizeof(CVariable) * variables()->capacity();
  unsigned mem_cls = sizeof(CClause) * clauses()->capacity();
  unsigned mem_cls_queue = sizeof(int) * _unused_clause_idx.size();
  unsigned mem_watched = 2 * num_clauses() * sizeof(CLitPoolElement *);
  unsigned mem_lit_clauses = 0;
#ifdef KEEP_LIT_CLAUSES
  mem_lit_clauses = num_literals() * sizeof(ClauseIdx);
#endif
  return (mem_lit_pool + mem_vars + mem_cls +
          mem_cls_queue + mem_watched + mem_lit_clauses);
}

unsigned CDatabase::mem_usage(void) {
  int mem_lit_pool = (lit_pool_size() + lit_pool_free_space()) *
                     sizeof(CLitPoolElement);
  int mem_vars = sizeof(CVariable) * variables()->capacity();
  int mem_cls = sizeof(CClause) * clauses()->capacity();
  int mem_cls_queue = sizeof(int) * _unused_clause_idx.size();
  int mem_watched = 0, mem_lit_clauses = 0;
  for (unsigned i = 0, sz = variables()->size(); i < sz ;  ++i) {
    CVariable & v = variable(i);
    mem_watched        += v.watched(0).capacity() + v.watched(1).capacity();
#ifdef KEEP_LIT_CLAUSES
    mem_lit_clauses += v.lit_clause(0).capacity() + v.lit_clause(1).capacity();
#endif
  }
  mem_watched *= sizeof(CLitPoolElement*);
  mem_lit_clauses *= sizeof(ClauseIdx);
  return (mem_lit_pool + mem_vars + mem_cls +
          mem_cls_queue + mem_watched + mem_lit_clauses);
}

int CDatabase::alloc_gid(void) {
  for (unsigned i = 1; i <= WORD_WIDTH; ++i) {
    if (is_gid_allocated(i) == false) {

      //AARON
      if (!_allocated_gid) {
        _min_idx = INT_MAX;
        _max_idx = -1;
      }

      _allocated_gid |= (1 << (i-1));
      return i;
    }
  }
  warning(_POSITION_, "Not enough GID");
  return VOLATILE_GID;
}

void CDatabase::free_gid(int gid) {
  assert(gid > 0 && "Can't free volatile or permanent group");
  assert(gid <= WORD_WIDTH && "gid > WORD_WIDTH?");
  if (!is_gid_allocated(gid)) {
    fatal(_POSITION_, "Can't free unallocated GID");
  }
  _allocated_gid &= (~(1<< (gid-1)));
}

bool CDatabase::is_gid_allocated(int gid) {
  if (gid == VOLATILE_GID || gid == PERMANENT_GID)
    return true;
  assert(gid <= WORD_WIDTH && gid > 0);
  if (_allocated_gid & (1 << (gid -1)))
    return true;
  return false;
}

int CDatabase::merge_clause_group(int g2, int g1) {
  assert(g1 >0 && g2> 0 && "Can't merge with permanent or volatile group");
  assert(g1 != g2);
  assert(is_gid_allocated(g1) && is_gid_allocated(g2));
  for (unsigned i = 0, sz = clauses()->size(); i < sz; ++i) {
    if (clause(i).status() != DELETED_CL) {
      if (clause(i).gid(g1) == true) {
        clause(i).clear_gid(g1);
        clause(i).set_gid(g2);
      }
    }
  }
  free_gid(g1);
  return g2;
}

void CDatabase::mark_clause_deleted(CClause & cl) {
  ++_stats.num_deleted_clauses;
  _stats.num_deleted_literals += cl.num_lits();
  CLAUSE_STATUS status = cl.status();
  if (status == ORIGINAL_CL)
     _stats.num_del_orig_cls++;
  cl.set_status(DELETED_CL);
  for (unsigned i = 0; i < cl.num_lits(); ++i) {
    CLitPoolElement & l = cl.literal(i);
    --variable(l.var_index()).lits_count(l.var_sign());
    l.val() = 0;
  }
  _unused_clause_idx.insert(&cl - &(*clauses()->begin()));
}

bool CDatabase::is_conflicting(ClauseIdx cl) {
  CLitPoolElement * lits = clause(cl).literals();
  for (int i = 0, sz= clause(cl).num_lits(); i < sz;  ++i) {
    if (literal_value(lits[i]) != 0)
      return false;
  }
  return true;
}

bool CDatabase::is_satisfied(ClauseIdx cl) {
  CLitPoolElement * lits = clause(cl).literals();
  for (int i = 0, sz = clause(cl).num_lits(); i < sz; ++i) {
    if (literal_value(lits[i]) == 1)
      return true;
  }
  return false;
}

bool CDatabase::is_unit(ClauseIdx cl) {
  int num_unassigned = 0;
  CLitPoolElement * lits = clause(cl).literals();
  for (unsigned i = 0, sz= clause(cl).num_lits(); i < sz;  ++i) {
    int value = literal_value(lits[i]);
    if (value == 1)
      return false;
    else if (value != 0)
      ++num_unassigned;
  }
  return num_unassigned == 1;
}

int CDatabase::find_unit_literal(ClauseIdx cl) {
  // will return 0 if not unit
  int unit_lit = 0;
  for (int i = 0, sz = clause(cl).num_lits(); i < sz;  ++i) {
    int value = literal_value(clause(cl).literal(i));
    if (value == 1)
      return 0;
    else if (value != 0) {
      if (unit_lit == 0)
        unit_lit = clause(cl).literals()[i].s_var();
      else
        return 0;
    }
  }
  return unit_lit;
}

inline CLitPoolElement * CDatabase::lit_pool_begin(void) {
  return _lit_pool_start;
}

inline CLitPoolElement * CDatabase::lit_pool_end(void) {
  return _lit_pool_finish;
}

inline void CDatabase::lit_pool_incr_size(int size) {
  _lit_pool_finish += size;
  assert(_lit_pool_finish <= _lit_pool_end_storage);
}

inline void CDatabase::lit_pool_push_back(int value) {
  assert(_lit_pool_finish <= _lit_pool_end_storage);
  _lit_pool_finish->val() = value;
  ++_lit_pool_finish;
}

inline int CDatabase::lit_pool_size(void) {
  return _lit_pool_finish - _lit_pool_start;
}

inline int CDatabase::lit_pool_free_space(void) {
  return _lit_pool_end_storage - _lit_pool_finish;
}

inline double CDatabase::lit_pool_utilization(void) {
    // minus num_clauses() is because of spacing (i.e. clause indices)
  return (double)num_literals() / ((double) (lit_pool_size() - num_clauses())) ;
}

inline CLitPoolElement & CDatabase::lit_pool(int i) {
  return _lit_pool_start[i];
}

void CDatabase::compact_lit_pool(void) {
  unsigned i, sz;
  int new_index = 1;
  // first do the compaction for the lit pool
  for (i = 1, sz = lit_pool_size(); i < sz;  ++i) {
    // begin with 1 because 0 position is always 0
    if (!lit_pool(i).is_literal() && !lit_pool(i-1).is_literal()) {
      continue;
    } else {
      lit_pool(new_index) = lit_pool(i);
      ++new_index;
    }
  }
  _lit_pool_finish = lit_pool_begin() + new_index;
  // update all the pointers to the literals;
  // 1. clean up the watched pointers from variables
  for (i = 1, sz = variables()->size(); i < sz;  ++i) {
    variable(i).watched(0).clear();
    variable(i).watched(1).clear();
  }
  for (i = 1, sz = lit_pool_size(); i < sz;  ++i) {
    CLitPoolElement & lit = lit_pool(i);
    // 2. reinsert the watched pointers
    if (lit.is_literal()) {
      if (lit.is_watched()) {
         int var_idx = lit.var_index();
         int sign = lit.var_sign();
         variable(var_idx).watched(sign).push_back(& lit_pool(i));
       }
    } else {  // lit is not literal
    // 3. update the clauses' first literal pointer
      int cls_idx = lit.get_clause_index();
      clause(cls_idx).first_lit() = &lit_pool(i) - clause(cls_idx).num_lits();
    }
  }
  ++_stats.num_compact;
}

bool CDatabase::enlarge_lit_pool(void) {
  // will return true if successful, otherwise false.
  unsigned i, sz;
  // if memory efficiency < 2/3, we do a compaction
  if (lit_pool_utilization() < 0.67) {
    compact_lit_pool();
    return true;
  }
  // otherwise we have to enlarge it.
  // first, check if memory is running out
  int current_mem = estimate_mem_usage();
  float grow_ratio = 1;
  if (current_mem < _params.mem_limit / 4)
    grow_ratio = 2;
  else if (current_mem < _params.mem_limit /2 )
    grow_ratio = 1.5;
  else if (current_mem < _params.mem_limit * 0.8)
    grow_ratio = 1.2;
  if (grow_ratio < 1.2) {
    if (lit_pool_utilization() < 0.9) {  // still has some garbage
      compact_lit_pool();
      return true;
    }
    else {
      //AARON
      _params.mem_limit *= 2;
      grow_ratio = 1.5;
    }
  }
  // second, make room for new lit pool.
  CLitPoolElement * old_start = _lit_pool_start;
  CLitPoolElement * old_finish = _lit_pool_finish;
  int old_size = _lit_pool_end_storage - _lit_pool_start;
  int new_size = (int)(old_size * grow_ratio);
  _lit_pool_start = (CLitPoolElement *) realloc(_lit_pool_start,
                                                sizeof(CLitPoolElement) *
                                                new_size);
  _lit_pool_finish = _lit_pool_start + (old_finish - old_start);
  _lit_pool_end_storage = _lit_pool_start + new_size;

  // update all the pointers
  long displacement = _lit_pool_start - old_start;
  for (i = 0; i < clauses()->size(); ++i) {
    if (clause(i).status() != DELETED_CL)
      clause(i).first_lit() += displacement;
  }
  for (i = 0, sz = variables()->size(); i < sz ;  ++i) {
    CVariable & v = variable(i);
    for (int j = 0; j < 2 ; ++j) {
      int k, sz1;
      vector<CLitPoolElement *> & watched = v.watched(j);
      for (k = 0, sz1 = watched.size(); k < sz1 ; ++k) {
        watched[k] += displacement;
      }
    }
  }
  ++_stats.num_enlarge;
  return true;
}

ClauseIdx CDatabase::get_free_clause_idx(void) {
  /*
  ClauseIdx new_cl;
  new_cl = _clauses.size();
  _clauses.resize(new_cl + 1);
  clause(new_cl).set_id(_stats.num_added_clauses);
  return new_cl;
  */
  //AARON
  if (_unused_clause_idx.size() == 0) {
    ClauseIdx new_cl;
    new_cl = _clauses.size();
    _clauses.resize(new_cl + 1);
    clause(new_cl).set_id(_stats.num_added_clauses);
    return new_cl;
  }
  else {
    set<ClauseIdx>::iterator it = _unused_clause_idx.begin();
    ClauseIdx new_cl = *it;
    _unused_clause_idx.erase(it);
    clause(new_cl).set_id(_stats.num_added_clauses);
    return new_cl;
  }
}

ClauseIdx CDatabase::add_clause(int * lits, int n_lits, int gflag) {
  int new_cl;
  // a. do we need to enlarge lits pool?
  while (lit_pool_free_space() <= n_lits + 1) {
    if (enlarge_lit_pool() == false)
      return -1;  // mem out, can't enlarge lit pool, because
      // ClauseIdx can't be -1, so it shows error.
  }
  // b. get a free cl index;
  new_cl = get_free_clause_idx();

  //AARON
  if (gflag != 0) {
    _min_idx = _min_idx > new_cl ? new_cl : _min_idx;
    _max_idx = _max_idx < new_cl ? new_cl : _max_idx;
  }
  if (n_lits == 1 && new_cl < _min_unit_idx)
    _min_unit_idx = new_cl;

  // c. add the clause lits to lits pool
  CClause & cl = clause(new_cl);
  cl.init(lit_pool_end(), n_lits, gflag);
  lit_pool_incr_size(n_lits + 1);
  if (n_lits == 2) {
    ++variable(lits[0]>>1).two_lits_count(lits[0] & 0x1);
    ++variable(lits[1]>>1).two_lits_count(lits[1] & 0x1);
  }
  for (int i = 0; i < n_lits; ++i) {
    int var_idx = lits[i] >> 1;
    assert((unsigned)var_idx < variables()->size());
    int var_sign = lits[i] & 0x1;
    cl.literal(i).set(var_idx, var_sign);
    ++variable(var_idx).lits_count(var_sign);
#ifdef KEEP_LIT_CLAUSES
    variable(var_idx).lit_clause(var_sign).push_back(new_cl);
#endif
  }
  // the element after the last one is the spacing element
  cl.literal(n_lits).set_clause_index(new_cl);
  // d. set the watched pointers
  if (cl.num_lits() > 1) {
    // add the watched literal. note: watched literal must be the last free var
    int max_idx = -1, max_dl = -1;
    int i, sz = cl.num_lits();
    // set the first watched literal
    for (i = 0; i < sz; ++i) {
      int v_idx = cl.literal(i).var_index();
      int v_sign = cl.literal(i).var_sign();
      CVariable & v = variable(v_idx);
      if (literal_value(cl.literal(i)) != 0) {
#ifdef WLEFT
	CLitPoolElement t = cl.literal(n_lits-1);
	cl.literal(n_lits-1) = cl.literal(i);
	cl.literal(i) = t;
        v.watched(v_sign).push_back(&cl.literal(n_lits-1));
        cl.literal(n_lits-1).set_watch(-1);
#else
        v.watched(v_sign).push_back(&cl.literal(i));
        cl.literal(i).set_watch(1);
#endif
        break;
      } else {
        if (v.dlevel() > max_dl) {
          max_dl = v.dlevel();
          max_idx = i;
        }
      }
    }
    if (i >= sz) {  // no unassigned literal. so watch literal with max dlevel
      int v_idx = cl.literal(max_idx).var_index();
      int v_sign = cl.literal(max_idx).var_sign();
#ifdef WLEFT
      CLitPoolElement t = cl.literal(n_lits-1);
      cl.literal(n_lits-1) = cl.literal(max_idx);
      cl.literal(max_idx) = t;
      variable(v_idx).watched(v_sign).push_back(&cl.literal(n_lits-1));
      cl.literal(n_lits-1).set_watch(-1);
#else
      variable(v_idx).watched(v_sign).push_back(&cl.literal(max_idx));
      cl.literal(max_idx).set_watch(1);
#endif
    }

    // set the second watched literal
    max_idx = -1;
    max_dl = -1;
    for (i = sz-1; i >= 0; --i) {
      if (cl.literal(i).is_watched())
        continue;  // need to watch two different literals
      int v_idx = cl.literal(i).var_index();
      int v_sign = cl.literal(i).var_sign();
      CVariable & v = variable(v_idx);
      if (literal_value(cl.literal(i)) != 0) {
#ifdef WLEFT
	CLitPoolElement t = cl.literal(n_lits-2);
	cl.literal(n_lits-2) = cl.literal(i);
	cl.literal(i) = t;
        v.watched(v_sign).push_back(&cl.literal(n_lits-2));
        cl.literal(n_lits-2).set_watch(-1);
#else
        v.watched(v_sign).push_back(&cl.literal(i));
        cl.literal(i).set_watch(-1);
#endif
        break;
      } else {
        if (v.dlevel() > max_dl) {
          max_dl = v.dlevel();
          max_idx = i;
        }
      }
    }
    if (i < 0) {
      int v_idx = cl.literal(max_idx).var_index();
      int v_sign = cl.literal(max_idx).var_sign();
#ifdef WLEFT
      CLitPoolElement t = cl.literal(n_lits-2);
      cl.literal(n_lits-2) = cl.literal(max_idx);
      cl.literal(max_idx) = t;
      variable(v_idx).watched(v_sign).push_back(&cl.literal(n_lits-2));
      cl.literal(n_lits-2).set_watch(-1);
#else
      variable(v_idx).watched(v_sign).push_back(&cl.literal(max_idx));
      cl.literal(max_idx).set_watch(-1);
#endif
    }
  }

  //AARON
  if (gflag == 0) {
    for (unsigned i = 0, sz = n_lits; i < sz; ++i) {
      unsigned v_idx = cl.literal(i).var_index();
      if (variable(v_idx).lits_count(0) != 0 &&
          variable(v_idx).lits_count(1) != 0) {
        set<unsigned>::iterator it = _puni_phased.find(v_idx);
        if (it != _puni_phased.end())
          _puni_phased.erase(it);
      }
    }
  }

  // update some statistics
  ++_stats.num_added_clauses;
  _stats.num_added_literals += n_lits;
  return new_cl;
}

void CDatabase::output_lit_pool_stats(void) {
  cout << "Lit_Pool Used " << lit_pool_size() << " Free "
       << lit_pool_free_space()
       << " Total " << lit_pool_size() + lit_pool_free_space()
       << " Num. Cl " << num_clauses() << " Num. Lit " << num_literals()
       << " Efficiency " <<  lit_pool_utilization() << endl;
}

void CDatabase::detail_dump_cl(ClauseIdx cl_idx, ostream & os) {
  os << "CL : " << cl_idx;
  CClause & cl = clause(cl_idx);
  if (cl.status() == DELETED_CL)
    os << "\t\t\t======removed=====";
  char value;
  for (unsigned i = 0; i < cl.num_lits(); ++i) {
    if (literal_value(cl.literal(i)) == 0)
      value = '0';
    else if (literal_value(cl.literal(i)) == 1)
      value = '1';
    else
      value = 'X';
    os << cl.literal(i) << "(" << value << "@"
       << variable(cl.literal(i).var_index()).dlevel()<< ")  ";
  }
  os << endl;
}

void CDatabase::dump(ostream & os) {
  unsigned i;
  os << "Dump Database: " << endl;
  for (i = 0; i < _clauses.size(); ++i)
    detail_dump_cl(i);
  for (i = 1; i < _variables.size(); ++i)
    os << "VID " << i << ":\t" << variable(i);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <SeekBar
        android:id="@+id/SeekBar01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <TextView
        android:id="@+id/TextView01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <EditText android:id="@+id/EditText01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnSave"
        android:text="Save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>


text:
class CreateSocialFeatureLikes < ActiveRecord::Migration
  def change
    create_table :social_feature_likes do |t|
      t.integer :post_id
      t.integer :user_id

      t.timestamps
    end
  end
end


text:
package org.apache.zookeeper.server.util;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.BitSet;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * This is a helper class to maintain the bit to specific value and the
 * reversed value to bit mapping.
 */
public class BitMap<T> {

    private final Map<T, Integer> value2Bit = new HashMap<T, Integer>();
    private final Map<Integer, T> bit2Value = new HashMap<Integer, T>();

    private final BitSet freedBitSet = new BitSet();
    private Integer nextBit = Integer.valueOf(0);

    private final ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();

    @SuppressFBWarnings(value = "DLS_DEAD_LOCAL_STORE", justification = "SpotBugs false positive")
    public Integer add(T value) {
        /*
         * Optimized for code which will add the same value again and again,
         * more specifically this is used to add new bit for watcher, and
         * the same watcher may watching thousands or even millions of nodes,
         * which will call add the same value of this function, check exist
         * using read lock will optimize the performance here.
         */
        Integer bit = getBit(value);
        if (bit != null) {
            return bit;
        }

        rwLock.writeLock().lock();
        try {
            bit = value2Bit.get(value);
            if (bit != null) {
                return bit;
            }
            bit = freedBitSet.nextSetBit(0);
            if (bit > -1) {
                freedBitSet.clear(bit);
            } else {
                bit = nextBit++;
            }

            value2Bit.put(value, bit);
            bit2Value.put(bit, value);
            return bit;
        } finally {
            rwLock.writeLock().unlock();
        }
    }

    public T get(int bit) {
        rwLock.readLock().lock();
        try {
            return bit2Value.get(bit);
        } finally {
            rwLock.readLock().unlock();
        }
    }

    public Integer getBit(T value) {
        rwLock.readLock().lock();
        try {
            return value2Bit.get(value);
        } finally {
            rwLock.readLock().unlock();
        }
    }

    public int remove(T value) {
        /*
         * remove only called once when the session is closed, so use write
         * lock directly without checking read lock.
         */
        rwLock.writeLock().lock();
        try {
            Integer bit = value2Bit.get(value);
            if (bit == null) {
                return -1;
            }
            value2Bit.remove(value);
            bit2Value.remove(bit);
            freedBitSet.set(bit);
            return bit;
        } finally {
            rwLock.writeLock().unlock();
        }
    }

    public T remove(int bit) {
        rwLock.writeLock().lock();
        try {
            T value = bit2Value.get(bit);
            if (value == null) {
                return null;
            }
            value2Bit.remove(value);
            bit2Value.remove(bit);
            freedBitSet.set(bit);
            return value;
        } finally {
            rwLock.writeLock().unlock();
        }
    }

    public int size() {
        rwLock.readLock().lock();
        try {
            return value2Bit.size();
        } finally {
            rwLock.readLock().unlock();
        }
    }

}


text:
module WorthSaving
  class ApplicationController < ::ApplicationController
  end
end


text:
package org.odlabs.wiquery.ui.sortable;

import org.odlabs.wiquery.core.options.IComplexOption;

/**
 * $Id: SortableRevert.java
 * <p>
 * Bean for the revert option for the Sortable behavior
 * </p>
 *
 * @author Julien Roche
 * @since 1.0
 */
public class SortableRevert implements IComplexOption
{
	// Constants
	/** Constant of serialization */
	private static final long serialVersionUID = 3404088696595137949L;

	// Properties
	private Boolean booleanParam;

	private Integer intParameter;

	/**
	 * Constructor
	 *
	 * @param booleanParam
	 *            Boolean parameter
	 */
	public SortableRevert(Boolean booleanParam)
	{
		this(booleanParam, null);
	}

	/**
	 * Constructor
	 *
	 * @param intParameter
	 *            Integer parameter
	 */
	public SortableRevert(Integer intParameter)
	{
		this(null, intParameter);
	}

	/**
	 * Constructor
	 *
	 * @param booleanParam
	 *            Boolean parameter
	 * @param intParameter
	 *            Integer parameter
	 */
	private SortableRevert(Boolean booleanParam, Integer intParameter)
	{
		super();
		setParam(booleanParam, intParameter);
	}

	/**
	 * @return the booleanParam
	 */
	public Boolean getBooleanParam()
	{
		return booleanParam;
	}

	/**
	 * @return the intParameter
	 */
	public Integer getIntParam()
	{
		return intParameter;
	}

	public CharSequence getJavascriptOption()
	{
		if (booleanParam == null && intParameter == null)
		{
			throw new IllegalArgumentException(
				"The SortableRevert must have one not null parameter");
		}

		CharSequence sequence = null;

		if (booleanParam != null)
		{
			sequence = booleanParam.toString();
		}
		else if (intParameter != null)
		{
			sequence = intParameter.toString();
		}
		else
		{
			throw new IllegalArgumentException(
				"The SortableRevert must have one not null parameter");
		}

		return sequence;
	}

	/**
	 * Set's the boolean parameter
	 *
	 * @param booleanParam
	 *            the boolean to set
	 */
	public void setBooleanParam(Boolean booleanParam)
	{
		setParam(booleanParam, null);
	}

	/**
	 * Set's the Integer parameter
	 *
	 * @param intParameter
	 *            the integer to set
	 */
	public void setIntParam(Integer intParameter)
	{
		setParam(null, intParameter);
	}

	/**
	 * Method setting the right parameter
	 *
	 * @param booleanParam
	 *            Boolean parameter
	 * @param intParameter
	 *            Integer parameter
	 */
	private void setParam(Boolean booleanParam, Integer intParameter)
	{
		this.booleanParam = booleanParam;
		this.intParameter = intParameter;
	}
}