text:
<?php
include 'dbc.php';
page_protect();
include 'config.php';
include 'pm.php';
?>
 <?php $rs_settings = mysql_query("select * from users where id='$_SESSION[user_id]'"); 			while ($row_settings = mysql_fetch_array($rs_settings)) {
			$name = $row_settings['full_name'];
			$uname = $row_settings['user_name'];
			$uid = $row_settings['id'];
			}
$msgcount = new cpm($uid);
$msgcount->getmessages();
if (isset($_GET['pl'])){
	$spl = filter($_GET['pl']);
$page_limit = $spl;
} else {
$page_limit = 10;
}

			?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>LinkStor : Your Links Anywhere</title>
<link rel="stylesheet" href="resources/css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="resources/css/style.css" type="text/css" media="screen" />
<link rel="stylesheet" href="resources/css/invalid.css" type="text/css" media="screen" />

Simpla Admin

			  Hello <?php echo $uname;?>,  <?php echo count($msgcount->messages); ?> Messages

				Contact Support | Sign Out

					Home

Overview

News

About LinkStor

						My Links

View My Links

Add a New Link

Favorite Links

						Your Account

Edit Account

My Messages

Account Support

						Settings

Give Feedback

Users and Permissions

Plugins & Extensions

Donate

3 Messages

					17th May 2009 by Admin

					Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue.
					Remove

					2nd May 2009 by Jane Doe

					Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis elit sit amet quam. Vivamus pretium ornare est.
					Remove

					25th April 2009 by Admin

					Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue.
					Remove

				<form action="#" method="post">

New Message

					<fieldset>
						<textarea class="textarea" name="textfield" cols="79" rows="5"></textarea>
					</fieldset>

					<fieldset>

						<select name="dropdown" class="small-input">
							<option value="option1">Send to...</option>
							<option value="option2">Everyone</option>
							<option value="option3">Admin</option>
							<option value="option4">Jane Doe</option>
						</select>

						<input class="button" type="submit" value="Send" />

					</fieldset>

				</form>

						Javascript is disabled or is not supported by your browser. Please upgrade your browser or enable Javascript to navigate the interface properly.

Welcome <?php echo $name; ?>

What would you like to do?

					Add Link

					My Links

					Favorite Links

					Manage Account

					Messages

Your Links

                <?
				if (isset($_GET['del'])){
	$sdel = filter($_GET['del']);
	$check = mysql_query("SELECT `user` from links WHERE `id`='$sdel'");
	$chk = mysql_fetch_array($check);
	if ($chk['user'] == $_SESSION['user_id']){

	$delok = "2";

	}
	if ($chk['user'] != $_SESSION['user_id']) {
	$delok = "1";

	}
}

				if ($delok == "1") {
				echo "

Error - Link can not be removed.

";
				}
				if ($delok == "2"){
					mysql_query("DELETE FROM links WHERE `id`='$sdel'") or die(mysql_error());
					 echo "

Link Removed Successfully!

"; }

				if (isset($_GET['fav'])){

	$sfav = filter($_GET['fav']);
	$check2 = mysql_query("SELECT `user` from links WHERE `id`='$sfav'");
	$chk2 = mysql_fetch_array($check2);
	if ($chk2['user'] == $_SESSION['user_id']){
		mysql_query("UPDATE links SET `fav`='1' WHERE `id`='$sfav'") or die(mysql_error());
		echo "

Link has been added to your favorites.

";
	} else {
		echo "

Link can not be added to your favorites.

";

		 }
}
if (isset($_GET['nfav'])){

	$unfav = filter($_GET['nfav']);
	$check3 = mysql_query("SELECT `user` from links WHERE `id`='$unfav'");
	$chk3 = mysql_fetch_array($check3);
	if ($chk3['user'] == $_SESSION['user_id']){
		mysql_query("UPDATE links SET `fav`='0' WHERE `id`='$unfav'") or die(mysql_error());
		echo "

Link has been removed from your favorites.

";
	} else {
		echo "

Link can not be removed from your favorites.

";

		 }
}
if (!empty($_POST['u'])){
if ($_POST['dropdown'] == "favorite"){
	foreach ($_POST['u'] as $uid) {
		$id = filter($uid);
		$check4 = mysql_query("SELECT `user` from links WHERE `id`='$id'");
	$chk4 = mysql_fetch_array($check4);
	if ($chk4['user'] == $_SESSION['user_id']){
		mysql_query("UPDATE links SET `fav`='1' WHERE `id`='$id'") or die(mysql_error());
		$bmsg = "Selected links have added to your favorites.";
	} else { $emsg = "Error - Could not add all or some of the selected links to your favorites."; }
	}
}
if ($_POST['dropdown'] == "unfavorite") {
	foreach ($_POST['u'] as $uid2) {
		$id2 = filter($uid2);
		$check5 = mysql_query("SELECT `user` from links WHERE `id`='$id2'");
	$chk5 = mysql_fetch_array($check5);
	if ($chk5['user'] == $_SESSION['user_id']){
		mysql_query("UPDATE links SET `fav`='0' WHERE `id`='$id2'") or die(mysql_error());
		$bmsg = "Selected links have been removed from your favorites.";
	} else { $emsg = "Error - Could not remove all or some of the selected links from your favorites."; }
}}
if ($_POST['dropdown'] == "Delete") {
	foreach ($_POST['u'] as $uid3) {
		$id3 = filter($uid3);
		$check6 = mysql_query("SELECT `user` from links WHERE `id`='$id3'");
	$chk6 = mysql_fetch_array($check6);
	if ($chk6['user'] == $_SESSION['user_id']){
		mysql_query("DELETE FROM links WHERE `id`='$id3'") or die(mysql_error());
		$bmsg = "Selected links have been deleted from your account.";
	} else { $emsg = "Error - Could not delete all or some of the selected links from your account."; }
	}
}

if (isset($bmsg)){
echo "

".$bmsg."

";
}
if (isset($emsg)){
echo "

".$emsg."

";
}
}

				?>

                <form action="mylinks.php" method="post">

				      <input class="check-all" type="checkbox" />
				      Title

Link

				      Description
				      Date
				      Favorite
				      Actions

				    <?php

					$sql = "SELECT * FROM links WHERE `user` = $_SESSION[user_id] ORDER BY date DESC";
					$rs_total = mysql_query($sql) or die(mysql_error());
	  $total = mysql_num_rows($rs_total);

	  if (!isset($_GET['page']) )
		{ $start=0; } else
		{ $start = ($_GET['page'] - 1) * $page_limit; }

	  $rs_results = mysql_query($sql . " limit $start,$page_limit") or die(mysql_error());
	  $total_pages = ceil($total/$page_limit);

					if(!empty($_GET['s'])){
						$ss = filter($_GET['s']);
					$results = mysql_query("SELECT * FROM `links` WHERE (`title` LIKE'%$ss%' OR `desc` LIKE'%$ss%') AND `user`='$_SESSION[user_id]'");
					if(!empty($results)){
						$rs_results = $results;
					}
					}
					 while ($rrows = mysql_fetch_array($rs_results)) {?>

				      <input name="u[]" type="checkbox" value="<?php echo $rrows['id']; ?>" id="u[]" />
				      <?php echo $rrows['title']; ?>

<a target="_blank" href="<? echo $rrows['url']; ?>"><?php if(strlen($rrows['url']) > 30 ){
					  $short = substr($rrows['url'],0,30)."...";
					  echo $short;
					  } else { echo $rrows['url']; }

					   ?>

				      <?php echo $rrows['desc']; ?>

				          <?php echo $rrows['date']; ?>

				      <span id="ban<?php echo $rrows['id']; ?>">
				        <?php if($rrows['fav'] == "0") { echo "No"; } else { echo "Yes"; } ?>

				      <? if($rrows['fav'] == "0") {?><a href="mylinks.php?fav=<? echo $rrows['id']; ?>"><? } else { ?><a href="mylinks.php?nfav=<? echo $rrows['id'] ?>"><? } ?>  <a href="mylinks.php?del=<? echo $rrows['id']; ?>">

				    <?php } ?>

                  <?
				  if ($total == "0"){
					echo "
You have no links saved in your account, click Add Link above to save one
";
				  }

				   ?>

											<select name="dropdown">
												<option value="option1">Choose an action...</option>
												<option value="favorite">Favorite</option>
                                                <option value="unfavorite">Unfavorite</option>
												<option value="Delete">Delete</option>
											</select>
											<input name="bulkdo" type="submit" id="bulkdo" value="Apply to Selected" class="button"></form>

											« First<a href="mylinks.php?page=<? if($_GET['page'] > 1) { echo $_GET['page'] - 1; } else { echo "1"; } ?>" title="Previous Page">« Previous

                                            <?php

	  // outputting the pages
		if ($total > $page_limit)
		{

		$i = 0;
		while ($i < $total_pages)
		{

		$page_no = $i+1;
		$qstr = ereg_replace("&page=[0-9]+","",$_SERVER['QUERY_STRING']);
		echo "$page_no ";
		$i++;
		}

		}  ?>
											<a href="mylinks.php?page=<? if ($_GET['page'] == $total_pages) { echo "2"; } else { echo $_GET['page'] + 1; }?>" title="Next Page">Next »<a href="mylinks.php?page=<? if ($total_pages > 0) { echo $total_pages; } else { echo "1";}?>" title="Last Page">Last »

<form action="mylinks.php" method="get">
              Display per page:    <input class="text-input" size="4" type="text" id="pl" value="<? if (isset($spl)) { echo $spl; } else { echo "10"; }   ?>" name="pl" />   <input type="submit" value="Update" class="button">

<input type="text" name="s" id="s" class="text-input" size="25" /> <input type="submit" value="Search" class="button" />
</form>

				  © Copyright 2013 LinkStor | Created by Michael Curry | Top

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Truncates file descriptor fd to offset bytes</title>

dio_tcsetattr

dio_write

Direct IO Functions

PHP Manual

dio_truncate

(PHP 4 >= 4.2.0, PHP 5 <= 5.0.5)

dio_truncate —
   Truncates file descriptor fd to offset bytes

Description

   bool dio_truncate
    ( resource $fd
   , int $offset
   )

   dio_truncate() truncates a file to at most
   offset bytes in size.

   If the file previously was larger than this size, the extra data is
   lost. If the file previously was shorter, it is unspecified whether the
   file is left unchanged or is extended. In the latter case the extended
   part reads as zero bytes.

Parameters

fd

       The file descriptor returned by dio_open().

offset

       The offset in bytes.

Return Values

   Returns TRUE on success or FALSE on failure.

Notes

Note: This function is not
implemented on Windows platforms.

dio_tcsetattr

dio_write

Direct IO Functions

PHP Manual


text:
namespace System {

class ContextGroup {
public:
  explicit ContextGroup(Dispatcher& dispatcher);
  ContextGroup(const ContextGroup&) = delete;
  ContextGroup(ContextGroup&& other);
  ~ContextGroup();
  ContextGroup& operator=(const ContextGroup&) = delete;
  ContextGroup& operator=(ContextGroup&& other);
  void interrupt();
  void spawn(std::function<void()>&& procedure);
  void wait();

private:
  Dispatcher* dispatcher;
  NativeContextGroup contextGroup;
};

}


text:
"""testing angular momentum generators. _fermion_spin_operators.py"""
import unittest
from openfermion.ops.operators import FermionOperator, BosonOperator
from openfermion.utils import commutator
from openfermion.transforms.opconversions import normal_ordered
from openfermion.hamiltonians.special_operators import (
    majorana_operator, number_operator, s_minus_operator, s_plus_operator,
    s_squared_operator, sx_operator, sy_operator, sz_operator, up_index,
    down_index)

class FermionSpinOperatorsTest(unittest.TestCase):

    def test_up_index(self):
        self.assertEqual(up_index(2), 4)
        self.assertEqual(up_index(5), 10)

    def test_up_down(self):
        self.assertEqual(down_index(2), 5)
        self.assertEqual(down_index(5), 11)

    def test_s_plus_operator(self):
        op = s_plus_operator(2)
        expected = (FermionOperator(((0, 1), (1, 0))) + FermionOperator(
            ((2, 1), (3, 0))))
        self.assertEqual(op, expected)

    def test_s_minus_operator(self):
        op = s_minus_operator(3)
        expected = (FermionOperator(((1, 1), (0, 0))) + FermionOperator(
            ((3, 1), (2, 0))) + FermionOperator(((5, 1), (4, 0))))
        self.assertEqual(op, expected)

    def test_sx_operator(self):
        op = sx_operator(2)
        expected = (FermionOperator(((0, 1), (1, 0)), 0.5) + FermionOperator(
            ((1, 1), (0, 0)), 0.5) + FermionOperator(
                ((2, 1), (3, 0)), 0.5) + FermionOperator(((3, 1), (2, 0)), 0.5))
        self.assertEqual(op, expected)

    def test_sy_operator(self):
        op = sy_operator(2)
        expected = (FermionOperator(((0, 1), (1, 0)), -0.5j) - FermionOperator(
            ((1, 1), (0, 0)), -0.5j) + FermionOperator(
                ((2, 1), (3, 0)), -0.5j) - FermionOperator(
                    ((3, 1), (2, 0)), -0.5j))
        self.assertEqual(op, expected)

    def test_sz_operator(self):
        op = sz_operator(2)
        expected = (FermionOperator(((0, 1), (0, 0)), 0.5) - FermionOperator(
            ((1, 1), (1, 0)), 0.5) + FermionOperator(
                ((2, 1), (2, 0)), 0.5) - FermionOperator(((3, 1), (3, 0)), 0.5))
        self.assertEqual(op, expected)

    def test_s_squared_operator(self):
        op = s_squared_operator(2)
        s_minus = (FermionOperator(((1, 1), (0, 0))) + FermionOperator(
            ((3, 1), (2, 0))))
        s_plus = (FermionOperator(((0, 1), (1, 0))) + FermionOperator(
            ((2, 1), (3, 0))))
        s_z = (FermionOperator(((0, 1), (0, 0)), 0.5) - FermionOperator(
            ((1, 1), (1, 0)), 0.5) + FermionOperator(
                ((2, 1), (2, 0)), 0.5) - FermionOperator(((3, 1), (3, 0)), 0.5))
        expected = s_minus * s_plus + s_z * s_z + s_z
        self.assertEqual(op, expected)

    def test_relations(self):
        n_spatial_orbitals = 2

        s_plus = s_plus_operator(n_spatial_orbitals)
        s_minus = s_minus_operator(n_spatial_orbitals)
        sx = sx_operator(n_spatial_orbitals)
        sy = sy_operator(n_spatial_orbitals)
        sz = sz_operator(n_spatial_orbitals)
        s_squared = s_squared_operator(n_spatial_orbitals)

        identity = FermionOperator(())

        self.assertEqual(normal_ordered(sx),
                         normal_ordered(.5 * (s_plus + s_minus)))
        self.assertEqual(normal_ordered(sy),
                         normal_ordered((.5 / 1.j) * (s_plus - s_minus)))
        self.assertEqual(normal_ordered(s_squared),
                         normal_ordered(sx**2 + sy**2 + sz**2))
        self.assertEqual(
            normal_ordered(s_squared),
            normal_ordered(s_plus * s_minus + sz * (sz - identity)))
        self.assertEqual(normal_ordered(commutator(s_plus, s_minus)),
                         normal_ordered(2 * sz))
        self.assertEqual(normal_ordered(commutator(sx, sy)),
                         normal_ordered(1.j * sz))

    def test_invalid_input(self):

        with self.assertRaises(TypeError):
            s_minus_operator('a')

        with self.assertRaises(TypeError):
            s_plus_operator('a')

        with self.assertRaises(TypeError):
            sx_operator('a')

        with self.assertRaises(TypeError):
            sy_operator('a')

        with self.assertRaises(TypeError):
            sz_operator('a')

        with self.assertRaises(TypeError):
            s_squared_operator('a')

class NumberOperatorTest(unittest.TestCase):

    def test_fermion_number_operator_site(self):
        op = number_operator(3, 2, 1j, -1)
        self.assertEqual(op, FermionOperator(((2, 1), (2, 0))) * 1j)

        op = number_operator(3, 2, 1j, 1)
        self.assertTrue(op == BosonOperator(((2, 1), (2, 0))) * 1j)

    def test_number_operator_nosite(self):
        op = number_operator(4, parity=-1)
        expected = (FermionOperator(((0, 1), (0, 0))) + FermionOperator(
            ((1, 1), (1, 0))) + FermionOperator(
                ((2, 1), (2, 0))) + FermionOperator(((3, 1), (3, 0))))
        self.assertEqual(op, expected)

        op = number_operator(4, parity=1)
        expected = (BosonOperator(((0, 1), (0, 0))) + BosonOperator(
            ((1, 1), (1, 0))) + BosonOperator(((2, 1), (2, 0))) + BosonOperator(
                ((3, 1), (3, 0))))
        self.assertTrue(op == expected)

    def test_bad_parity(self):
        with self.assertRaises(ValueError):
            number_operator(4, parity=2)

class MajoranaOperatorTest(unittest.TestCase):

    def test_init(self):
        # Test 'c' operator
        op1 = majorana_operator((2, 0))
        op2 = majorana_operator('c2')
        op3 = majorana_operator(u'c2')
        correct = FermionOperator('2^') + FermionOperator('2')
        self.assertEqual(op1, op2)
        self.assertEqual(op1, op3)
        self.assertEqual(op1, correct)

        # Test 'd' operator
        op1 = majorana_operator((3, 1))
        op2 = majorana_operator('d3')
        correct = FermionOperator('3^', 1.j) - FermionOperator('3', 1.j)
        self.assertEqual(op1, op2)
        self.assertEqual(op1, correct)

        with self.assertRaises(ValueError):
            _ = majorana_operator('A2')

    def test_none_term(self):
        majorana_operator()
        self.assertEqual(majorana_operator(), FermionOperator())

    def test_bad_coefficient(self):
        with self.assertRaises(ValueError):
            majorana_operator((1, 1), 'a')

    def test_bad_term(self):
        with self.assertRaises(ValueError):
            majorana_operator((2, 2))
        with self.assertRaises(ValueError):
            majorana_operator('a')
        with self.assertRaises(ValueError):
            majorana_operator(2)


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<messageSchema package="SBE tests"
               id="13"
               semanticVersion="5.2"
               description="Unit Test"
               byteOrder="littleEndian">
    <types>
        <enum name="NullBoolean" encodingType="uint8" nullValue="255" semanticType="Boolean">
            <validValue name="F">0</validValue>
            <validValue name="T">1</validValue>
            <validValue name="BOGUS">255</validValue>
        </enum>
        <type name="ConstButNoValue" primitiveType="char" presence="constant"></type>
    </types>
    <message name="Message1" id="1">
        <field name="word!" id="10" type="uint32" semanticType="int"/>
    </message>
</messageSchema>


text:
<?php
	include_once('procedures.php');
	$gameList 		= getGameList();

	if (isActiveUser())
	{

		if (stripos($_SERVER['REQUEST_URI'], 'APimageViewer'))
			$_SESSION['adminPanelState'] = 'APimageViewer.php';

		// сессия состояния

		$typeId = -1;
		if (isset($_GET['type']))
			$typeId = intval($_GET['type']);

		// сессия - typeId
		if (stripos($_SERVER['REQUEST_URI'], 'APimageViewer'))
			$_SESSION['adminImgTypeId'] = $typeId;

		$gameId = -1;
		if (isset($_GET['game']))
			$gameId = intval($_GET['game']);

		// сессия - gameId
		if (stripos($_SERVER['REQUEST_URI'], 'APimageViewer'))
			$_SESSION['adminImgGameId'] = $gameId;

		// сбор инфы из бд
		$imageData = getImageData($typeId, $gameId);

?>

Viewer

		Категория изображения:
		<select id = "typeSelector" class="form-control" onchange = "loadViewerData(getTypeSelector(), -1)">
			<option value = "-1">Нет категории</option>
			<option value = "0">Новости</option>
			<option value = "1">Визуализатор</option>
		</select>

	<?php
		if ($typeId == 1)
		{
	 ?>

		Игра:
		<select id = "gameSelector" class="form-control" onchange = "loadViewerData(getTypeSelector(), getGameSelector())">
			<?php
				foreach ($gameList as $game)
				{
			?>
				<option value = "<?php echo $game['id']; ?>">
					<?php echo $game['name']; ?>
				</option>
			<?php
				}
			?>
		</select>

	<?php
		}
	?>

			Изображение
			Описание
			Путь

		<?php
			foreach ($imageData as $image)
			{
		?>

					<img src = "<?php echo getImageById($image['id']);?>">

				<?php echo $image['description']; ?>
				<?php echo getImageById($image['id']); ?>
				<button type = "submit" name = "deleteImage" class = "btn btn-danger" onclick = "deleteImage(<?php echo $image['id']; ?>);">Удалить</button>

		<?php
			}
		?>

	<?php
		}
		else
		{
	?>

Тебя не должно быть здесь!

	<?php
		}
	?>


text:
Coding Style guide for LTFS
=============

Naming conventions
-------------

- We don't use capital letters, except on defines and enumerators (see below).
- Public APIs are always prefixed by the name of that module:
  * ltfs.c: ltfs_statfs(), ltfs_open(), ltfs_close(), ltfs_read()
  * fs.c: fs_resolve_dentry(), fs_set_name(), fs_set_creation_time()

Spaces, tabs and commas
-------------

When indenting the code, always use TABs with 4 spaces. Do not replace TABs by spaces. Remove trailing spaces of a line and empty lines at the end of file.

When writing arguments to a function or defining enums, also use the following comma conventions:

```
call_function(arg1, arg2, arg3);

call_another_function(
	very_long_argument1,
	very_long_argument2,
	very_long_argument3
	);

enum very_cool_enumerator {
	VERY_COOL_1,
	VERY_COOL_2,
	VERY_COOL_3,
};
```

Macros and defines
-------------

When defining wrappers around functions using macros do that using lowercase characters. Defines always go in uppercase.

```
#define wrapper_around_some_function(x,y) \
	...

#define LTFS_MAX_VALUE 2112
```

Functions
-------------

Return type, function name and its parameters should go all in a single line, except if the parameters are too long.

```
void ltfs_function(void *params)
{
}

void ltfs_function_with_many_parameters(void *params1,
	void *params2, void *params3)
{
}
```

Conditional tests
-------------

```
if (condition) {
	line 1;
	line 2;
} else
	line 3;

if (another condition)
	do this;
else
	do that;

if (yet another condition) {
	/*
	 * It's ok to open brackets when adding comments,
	 * just to make it clear where the scope ends.
	 * That can improve readability when comments
	 * span across multiple lines.
	 */
	 do something else;
}
```

Loops
-------------

```
for (x=start; x<end; ++x) {
	body
}
```

Comments
-------------

Please do not use C++ style comments (//), except when
temporarily commenting out a line of code. If too many
lines are being commented out consider using #if 0 instead
or, preferably, just remove that code completely.

For comments, always use the C style (/* comments */),
even if that's just a single line.

For documenting functions, please use the Doxygen-friendly
format below:

```
/**
 * General comments about the function go here.
 * @param var1 Describe what var1 does.
 * @param var2 Describe what var2 does.
 * @return Describe what's expected to be returned both on
 *  success and on error situation. Also, note that we
 *  tabulate with one extra space when the comments span
 *  multiple lines.
 */
int function(void *var1, void *var2)
{
}
```

Maximum line length
-------------

Lines must not exceed 100 characters.


text:
import { getScreen } from './interface/screen';
import { getCommands } from './util/command-util';
import { generateLog } from './util/log-util';
import { logger } from './util/logger';
import { GIT_LOG_ARGS, stash } from './util/stash';

export const run = (args: string[]): void => {
	stash.set(GIT_LOG_ARGS, args);

	generateLog(getScreen(getCommands()));
};

export const runFromPipedData = (): void => {
	logger.warn('Piping into jack is not currently supported.');
	logger.warn(
		'If you would like to contribute or comment, please see the issue on ' +
			'GitHub at https://github.com/drewbrokke/jack/issues/9.',
	);

	process.exit(1);
};


text:
<?php

/**********************************************
	Filter inline blocks of raw HTML
***********************************************/
global $wsh_raw_parts;
$wsh_raw_parts=array();

/**
 * Extract content surrounded by [raw] or other supported tags
 * and replace it with placeholder text.
 *
 * @global array $wsh_raw_parts Used to store the extracted content blocks.
 *
 * @param string $text The input content to filter.
 * @param bool $keep_tags Store both the tagged content and the tags themselves. Defaults to false - storing only the content.
 * @return string Filtered content.
 */
function wsh_extract_exclusions($text, $keep_tags = false){
	global $wsh_raw_parts, $wp_current_filter;
	//Note to self: The regexp version was much shorter, but it had problems with big posts.

	$tags = array(array('', ''), array('[raw]', '[/raw]'), array('', ''));

	foreach ($tags as $tag_pair){
		list($start_tag, $end_tag) = $tag_pair;

		//Find the start tag
		$start = stripos($text, $start_tag, 0);
		while($start !== false){
			$content_start = $start + strlen($start_tag);

			//find the end tag
			$fin = stripos($text, $end_tag, $content_start);

			//break if there's no end tag
			if ($fin == false) break;

			//extract the content between the tags
			$content = substr($text, $content_start,$fin-$content_start);

			if ( (array_search('get_the_excerpt', $wp_current_filter) !== false) || (array_search('the_excerpt', $wp_current_filter) !== false) ){
				//Strip out the raw blocks when displaying an excerpt
				$replacement = '';
			} else {
				//Store the content and replace it with a marker
				if ( $keep_tags ){
					$wsh_raw_parts[]=$start_tag.$content.$end_tag;
				} else {
					$wsh_raw_parts[]=$content;
				}
				$replacement = "!RAWBLOCK".(count($wsh_raw_parts)-1)."!";
			}
			$text = substr_replace($text, $replacement, $start,
				$fin+strlen($end_tag)-$start
			);

			//Have we reached the end of the string yet?
			if ($start + strlen($replacement) > strlen($text)) break;

			//Find the next start tag
			$start = stripos($text, $start_tag, $start + strlen($replacement));
		}
	}
	return $text;
}

/**
 * Replace the placeholders created by wsh_extract_exclusions() with the original content.
 *
 * @global array $wsh_raw_parts Used to check if there is anything to insert.
 *
 * @param string $text The input content to filter.
 * @param callable|string $placeholder_callback Optional. The callback that will be used to process each placeholder.
 * @return string Filtered content.
 */
function wsh_insert_exclusions($text, $placeholder_callback = 'wsh_insertion_callback'){
	global $wsh_raw_parts;
	if(!isset($wsh_raw_parts)) return $text;
	return preg_replace_callback('/(
)?!RAWBLOCK(?P<index>\d+?)!(\s*?<\/p>)?/', $placeholder_callback, $text);
}

/**
 * Get the original content associated with a placeholder.
 *
 * @param array $matches Regex matches for a specific placeholder. @see wsh_insert_exclusions()
 * @return string Original content.
 */
function wsh_get_block_from_matches($matches) {
	global $wsh_raw_parts;

	if ( isset($matches['index']) ) {
		$index = $matches['index'];
	} else if ( isset($matches[2]) ) {
		$index = $matches[2];
	} else {
		return '{Invalid RAW block}';
	}

	$index = intval($index);
	return $wsh_raw_parts[$index];
}

/**
 * Regex callback for wsh_insert_exclusions. Returns the extracted content
 * corresponding to a matched placeholder.
 *
 * @param array $matches Regex matches.
 * @return string Replacement string for this match.
 */
function wsh_insertion_callback($matches){
	$openingParagraph = isset($matches[1]) ? $matches[1] : '';
	$closingParagraph = isset($matches[3]) ? $matches[3] : '';
	$code = wsh_get_block_from_matches($matches);

	//If the [raw] block is wrapped in its own paragraph, strip the
...
 tags. If there's
	//only one of
|
 tag present, keep it - it's probably part of a larger paragraph.
	if ( empty($openingParagraph) || empty($closingParagraph) ) {
		$code = $openingParagraph . $code . $closingParagraph;
	}
	return $code;
}

function wsh_setup_content_filters() {
	//Extract the tagged content before WP can get to it, then re-insert it later.
	add_filter('the_content', 'wsh_extract_exclusions', 2);

	//A workaround for WP-Syntax. If we run our insertion callback at the normal, extra-late
	//priority, WP-Syntax will see the wrong content when it runs its own content substitution hook.
	//We adapt to that by running our callback slightly earlier than WP-Syntax's.
	$wp_syntax_priority = has_filter('the_content', 'wp_syntax_after_filter');
	if ( $wp_syntax_priority === false && class_exists('WP_Syntax') ) {
		//Newer versions of WP-Syntax use a class with static methods instead of plain functions.
		$wp_syntax_priority = has_filter('the_content', array('WP_Syntax', 'afterFilter'));
	}
	if ( $wp_syntax_priority !== false ) {
		$rawhtml_priority = $wp_syntax_priority - 1;
	} else {
		$rawhtml_priority = 1001;
	}
	add_filter('the_content', 'wsh_insert_exclusions', $rawhtml_priority);
}
add_action('plugins_loaded', 'wsh_setup_content_filters', 11);

/*
 * WordPress can also mangle code when initializing the post/page editor.
 * To prevent this, we override the the_editor_content filter in almost
 * the same way that we did the_content.
 */

function wsh_extract_exclusions_for_editor($text){
	return wsh_extract_exclusions($text, true);
}

function wsh_insert_exclusions_for_editor($text){
	return wsh_insert_exclusions($text, 'wsh_insertion_callback_for_editor');
}

function wsh_insertion_callback_for_editor($matches){
	$code = wsh_get_block_from_matches($matches);
	return htmlspecialchars($code, ENT_NOQUOTES);
}

add_filter('the_editor_content', 'wsh_extract_exclusions_for_editor', 2);
add_filter('the_editor_content', 'wsh_insert_exclusions_for_editor', 1001);


text:
package org.pentaho.profiling.services;

import org.pentaho.profiling.api.StreamingProfile;
import org.pentaho.profiling.api.StreamingProfileService;
import org.pentaho.profiling.api.action.ProfileActionException;
import org.pentaho.profiling.api.doc.rest.Body;
import org.pentaho.profiling.api.doc.rest.ErrorCode;
import org.pentaho.profiling.api.doc.rest.Example;
import org.pentaho.profiling.api.doc.rest.SuccessResponseCode;
import org.pentaho.profiling.api.json.ObjectMapperFactory;
import org.pentaho.profiling.api.metrics.field.DataSourceFieldValue;
import org.pentaho.profiling.api.sample.SampleProviderManager;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.jws.WebService;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * Created by bryan on 3/26/15.
 */
@Produces( { MediaType.APPLICATION_JSON } )
@Consumes( { MediaType.APPLICATION_JSON } )
@WebService
public class StreamingProfileServiceRestImpl implements StreamingProfileService {
  public static final String JAVA_UTIL_LIST = "java.util.List";
  private static final Logger LOGGER = LoggerFactory.getLogger( StreamingProfileServiceRestImpl.class );
  private final StreamingProfileService delegate;
  private final ObjectMapper objectMapper;
  private final SampleProviderManager sampleProviderManager;

  public StreamingProfileServiceRestImpl( StreamingProfileService delegate, ObjectMapperFactory objectMapperFactory,
                                          SampleProviderManager sampleProviderManager ) {
    this.delegate = delegate;
    this.sampleProviderManager = sampleProviderManager;
    this.objectMapper = objectMapperFactory.createMapper();
  }

  /**
   * Returns the streaming profile for the given profile id.
   *
   * @param profileId The profile id.
   * @return The streaming profile for the given profile id.
   */
  @GET
  @Path( "/{profileId}" )
  @SuccessResponseCode( 200 )
  @ErrorCode( code = 404, reason = "Streaming profile with given id doesn't exist." )
  @Override public StreamingProfile getStreamingProfile( @PathParam( "profileId" ) String profileId ) {
    StreamingProfile streamingProfile = delegate.getStreamingProfile( profileId );
    if ( streamingProfile == null ) {
      throw new WebApplicationException( 404 );
    }
    return streamingProfile;
  }

  public List<Example> getStreamingProfileExample() {
    List<Example> examples = new ArrayList<Example>();
    for ( StreamingProfile streamingProfile : sampleProviderManager.provide( StreamingProfile.class ) ) {
      Example example = new Example();
      example.getPathParameters().put( "profileId", streamingProfile.getId() );
      example.setResponse( streamingProfile );
      examples.add( example );
    }
    return examples;
  }

  @Override public void processRecord( String profileId, List<DataSourceFieldValue> dataSourceFieldValues )
    throws ProfileActionException {
    delegate.processRecord( profileId, dataSourceFieldValues );
  }

  /**
   * Sends the record into the streaming profile to be processed.
   *
   * @param streamingRecordWrapper The record.
   * @throws ProfileActionException
   */
  @POST
  @Path( "/processRecord" )
  @SuccessResponseCode( 204 )
  @ErrorCode( code = 500, reason = "Error processing the record." )
  public void processRecord( StreamingRecordWrapper streamingRecordWrapper ) {
    try {
      processRecord( streamingRecordWrapper.getProfileId(), streamingRecordWrapper.getDataSourceFieldValues() );
    } catch ( ProfileActionException e ) {
      throw new WebApplicationException( 500 );
    }
  }

  public List<Example> processRecordExample() {
    List<Example> examples = new ArrayList<Example>();
    DataSourceFieldValue name = new DataSourceFieldValue( "Bob" );
    name.setLogicalName( "name" );
    name.setPhysicalName( "person.name" );
    DataSourceFieldValue age = new DataSourceFieldValue( 25 );
    age.setLogicalName( "age" );
    age.setPhysicalName( "person.age" );
    StreamingRecordWrapper streamingRecordWrapper =
      new StreamingRecordWrapper( UUID.randomUUID().toString(), new ArrayList<DataSourceFieldValue>(
        Arrays.<DataSourceFieldValue>asList( name, age ) ) );
    examples.add( new Example( null, null, streamingRecordWrapper, null ) );
    return examples;
  }

  /**
   * Processes a list of records.
   *
   * @param profileId          The profile id to send the records into.
   * @param httpServletRequest
   * @throws ProfileActionException
   * @throws IOException
   */
  @POST
  @Path( "/processRecords/{profileId}" )
  @SuccessResponseCode( 204 )
  @Body( name = "records", type = JAVA_UTIL_LIST, description = "The list of records." )
  public void processRecords( @PathParam( "profileId" ) String profileId,
                              @Context HttpServletRequest httpServletRequest )
    throws ProfileActionException, IOException {
    StreamingProfile streamingProfile = delegate.getStreamingProfile( profileId );
    if ( streamingProfile == null ) {
      LOGGER.warn( "Attempted to process records for nonexistent profile: " + profileId );
    }
    JsonFactory jsonFactory = objectMapper.getJsonFactory();
    JsonParser jsonParser = jsonFactory.createJsonParser( httpServletRequest.getInputStream() );
    if ( jsonParser.nextToken() != JsonToken.START_ARRAY ) {
      throw new IOException( "Expected request to start with array open" );
    }
    while ( jsonParser.nextToken() != JsonToken.END_ARRAY ) {
      List<DataSourceFieldValue> record =
        objectMapper.readValue( jsonParser, new TypeReference<List<DataSourceFieldValue>>() {
        } );
      streamingProfile.processRecord( record );
    }
  }

  public List<Example> processRecordsExample() {
    List<Example> examples = new ArrayList<Example>();
    List<DataSourceFieldValue> record = new ArrayList<DataSourceFieldValue>();
    DataSourceFieldValue name = new DataSourceFieldValue( "Bob" );
    name.setLogicalName( "name" );
    name.setPhysicalName( "person.name" );
    record.add( name );
    DataSourceFieldValue age = new DataSourceFieldValue( 25 );
    age.setLogicalName( "age" );
    age.setPhysicalName( "person.age" );
    record.add( age );
    List<List<DataSourceFieldValue>> records = new ArrayList<List<DataSourceFieldValue>>();
    records.add( record );
    record = new ArrayList<DataSourceFieldValue>();
    name = new DataSourceFieldValue( "Jane" );
    name.setLogicalName( "name" );
    name.setPhysicalName( "person.name" );
    record.add( name );
    age = new DataSourceFieldValue( 45 );
    age.setLogicalName( "age" );
    age.setPhysicalName( "person.age" );
    record.add( age );
    records.add( record );
    Example example = new Example();
    example.setBody( records );
    example.getPathParameters().put( "profileId", UUID.randomUUID().toString() );
    examples.add( example );
    return examples;
  }
}


text:
typedef struct Rulebook_s {
  FARule *rules[MAX_RULES];
  unsigned int count;
} Rulebook;

Rulebook* Rulebook_create();
void Rulebook_add_rule(Rulebook *rulebook, FARule *rule);
unsigned int Rulebook_next_state(Rulebook *rulebook, unsigned int state, char character);
void Rulebook_destroy(Rulebook *rulebook);
Set* Rulebook_next_states(Rulebook *rulebook, Set *states, char character);
Set* Rulebook_follow_free_moves(Rulebook *rulebook, Set *states);

#endif


text:
from clime.core import Command
from clime.core import Program

import sys

def parse(sdk, path):
    print sdk

def cmd_main():
    parse_command = Command(parse)
    parse_command.execute(' '.join(sys.argv[1:]))


text:
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.

#if !NO_PERF
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Threading;

namespace System.Reactive.Linq.ObservableImpl
{
    class Buffer<TSource> : Producer<IList<TSource>>
    {
        private readonly IObservable<TSource> _source;
        private readonly int _count;
        private readonly int _skip;

        private readonly TimeSpan _timeSpan;
        private readonly TimeSpan _timeShift;
        private readonly IScheduler _scheduler;

        public Buffer(IObservable<TSource> source, int count, int skip)
        {
            _source = source;
            _count = count;
            _skip = skip;
        }

        public Buffer(IObservable<TSource> source, TimeSpan timeSpan, TimeSpan timeShift, IScheduler scheduler)
        {
            _source = source;
            _timeSpan = timeSpan;
            _timeShift = timeShift;
            _scheduler = scheduler;
        }

        public Buffer(IObservable<TSource> source, TimeSpan timeSpan, int count, IScheduler scheduler)
        {
            _source = source;
            _timeSpan = timeSpan;
            _count = count;
            _scheduler = scheduler;
        }

        protected override IDisposable Run(IObserver<IList<TSource>> observer, IDisposable cancel, Action<IDisposable> setSink)
        {
            if (_scheduler == null)
            {
                var sink = new _(this, observer, cancel);
                setSink(sink);
                return sink.Run();
            }
            else if (_count > 0)
            {
                var sink = new Impl(this, observer, cancel);
                setSink(sink);
                return sink.Run();
            }
            else
            {
                if (_timeSpan == _timeShift)
                {
                    var sink = new BufferTimeShift(this, observer, cancel);
                    setSink(sink);
                    return sink.Run();
                }
                else
                {
                    var sink = new BufferImpl(this, observer, cancel);
                    setSink(sink);
                    return sink.Run();
                }
            }
        }

        class _ : Sink<IList<TSource>>, IObserver<TSource>
        {
            private readonly Buffer<TSource> _parent;

            public _(Buffer<TSource> parent, IObserver<IList<TSource>> observer, IDisposable cancel)
                : base(observer, cancel)
            {
                _parent = parent;
            }

            private Queue<IList<TSource>> _queue;
            private int _n;

            public IDisposable Run()
            {
                _queue = new Queue<IList<TSource>>();
                _n = 0;

                CreateWindow();
                return _parent._source.SubscribeSafe(this);
            }

            private void CreateWindow()
            {
                var s = new List<TSource>();
                _queue.Enqueue(s);
            }

            public void OnNext(TSource value)
            {
                foreach (var s in _queue)
                    s.Add(value);

                var c = _n - _parent._count + 1;
                if (c >= 0 && c % _parent._skip == 0)
                {
                    var s = _queue.Dequeue();
                    if (s.Count > 0)
                        base._observer.OnNext(s);
                }

                _n++;
                if (_n % _parent._skip == 0)
                    CreateWindow();
            }

            public void OnError(Exception error)
            {
                while (_queue.Count > 0)
                    _queue.Dequeue().Clear();

                base._observer.OnError(error);
                base.Dispose();
            }

            public void OnCompleted()
            {
                while (_queue.Count > 0)
                {
                    var s = _queue.Dequeue();
                    if (s.Count > 0)
                        base._observer.OnNext(s);
                }

                base._observer.OnCompleted();
                base.Dispose();
            }
        }

        class BufferImpl : Sink<IList<TSource>>, IObserver<TSource>
        {
            private readonly Buffer<TSource> _parent;

            public BufferImpl(Buffer<TSource> parent, IObserver<IList<TSource>> observer, IDisposable cancel)
                : base(observer, cancel)
            {
                _parent = parent;
            }

            private TimeSpan _totalTime;
            private TimeSpan _nextShift;
            private TimeSpan _nextSpan;

            private object _gate;
            private Queue<List<TSource>> _q;

            private SerialDisposable _timerD;

            public IDisposable Run()
            {
                _totalTime = TimeSpan.Zero;
                _nextShift = _parent._timeShift;
                _nextSpan = _parent._timeSpan;

                _gate = new object();
                _q = new Queue<List<TSource>>();

                _timerD = new SerialDisposable();

                CreateWindow();
                CreateTimer();

                var subscription = _parent._source.SubscribeSafe(this);

                return new CompositeDisposable { _timerD, subscription };
            }

            private void CreateWindow()
            {
                var s = new List<TSource>();
                _q.Enqueue(s);
            }

            private void CreateTimer()
            {
                var m = new SingleAssignmentDisposable();
                _timerD.Disposable = m;

                var isSpan = false;
                var isShift = false;
                if (_nextSpan == _nextShift)
                {
                    isSpan = true;
                    isShift = true;
                }
                else if (_nextSpan < _nextShift)
                    isSpan = true;
                else
                    isShift = true;

                var newTotalTime = isSpan ? _nextSpan : _nextShift;
                var ts = newTotalTime - _totalTime;
                _totalTime = newTotalTime;

                if (isSpan)
                    _nextSpan += _parent._timeShift;
                if (isShift)
                    _nextShift += _parent._timeShift;

                m.Disposable = _parent._scheduler.Schedule(new State { isSpan = isSpan, isShift = isShift }, ts, Tick);
            }

            struct State
            {
                public bool isSpan;
                public bool isShift;
            }

            private IDisposable Tick(IScheduler self, State state)
            {
                lock (_gate)
                {
                    //
                    // Before v2, the two operations below were reversed. This doesn't have an observable
                    // difference for Buffer, but is done to keep code consistent with Window, where we
                    // took a breaking change in v2 to ensure consistency across overloads. For more info,
                    // see the comment in Tick for Window.
                    //
                    if (state.isSpan)
                    {
                        var s = _q.Dequeue();
                        base._observer.OnNext(s);
                    }

                    if (state.isShift)
                    {
                        CreateWindow();
                    }
                }

                CreateTimer();

                return Disposable.Empty;
            }

            public void OnNext(TSource value)
            {
                lock (_gate)
                {
                    foreach (var s in _q)
                        s.Add(value);
                }
            }

            public void OnError(Exception error)
            {
                lock (_gate)
                {
                    while (_q.Count > 0)
                        _q.Dequeue().Clear();

                    base._observer.OnError(error);
                    base.Dispose();
                }
            }

            public void OnCompleted()
            {
                lock (_gate)
                {
                    while (_q.Count > 0)
                        base._observer.OnNext(_q.Dequeue());

                    base._observer.OnCompleted();
                    base.Dispose();
                }
            }
        }

        class BufferTimeShift : Sink<IList<TSource>>, IObserver<TSource>
        {
            private readonly Buffer<TSource> _parent;

            public BufferTimeShift(Buffer<TSource> parent, IObserver<IList<TSource>> observer, IDisposable cancel)
                : base(observer, cancel)
            {
                _parent = parent;
            }

            private object _gate;
            private List<TSource> _list;

            public IDisposable Run()
            {
                _gate = new object();
                _list = new List<TSource>();

                var d = _parent._scheduler.SchedulePeriodic(_parent._timeSpan, Tick);
                var s = _parent._source.SubscribeSafe(this);

                return new CompositeDisposable(d, s);
            }

            private void Tick()
            {
                lock (_gate)
                {
                    base._observer.OnNext(_list);
                    _list = new List<TSource>();
                }
            }

            public void OnNext(TSource value)
            {
                lock (_gate)
                {
                    _list.Add(value);
                }
            }

            public void OnError(Exception error)
            {
                lock (_gate)
                {
                    _list.Clear();

                    base._observer.OnError(error);
                    base.Dispose();
                }
            }

            public void OnCompleted()
            {
                lock (_gate)
                {
                    base._observer.OnNext(_list);
                    base._observer.OnCompleted();
                    base.Dispose();
                }
            }
        }

        class Impl : Sink<IList<TSource>>, IObserver<TSource>
        {
            private readonly Buffer<TSource> _parent;

            public Impl(Buffer<TSource> parent, IObserver<IList<TSource>> observer, IDisposable cancel)
                : base(observer, cancel)
            {
                _parent = parent;
            }

            private object _gate;
            private IList<TSource> _s;
            private int _n;
            private int _windowId;

            private SerialDisposable _timerD;

            public IDisposable Run()
            {
                _gate = new object();
                _s = default(IList<TSource>);
                _n = 0;
                _windowId = 0;

                _timerD = new SerialDisposable();

                _s = new List<TSource>();
                CreateTimer(0);

                var subscription = _parent._source.SubscribeSafe(this);

                return new CompositeDisposable { _timerD, subscription };
            }

            private void CreateTimer(int id)
            {
                var m = new SingleAssignmentDisposable();
                _timerD.Disposable = m;

                m.Disposable = _parent._scheduler.Schedule(id, _parent._timeSpan, Tick);
            }

            private IDisposable Tick(IScheduler self, int id)
            {
                var d = Disposable.Empty;

                var newId = 0;
                lock (_gate)
                {
                    if (id != _windowId)
                        return d;

                    _n = 0;
                    newId = ++_windowId;

                    var res = _s;
                    _s = new List<TSource>();
                    base._observer.OnNext(res);
                }

                CreateTimer(newId);

                return d;
            }

            public void OnNext(TSource value)
            {
                var newWindow = false;
                var newId = 0;

                lock (_gate)
                {
                    _s.Add(value);

                    _n++;
                    if (_n == _parent._count)
                    {
                        newWindow = true;
                        _n = 0;
                        newId = ++_windowId;

                        var res = _s;
                        _s = new List<TSource>();
                        base._observer.OnNext(res);
                    }
                }

                if (newWindow)
                    CreateTimer(newId);
            }

            public void OnError(Exception error)
            {
                lock (_gate)
                {
                    _s.Clear();
                    base._observer.OnError(error);
                    base.Dispose();
                }
            }

            public void OnCompleted()
            {
                lock (_gate)
                {
                    base._observer.OnNext(_s);
                    base._observer.OnCompleted();
                    base.Dispose();
                }
            }
        }
    }

    class Buffer<TSource, TBufferClosing> : Producer<IList<TSource>>
    {
        private readonly IObservable<TSource> _source;
        private readonly Func<IObservable<TBufferClosing>> _bufferClosingSelector;
        private readonly IObservable<TBufferClosing> _bufferBoundaries;

        public Buffer(IObservable<TSource> source, Func<IObservable<TBufferClosing>> bufferClosingSelector)
        {
            _source = source;
            _bufferClosingSelector = bufferClosingSelector;
        }

        public Buffer(IObservable<TSource> source, IObservable<TBufferClosing> bufferBoundaries)
        {
            _source = source;
            _bufferBoundaries = bufferBoundaries;
        }

        protected override IDisposable Run(IObserver<IList<TSource>> observer, IDisposable cancel, Action<IDisposable> setSink)
        {
            if (_bufferClosingSelector != null)
            {
                var sink = new _(this, observer, cancel);
                setSink(sink);
                return sink.Run();
            }
            else
            {
                var sink = new Beta(this, observer, cancel);
                setSink(sink);
                return sink.Run();
            }
        }

        class _ : Sink<IList<TSource>>, IObserver<TSource>
        {
            private readonly Buffer<TSource, TBufferClosing> _parent;

            public _(Buffer<TSource, TBufferClosing> parent, IObserver<IList<TSource>> observer, IDisposable cancel)
                : base(observer, cancel)
            {
                _parent = parent;
            }

            private IList<TSource> _buffer;
            private object _gate;
            private AsyncLock _bufferGate;

            private SerialDisposable _m;

            public IDisposable Run()
            {
                _buffer = new List<TSource>();
                _gate = new object();
                _bufferGate = new AsyncLock();

                _m = new SerialDisposable();
                var groupDisposable = new CompositeDisposable(2) { _m };

                groupDisposable.Add(_parent._source.SubscribeSafe(this));

                _bufferGate.Wait(CreateBufferClose);

                return groupDisposable;
            }

            private void CreateBufferClose()
            {
                var bufferClose = default(IObservable<TBufferClosing>);
                try
                {
                    bufferClose = _parent._bufferClosingSelector();
                }
                catch (Exception exception)
                {
                    lock (_gate)
                    {
                        base._observer.OnError(exception);
                        base.Dispose();
                    }
                    return;
                }

                var closingSubscription = new SingleAssignmentDisposable();
                _m.Disposable = closingSubscription;
                closingSubscription.Disposable = bufferClose.SubscribeSafe(new Omega(this, closingSubscription));
            }

            private void CloseBuffer(IDisposable closingSubscription)
            {
                closingSubscription.Dispose();

                lock (_gate)
                {
                    var res = _buffer;
                    _buffer = new List<TSource>();
                    base._observer.OnNext(res);
                }

                _bufferGate.Wait(CreateBufferClose);
            }

            class Omega : IObserver<TBufferClosing>
            {
                private readonly _ _parent;
                private readonly IDisposable _self;

                public Omega(_ parent, IDisposable self)
                {
                    _parent = parent;
                    _self = self;
                }

                public void OnNext(TBufferClosing value)
                {
                    _parent.CloseBuffer(_self);
                }

                public void OnError(Exception error)
                {
                    _parent.OnError(error);
                }

                public void OnCompleted()
                {
                    _parent.CloseBuffer(_self);
                }
            }

            public void OnNext(TSource value)
            {
                lock (_gate)
                {
                    _buffer.Add(value);
                }
            }

            public void OnError(Exception error)
            {
                lock (_gate)
                {
                    _buffer.Clear();
                    base._observer.OnError(error);
                    base.Dispose();
                }
            }

            public void OnCompleted()
            {
                lock (_gate)
                {
                    base._observer.OnNext(_buffer);
                    base._observer.OnCompleted();
                    base.Dispose();
                }
            }
        }

        class Beta : Sink<IList<TSource>>, IObserver<TSource>
        {
            private readonly Buffer<TSource, TBufferClosing> _parent;

            public Beta(Buffer<TSource, TBufferClosing> parent, IObserver<IList<TSource>> observer, IDisposable cancel)
                : base(observer, cancel)
            {
                _parent = parent;
            }

            private IList<TSource> _buffer;
            private object _gate;

            private RefCountDisposable _refCountDisposable;

            public IDisposable Run()
            {
                _buffer = new List<TSource>();
                _gate = new object();

                var d = new CompositeDisposable(2);
                _refCountDisposable = new RefCountDisposable(d);

                d.Add(_parent._source.SubscribeSafe(this));
                d.Add(_parent._bufferBoundaries.SubscribeSafe(new Omega(this)));

                return _refCountDisposable;
            }

            class Omega : IObserver<TBufferClosing>
            {
                private readonly Beta _parent;

                public Omega(Beta parent)
                {
                    _parent = parent;
                }

                public void OnNext(TBufferClosing value)
                {
                    lock (_parent._gate)
                    {
                        var res = _parent._buffer;
                        _parent._buffer = new List<TSource>();
                        _parent._observer.OnNext(res);
                    }
                }

                public void OnError(Exception error)
                {
                    _parent.OnError(error);
                }

                public void OnCompleted()
                {
                    _parent.OnCompleted();
                }
            }

            public void OnNext(TSource value)
            {
                lock (_gate)
                {
                    _buffer.Add(value);
                }
            }

            public void OnError(Exception error)
            {
                lock (_gate)
                {
                    _buffer.Clear();
                    base._observer.OnError(error);
                    base.Dispose();
                }
            }

            public void OnCompleted()
            {
                lock (_gate)
                {
                    base._observer.OnNext(_buffer);
                    base._observer.OnCompleted();
                    base.Dispose();
                }
            }
        }
    }
}
#endif


text:
namespace password_manager {

class MockCredentialsCleaner : public CredentialsCleaner {
 public:
  MockCredentialsCleaner() = default;
  ~MockCredentialsCleaner() override = default;
  MOCK_METHOD0(NeedsCleaning, bool());
  MOCK_METHOD1(StartCleaning, void(Observer* observer));

 private:
  DISALLOW_COPY_AND_ASSIGN(MockCredentialsCleaner);
};

class DestructionCheckableCleanerRunner : public CredentialsCleanerRunner {
 public:
  // |object_destroyed| is used to inform caller that the object destroyed
  // itself.
  explicit DestructionCheckableCleanerRunner(bool* object_destroyed)
      : object_destroyed_(object_destroyed) {}

 private:
  ~DestructionCheckableCleanerRunner() override { *object_destroyed_ = true; }

  // The class will assign true to the pointee on destruction.
  bool* object_destroyed_;
};

class CredentialsCleanerRunnerTest : public ::testing::Test {
 public:
  CredentialsCleanerRunnerTest() = default;

  ~CredentialsCleanerRunnerTest() override { EXPECT_TRUE(runner_destroyed_); }

 protected:
  CredentialsCleanerRunner* GetRunner() { return cleaning_tasks_runner_; }

 private:
  bool runner_destroyed_ = false;

  // This is a non-owning pointer, because the runner will delete itself.
  DestructionCheckableCleanerRunner* cleaning_tasks_runner_ =
      new DestructionCheckableCleanerRunner(&runner_destroyed_);

  DISALLOW_COPY_AND_ASSIGN(CredentialsCleanerRunnerTest);
};

// This test would fail if the object doesn't delete itself.
TEST_F(CredentialsCleanerRunnerTest, EmptyTasks) {
  GetRunner()->StartCleaning();
}

// In this test we check that credential clean-ups runner executes the clean-up
// tasks in the order they were added.
TEST_F(CredentialsCleanerRunnerTest, NonEmptyTasks) {
  static constexpr int kCleanersCount = 5;

  auto* cleaning_tasks_runner = GetRunner();
  std::vector<MockCredentialsCleaner*> raw_cleaners;
  for (int i = 0; i < kCleanersCount; ++i) {
    auto cleaner = std::make_unique<MockCredentialsCleaner>();
    raw_cleaners.push_back(cleaner.get());
    EXPECT_CALL(*cleaner, NeedsCleaning).WillOnce(::testing::Return(true));
    cleaning_tasks_runner->MaybeAddCleaningTask(std::move(cleaner));
  }

  ::testing::InSequence dummy;
  for (MockCredentialsCleaner* cleaner : raw_cleaners)
    EXPECT_CALL(*cleaner, StartCleaning(cleaning_tasks_runner));

  cleaning_tasks_runner->StartCleaning();
  for (int i = 0; i < kCleanersCount; ++i)
    cleaning_tasks_runner->CleaningCompleted();
}

}  // namespace password_manager


text:
//
//  BMBaseViewController.h
//  WeexDemo
//
//  Created by XHY on 2017/1/12.
//  Copyright © 2017年 taobao. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "BMRouterModel.h"
#import "BMCommonRequest.h"

@interface BMBaseViewController : UIViewController

@property (nonatomic, strong) WXSDKInstance *instance;      /**< instance */
@property (nonatomic, strong) NSURL *url;
@property (nonatomic, strong) BMRouterModel *routerModel;   /**< 页面导航信息 */

/* 刷新weex页面 */
- (void)refreshWeex;

/* 属于此页面的请求 请调用此方法来将请求的引用添加给此页面,在页面执行viewDidAppear方法时会cancel掉请求 */
- (void)addRequest:(BMCommonRequest *)request;

@end


text:
/**
 *
 * @author greg (at) myrobotlab.org
 *
 * This file is part of MyRobotLab (http://myrobotlab.org).
 *
 * MyRobotLab is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version (subject to the "Classpath" exception
 * as provided in the LICENSE.txt file that accompanied this code).
 *
 * MyRobotLab is distributed in the hope that it will be useful or fun,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * All libraries in thirdParty bundle are subject to their own license
 * requirements - please refer to http://myrobotlab.org/libraries for
 * details.
 *
 * Enjoy !
 *
 * */

package org.myrobotlab.control;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.service.GUIService;
import org.myrobotlab.service.PID;
import org.slf4j.Logger;

public class PIDGUI extends ServiceGUI implements ActionListener {

	JTextField kp = new JTextField(10);
	JTextField ki = new JTextField(10);
	JTextField kd = new JTextField(10);
	JButton setPID = new JButton("set");

	JButton direction = new JButton("invert");
	JButton setPid = new JButton("set pid");

	static final long serialVersionUID = 1L;
	public final static Logger log = LoggerFactory.getLogger(PIDGUI.class.getCanonicalName());

	public PIDGUI(final String boundServiceName, final GUIService myService, final JTabbedPane tabs) {
		super(boundServiceName, myService, tabs);
	}

	public void init() {
		gc.gridx = 0;
		gc.gridy = 0;

		direction.addActionListener(this);
		setPID.addActionListener(this);

		JPanel flow = new JPanel();

		flow.add(new JLabel("Kp"));
		flow.add(kp);
		flow.add(new JLabel("Ki"));
		flow.add(ki);
		flow.add(new JLabel("Kd"));
		flow.add(kd);
		flow.add(setPID);
		flow.add(direction);

		display.add(flow);
	}

	public void getState(final PID pid) {
		log.info("here");
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				int dir = pid.getControllerDirection();
				if (dir == PID.DIRECTION_REVERSE)
				{
					direction.setText("direct");
				} else {
					direction.setText("invert");
				}

				ki.setText(String.format("%s", pid.getKi()));
				kp.setText(String.format("%s", pid.getKp()));
				kd.setText(String.format("%s", pid.getKd()));

			}
		});
	}

	@Override
	public void attachGUI() {
		subscribe("publishState", "getState", PID.class);
		myService.send(boundServiceName, "publishState");
	}

	@Override
	public void detachGUI() {
		unsubscribe("publishState", "getState", PID.class);
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		Object o = event.getSource();
		if (o == direction)
		{
			if (direction.getText().equals("invert"))
			{
				myService.send(boundServiceName, "setControllerDirection", new Integer(PID.DIRECTION_REVERSE));
				direction.setText("direct");
			} else {
				myService.send(boundServiceName, "setControllerDirection", new Integer(PID.DIRECTION_DIRECT));
				direction.setText("invert");
			}
		} else if (o == setPID)
		{
			Double Kp = Double.parseDouble(kp.getText());
			Double Ki = Double.parseDouble(ki.getText());
			Double Kd = Double.parseDouble(kd.getText());
			myService.send(boundServiceName, "setPID", Kp, Ki, Kd);
		}

	}

}


text:
class Ey::Core::Client
  class Real
    def get_database_servers_firewalls(params={})
      query = Ey::Core.paging_parameters(params)
      url = params.delete("url")
      id = params["database_server_id"]

      request(
        :params => params,
        :query  => query,
        :path   => "/database-servers/#{id}/firewalls",
        :url    => url,
      )
    end
  end

  class Mock
    def get_database_servers_firewalls(params={})
      extract_url_params!(params)

      headers, firewalls_page = search_and_page(params, :firewalls, search_keys: %w[cluster name])

      response(
        :body    => {"firewalls" => firewalls_page},
        :status  => 200,
        :headers => headers
      )
    end
  end
end


text:
<?php
/** src/App/Controller/AbstractController.php */
namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController as Controller;
use Symfony\Component\HttpFoundation\JsonResponse;

/**
 * Class AbstractController
 * @package App\Controller
 */
abstract class AbstractController extends Controller
{
    /**
     * Format alert response
     * @param string $message
     * @return JsonResponse
     */
    protected function alert($message)
    {
        return $this->json(['status' => "alert", 'errorMessage' => $message]);
    }

    /**
     * Format error response
     * @param string $message
     * @return JsonResponse
     */
    protected function error($message)
    {
        return $this->json(['status' => "error", 'errorMessage' => $message]);
    }
}


text:
class ModuleDocFragment(object):

    # Standard documentation fragment
    DOCUMENTATION = r'''
options:
  backup:
    description:
    - Create a backup file including the timestamp information so you can get
      the original file back if you somehow clobbered it incorrectly.
    type: bool
    default: no
'''


text:
mod block_wand;
mod boolean_query;
mod boolean_weight;

pub(crate) use self::block_wand::{block_wand, block_wand_single_scorer};
pub use self::boolean_query::BooleanQuery;

#[cfg(test)]
mod tests {

    use super::*;
    use crate::collector::tests::TEST_COLLECTOR_WITH_SCORE;
    use crate::collector::TopDocs;
    use crate::query::score_combiner::SumWithCoordsCombiner;
    use crate::query::term_query::TermScorer;
    use crate::query::{
        Intersection, Occur, Query, QueryParser, RequiredOptionalScorer, Scorer, TermQuery,
    };
    use crate::schema::*;
    use crate::{assert_nearly_equals, DocAddress, DocId, Index, Score};

    fn aux_test_helper() -> crate::Result<(Index, Field)> {
        let mut schema_builder = Schema::builder();
        let text_field = schema_builder.add_text_field("text", TEXT);
        let schema = schema_builder.build();
        let index = Index::create_in_ram(schema);
        {
            // writing the segment
            let mut index_writer = index.writer_for_tests()?;
            index_writer.add_document(doc!(text_field => "a b c"))?;
            index_writer.add_document(doc!(text_field => "a c"))?;
            index_writer.add_document(doc!(text_field => "b c"))?;
            index_writer.add_document(doc!(text_field => "a b c d"))?;
            index_writer.add_document(doc!(text_field => "d"))?;
            index_writer.commit()?;
        }
        Ok((index, text_field))
    }

    #[test]
    pub fn test_boolean_non_all_term_disjunction() -> crate::Result<()> {
        let (index, text_field) = aux_test_helper()?;
        let query_parser = QueryParser::for_index(&index, vec![text_field]);
        let query = query_parser.parse_query("(+a +b) d")?;
        let searcher = index.reader()?.searcher();
        assert_eq!(query.count(&searcher)?, 3);
        Ok(())
    }

    #[test]
    pub fn test_boolean_single_must_clause() -> crate::Result<()> {
        let (index, text_field) = aux_test_helper()?;
        let query_parser = QueryParser::for_index(&index, vec![text_field]);
        let query = query_parser.parse_query("+a")?;
        let searcher = index.reader()?.searcher();
        let weight = query.weight(&searcher, true)?;
        let scorer = weight.scorer(searcher.segment_reader(0u32), 1.0)?;
        assert!(scorer.is::<TermScorer>());
        Ok(())
    }

    #[test]
    pub fn test_boolean_termonly_intersection() -> crate::Result<()> {
        let (index, text_field) = aux_test_helper()?;
        let query_parser = QueryParser::for_index(&index, vec![text_field]);
        let searcher = index.reader()?.searcher();
        {
            let query = query_parser.parse_query("+a +b +c")?;
            let weight = query.weight(&searcher, true)?;
            let scorer = weight.scorer(searcher.segment_reader(0u32), 1.0)?;
            assert!(scorer.is::<Intersection<TermScorer>>());
        }
        {
            let query = query_parser.parse_query("+a +(b c)")?;
            let weight = query.weight(&searcher, true)?;
            let scorer = weight.scorer(searcher.segment_reader(0u32), 1.0)?;
            assert!(scorer.is::<Intersection<Box<dyn Scorer>>>());
        }
        Ok(())
    }

    #[test]
    pub fn test_boolean_reqopt() -> crate::Result<()> {
        let (index, text_field) = aux_test_helper()?;
        let query_parser = QueryParser::for_index(&index, vec![text_field]);
        let searcher = index.reader()?.searcher();
        {
            let query = query_parser.parse_query("+a b")?;
            let weight = query.weight(&searcher, true)?;
            let scorer = weight.scorer(searcher.segment_reader(0u32), 1.0)?;
            assert!(scorer.is::<RequiredOptionalScorer<
                Box<dyn Scorer>,
                Box<dyn Scorer>,
                SumWithCoordsCombiner,
            >>());
        }
        {
            let query = query_parser.parse_query("+a b")?;
            let weight = query.weight(&searcher, false)?;
            let scorer = weight.scorer(searcher.segment_reader(0u32), 1.0)?;
            assert!(scorer.is::<TermScorer>());
        }
        Ok(())
    }

    #[test]
    pub fn test_boolean_query() -> crate::Result<()> {
        let (index, text_field) = aux_test_helper()?;

        let make_term_query = |text: &str| {
            let term_query = TermQuery::new(
                Term::from_field_text(text_field, text),
                IndexRecordOption::Basic,
            );
            let query: Box<dyn Query> = Box::new(term_query);
            query
        };

        let reader = index.reader()?;

        let matching_docs = |boolean_query: &dyn Query| {
            reader
                .searcher()
                .search(boolean_query, &TEST_COLLECTOR_WITH_SCORE)
                .unwrap()
                .docs()
                .iter()
                .cloned()
                .map(|doc| doc.doc_id)
                .collect::<Vec<DocId>>()
        };
        {
            let boolean_query = BooleanQuery::new(vec![(Occur::Must, make_term_query("a"))]);
            assert_eq!(matching_docs(&boolean_query), vec![0, 1, 3]);
        }
        {
            let boolean_query = BooleanQuery::new(vec![(Occur::Should, make_term_query("a"))]);
            assert_eq!(matching_docs(&boolean_query), vec![0, 1, 3]);
        }
        {
            let boolean_query = BooleanQuery::new(vec![
                (Occur::Should, make_term_query("a")),
                (Occur::Should, make_term_query("b")),
            ]);
            assert_eq!(matching_docs(&boolean_query), vec![0, 1, 2, 3]);
        }
        {
            let boolean_query = BooleanQuery::new(vec![
                (Occur::Must, make_term_query("a")),
                (Occur::Should, make_term_query("b")),
            ]);
            assert_eq!(matching_docs(&boolean_query), vec![0, 1, 3]);
        }
        {
            let boolean_query = BooleanQuery::new(vec![
                (Occur::Must, make_term_query("a")),
                (Occur::Should, make_term_query("b")),
                (Occur::MustNot, make_term_query("d")),
            ]);
            assert_eq!(matching_docs(&boolean_query), vec![0, 1]);
        }
        {
            let boolean_query = BooleanQuery::new(vec![(Occur::MustNot, make_term_query("d"))]);
            assert_eq!(matching_docs(&boolean_query), Vec::<u32>::new());
        }
        Ok(())
    }

    #[test]
    pub fn test_boolean_query_two_excluded() -> crate::Result<()> {
        let (index, text_field) = aux_test_helper()?;

        let make_term_query = |text: &str| {
            let term_query = TermQuery::new(
                Term::from_field_text(text_field, text),
                IndexRecordOption::Basic,
            );
            let query: Box<dyn Query> = Box::new(term_query);
            query
        };

        let reader = index.reader()?;

        let matching_topdocs = |query: &dyn Query| {
            reader
                .searcher()
                .search(query, &TopDocs::with_limit(3))
                .unwrap()
        };

        let score_doc_4: Score; // score of doc 4 should not be influenced by exclusion
        {
            let boolean_query_no_excluded =
                BooleanQuery::new(vec![(Occur::Must, make_term_query("d"))]);
            let topdocs_no_excluded = matching_topdocs(&boolean_query_no_excluded);
            assert_eq!(topdocs_no_excluded.len(), 2);
            let (top_score, top_doc) = topdocs_no_excluded[0];
            assert_eq!(top_doc, DocAddress::new(0, 4));
            assert_eq!(topdocs_no_excluded[1].1, DocAddress::new(0, 3)); // ignore score of doc 3.
            score_doc_4 = top_score;
        }

        {
            let boolean_query_two_excluded = BooleanQuery::new(vec![
                (Occur::Must, make_term_query("d")),
                (Occur::MustNot, make_term_query("a")),
                (Occur::MustNot, make_term_query("b")),
            ]);
            let topdocs_excluded = matching_topdocs(&boolean_query_two_excluded);
            assert_eq!(topdocs_excluded.len(), 1);
            let (top_score, top_doc) = topdocs_excluded[0];
            assert_eq!(top_doc, DocAddress::new(0, 4));
            assert_eq!(top_score, score_doc_4);
        }
        Ok(())
    }

    #[test]
    pub fn test_boolean_query_with_weight() -> crate::Result<()> {
        let mut schema_builder = Schema::builder();
        let text_field = schema_builder.add_text_field("text", TEXT);
        let schema = schema_builder.build();
        let index = Index::create_in_ram(schema);
        {
            let mut index_writer = index.writer_for_tests()?;
            index_writer.add_document(doc!(text_field => "a b c"))?;
            index_writer.add_document(doc!(text_field => "a c"))?;
            index_writer.add_document(doc!(text_field => "b c"))?;
            index_writer.commit()?;
        }
        let term_a: Box<dyn Query> = Box::new(TermQuery::new(
            Term::from_field_text(text_field, "a"),
            IndexRecordOption::WithFreqs,
        ));
        let term_b: Box<dyn Query> = Box::new(TermQuery::new(
            Term::from_field_text(text_field, "b"),
            IndexRecordOption::WithFreqs,
        ));
        let reader = index.reader().unwrap();
        let searcher = reader.searcher();
        let boolean_query =
            BooleanQuery::new(vec![(Occur::Should, term_a), (Occur::Should, term_b)]);
        let boolean_weight = boolean_query.weight(&searcher, true).unwrap();
        {
            let mut boolean_scorer = boolean_weight.scorer(searcher.segment_reader(0u32), 1.0)?;
            assert_eq!(boolean_scorer.doc(), 0u32);
            assert_nearly_equals!(boolean_scorer.score(), 0.84163445);
        }
        {
            let mut boolean_scorer = boolean_weight.scorer(searcher.segment_reader(0u32), 2.0)?;
            assert_eq!(boolean_scorer.doc(), 0u32);
            assert_nearly_equals!(boolean_scorer.score(), 1.6832689);
        }
        Ok(())
    }

    #[test]
    pub fn test_intersection_score() -> crate::Result<()> {
        let (index, text_field) = aux_test_helper()?;

        let make_term_query = |text: &str| {
            let term_query = TermQuery::new(
                Term::from_field_text(text_field, text),
                IndexRecordOption::Basic,
            );
            let query: Box<dyn Query> = Box::new(term_query);
            query
        };
        let reader = index.reader()?;
        let score_docs = |boolean_query: &dyn Query| {
            let fruit = reader
                .searcher()
                .search(boolean_query, &TEST_COLLECTOR_WITH_SCORE)
                .unwrap();
            fruit.scores().to_vec()
        };

        {
            let boolean_query = BooleanQuery::new(vec![
                (Occur::Must, make_term_query("a")),
                (Occur::Must, make_term_query("b")),
            ]);
            let scores = score_docs(&boolean_query);
            assert_nearly_equals!(scores[0], 0.977973);
            assert_nearly_equals!(scores[1], 0.84699446);
        }
        Ok(())
    }

    #[test]
    pub fn test_explain() -> crate::Result<()> {
        let mut schema_builder = Schema::builder();
        let text = schema_builder.add_text_field("text", STRING);
        let schema = schema_builder.build();
        let index = Index::create_in_ram(schema);
        let mut index_writer = index.writer_with_num_threads(1, 5_000_000)?;
        index_writer.add_document(doc!(text=>"a"))?;
        index_writer.add_document(doc!(text=>"b"))?;
        index_writer.commit()?;
        let searcher = index.reader()?.searcher();
        let term_a: Box<dyn Query> = Box::new(TermQuery::new(
            Term::from_field_text(text, "a"),
            IndexRecordOption::Basic,
        ));
        let term_b: Box<dyn Query> = Box::new(TermQuery::new(
            Term::from_field_text(text, "b"),
            IndexRecordOption::Basic,
        ));
        let query = BooleanQuery::from(vec![(Occur::Should, term_a), (Occur::Should, term_b)]);
        let explanation = query.explain(&searcher, DocAddress::new(0, 0u32))?;
        assert_nearly_equals!(explanation.value(), std::f32::consts::LN_2);
        Ok(())
    }
}


text:
require 'spec_helper'

describe ExecutionTimer do

  describe '#get_time' do

    before do
      @prc = Proc.new do
        "a"*1_000_000_000
      end
    end

    it 'should return milliseconds when given a block' do
      expect(described_class.get_time &@prc).to be_an_instance_of(Fixnum)
    end

    it 'should raise ArgumentError if no block given' do
      expect{ described_class.get_time 'hello' }.to raise_error(ArgumentError)
    end

  end

end