text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>EAPSI: End-On vs. Side-On Dinitrogen Binding in Homogeneous and Heterogeneous Transition Metal Cataly</AwardTitle>
    <AwardEffectiveDate>06/01/2008</AwardEffectiveDate>
    <AwardExpirationDate>05/31/2009</AwardExpirationDate>
    <AwardAmount>5637</AwardAmount>
    <AwardInstrument>
      <Value>Fellowship</Value>
    </AwardInstrument>
    <Organization>
      01090000
      <Directorate>
        <LongName>Office Of The Director</LongName>
      </Directorate>
      <Division>
        <LongName>Office Of Internatl Science &Engineering</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Anne L. Emig</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration>2008 EAPSI Fellowship<br/>This award supports a U.S. graduate student to conduct an individual research project at one of seven locations in East Asia and the Pacific region (Australia, China, Japan, Korea, New Zealand, Singapore, Taiwan). The research project will provide the student with a first-hand mentored research experience, an introduction to science and science policy infrastructure, and an orientation to the culture and language of the location. The primary goals of the East Asia Summer Institute program are to expose students to science and engineering in the context of a research laboratory, and to initiate early-career professional relationships that will foster research collaborations with foreign counterparts in the future.</AbstractNarration>
    <MinAmdLetterDate>05/15/2008</MinAmdLetterDate>
    <MaxAmdLetterDate>05/15/2008</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>0812806</AwardID>
    <Investigator>
      <FirstName>Aaron</FirstName>
      <LastName>Pierpont</LastName>
      <EmailAddress/>
      <StartDate>05/15/2008</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Pierpont Aaron</Name>
      <CityName>Denton</CityName>
      <ZipCode>762015070</ZipCode>
      <PhoneNumber/>
      <StreetAddress/>
      <CountryName>United States</CountryName>
      <StateName>Texas</StateName>
      <StateCode>TX</StateCode>
    </Institution>
    <FoaInformation>
      0000099
      <Name>Other Applications NEC</Name>
    </FoaInformation>
  </Award>
</rootTag>


text:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class EnemyCounter : MonoBehaviour {
	public GameRounds Rounds;
	public HUDManager HudManager;

	public int TotalEnemies;
	public int TotalCapturedEnemies;
	public int TotalMissedEnemies;
	public float TotalMoneyUSD;

	public int RoundTotalEnemies;
	public int RoundRunningEnemies;
	public int RoundCapturedEnemies;
	public int RoundMissedEnemies;

	public void Awake()
	{
		Rounds.RoundStarted += RoundStarted;
	}

	public void Start()
	{
		HudManager.SetMissed(RoundMissedEnemies, Rounds.CurrentRound.MaxMissedEnemies);
	}

	public void RoundStarted(int round)
	{
		RoundTotalEnemies = 0;
		RoundRunningEnemies = 0;
		RoundCapturedEnemies = 0;
		RoundMissedEnemies = 0;
	}

	public void CountCreated()
	{
		TotalEnemies++;
		RoundRunningEnemies++;
		RoundTotalEnemies++;

		HudManager.SetTotal(RoundTotalEnemies);
	}

	public void CountCaptured()
	{
		RoundRunningEnemies--;
		RoundCapturedEnemies++;
		TotalCapturedEnemies++;

		HudManager.SetCaptured(RoundCapturedEnemies);
	}

	public void CountMissed()
	{
		RoundRunningEnemies--;
		RoundMissedEnemies++;
		TotalMissedEnemies++;

		HudManager.SetMissed(RoundMissedEnemies, Rounds.CurrentRound.MaxMissedEnemies);
		HudManager.SetExchangeRate(-.1F);
	}

	public void AddUSD(int value) {

		// get the current USD labe as a float
		var currentUSD = float.Parse(HudManager.MoneyUSDValue.text);

		// add the new value
		currentUSD += value;

		// Update all money
		HudManager.UpdateMoney(currentUSD);
	}
}

redpajama_set_name: RedPajamaGithub


text:
describe("Tests dealing with spies", function()
	local test = {}

	before_each(function()
		test = {key = function()
			return "derp"
		end}
	end)
--[[
	it("checks if a spy actually executes the internal function", function()
		spy.on(test, "key")
		assert(test.key() == "derp")
	end)
]]
	it("checks to see if spy keeps track of arguments", function()

		spy.on(test, "key")

		test.key("derp")
		assert.spy(test.key).was.called_with("derp")
		assert.errors(function() assert.spy(test.key).was.called_with("herp") end)
	end)

	it("checks to see if spy keeps track of number of calls", function()
		 spy.on(test, "key")
		 test.key()
		 test.key("test")
		 assert.spy(test.key).was.called(2)
	end)

	it("checks called() and called_with() assertions", function()
		local s = spy.new(function() end)

		s(1, 2, 3)
		s("a", "b", "c")
		assert.spy(s).was.called()
		assert.spy(s).was.called(2) -- twice!
		assert.spy(s).was_not.called(3)
		assert.spy(s).was_not.called_with({1, 2, 3}) -- mind the accolades
		assert.spy(s).was.called_with(1, 2, 3)
		assert.has_error(function() assert.spy(s).was.called_with(5, 6) end)
	end)

	it("checks spies to fail when spying on non-callable elements", function()
		local s
		local testfunc = function()
			spy.new(s)
		end
		-- try some types to fail
		s = "some string";	assert.has_error(testfunc)
		s = 10;						 assert.has_error(testfunc)
		s = true;					 assert.has_error(testfunc)
		-- try some types to succeed
		s = function() end; assert.has_no_error(testfunc)
		s = setmetatable( {}, { __call = function() end } ); assert.has_no_error(testfunc)
	end)

	it("checks reverting a spy.on call", function()
		 local old = test.key
		 local s = spy.on(test, "key")
		 test.key()
		 test.key("test")
		 assert.spy(test.key).was.called(2)
		 -- revert and call again
		 s:revert()
		 assert.are.equal(old, test.key)
		 test.key()
		 test.key("test")
		 assert.spy(s).was.called(2) -- still two, spy was removed
	end)

	it("checks reverting a spy.new call", function()
		 local calls = 0
		 local old = function() calls = calls + 1 end
		 local s = spy.new(old)
		 assert.is_table(s)
		 s()
		 s()
		 assert.spy(s).was.called(2)
		 assert.are.equal(calls, 2)
		 local old_s = s
		 s = s:revert()
		 assert.are.equal(s, old)
		 s()
		 assert.spy(old_s).was.called(2)	-- still two, spy was removed
		 assert.are.equal(calls, 3)
	end)

end)


text:
package com.ensoft.restafari.helper;

import android.util.Log;

import java.lang.reflect.Constructor;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class ReflectionHelper
{
	private static final String TAG = ReflectionHelper.class.getSimpleName();

	@SuppressWarnings("unchecked")
	public static <T> T createInstance(Class<?> clazz)
	{
		String msg = null;
		Object newInstance = null;
		try
		{
			for ( Constructor<?> constructor : clazz.getConstructors() )
			{
				if ( constructor.getParameterTypes().length == 0 )
				{
					newInstance = constructor.newInstance();

					break;
				}
			}

			if ( null == newInstance )
			{
				msg = "Class must have a default constructor without parameters";
			}
		}
		catch (IllegalArgumentException e)
		{
			msg = e.getMessage();
		}
		catch (Exception e)
		{
			msg = "ReflectiveOperationException";
		}
		finally
		{
			if (msg != null)
			{
				Log.e( TAG, "error instantiating type " + clazz.getSimpleName() + "\n" + msg );
				newInstance = null;
			}
		}

		return (T) newInstance;
	}

	public static Type getTypeArgument( Object object, int position)
	{
		Type genericType = null;

		if (object != null)
		{
			try
			{
				genericType = ((ParameterizedType) object.getClass().getGenericSuperclass()).getActualTypeArguments()[position];
			}
			catch (Exception e)
			{
				//do nothing
			}
		}

		return genericType;
	}
}


text:
The floskell configuration file is a `JSON` file.  The basic structure
is as follows:

```json
{
  "language": "Haskell2010",
  "extensions": [],
  "style": "base",
  "formatting": {
    "penalty": {...},
    "layout": {...},
    "indent": {...},
    "align": {...},
    "group": {...},
    "op": {...},
    "options": {...}
    }
  }
}
```

## Parser Settings

* `language` (`Haskell2010`): The Haskell language standard for parsing source files.
  Either `Haskell98` or `Haskell2010`.

  ```json
  {
    "language": "Haskell2010"
  }
  ```

* `extensions` (`[]`): A list of extensions to be enabled or disabled.  Check
  the output of `floskell --help` for the full list of extensions.  To
  disable an extension, prefix the extension with `No`.

  ```json
  {
    "extensions": ["RecordWildCards", "NoTypeFamilies"]
  }
  ```

* `fixities` (`[]`): A list of additional infix declarations to use
  while parsing.  Check the output of `floskell --help` for a list of
  built-in declarations.

  ```json
  {
    "fixities": ["infixr 9 ."]
  }
  ```

## Style Definition

* `style` (`base`): The formatting style to use.  The style can be fine-tuned
  using the `formatting` configuration element.  Check the output of
  `floskell --help` for the full list of styles.

* `formatting` (`{}`): Formatting settings, applied on top of the selected
  style.

### Line Penalty

* `penalty`: Defines the parameters for the penalty function used to
  judge the overall layout.

  * `indent` (`1`): Penalty for each indentation character.
  * `linebreak` (`10`): Penalty for each line.
  * `max-line-length` (`80`): Character limit for each line.
  * `overfull` (`10`): Penalty for each character over the line limit.
  * `overfull-once` (`200`): Penalty for each overfull line.

### Layout Rules

* `layout`: Defines the accepted layout choices for all configurable
  language constructs.

  Allowed values are `flex`, `vertical`, or `try-oneline`.

  * `app` (`flex`): Function application
  * `con-decls` (`flex`): Data constructor declarations
  * `declaration` (`flex`): Declarations
  * `export-spec-list` (`flex`): Module export list
  * `if` (`flex`): If-then-else
  * `import-spec-list` (`flex`): Module import lists
  * `infix-app` (`flex`): Infix operator application
  * `let` (`flex`): Let-in
  * `list-comp` (`flex`): List comprehensions
  * `record` (`flex`): Record declaration, construction, and update
  * `type` (`flex`): Types in signatures

### Indentation Rules

* `indent`: Defines the indentation choices for all configurable
  language constructs.

  Allowed values (except for `onside`, `deriving`, `where`) are
  `align`, `indent-by n`, and `align-or-indent-by n`.

  Allowed values for `onside` are all integers greater than zero.

  Allowed values for `deriving` and `where` are all integers greater
  than or equal to zero.

  * `onside` (`4`): Onside indentation
  * `deriving` (`4`): Indentation for deriving lists
  * `where` (`2`): Indentation for where keyword after functions
  * `case` (`indent-by 4`): Case analysis
  * `class` (`indent-by 4`): Class and instance declarations
  * `do` (`indent-by 4`): Do and recursive do blocks
  * `export-spec-list` (`indent-by 4`): Module export list
  * `if` (`indent-by 4`): If-then-else
  * `import-spec-list` (`indent-by 4`): Module import lists
  * `let` (`indent-by 4`): Let bindings
  * `let-binds` (`indent-by 4`): Let bindings
  * `let-in` (`indent-by 4`): Expression in let
  * `multi-if` (`indent-by 4`): Guards and multi-way if
  * `typesig` (`indent-by 4`): Type signatures
  * `where-binds` (`indent-by 2`): Bindings in where block after functions

### Tabstop Alignment

* `align`: Defines the enabled tabstop alignments and their limitations.

  Allowed values, except for `limits`, are `true` and `false`.

  The item `limits` must be a list with two integers, the first
  integer is a number of character (`absolute limit`), the second a
  percentage (`relative limit`).  Alignment will be disabled if the
  length of any inserted padding is larger than `absolute limit` and
  is larger than `relative limit` of the maximum field length (tabstop
  column minus indentation).

  * `limits` (`[10, 25]`): Alignment limits
  * `case` (`false`): Case patterns
  * `class` (`false`): Declarations inside class and instance declarations
  * `import-module` (`false`): Names of imported modules
  * `import-spec` (`false`): Module import lists
  * `let-binds` (`false`): Let bindings
  * `matches` (`false`): Function match clauses
  * `record-fields` (`false`): Record field assignments and type signatures
  * `where` (`false`): Declarations in where bindings for functions

### Whitespace Rules

* `group`: Defines whitespace rules for parentheses, brackets,
  braces, and other enclosing punctuation characters.

  The `group` item is a map from enclosing punctuation (identified
  by the opening characters) and optional context to a whitespace
  configuration. The key can be either

  * `default`: Defines the fallback whitespace configuration,

  * `* in <context>`: Defines the default whitespace configuration
    within the given context,

  * `<punct> in *`: Defines the default whitespace configuration for
    the given punctuation, or

  * `<punct> in <context>`: Defines the whitespace configuration for
    the given punctuation within the given context,

  where context is one of `declaration`, `type`, `pattern`,
  `expression`, or `other`.

  The value is an object with the following fields:

  * `spaces`: Where to insert spaces.
  * `linebreaks`: Where to insert linebreaks.
  * `force-linebreak`: Whether to enforce vertical layout.

  An example:

  ```haskell
  {
    "group": {
      "default": {
        "spaces": "none",
        "linebreaks": "after",
        "force-linebreak": false
      },
      "(": {
        "spaces": "both",
        "linebreaks": "after",
        "force-linebreak": false
      },
      "( in pattern": {
        "spaces": "none",
        "linebreaks": "none",
        "force-linebreak": false
      }
    }
  }
  ```

* `op`: Defines whitespacce rules for infix operators.

  See `group` above.

### Other Style Options

* `options`: Defines additional formatting rules for module heads.

  * `align-sum-type-decl` (`false`): Whether to align `=` with `|` in the
    declaration of sum types.
  * `preserve-vertical-space` (`false`): Whether to preserve additional vertical
    space between declarations, statements, and a few other places.
  * `decl-no-blank-lines` (`[]`): Where to (not) insert blank lines between
    declarations (`module`, `class`, `instance`, `where`).
  * `sort-import-lists` (`false`): Whether to sort import statements by the name
    of the imported module.
  * `sort-imports` (`false`): How to sort import lists (see below).
  * `sort-pragmas` (`false`): Whether to sort module pragmas (`LANGUAGE`,
    `OPTION`, and `ANN`).
  * `flexible-oneline` (`false`): Allow `do`, `mdo`, `case ... of`, `\case`, and
    `\... ->` in `try-oneline` layout.
  * `split-language-pragmas` (`false`): Whether to split `LANGUAGE` pragmas.
  * `align-let-binds-and-in-expr` (`false`): Whether to align `let` bindings and
    the `in` expression, in a let expression.

#### Sorting Imports

There are three import sorting modes:

  * No sorting (`sort-imports: false`).  This mode will retain the
    order of imports and any blank lines between imports.

  * Sort imports and group by the first component of the module path
    (`sort-imports: true`): Data.Maybe goes with Data.Either,
    Control.Monad goes with Control.Applicative.

    This mode is equivalent to:

    ``` json
    "sort-imports": [
      {
        "prefixes": [""],
        "order": "grouped"
      }
    ]
    ```

  * Configurable grouping and sorting (`sort-imports:
    [...]`). `sort-imports` is a list of group declarations, where
    each group defines a set of module prefixes and an order.

    Each import is assigned to a group based on the longest matching
    prefix. Imports without a match are assigned to an implicit final
    group with order `keep`. You can manually collect all left-over
    imports by specifying a group with an empty prefix.

    The order can be one of `keep`, `sorted`, or `grouped`.  `keep`
    retains the manual order of imports of the input file, `sorted`
    will sort imports within the group, and `grouped` will sort and
    then group imports within the group based on the first component
    after the common prefix of the group's prefixes.

    For example:

    ``` json
    "sort-imports": [
      {
        "prefixes": [ "" ],
        "order": "grouped"
      },
      {
        "prefixes": [ "Floskell" ],
        "order": "sorted"
      },
      {
        "prefixes": [ "Test" ],
        "order": "grouped"
      },
      {
        "prefixes": [ "Prelude" ],
        "order": "sorted"
      }
    ]
    ```

    This configuration will first place all 'generic' imports, sorted
    and grouped on the top-level module name component. E.g. all of
    "Control", then "Data", etc.

    After that, there is a sorted section of 'local' imports
    (everything within "Floskell"), without any subdivision.

    Following are all imports from "Test", again sorted and grouped
    based on the first component after "Test".

    Lastly, any imports of "Prelude".


text:
package com.sayemahmed.example.executor;

import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.Timer;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.activeThreads;
import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.failedTasks;
import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.maxPoolSize;
import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.queueSize;
import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.successfulTasks;
import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.taskExecution;

/**
 * @author MD Sayem Ahmed
 */
@SuppressWarnings({"WeakerAccess", "unused"})
@Slf4j
public class MonitoredThreadPoolExecutor extends ThreadPoolExecutor {
  private final MetricRegistry metricRegistry;
  private final String metricsPrefix;
  private ThreadLocal<Timer.Context> taskExecutionTimer = new ThreadLocal<>();

  public MonitoredThreadPoolExecutor(
      int corePoolSize,
      int maximumPoolSize,
      long keepAliveTime,
      TimeUnit unit,
      BlockingQueue<Runnable> workQueue,
      MetricRegistry metricRegistry,
      String poolName
  ) {
    super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    this.metricRegistry = metricRegistry;
    this.metricsPrefix = MetricRegistry.name(getClass(), poolName);
    registerGauges();
  }

  public MonitoredThreadPoolExecutor(
      int corePoolSize,
      int maximumPoolSize,
      long keepAliveTime,
      TimeUnit unit,
      BlockingQueue<Runnable> workQueue,
      ThreadFactory threadFactory,
      MetricRegistry metricRegistry,
      String poolName
  ) {
    super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory);
    this.metricRegistry = metricRegistry;
    this.metricsPrefix = MetricRegistry.name(getClass(), poolName);
    registerGauges();
  }

  public MonitoredThreadPoolExecutor(
      int corePoolSize,
      int maximumPoolSize,
      long keepAliveTime,
      TimeUnit unit,
      BlockingQueue<Runnable> workQueue,
      RejectedExecutionHandler handler,
      MetricRegistry metricRegistry,
      String poolName
  ) {
    super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler);
    this.metricRegistry = metricRegistry;
    this.metricsPrefix = MetricRegistry.name(getClass(), poolName);
    registerGauges();
  }

  public MonitoredThreadPoolExecutor(
      int corePoolSize,
      int maximumPoolSize,
      long keepAliveTime,
      TimeUnit unit,
      BlockingQueue<Runnable> workQueue,
      ThreadFactory threadFactory,
      RejectedExecutionHandler handler,
      MetricRegistry metricRegistry,
      String poolName
  ) {
    super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler);
    this.metricRegistry = metricRegistry;
    this.metricsPrefix = MetricRegistry.name(getClass(), poolName);
    registerGauges();
  }

  @Override
  protected void beforeExecute(Thread thread, Runnable task) {
    super.beforeExecute(thread, task);
    Timer timer = metricRegistry.timer(MetricRegistry.name(metricsPrefix, taskExecution));
    taskExecutionTimer.set(timer.time());
  }

  @Override
  protected void afterExecute(Runnable task, Throwable throwable) {
    Timer.Context context = taskExecutionTimer.get();
    context.stop();

    super.afterExecute(task, throwable);
    if (throwable == null && task instanceof Future<?> && ((Future<?>) task).isDone()) {
      try {
        ((Future<?>) task).get();
      } catch (CancellationException ce) {
        throwable = ce;
      } catch (ExecutionException ee) {
        throwable = ee.getCause();
      } catch (InterruptedException ie) {
        Thread.currentThread().interrupt();
      }
    }
    if (throwable != null) {
      Counter failedTasksCounter = metricRegistry.counter(MetricRegistry.name(metricsPrefix, failedTasks));
      failedTasksCounter.inc();
    } else {
      Counter successfulTasksCounter = metricRegistry.counter(
          MetricRegistry.name(metricsPrefix, successfulTasks));
      successfulTasksCounter.inc();
    }
  }

  private void registerGauges() {
    metricRegistry.register(MetricRegistry.name(metricsPrefix, MonitoringKey.corePoolSize),
        (Gauge<Integer>) this::getCorePoolSize);
    metricRegistry.register(MetricRegistry.name(metricsPrefix, activeThreads),
        (Gauge<Integer>) this::getActiveCount);
    metricRegistry.register(MetricRegistry.name(metricsPrefix, maxPoolSize),
        (Gauge<Integer>) this::getMaximumPoolSize);
    metricRegistry.register(MetricRegistry.name(metricsPrefix, queueSize),
        (Gauge<Integer>) () -> getQueue().size());
  }

  static class MonitoringKey {
    static final String taskExecution = "task-execution";
    static final String failedTasks = "failed-tasks";
    static final String successfulTasks = "successful-tasks";
    static final String corePoolSize = "corePoolSize";
    static final String activeThreads = "activeThreads";
    static final String maxPoolSize = "maxPoolSize";
    static final String queueSize = "queueSize";
  }
}


text:
A dead simple heroku ready travis daily sceduler

## Note 2015-09-04

https://nightli.es/ is an independent service that the travis team [suggests using](https://github.com/travis-ci/travis-ci/issues/582). I switched to this one myself, and am not intending to maintain daily-travis from now on.

## Usage

* Clone this repo locally

```shell
git clone https://github.com/philou/daily-travis.git
```

* If you don't have it yet, install the [heroku toolbelt](https://devcenter.heroku.com/articles/quickstart)

* Create an heroku app to deploy to

```shell
heroku apps:create <my-lib>-daily-travis
```

* Deploy to heroku

```shell
git push heroku master
```

* Generate a github token

Explanations are [here](https://help.github.com/articles/creating-an-access-token-for-command-line-use). Default authorizations are fine.
Note the token somewhere.

* Add the parameters to your heroku app

```shell
heroku config:add TRAVIS_REPOSITORY=<github-user>/<github-repo>
heroku config:add GITHUB_TOKEN=<github-token>
```

* Test that the latest build is restarted by manually running

```shell
heroku run rake build
```

* Add the scheduler to your heroku app

```shell
heroku addons:add scheduler:standard
heroku addons:open scheduler
```

* Add the task ```rake build``` to your heroku scheduler

## Alternatives

* https://nightli.es/ is an independent service that the travis team [suggests using](https://github.com/travis-ci/travis-ci/issues/582)
* The [travis-cron](http://traviscron.pythonanywhere.com/) web app and [git repo](https://github.com/FiloSottile/travis-cron). Which is manually moderated.


text:
namespace v8 {
namespace internal {
namespace interpreter {

// static
const char* Bytecodes::ToString(Bytecode bytecode) {
  switch (bytecode) {
#define CASE(Name, ...)   \
  case Bytecode::k##Name: \
    return #Name;
    BYTECODE_LIST(CASE)
#undef CASE
  }
  UNREACHABLE();
  return "";
}

// static
const char* Bytecodes::OperandTypeToString(OperandType operand_type) {
  switch (operand_type) {
#define CASE(Name, _)        \
  case OperandType::k##Name: \
    return #Name;
    OPERAND_TYPE_LIST(CASE)
#undef CASE
  }
  UNREACHABLE();
  return "";
}

// static
const char* Bytecodes::OperandSizeToString(OperandSize operand_size) {
  switch (operand_size) {
    case OperandSize::kNone:
      return "None";
    case OperandSize::kByte:
      return "Byte";
    case OperandSize::kShort:
      return "Short";
  }
  UNREACHABLE();
  return "";
}

// static
uint8_t Bytecodes::ToByte(Bytecode bytecode) {
  return static_cast<uint8_t>(bytecode);
}

// static
Bytecode Bytecodes::FromByte(uint8_t value) {
  Bytecode bytecode = static_cast<Bytecode>(value);
  DCHECK(bytecode <= Bytecode::kLast);
  return bytecode;
}

// static
int Bytecodes::Size(Bytecode bytecode) {
  DCHECK(bytecode <= Bytecode::kLast);
  switch (bytecode) {
#define CASE(Name, ...)   \
  case Bytecode::k##Name: \
    return BytecodeTraits<__VA_ARGS__, OPERAND_TERM>::kSize;
    BYTECODE_LIST(CASE)
#undef CASE
  }
  UNREACHABLE();
  return 0;
}

// static
int Bytecodes::NumberOfOperands(Bytecode bytecode) {
  DCHECK(bytecode <= Bytecode::kLast);
  switch (bytecode) {
#define CASE(Name, ...)   \
  case Bytecode::k##Name: \
    return BytecodeTraits<__VA_ARGS__, OPERAND_TERM>::kOperandCount;
    BYTECODE_LIST(CASE)
#undef CASE
  }
  UNREACHABLE();
  return 0;
}

// static
OperandType Bytecodes::GetOperandType(Bytecode bytecode, int i) {
  DCHECK(bytecode <= Bytecode::kLast);
  switch (bytecode) {
#define CASE(Name, ...)   \
  case Bytecode::k##Name: \
    return BytecodeTraits<__VA_ARGS__, OPERAND_TERM>::GetOperandType(i);
    BYTECODE_LIST(CASE)
#undef CASE
  }
  UNREACHABLE();
  return OperandType::kNone;
}

// static
OperandSize Bytecodes::GetOperandSize(Bytecode bytecode, int i) {
  DCHECK(bytecode <= Bytecode::kLast);
  switch (bytecode) {
#define CASE(Name, ...)   \
  case Bytecode::k##Name: \
    return BytecodeTraits<__VA_ARGS__, OPERAND_TERM>::GetOperandSize(i);
    BYTECODE_LIST(CASE)
#undef CASE
  }
  UNREACHABLE();
  return OperandSize::kNone;
}

// static
int Bytecodes::GetOperandOffset(Bytecode bytecode, int i) {
  DCHECK(bytecode <= Bytecode::kLast);
  switch (bytecode) {
#define CASE(Name, ...)   \
  case Bytecode::k##Name: \
    return BytecodeTraits<__VA_ARGS__, OPERAND_TERM>::GetOperandOffset(i);
    BYTECODE_LIST(CASE)
#undef CASE
  }
  UNREACHABLE();
  return 0;
}

// static
OperandSize Bytecodes::SizeOfOperand(OperandType operand_type) {
  switch (operand_type) {
#define CASE(Name, Size)     \
  case OperandType::k##Name: \
    return Size;
    OPERAND_TYPE_LIST(CASE)
#undef CASE
  }
  UNREACHABLE();
  return OperandSize::kNone;
}

// static
bool Bytecodes::IsJump(Bytecode bytecode) {
  return bytecode == Bytecode::kJump || bytecode == Bytecode::kJumpIfTrue ||
         bytecode == Bytecode::kJumpIfFalse ||
         bytecode == Bytecode::kJumpIfToBooleanTrue ||
         bytecode == Bytecode::kJumpIfToBooleanFalse ||
         bytecode == Bytecode::kJumpIfNull ||
         bytecode == Bytecode::kJumpIfUndefined;
}

// static
bool Bytecodes::IsJumpConstant(Bytecode bytecode) {
  return bytecode == Bytecode::kJumpConstant ||
         bytecode == Bytecode::kJumpIfTrueConstant ||
         bytecode == Bytecode::kJumpIfFalseConstant ||
         bytecode == Bytecode::kJumpIfToBooleanTrueConstant ||
         bytecode == Bytecode::kJumpIfToBooleanFalseConstant ||
         bytecode == Bytecode::kJumpIfNull ||
         bytecode == Bytecode::kJumpIfUndefinedConstant;
}

// static
std::ostream& Bytecodes::Decode(std::ostream& os, const uint8_t* bytecode_start,
                                int parameter_count) {
  Vector<char> buf = Vector<char>::New(50);

  Bytecode bytecode = Bytecodes::FromByte(bytecode_start[0]);
  int bytecode_size = Bytecodes::Size(bytecode);

  for (int i = 0; i < bytecode_size; i++) {
    SNPrintF(buf, "%02x ", bytecode_start[i]);
    os << buf.start();
  }
  const int kBytecodeColumnSize = 6;
  for (int i = bytecode_size; i < kBytecodeColumnSize; i++) {
    os << "   ";
  }

  os << bytecode << " ";

  int number_of_operands = NumberOfOperands(bytecode);
  for (int i = 0; i < number_of_operands; i++) {
    OperandType op_type = GetOperandType(bytecode, i);
    const uint8_t* operand_start =
        &bytecode_start[GetOperandOffset(bytecode, i)];
    switch (op_type) {
      case interpreter::OperandType::kCount8:
        os << "#" << static_cast<unsigned int>(*operand_start);
        break;
      case interpreter::OperandType::kIdx8:
        os << "[" << static_cast<unsigned int>(*operand_start) << "]";
        break;
      case interpreter::OperandType::kIdx16: {
        os << "[" << ReadUnalignedUInt16(operand_start) << "]";
        break;
      }
      case interpreter::OperandType::kImm8:
        os << "#" << static_cast<int>(static_cast<int8_t>(*operand_start));
        break;
      case interpreter::OperandType::kReg8:
      case interpreter::OperandType::kMaybeReg8: {
        Register reg = Register::FromOperand(*operand_start);
        if (reg.is_function_context()) {
          os << "<context>";
        } else if (reg.is_function_closure()) {
          os << "<closure>";
        } else if (reg.is_parameter()) {
          int parameter_index = reg.ToParameterIndex(parameter_count);
          if (parameter_index == 0) {
            os << "<this>";
          } else {
            os << "a" << parameter_index - 1;
          }
        } else {
          os << "r" << reg.index();
        }
        break;
      }
      case interpreter::OperandType::kNone:
        UNREACHABLE();
        break;
    }
    if (i != number_of_operands - 1) {
      os << ", ";
    }
  }
  return os;
}

std::ostream& operator<<(std::ostream& os, const Bytecode& bytecode) {
  return os << Bytecodes::ToString(bytecode);
}

std::ostream& operator<<(std::ostream& os, const OperandType& operand_type) {
  return os << Bytecodes::OperandTypeToString(operand_type);
}

std::ostream& operator<<(std::ostream& os, const OperandSize& operand_size) {
  return os << Bytecodes::OperandSizeToString(operand_size);
}

static const int kLastParamRegisterIndex =
    -InterpreterFrameConstants::kLastParamFromRegisterPointer / kPointerSize;
static const int kFunctionClosureRegisterIndex =
    -InterpreterFrameConstants::kFunctionFromRegisterPointer / kPointerSize;
static const int kFunctionContextRegisterIndex =
    -InterpreterFrameConstants::kContextFromRegisterPointer / kPointerSize;

// Registers occupy range 0-127 in 8-bit value leaving 128 unused values.
// Parameter indices are biased with the negative value kLastParamRegisterIndex
// for ease of access in the interpreter.
static const int kMaxParameterIndex = 128 + kLastParamRegisterIndex;

Register Register::FromParameterIndex(int index, int parameter_count) {
  DCHECK_GE(index, 0);
  DCHECK_LT(index, parameter_count);
  DCHECK_LE(parameter_count, kMaxParameterIndex + 1);
  int register_index = kLastParamRegisterIndex - parameter_count + index + 1;
  DCHECK_LT(register_index, 0);
  DCHECK_GE(register_index, Register::kMinRegisterIndex);
  return Register(register_index);
}

int Register::ToParameterIndex(int parameter_count) const {
  DCHECK(is_parameter());
  return index() - kLastParamRegisterIndex + parameter_count - 1;
}

Register Register::function_closure() {
  return Register(kFunctionClosureRegisterIndex);
}

bool Register::is_function_closure() const {
  return index() == kFunctionClosureRegisterIndex;
}

Register Register::function_context() {
  return Register(kFunctionContextRegisterIndex);
}

bool Register::is_function_context() const {
  return index() == kFunctionContextRegisterIndex;
}

int Register::MaxParameterIndex() { return kMaxParameterIndex; }

uint8_t Register::ToOperand() const { return static_cast<uint8_t>(-index_); }

Register Register::FromOperand(uint8_t operand) {
  return Register(-static_cast<int8_t>(operand));
}

bool Register::AreContiguous(Register reg1, Register reg2, Register reg3,
                             Register reg4, Register reg5) {
  if (reg1.index() + 1 != reg2.index()) {
    return false;
  }
  if (reg3.is_valid() && reg2.index() + 1 != reg3.index()) {
    return false;
  }
  if (reg4.is_valid() && reg3.index() + 1 != reg4.index()) {
    return false;
  }
  if (reg5.is_valid() && reg4.index() + 1 != reg5.index()) {
    return false;
  }
  return true;
}

}  // namespace interpreter
}  // namespace internal
}  // namespace v8


text:
package com.salesmanager.core.business.catalog.product.dao.price;

import org.springframework.stereotype.Repository;

import com.mysema.query.jpa.JPQLQuery;
import com.mysema.query.jpa.impl.JPAQuery;
import com.salesmanager.core.business.catalog.product.model.QProduct;
import com.salesmanager.core.business.catalog.product.model.availability.QProductAvailability;
import com.salesmanager.core.business.catalog.product.model.price.ProductPrice;
import com.salesmanager.core.business.catalog.product.model.price.QProductPrice;
import com.salesmanager.core.business.catalog.product.model.price.QProductPriceDescription;
import com.salesmanager.core.business.generic.dao.SalesManagerEntityDaoImpl;

@Repository("productPriceDao")
public class ProductPriceDaoImpl extends SalesManagerEntityDaoImpl<Long, ProductPrice>
	implements ProductPriceDao {

	@Override
	public ProductPrice getById(Long id) {
		QProductPrice qEntity = QProductPrice.productPrice;
		QProductAvailability qAvailability = QProductAvailability.productAvailability;
		QProductPriceDescription qEntityDescription = QProductPriceDescription.productPriceDescription;
		QProduct qProduct = QProduct.product;

		JPQLQuery query = new JPAQuery (getEntityManager());

		query.from(qEntity)
			.innerJoin(qEntity.productAvailability,qAvailability).fetch()
			.innerJoin(qAvailability.product,qProduct).fetch()
			.leftJoin(qEntity.descriptions, qEntityDescription).fetch()
			.innerJoin(qProduct.merchantStore).fetch()
			.where(qEntity.id.eq(id));

		return query.uniqueResult(qEntity);
	}

}


text:
package org.apache.flink.table.planner.plan.nodes.physical.stream

import org.apache.flink.annotation.VisibleForTesting
import org.apache.flink.api.dag.Transformation
import org.apache.flink.cep.EventComparator
import org.apache.flink.cep.nfa.aftermatch.AfterMatchSkipStrategy
import org.apache.flink.cep.nfa.compiler.NFACompiler
import org.apache.flink.cep.operator.CepOperator
import org.apache.flink.cep.pattern.Pattern
import org.apache.flink.cep.pattern.Quantifier.QuantifierProperty
import org.apache.flink.cep.pattern.conditions.BooleanConditions
import org.apache.flink.streaming.api.operators.ProcessOperator
import org.apache.flink.streaming.api.transformations.OneInputTransformation
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.table.api.{TableConfig, TableException, ValidationException}
import org.apache.flink.table.data.RowData
import org.apache.flink.table.planner.calcite.FlinkTypeFactory
import org.apache.flink.table.planner.codegen.sort.ComparatorCodeGenerator
import org.apache.flink.table.planner.codegen.{CodeGeneratorContext, MatchCodeGenerator}
import org.apache.flink.table.planner.delegation.StreamPlanner
import org.apache.flink.table.planner.plan.logical.MatchRecognize
import org.apache.flink.table.planner.plan.nodes.exec.{ExecNode, StreamExecNode}
import org.apache.flink.table.planner.plan.utils.PythonUtil.containsPythonCall
import org.apache.flink.table.planner.plan.utils.RelExplainUtil._
import org.apache.flink.table.planner.plan.utils.{KeySelectorUtil, RexDefaultVisitor, SortUtil}
import org.apache.flink.table.runtime.operators.`match`.{RowDataEventComparator, RowtimeProcessFunction}
import org.apache.flink.table.runtime.typeutils.InternalTypeInfo
import org.apache.flink.table.types.logical.RowType
import org.apache.flink.util.MathUtils

import org.apache.calcite.plan.{RelOptCluster, RelTraitSet}
import org.apache.calcite.rel.RelFieldCollation.Direction
import org.apache.calcite.rel._
import org.apache.calcite.rel.`type`.RelDataType
import org.apache.calcite.rex._
import org.apache.calcite.sql.SqlKind
import org.apache.calcite.sql.SqlMatchRecognize.AfterOption
import org.apache.calcite.sql.`type`.SqlTypeFamily
import org.apache.calcite.sql.fun.SqlStdOperatorTable._
import org.apache.calcite.tools.RelBuilder

import _root_.java.lang.{Boolean => JBoolean, Long => JLong}
import _root_.java.util

import _root_.scala.collection.JavaConversions._

/**
  * Flink RelNode which matches along with LogicalMatch.
  */
class StreamExecMatch(
    cluster: RelOptCluster,
    traitSet: RelTraitSet,
    inputNode: RelNode,
    logicalMatch: MatchRecognize,
    outputRowType: RelDataType)
  extends SingleRel(cluster, traitSet, inputNode)
  with StreamPhysicalRel
  with StreamExecNode[RowData] {

  if (logicalMatch.measures.values().exists(containsPythonCall(_)) ||
    logicalMatch.patternDefinitions.values().exists(containsPythonCall(_))) {
    throw new TableException("Python Function can not be used in MATCH_RECOGNIZE for now.")
  }

  override def requireWatermark: Boolean = {
    val rowtimeFields = getInput.getRowType.getFieldList
      .filter(f => FlinkTypeFactory.isRowtimeIndicatorType(f.getType))
    rowtimeFields.nonEmpty
  }

  override def deriveRowType(): RelDataType = outputRowType

  override def copy(traitSet: RelTraitSet, inputs: util.List[RelNode]): RelNode = {
    new StreamExecMatch(
      cluster,
      traitSet,
      inputs.get(0),
      logicalMatch,
      outputRowType)
  }

  override def explainTerms(pw: RelWriter): RelWriter = {
    val inputRowType = getInput.getRowType
    val fieldNames = inputRowType.getFieldNames.toList
    super.explainTerms(pw)
      .itemIf("partitionBy",
        fieldToString(logicalMatch.partitionKeys.toArray, inputRowType),
        !logicalMatch.partitionKeys.isEmpty)
      .itemIf("orderBy",
        collationToString(logicalMatch.orderKeys, inputRowType),
        !logicalMatch.orderKeys.getFieldCollations.isEmpty)
      .itemIf("measures",
        measuresDefineToString(logicalMatch.measures, fieldNames, getExpressionString),
        !logicalMatch.measures.isEmpty)
      .item("rowsPerMatch", rowsPerMatchToString(logicalMatch.allRows))
      .item("after", afterMatchToString(logicalMatch.after, fieldNames))
      .item("pattern", logicalMatch.pattern.toString)
      .itemIf("subset",
        subsetToString(logicalMatch.subsets),
        !logicalMatch.subsets.isEmpty)
      .item("define", logicalMatch.patternDefinitions)
  }

  private def translateTimeBound(interval: RexNode): Time = {
    interval match {
      case x: RexLiteral if x.getTypeName.getFamily == SqlTypeFamily.INTERVAL_DAY_TIME =>
        Time.milliseconds(x.getValueAs(classOf[JLong]))
      case _ =>
        throw new TableException("Only constant intervals with millisecond resolution " +
          "are supported as time constraints of patterns.")
    }
  }

  @VisibleForTesting
  private[flink] def translatePattern(
      config: TableConfig,
      relBuilder: RelBuilder,
      inputRowType: RowType): (Pattern[RowData, RowData], Seq[String]) = {
    val patternVisitor = new PatternVisitor(config, relBuilder, inputRowType, logicalMatch)
    val cepPattern = if (logicalMatch.interval != null) {
      val interval = translateTimeBound(logicalMatch.interval)
      logicalMatch.pattern.accept(patternVisitor).within(interval)
    } else {
      logicalMatch.pattern.accept(patternVisitor)
    }
    (cepPattern, patternVisitor.names.toSeq)
  }

  //~ ExecNode methods -----------------------------------------------------------

  override def getInputNodes: util.List[ExecNode[StreamPlanner, _]] = {
    List(getInput.asInstanceOf[ExecNode[StreamPlanner, _]])
  }

  override def replaceInputNode(
    ordinalInParent: Int,
    newInputNode: ExecNode[StreamPlanner, _]): Unit = {
    replaceInput(ordinalInParent, newInputNode.asInstanceOf[RelNode])
  }

  override protected def translateToPlanInternal(
      planner: StreamPlanner): Transformation[RowData] = {

    val config = planner.getTableConfig
    val relBuilder = planner.getRelBuilder
    val returnType = FlinkTypeFactory.toLogicalRowType(getRowType)
    val inputRowType = FlinkTypeFactory.toLogicalRowType(getInput.getRowType)

    val inputTransform = getInputNodes.get(0).translateToPlan(planner)
      .asInstanceOf[Transformation[RowData]]

    val (timestampedInput, comparator) = translateOrder(
      config, inputTransform, logicalMatch.orderKeys)

    val (cepPattern, patternNames) = translatePattern(
      config,
      relBuilder,
      inputRowType)

    //TODO remove this once it is supported in CEP library
    if (NFACompiler.canProduceEmptyMatches(cepPattern)) {
      throw new TableException(
        "Patterns that can produce empty matches are not supported. There must be at least one " +
          "non-optional state.")
    }

    //TODO remove this once it is supported in CEP library
    if (cepPattern.getQuantifier.hasProperty(QuantifierProperty.GREEDY)) {
      throw new TableException(
        "Greedy quantifiers are not allowed as the last element of a Pattern yet. Finish your " +
          "pattern with either a simple variable or reluctant quantifier.")
    }

    if (logicalMatch.allRows) {
      throw new TableException("All rows per match mode is not supported yet.")
    } else {
      val partitionKeys = logicalMatch.partitionKeys
      val timeOrderField = SortUtil.getFirstSortField(logicalMatch.orderKeys, getInput.getRowType)
      val isProctime = FlinkTypeFactory.isProctimeIndicatorType(timeOrderField.getType)
      val inputTypeInfo = inputTransform.getOutputType.asInstanceOf[InternalTypeInfo[RowData]]
      val inputSerializer = inputTypeInfo.createSerializer(planner.getExecEnv.getConfig)
      val nfaFactory = NFACompiler.compileFactory(cepPattern, false)
      val generator = new MatchCodeGenerator(
        CodeGeneratorContext(config),
        relBuilder,
        false,
        patternNames)
      generator.bindInput(inputRowType)
      val patternProcessFunction = generator.generateOneRowPerMatchExpression(
        returnType,
        partitionKeys,
        logicalMatch.measures)
      val operator = new CepOperator[RowData, RowData, RowData](
        inputSerializer,
        isProctime,
        nfaFactory,
        comparator,
        cepPattern.getAfterMatchSkipStrategy,
        patternProcessFunction,
        null
      )
      val outputRowTypeInfo = InternalTypeInfo.of(FlinkTypeFactory.toLogicalRowType(getRowType))
      val transformation = new OneInputTransformation[RowData, RowData](
        timestampedInput,
        getRelDetailedDescription,
        operator,
        outputRowTypeInfo,
        timestampedInput.getParallelism
      )
      if (inputsContainSingleton()) {
        transformation.setParallelism(1)
        transformation.setMaxParallelism(1)
      }
      setKeySelector(transformation, inputTypeInfo)
      transformation
    }
  }

  private def translateOrder(
      config: TableConfig,
      inputTransform: Transformation[RowData],
      orderKeys: RelCollation): (Transformation[RowData], EventComparator[RowData]) = {

    if (orderKeys.getFieldCollations.size() == 0) {
      throw new ValidationException("You must specify either rowtime or proctime for order by.")
    }

    // need to identify time between others order fields. Time needs to be first sort element
    val timeOrderField = SortUtil.getFirstSortField(orderKeys, getInput.getRowType)

    if (!FlinkTypeFactory.isTimeIndicatorType(timeOrderField.getType)) {
      throw new ValidationException(
        "You must specify either rowtime or proctime for order by as the first one.")
    }

    // time ordering needs to be ascending
    if (SortUtil.getFirstSortDirection(orderKeys) != Direction.ASCENDING) {
      throw new ValidationException(
        "Primary sort order of a streaming table must be ascending on time.")
    }

    val eventComparator = if (orderKeys.getFieldCollations.size() > 1) {
      val inputType = FlinkTypeFactory.toLogicalRowType(getInput.getRowType)
      val (keys, orders, nullsIsLast) = SortUtil.getKeysAndOrders(orderKeys.getFieldCollations)
      val keyTypes = keys.map(inputType.getTypeAt)
      val rowComparator = ComparatorCodeGenerator.gen(
        config,
        "RowDataComparator",
        keys,
        keyTypes,
        orders,
        nullsIsLast)
      new RowDataEventComparator(rowComparator)
    } else {
      null
    }

    val timestampedInputTransform =
      if (FlinkTypeFactory.isRowtimeIndicatorType(timeOrderField.getType)) {
        // copy the rowtime field into the StreamRecord timestamp field
        val timeIdx = timeOrderField.getIndex
        val inputTypeInfo = inputTransform.getOutputType
        val precision = timeOrderField.getType.getPrecision
        val transformation = new OneInputTransformation(
          inputTransform,
          s"rowtime field: ($timeOrderField)",
          new ProcessOperator(new RowtimeProcessFunction(timeIdx, inputTypeInfo, precision)),
          inputTypeInfo,
          inputTransform.getParallelism)
        if (inputsContainSingleton()) {
          transformation.setParallelism(1)
          transformation.setMaxParallelism(1)
        }
        transformation
      } else {
        inputTransform
      }

    (timestampedInputTransform, eventComparator)
  }

  private def setKeySelector(
      transform: OneInputTransformation[RowData, _],
      inputTypeInfo: InternalTypeInfo[RowData]): Unit = {
    val selector = KeySelectorUtil.getRowDataSelector(
      logicalMatch.partitionKeys.toArray,
      inputTypeInfo)
    transform.setStateKeySelector(selector)
    transform.setStateKeyType(selector.getProducedType)
  }
}

private class PatternVisitor(
    config: TableConfig,
    relBuilder: RelBuilder,
    inputRowType: RowType,
    logicalMatch: MatchRecognize)
  extends RexDefaultVisitor[Pattern[RowData, RowData]] {

  private var pattern: Pattern[RowData, RowData] = _
  val names = new collection.mutable.LinkedHashSet[String]()

  override def visitLiteral(literal: RexLiteral): Pattern[RowData, RowData] = {
    val patternName = literal.getValueAs(classOf[String])
    pattern = translateSingleVariable(Option.apply(pattern), patternName)

    val patternDefinition = logicalMatch.patternDefinitions.get(patternName)
    if (patternDefinition != null) {
      val generator = new MatchCodeGenerator(
        CodeGeneratorContext(config),
        relBuilder,
        false,
        names.toSeq,
        Some(patternName))
      generator.bindInput(inputRowType)
      val condition = generator.generateIterativeCondition(patternDefinition)

      pattern.where(condition)
    } else {
      pattern.where(BooleanConditions.trueFunction())
    }
  }

  override def visitCall(call: RexCall): Pattern[RowData, RowData] = {
    call.getOperator match {
      case PATTERN_CONCAT =>
        val left = call.operands.get(0)
        val right = call.operands.get(1)

        pattern = left.accept(this)
        pattern = right.accept(this)
        pattern

      case PATTERN_QUANTIFIER =>
        val name = call.operands.get(0) match {
          case c: RexLiteral => c
          case x => throw new TableException(s"Expression not supported: $x Group patterns are " +
            s"not supported yet.")
        }
        pattern = name.accept(this)
        val startNum = MathUtils.checkedDownCast(call.operands.get(1).asInstanceOf[RexLiteral]
          .getValueAs(classOf[JLong]))
        val endNum = MathUtils.checkedDownCast(call.operands.get(2).asInstanceOf[RexLiteral]
          .getValueAs(classOf[JLong]))
        val isGreedy = !call.operands.get(3).asInstanceOf[RexLiteral]
          .getValueAs(classOf[JBoolean])

        applyQuantifier(pattern, startNum, endNum, isGreedy)

      case PATTERN_ALTER =>
        throw new TableException(
          s"Expression not supported: $call. Currently, CEP doesn't support branching patterns.")

      case PATTERN_PERMUTE =>
        throw new TableException(
          s"Expression not supported: $call. Currently, CEP doesn't support PERMUTE patterns.")

      case PATTERN_EXCLUDE =>
        throw new TableException(
          s"Expression not supported: $call. Currently, CEP doesn't support '{-' '-}' patterns.")
    }
  }

  override def visitNode(rexNode: RexNode): Pattern[RowData, RowData] = throw new TableException(
    s"Unsupported expression within Pattern: [$rexNode]")

  private def translateSkipStrategy = {
    val getPatternTarget = () => logicalMatch.after.asInstanceOf[RexCall].getOperands.get(0)
      .asInstanceOf[RexLiteral].getValueAs(classOf[String])

    logicalMatch.after.getKind match {
      case SqlKind.LITERAL =>
        logicalMatch.after.asInstanceOf[RexLiteral].getValueAs(classOf[AfterOption]) match {
          case AfterOption.SKIP_PAST_LAST_ROW => AfterMatchSkipStrategy.skipPastLastEvent()
          case AfterOption.SKIP_TO_NEXT_ROW => AfterMatchSkipStrategy.skipToNext()
        }
      case SqlKind.SKIP_TO_FIRST =>
        AfterMatchSkipStrategy.skipToFirst(getPatternTarget()).throwExceptionOnMiss()
      case SqlKind.SKIP_TO_LAST =>
        AfterMatchSkipStrategy.skipToLast(getPatternTarget()).throwExceptionOnMiss()
      case _ => throw new IllegalStateException(s"Corrupted query tree. Unexpected " +
        s"${logicalMatch.after} for after match strategy.")
    }
  }

  private def translateSingleVariable(
      previousPattern: Option[Pattern[RowData, RowData]],
      patternName: String)
    : Pattern[RowData, RowData] = {
    if (names.contains(patternName)) {
      throw new TableException("Pattern variables must be unique. That might change in the future.")
    } else {
      names.add(patternName)
    }

    previousPattern match {
      case Some(p) => p.next(patternName)
      case None =>
        Pattern.begin(patternName, translateSkipStrategy)
    }
  }

  private def applyQuantifier(
      pattern: Pattern[RowData, RowData],
      startNum: Int,
      endNum: Int,
      greedy: Boolean)
    : Pattern[RowData, RowData] = {
    val isOptional = startNum == 0 && endNum == 1

    val newPattern = if (startNum == 0 && endNum == -1) { // zero or more
      pattern.oneOrMore().optional().consecutive()
    } else if (startNum == 1 && endNum == -1) { // one or more
      pattern.oneOrMore().consecutive()
    } else if (isOptional) { // optional
      pattern.optional()
    } else if (endNum != -1) { // times
      pattern.times(startNum, endNum).consecutive()
    } else { // times or more
      pattern.timesOrMore(startNum).consecutive()
    }

    if (greedy && (isOptional || startNum == endNum)) {
      newPattern
    } else if (greedy) {
      newPattern.greedy()
    } else if (isOptional) {
      throw new TableException("Reluctant optional variables are not supported yet.")
    } else {
      newPattern
    }
  }
}


text:
WITH
	columns
AS( --Function wich excludes preinserted Tables from the query
	SELECT columns.*
	FROM
		information_schema.columns
		LEFT JOIN
			public.table_ignore ON
			columns.table_name = table_ignore.table_name
	WHERE
		table_schema = 'public' AND
		ignore IS NULL
),
	number_of_columns_in_constraint
AS ( --Function which counts the colums of a constraint on a table (for array-class purpose)
	SELECT key_column_usage.table_name, key_column_usage.constraint_name, count(*) as number_of_columns
	FROM
		information_schema.key_column_usage
		LEFT JOIN
			public.table_ignore ON key_column_usage.table_name = table_ignore.table_name
	WHERE
		key_column_usage.table_schema = 'public'
		AND
		table_ignore.ignore IS NULL
	GROUP BY key_column_usage.constraint_name,
		key_column_usage.table_name
),
	keyvalues
as (SELECT --Function which provides a table where all columns have an attribute showing what kind of key they have (N = no key, P = Primary Key, F = Foreign key) Unique constraints are listed under no key.
	'N' as type,
	col.table_name,
	col.column_name,
	source.constraint_name,
	table_constraints.constraint_type,
	--source.table_name as schlüsselquelle_tabelle,
	--source.column_name as schlüsselquelle_spalte,
	target.table_name as target
	--target.column_name as schlüsselziel_spalte
FROM
	columns as col
	LEFT JOIN
		information_schema.key_column_usage as source ON
			col.table_name = source.table_name AND
			col.column_name = source.column_name
	LEFT JOIN
		information_schema.constraint_column_usage as target ON
			source.constraint_name = target.constraint_name
	LEFT JOIN
		information_schema.table_constraints ON
			source.constraint_name = table_constraints.constraint_name
	LEFT JOIN
		number_of_columns_in_constraint as nucic ON
			source.constraint_name = nucic.constraint_name
WHERE
	col.table_schema='public' AND
	(source.constraint_name IS NULL OR (
	 NOT table_constraints.constraint_type ilike '%PRIMARY%' AND
	 NOT table_constraints.constraint_type ilike '%FOREIGN%' AND
	 nucic.number_of_columns < 2)) --Used to filter the UNIQUE Constraints defining array classes...

UNION

SELECT
	'P' as type,
	col.table_name ,
	col.column_name,
	source.constraint_name,
	table_constraints.constraint_type,
	--source.table_name as schlüsselquelle_tabelle,
	--source.column_name as schlüsselquelle_spalte,
	target.table_name as target
	--target.column_name as schlüsselziel_spalte
FROM
	columns as col
	LEFT JOIN
		information_schema.key_column_usage as source ON
			col.table_name = source.table_name AND
			col.column_name = source.column_name
	LEFT JOIN
		information_schema.constraint_column_usage as target ON
			source.constraint_name = target.constraint_name AND
			source.table_name = target.table_name AND
			source.column_name = target.column_name
	LEFT JOIN
		information_schema.table_constraints ON
			source.constraint_name = table_constraints.constraint_name
WHERE
	col.table_schema='public' AND
	table_constraints.constraint_type ilike '%PRIMARY%'

UNION

SELECT
	'F' as type,
	col.table_name,
	col.column_name,
	source.constraint_name,
	table_constraints.constraint_type,
	--source.table_name as schlüsselquelle_tabelle,
	--source.column_name as schlüsselquelle_spalte,
	target.table_name as target
	--target.column_name as schlüsselziel_spalte
FROM
	columns as col
	LEFT JOIN
		information_schema.key_column_usage as source ON
			col.table_name = source.table_name AND
			col.column_name = source.column_name
	LEFT JOIN
		information_schema.constraint_column_usage as target ON
			source.constraint_name = target.constraint_name AND
			(source.table_name != target.table_name OR
			source.column_name != target.column_name)
	LEFT JOIN
		information_schema.table_constraints ON
			source.constraint_name = table_constraints.constraint_name
WHERE
	col.table_schema='public' AND
	table_constraints.constraint_type ilike '%FOREIGN%'
ORDER BY type
),
	descriptions
as (SELECT --Used to reference the descriptions of columns
	columns.table_schema,
	columns.table_name,
	columns.column_name,
	pg_description.description
FROM
	pg_catalog.pg_statio_all_tables as all_tables --Some statistics table, used to get the id for the combination of a schema- and tablename
	RIGHT JOIN pg_catalog.pg_description on       -- table wich contains the descriptions of columns, only referenced by the table id.
		pg_description.objoid = all_tables.relid
	RIGHT JOIN columns ON 			      -- join daescription and oids with the notinsertet columns to get the description for specific columns needed to recocnize array-links
		pg_description.objsubid=columns.ordinal_position AND
		columns.table_schema = all_tables.schemaname AND
		columns.table_name = all_tables.relname
WHERE
	columns.table_schema = 'public'
),
	arrayseeker
as(SELECT --The arrayseeker seeks an array and returns table and column and target table, of the backlink
	descriptions.column_name as start_column,
	keyvalues.table_name,
	keyvalues.column_name,
	keyvalues.target
FROM
	keyvalues,
	descriptions
WHERE
	keyvalues.target = descriptions.table_name
	AND
	keyvalues.table_name = descriptions.description
)

INSERT
	into public.cs_attr
( SELECT -- NO Key Columns
	nextval('cs_attr_sequence'),-- as id,
	cs_class.id,-- as class_id,
	cs_type.id,-- as type_id,
	columns.column_name,-- as name,
	columns.column_name,-- as field_name,
	FALSE,-- as foreign_key,
	FALSE,-- as substitute,
	NULL::integer,-- as foreign_key_references_to,
	'',-- as descr,
	TRUE,-- as visible,
	FALSE,-- as indexed,
	FALSE,-- as isArray,
	'',-- as array_key,
	NULL::integer,-- as editor,--   	       	  ______________                                                        _______   ________   _______  _______   ________   _______         ______________ ______________ ______________ ______________ ______________
	NULL::integer,-- as tostring,-- 	      	 /-h == == == h-\  |\__________/| |\__________/| |\__________/|  _______^____ \\__H  ==  H__// ____^__^____ \\__H  ==  H__// ____^_______  |            | |            | |            | |            | |            |
	NULL::integer,-- as complex_editor,--   	^-oo----------oo-^=^oo--------oo^=^oo--------oo^=^oo--------oo^=^oo-oo--oo-oo^    `------´    ^oo-oo--oo-oo^    `------´    ^oo-oo--oo-oo^=^oo--------oo^=^oo--------oo^=^oo--------oo^=^oo--------oo^=^oo--------oo^
	columns.is_nullable::boolean,-- as optional,
	NULL,-- as default_value,
	NULL::integer,-- as from_string,
	(columns.ordinal_position - 1),-- as pos,
	columns.character_maximum_length,
	NULL::integer,-- as scale,
	FALSE-- as extension_at

FROM
	public.cs_class,
	public.cs_type,
	columns
	INNER JOIN
		keyvalues ON
			columns.table_name = keyvalues.table_name AND
			columns.column_name = keyvalues.column_name
WHERE
	columns.table_schema = 'public'
	AND
	columns.udt_name ilike cs_type.name
	AND
	columns.table_name = cs_class.name
	AND
	keyvalues.type = 'N'
)
UNION

(SELECT --Primary Key Columns
	nextval('cs_attr_sequence'),-- as id,
	cs_class.id,-- as class_id,
	cs_type.id,-- as type_id,
	columns.column_name,-- as name,
	columns.column_name,-- as field_name,
	FALSE,-- as foreign_key,
	FALSE,-- as substitute,
	NULL::integer,-- as foreign_key_references_to,
	'Primärschlüssel',-- as descr,
	FALSE,-- as visible,
	FALSE,-- as indexed,
	FALSE,-- as isArray,
	'',-- as array_key,
	NULL::integer,-- as editor,--   	       	  ______________                                                        _______   ________   _______                 _______   ________   _______         ______________ ______________ ______________
	NULL::integer,-- as tostring,-- 	      	 /-h == == == h-\  |\__________/| |\__________/| |\__________/|  _______^____ \\__H  ==  H__// ____^_______   _______^____ \\__H  ==  H__// ____^_______  |            | |            | |            |
	NULL::integer,-- as complex_editor,--   	^-oo----------oo-^=^oo--------oo^=^oo--------oo^=^oo--------oo^=^oo-oo--oo-oo^    `------´    ^oo-oo--oo-oo^=^oo-oo--oo-oo^    `------´    ^oo-oo--oo-oo^=^oo--------oo^=^oo--------oo^=^oo--------oo^
	columns.is_nullable::boolean,-- as optional,
	NULL,-- as default_value,
	NULL::integer,-- as from_string,
	(columns.ordinal_position - 1),-- as pos,
	columns.character_maximum_length,
	NULL::integer,-- as scale,
	FALSE-- as extension_at

FROM
	public.cs_class,
	public.cs_type,
	columns
	INNER JOIN
		keyvalues ON
			columns.table_name = keyvalues.table_name AND
			columns.column_name = keyvalues.column_name
WHERE
	columns.table_schema = 'public'
	AND
	columns.udt_name ilike cs_type.name
	AND
	columns.table_name = cs_class.name
	AND
	keyvalues.type = 'P'
)
UNION

(SELECT --Foreign Key collumns (without backreference and array-link)
	nextval('cs_attr_sequence'),-- as id,
	cs_class.id,-- as class_id,
	cs_type.id,-- as type_id,
	columns.column_name,-- as name,
	columns.column_name,-- as field_name,
	TRUE,-- as foreign_key,-- In cids it is no foreign key, if it's the backlink of an array.
	FALSE,-- as substitute,
	cs_type.class_id,-- as foreign_key_references_to,
	'',-- as descr,
	TRUE,-- as visible,
	FALSE,-- as indexed,
	FALSE,-- as isArray,
	'',-- as array_key,
	NULL::integer,-- as editor,--   	       	  ______________                                                        _______   ________   _______         ______________ ______________ ______________
	NULL::integer,-- as tostring,-- 	      	 /-h == == == h-\  |\__________/| |\__________/| |\__________/|  _______^____ \\__H  ==  H__// ____^_______  |            | |            | |            | |\__________/| |\__________/| |\__________/|
	NULL::integer,-- as complex_editor,--   	^-oo----------oo-^=^oo--------oo^=^oo--------oo^=^oo--------oo^=^oo-oo--oo-oo^    `------´    ^oo-oo--oo-oo^=^oo--------oo^=^oo--------oo^=^oo--------oo^=^oo--------oo^=^oo--------oo^=^oo--------oo^
	columns.is_nullable::boolean,-- as optional,
	NULL,-- as default_value,
	NULL::integer,-- as from_string,
	(columns.ordinal_position - 1),-- as pos,
	columns.character_maximum_length,-- as precision,
	NULL::integer,-- as scale,
	FALSE-- as extension_at

FROM
	public.cs_class,
	public.cs_type,
	columns
	INNER JOIN
		keyvalues ON
			columns.table_name = keyvalues.table_name AND
			columns.column_name = keyvalues.column_name
	INNER JOIN
		descriptions ON
			columns.table_name = descriptions.table_name AND
			columns.column_name = descriptions.column_name
	LEFT JOIN
		arrayseeker ON
			columns.table_name = arrayseeker.table_name
WHERE
	columns.table_schema = 'public'
	AND
	keyvalues.target ilike cs_type.name
	AND
	columns.table_name = cs_class.name
	AND
	keyvalues.type = 'F'
	AND
	descriptions.description IS NULL AND
	(NOT columns.column_name = arrayseeker.column_name OR arrayseeker.column_name IS NULL)
)
UNION

(SELECT DISTINCT--Array-Link Columns
	nextval('cs_attr_sequence'),-- as id,
	cs_class.id,-- as class_id,
	cs_type.id,-- as type_id,
	columns.column_name,-- as name,
	columns.column_name,-- as field_name,
	TRUE,-- as foreign_key,
	FALSE,-- as substitute,
	cs_type.class_id,-- as foreign_key_references_to,
	'',-- as descr,
	TRUE,-- as visible,
	FALSE,-- as indexed,
	TRUE,-- as isArray,
	arrayseeker.column_name,-- as array_key,
	NULL::integer,-- as editor,--   	       	  ______________                                                        _______   ________   _______         ______________ ______________ ______________ ______________ ______________ ______________
	NULL::integer,-- as tostring,-- 	      	 /-h == == == h-\  |\__________/| |\__________/| |\__________/|  _______^____ \\__H  ==  H__// ____^_______  |            | |            | |            | |            | |            | |            |
	NULL::integer,-- as complex_editor,--   	^-oo----------oo-^=^oo--------oo^=^oo--------oo^=^oo--------oo^=^oo-oo--oo-oo^    `------´    ^oo-oo--oo-oo^=^oo--------oo^=^oo--------oo^=^oo--------oo^=^oo--------oo^=^oo--------oo^=^oo--------oo^
	columns.is_nullable::boolean as optional,
	NULL,-- as default_value,
	NULL::integer,-- as from_string,
	(columns.ordinal_position - 1),-- as pos,
	columns.character_maximum_length,-- as precision,
	NULL::integer,-- as scale,
	FALSE-- as extension_at

FROM
	public.cs_class,
	public.cs_type,
	columns
	INNER JOIN
		keyvalues ON
			columns.table_name = keyvalues.table_name AND
			columns.column_name = keyvalues.column_name
	INNER JOIN
		descriptions ON
			columns.table_name = descriptions.table_name AND
			columns.column_name = descriptions.column_name
	LEFT JOIN
		arrayseeker ON
			arrayseeker.target = columns.table_name AND
			arrayseeker.start_column = columns.column_name

WHERE
	columns.table_schema = 'public'
	AND
	descriptions.description ilike cs_type.name
	AND
	columns.table_name = cs_class.name
	AND
	keyvalues.type = 'F'
	AND
	NOT descriptions.description IS NULL
)
UNION
(SELECT --backreference collumns
	nextval('cs_attr_sequence'),-- as id,
	cs_class.id,-- as class_id,
	2,-- as type_id,
	columns.column_name,-- as name,
	columns.column_name,-- as field_name,
	FALSE,-- as foreign_key,-- In cids it is no foreign key, if it's the backlink of an array.
	FALSE,-- as substitute,
	NULL::integer,-- as foreign_key_references_to,
	'',-- as descr,
	TRUE,-- as visible,
	FALSE,-- as indexed,
	FALSE,-- as isArray,
	'',-- as array_key,
	NULL::integer,-- as editor,--   	       	  ______________                                                        _______   ________   _______
	NULL::integer,-- as tostring,-- 	      	 /-h == == == h-\  |\__________/| |\__________/| |\__________/|  _______^____ \\__H  ==  H__// ____^_______
	NULL::integer,-- as complex_editor,--   	^-oo----------oo-^=^oo--------oo^=^oo--------oo^=^oo--------oo^=^oo-oo--oo-oo^    `------´    ^oo-oo--oo-oo^
	columns.is_nullable::boolean,-- as optional,
	NULL,-- as default_value,
	NULL::integer,-- as from_string,
	(columns.ordinal_position - 1),-- as pos,
	columns.character_maximum_length,-- as precision,
	NULL::integer,-- as scale,
	FALSE-- as extension_at

FROM
	public.cs_class,
	public.cs_type,
	columns
	INNER JOIN
		keyvalues ON
			columns.table_name = keyvalues.table_name AND
			columns.column_name = keyvalues.column_name
	INNER JOIN
		descriptions ON
			columns.table_name = descriptions.table_name AND
			columns.column_name = descriptions.column_name
	LEFT JOIN
		arrayseeker ON
			columns.table_name = arrayseeker.table_name
WHERE
	columns.table_schema = 'public'
	AND
	keyvalues.target ilike cs_type.name
	AND
	columns.table_name = cs_class.name
	AND
	keyvalues.type = 'F'
	AND
	descriptions.description IS NULL
	AND
	columns.column_name = arrayseeker.column_name
)


text:
package edu.ucsb.cs56.w14.lab05.davidacevedo;
/**
 * A Cell Phone identified by it's model and code name
 *
 * @author David Acevedo
 * @version 2/11/2014 for lab04, cs56, W14
 */
public class CellPhone {
    private String model; // Model: the name of the phone e.g. Nexus 5

    private String codeName; //Code Name: the code name of the phone e.g. hammerhead

    /**
       Two-arg constructor
       @param model - public name of the phone, e.g. Nexus 5
       @param codeName - code name of the phone, e.g "hammerhead"
    */

    public CellPhone(String codeName, String model) {
		this.model = model;
		this.codeName = codeName;
    }

    /**
	* Get the model
	*
	* @return model, public name of the phone, e.g. Nexus 5
    */

    public String getModel () { return this.model; }

    /**
	* Get the code name
	*
	* @return codeName of the phone, e.g "hammerhead"
    */
    public String getCodeName () {return this.codeName; }

    /**
     * convert to String representation in format [codeName,model]
     * e.g. <code>["hammerhead","Nexus 5"]</code>
	 *
     * @return formatted string, [codeName,model]
    */

    @Override
    public String toString() {
	return "[" + getCodeName() + "," + getModel() + "]";
    }

    /**
	 * hashcode to be used for hash tables, etc.
	 * based only on the codeName value.
     */

    @Override
    public int hashCode() {
        return codeName.hashCode();
    }

    /**
	 * compare for equality based on codeName
	 *
	 * @return true if parameter is a CellPhone with same codeName, otherwise false
     */

    @Override
    public boolean equals(Object o) {
        if (o==null) return false;
		if (! (o instanceof CellPhone) ) return false;
		CellPhone c = (CellPhone) o;
		return (c.getCodeName() == this.getCodeName());
    }

    public static void main(String [] args){
	CellPhone cell = new CellPhone("hammerhead", "Nexus 5");
	System.out.println(cell.toString());
    }

}


text:
slug: in-stock-ships-today
name: IN STOCK, SHIPS TODAY
---


text:
package com.google.bitcoin.core;

import java.io.IOException;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Map;

/**
 * A transfer of coins from one address to another creates a transaction in which the outputs
 * can be claimed by the recipient in the input of another transaction. You can imagine a
 * transaction as being a module which is wired up to others, the inputs of one have to be wired
 * to the outputs of another. The exceptions are coinbase transactions, which create new coins.
 */
public class TransactionInput extends Message implements Serializable {
    private static final long serialVersionUID = 2;
    public static final byte[] EMPTY_ARRAY = new byte[0];

    // Allows for altering transactions after they were broadcast. Tx replacement is currently disabled in the C++
    // client so this is always the UINT_MAX.
    // TODO: Document this in more detail and build features that use it.
    long sequence;
    // Data needed to connect to the output of the transaction we're gathering coins from.
    TransactionOutPoint outpoint;
    // The "script bytes" might not actually be a script. In coinbase transactions where new coins are minted there
    // is no input transaction, so instead the scriptBytes contains some extra stuff (like a rollover nonce) that we
    // don't care about much. The bytes are turned into a Script object (cached below) on demand via a getter.
    byte[] scriptBytes;
    // The Script object obtained from parsing scriptBytes. Only filled in on demand and if the transaction is not
    // coinbase.
    transient private Script scriptSig;
    // A pointer to the transaction that owns this input.
    Transaction parentTransaction;

    /** Used only in creation of the genesis block. */
    TransactionInput(NetworkParameters params, Transaction parentTransaction, byte[] scriptBytes) {
        super(params);
        this.scriptBytes = scriptBytes;
        this.outpoint = new TransactionOutPoint(params, -1, null);
        this.sequence = 0xFFFFFFFFL;
        this.parentTransaction = parentTransaction;
    }

    /** Creates an UNSIGNED input that links to the given output */
    TransactionInput(NetworkParameters params, Transaction parentTransaction, TransactionOutput output) {
        super(params);
        long outputIndex = output.getIndex();
        outpoint = new TransactionOutPoint(params, outputIndex, output.parentTransaction);
        scriptBytes = EMPTY_ARRAY;
        sequence = 0xFFFFFFFFL;
        this.parentTransaction = parentTransaction;
    }

    /** Deserializes an input message. This is usually part of a transaction message. */
    public TransactionInput(NetworkParameters params, Transaction parentTransaction,
                            byte[] payload, int offset) throws ProtocolException {
        super(params, payload, offset);
        this.parentTransaction = parentTransaction;
    }

    void parse() throws ProtocolException {
        outpoint = new TransactionOutPoint(params, bytes, cursor);
        cursor += outpoint.getMessageSize();
        int scriptLen = (int) readVarInt();
        scriptBytes = readBytes(scriptLen);
        sequence = readUint32();
    }

    @Override
    public void bitcoinSerializeToStream(OutputStream stream) throws IOException {
        outpoint.bitcoinSerializeToStream(stream);
        stream.write(new VarInt(scriptBytes.length).encode());
        stream.write(scriptBytes);
        Utils.uint32ToByteStreamLE(sequence, stream);
    }

    /**
     * Coinbase transactions have special inputs with hashes of zero. If this is such an input, returns true.
     */
    public boolean isCoinBase() {
        return outpoint.hash.equals(Sha256Hash.ZERO_HASH);
    }

    /**
     * Returns the input script.
     */
    public Script getScriptSig() throws ScriptException {
        // Transactions that generate new coins don't actually have a script. Instead this
        // parameter is overloaded to be something totally different.
        if (scriptSig == null) {
            assert scriptBytes != null;
            scriptSig = new Script(params, scriptBytes, 0, scriptBytes.length);
        }
        return scriptSig;
    }

    /**
     * Convenience method that returns the from address of this input by parsing the scriptSig.
     * @throws ScriptException if the scriptSig could not be understood (eg, if this is a coinbase transaction).
     */
    public Address getFromAddress() throws ScriptException {
        assert !isCoinBase();
        return getScriptSig().getFromAddress();
    }

    /** Returns a human readable debug string. */
    public String toString() {
        if (isCoinBase())
            return "TxIn: COINBASE";
        try {
            return "TxIn from " + Utils.bytesToHexString(getScriptSig().getPubKey()) + " script:" +
                    getScriptSig().toString();
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        }
    }

    enum ConnectionResult {
        NO_SUCH_TX,
        ALREADY_SPENT,
        SUCCESS
    }

    // TODO: Clean all this up once TransactionOutPoint disappears.

    /**
     * Locates the referenced output from the given pool of transactions.
     * @return The TransactionOutput or null if the transactions map doesn't contain the referenced tx.
     */
    TransactionOutput getConnectedOutput(Map<Sha256Hash, Transaction> transactions) {
        Transaction tx = transactions.get(outpoint.hash);
        if (tx == null)
            return null;
        TransactionOutput out = tx.outputs.get((int)outpoint.index);
        return out;
    }

    /**
     * Connects this input to the relevant output of the referenced transaction if it's in the given map.
     * Connecting means updating the internal pointers and spent flags.
     *
     * @param transactions Map of txhash->transaction.
     * @param disconnect Whether to abort if there's a pre-existing connection or not.
     * @return true if connection took place, false if the referenced transaction was not in the list.
     */
    ConnectionResult connect(Map<Sha256Hash, Transaction> transactions, boolean disconnect) {
        Transaction tx = transactions.get(outpoint.hash);
        if (tx == null)
            return TransactionInput.ConnectionResult.NO_SUCH_TX;
        TransactionOutput out = tx.outputs.get((int)outpoint.index);
        if (!out.isAvailableForSpending()) {
            if (disconnect)
                out.markAsUnspent();
            else
                return TransactionInput.ConnectionResult.ALREADY_SPENT;
        }
        outpoint.fromTx = tx;
        out.markAsSpent(this);
        return TransactionInput.ConnectionResult.SUCCESS;
    }

    /**
     * Release the connected output, making it spendable once again.
     *
     * @return true if the disconnection took place, false if it was not connected.
     */
    boolean disconnect() {
        if (outpoint.fromTx == null) return false;
        outpoint.fromTx.outputs.get((int)outpoint.index).markAsUnspent();
        outpoint.fromTx = null;
        return true;
    }
}


text:
'''
Created on 9 Sep 2017

First Common Ancestor

@author: igoroya
'''
from chapter4 import utils

def find_first_common_ancestor(root, p, q):
    node, is_ancestor = common_ancestor_helper(root, p, q)
    return node if is_ancestor else None

def common_ancestor_helper(root, p, q):

    if root is None:
        return (None, False)

    if (root is p) and (root is q):
        # here we find that the node is at same time p and q
        return (root, True)

    left_node, is_left = common_ancestor_helper(root.left, p, q)
    if is_left:
        # Here we have that node at left is both p and q
        return (left_node, is_left)

    right_node, is_right = common_ancestor_helper(root.right, p, q)
    if is_right:
        # Here we have that node at right is both p and q
        return (right_node, is_right)

    if (left_node is not None) and (right_node is not None):
        # Here we have found one ancerstor at left and other at right
        return (root, True)
    elif (root is p) or (root is q):
        # here we find one of the ancestors
        is_ancestor =  (left_node is not None) or (right_node is not None)
        return (root, is_ancestor)
    else:
        # Here we arrive at one leaf of the tree and ancestor was not found
        return (left_node, False) if left_node is not None else (right_node, False)

if __name__ == '__main__':
    my_root_node = utils.BinaryTreeNode(17)
    my_root_node.left = utils.BinaryTreeNode(12)
    my_root_node.right = utils.BinaryTreeNode(23)
    my_root_node.left.left = utils.BinaryTreeNode(19)
    my_root_node.left.right = utils.BinaryTreeNode(28)
    my_root_node.right.left = utils.BinaryTreeNode(190)
    my_root_node.right.right = utils.BinaryTreeNode(280)
    my_root_node.left.left.left = utils.BinaryTreeNode(119)
    my_root_node.left.right.left = utils.BinaryTreeNode(128)
    my_root_node.left.right.left.right = utils.BinaryTreeNode(444)

    """
                            17
                12                 23
            19       28       190     280
        119       128
                      444
    """

    node_k = utils.BinaryTreeNode(64)

    print(find_first_common_ancestor(my_root_node,  my_root_node.left,  my_root_node.right))


text:
namespace remoting {

HostStatusLogger::HostStatusLogger(scoped_refptr<HostStatusMonitor> monitor,
                                   LogToServer* log_to_server)
    : log_to_server_(log_to_server), monitor_(monitor) {
  DCHECK(log_to_server_);
  DCHECK(monitor_);
  monitor_->AddStatusObserver(this);
}

HostStatusLogger::~HostStatusLogger() {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  monitor_->RemoveStatusObserver(this);
}

void HostStatusLogger::LogSessionStateChange(const std::string& jid,
                                             bool connected) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);

  std::unique_ptr<ServerLogEntry> entry(
      MakeLogEntryForSessionStateChange(connected));
  AddHostFieldsToLogEntry(entry.get());
  entry->AddModeField(log_to_server_->mode());

  if (connected && connection_route_type_.count(jid) > 0)
    AddConnectionTypeToLogEntry(entry.get(), connection_route_type_[jid]);

  log_to_server_->Log(*entry.get());
}

void HostStatusLogger::OnClientConnected(const std::string& jid) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  LogSessionStateChange(jid, true);
}

void HostStatusLogger::OnClientDisconnected(const std::string& jid) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  LogSessionStateChange(jid, false);
  connection_route_type_.erase(jid);
}

void HostStatusLogger::OnClientRouteChange(
    const std::string& jid,
    const std::string& channel_name,
    const protocol::TransportRoute& route) {
  // Store connection type for the video channel. It is logged later
  // when client authentication is finished. For WebRTC clients, the
  // route-change notification is not per-channel, so the channel_name is
  // empty.
  if (channel_name.empty() || channel_name == kVideoChannelName) {
    connection_route_type_[jid] = route.type;
  }
}

}  // namespace remoting


text:
<?php

namespace Respect\Validation\Exceptions;

class EndsWithException extends ValidationException
{

    public static $defaultTemplates = array(
        self::MODE_DEFAULT => array(
            self::STANDARD => '{{name}} must end with ({{endValue}})',
        ),
        self::MODE_NEGATIVE => array(
            self::STANDARD => '{{name}} must not end with ({{endValue}})',
        )
    );

}


text:
/*
 * Generated by asn1c-0.9.28 (http://lionet.info/asn1c)
 * From ASN.1 module "Lightweight-Directory-Access-Protocol-V3"
 * 	found in "../ldap.asn1"
 * 	`asn1c -fcompound-names`
 */

#include "Filter.h"

static int memb_and_constraint_1(asn_TYPE_descriptor_t *td, const void *sptr,
                                 asn_app_constraint_failed_f *ctfailcb,
                                 void *app_key)
{
    size_t size;

    if (!sptr) {
        _ASN_CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name,
                    __FILE__, __LINE__);
        return -1;
    }

    /* Determine the number of elements */
    size = _A_CSET_FROM_VOID(sptr)->count;

    if ((size >= 1)) {
        /* Perform validation of the inner elements */
        return td->check_constraints(td, sptr, ctfailcb, app_key);
    } else {
        _ASN_CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)",
                    td->name, __FILE__, __LINE__);
        return -1;
    }
}

static int memb_or_constraint_1(asn_TYPE_descriptor_t *td, const void *sptr,
                                asn_app_constraint_failed_f *ctfailcb,
                                void *app_key)
{
    size_t size;

    if (!sptr) {
        _ASN_CTFAIL(app_key, td, sptr, "%s: value not given (%s:%d)", td->name,
                    __FILE__, __LINE__);
        return -1;
    }

    /* Determine the number of elements */
    size = _A_CSET_FROM_VOID(sptr)->count;

    if ((size >= 1)) {
        /* Perform validation of the inner elements */
        return td->check_constraints(td, sptr, ctfailcb, app_key);
    } else {
        _ASN_CTFAIL(app_key, td, sptr, "%s: constraint failed (%s:%d)",
                    td->name, __FILE__, __LINE__);
        return -1;
    }
}

static asn_TYPE_member_t asn_MBR_and_2[] = {
    {ATF_POINTER, 0, 0, -1 /* Ambiguous tag (CHOICE?) */, 0, &asn_DEF_Filter,
     0, /* Defer constraints checking to the member type */
     0, /* PER is not compiled, use -gen-PER */
     0, "filter"},
};
static const ber_tlv_tag_t asn_DEF_and_tags_2[] = {
    (ASN_TAG_CLASS_CONTEXT | (0 << 2)), (ASN_TAG_CLASS_UNIVERSAL | (17 << 2))};
static asn_SET_OF_specifics_t asn_SPC_and_specs_2 = {
    sizeof(struct Filter__And), offsetof(struct Filter__And, _asn_ctx),
    2, /* XER encoding is XMLValueList */
};
static /* Use -fall-defs-global to expose */
    asn_TYPE_descriptor_t asn_DEF_and_2 = {
        "and", "and", SET_OF_free, SET_OF_print, SET_OF_constraint,
        SET_OF_decode_ber, SET_OF_encode_der, SET_OF_decode_xer,
        SET_OF_encode_xer, 0, 0, /* No PER support, use "-gen-PER" to enable */
        0,                       /* Use generic outmost tag fetcher */
        asn_DEF_and_tags_2,
        sizeof(asn_DEF_and_tags_2) / sizeof(asn_DEF_and_tags_2[0]) - 1, /* 1 */
        asn_DEF_and_tags_2, /* Same as above */
        sizeof(asn_DEF_and_tags_2) / sizeof(asn_DEF_and_tags_2[0]), /* 2 */
        0,                   /* No PER visible constraints */
        asn_MBR_and_2, 1,    /* Single element */
        &asn_SPC_and_specs_2 /* Additional specs */
};

static asn_TYPE_member_t asn_MBR_or_4[] = {
    {ATF_POINTER, 0, 0, -1 /* Ambiguous tag (CHOICE?) */, 0, &asn_DEF_Filter,
     0, /* Defer constraints checking to the member type */
     0, /* PER is not compiled, use -gen-PER */
     0, "filter"},
};
static const ber_tlv_tag_t asn_DEF_or_tags_4[] = {
    (ASN_TAG_CLASS_CONTEXT | (1 << 2)), (ASN_TAG_CLASS_UNIVERSAL | (17 << 2))};
static asn_SET_OF_specifics_t asn_SPC_or_specs_4 = {
    sizeof(struct Filter__Or), offsetof(struct Filter__Or, _asn_ctx),
    2, /* XER encoding is XMLValueList */
};
static /* Use -fall-defs-global to expose */
    asn_TYPE_descriptor_t asn_DEF_or_4 = {
        "or", "or", SET_OF_free, SET_OF_print, SET_OF_constraint,
        SET_OF_decode_ber, SET_OF_encode_der, SET_OF_decode_xer,
        SET_OF_encode_xer, 0, 0, /* No PER support, use "-gen-PER" to enable */
        0,                       /* Use generic outmost tag fetcher */
        asn_DEF_or_tags_4,
        sizeof(asn_DEF_or_tags_4) / sizeof(asn_DEF_or_tags_4[0]) - 1, /* 1 */
        asn_DEF_or_tags_4, /* Same as above */
        sizeof(asn_DEF_or_tags_4) / sizeof(asn_DEF_or_tags_4[0]), /* 2 */
        0,                  /* No PER visible constraints */
        asn_MBR_or_4, 1,    /* Single element */
        &asn_SPC_or_specs_4 /* Additional specs */
};

static asn_TYPE_member_t asn_MBR_Filter_1[] = {
    {ATF_NOFLAGS, 0, offsetof(struct Filter, choice.And),
     (ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, &asn_DEF_and_2,
     memb_and_constraint_1, 0, /* PER is not compiled, use -gen-PER */
     0, "and"},
    {ATF_NOFLAGS, 0, offsetof(struct Filter, choice.Or),
     (ASN_TAG_CLASS_CONTEXT | (1 << 2)), 0, &asn_DEF_or_4, memb_or_constraint_1,
     0, /* PER is not compiled, use -gen-PER */
     0, "or"},
    {ATF_POINTER, 0, offsetof(struct Filter, choice.Not),
     (ASN_TAG_CLASS_CONTEXT | (2 << 2)), +1, /* EXPLICIT tag at current level */
     &asn_DEF_Filter, 0, /* Defer constraints checking to the member type */
     0,                  /* PER is not compiled, use -gen-PER */
     0, "not"},
    {ATF_NOFLAGS, 0, offsetof(struct Filter, choice.equalityMatch),
     (ASN_TAG_CLASS_CONTEXT | (3 << 2)), -1, /* IMPLICIT tag at current level */
     &asn_DEF_AttributeValueAssertion,
     0, /* Defer constraints checking to the member type */
     0, /* PER is not compiled, use -gen-PER */
     0, "equalityMatch"},
    {ATF_NOFLAGS, 0, offsetof(struct Filter, choice.substrings),
     (ASN_TAG_CLASS_CONTEXT | (4 << 2)), -1, /* IMPLICIT tag at current level */
     &asn_DEF_SubstringFilter,
     0, /* Defer constraints checking to the member type */
     0, /* PER is not compiled, use -gen-PER */
     0, "substrings"},
    {ATF_NOFLAGS, 0, offsetof(struct Filter, choice.greaterOrEqual),
     (ASN_TAG_CLASS_CONTEXT | (5 << 2)), -1, /* IMPLICIT tag at current level */
     &asn_DEF_AttributeValueAssertion,
     0, /* Defer constraints checking to the member type */
     0, /* PER is not compiled, use -gen-PER */
     0, "greaterOrEqual"},
    {ATF_NOFLAGS, 0, offsetof(struct Filter, choice.lessOrEqual),
     (ASN_TAG_CLASS_CONTEXT | (6 << 2)), -1, /* IMPLICIT tag at current level */
     &asn_DEF_AttributeValueAssertion,
     0, /* Defer constraints checking to the member type */
     0, /* PER is not compiled, use -gen-PER */
     0, "lessOrEqual"},
    {ATF_NOFLAGS, 0, offsetof(struct Filter, choice.present),
     (ASN_TAG_CLASS_CONTEXT | (7 << 2)), -1, /* IMPLICIT tag at current level */
     &asn_DEF_AttributeDescription,
     0, /* Defer constraints checking to the member type */
     0, /* PER is not compiled, use -gen-PER */
     0, "present"},
    {ATF_NOFLAGS, 0, offsetof(struct Filter, choice.approxMatch),
     (ASN_TAG_CLASS_CONTEXT | (8 << 2)), -1, /* IMPLICIT tag at current level */
     &asn_DEF_AttributeValueAssertion,
     0, /* Defer constraints checking to the member type */
     0, /* PER is not compiled, use -gen-PER */
     0, "approxMatch"},
    {ATF_NOFLAGS, 0, offsetof(struct Filter, choice.extensibleMatch),
     (ASN_TAG_CLASS_CONTEXT | (9 << 2)), -1, /* IMPLICIT tag at current level */
     &asn_DEF_MatchingRuleAssertion,
     0, /* Defer constraints checking to the member type */
     0, /* PER is not compiled, use -gen-PER */
     0, "extensibleMatch"},
};
static const asn_TYPE_tag2member_t asn_MAP_Filter_tag2el_1[] = {
    {(ASN_TAG_CLASS_CONTEXT | (0 << 2)), 0, 0, 0}, /* and */
    {(ASN_TAG_CLASS_CONTEXT | (1 << 2)), 1, 0, 0}, /* or */
    {(ASN_TAG_CLASS_CONTEXT | (2 << 2)), 2, 0, 0}, /* not */
    {(ASN_TAG_CLASS_CONTEXT | (3 << 2)), 3, 0, 0}, /* equalityMatch */
    {(ASN_TAG_CLASS_CONTEXT | (4 << 2)), 4, 0, 0}, /* substrings */
    {(ASN_TAG_CLASS_CONTEXT | (5 << 2)), 5, 0, 0}, /* greaterOrEqual */
    {(ASN_TAG_CLASS_CONTEXT | (6 << 2)), 6, 0, 0}, /* lessOrEqual */
    {(ASN_TAG_CLASS_CONTEXT | (7 << 2)), 7, 0, 0}, /* present */
    {(ASN_TAG_CLASS_CONTEXT | (8 << 2)), 8, 0, 0}, /* approxMatch */
    {(ASN_TAG_CLASS_CONTEXT | (9 << 2)), 9, 0, 0}  /* extensibleMatch */
};
static asn_CHOICE_specifics_t asn_SPC_Filter_specs_1 = {
    sizeof(struct Filter), offsetof(struct Filter, _asn_ctx),
    offsetof(struct Filter, present), sizeof(((struct Filter *)0)->present),
    asn_MAP_Filter_tag2el_1, 10, /* Count of tags in the map */
    0, 10                        /* Extensions start */
};
asn_TYPE_descriptor_t asn_DEF_Filter = {
    "Filter",               "Filter",          CHOICE_free,
    CHOICE_print,           CHOICE_constraint, CHOICE_decode_ber,
    CHOICE_encode_der,      CHOICE_decode_xer, CHOICE_encode_xer,
    0,                      0,  /* No PER support, use "-gen-PER" to enable */
    CHOICE_outmost_tag,     0,  /* No effective tags (pointer) */
    0,                          /* No effective tags (count) */
    0,                          /* No tags (pointer) */
    0,                          /* No tags (count) */
    0,                          /* No PER visible constraints */
    asn_MBR_Filter_1,       10, /* Elements count */
    &asn_SPC_Filter_specs_1     /* Additional specs */
};


text:
require 'rails_helper'

RSpec.describe ApplicationController do
  it_behaves_like 'Nyauth::SessionConcern'
end


text:
package org.openqa.selenium.server.commands;

import org.openqa.jetty.http.HttpRequest;
import org.openqa.jetty.http.HttpResponse;

import java.util.*;
import java.text.SimpleDateFormat;

public class CaptureNetworkTrafficCommand extends Command {
    private static final List<Entry> entries = Collections.synchronizedList(new ArrayList<Entry>());

    public static void clear() {
        entries.clear();
    }

    public static void capture(Entry entry) {
        entries.add(entry);
    }

    private String type; // ie: XML, JSON, plain text, etc

    public CaptureNetworkTrafficCommand(String type) {
        this.type = type;
    }

    public String execute() {
        StringBuilder sb = new StringBuilder();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

        if ("json".equalsIgnoreCase(type)) {
            /*

            [{
            statusCode: 200,
            method: 'GET',
            url: 'http://foo.com/index.html',
            bytes: 12422,
            start: '2009-03-15T14:23:00.000-0700',
            end: '2009-03-15T14:23:00.102-0700',
            timeInMillis: 102,
            requestHeaders: [{
              name: 'Foo',
              value: 'Bar'
            }],
            responseHeaders: [{
              name: 'Baz',
              value: 'Blah'
            }]
            },{
            ...
            }]

             */

            sb.append("[");

            synchronized(entries) {
                for (final Iterator<Entry> iterator = entries.iterator(); iterator.hasNext();) {
                    final Entry entry = iterator.next();
                    sb.append("{\n");

                    sb.append(jsonKey("statusCode")).append(entry.statusCode).append(",\n");
                    sb.append(jsonKey("method")).append(json(entry.method)).append(",\n");
                    sb.append(jsonKey("url")).append(json(entry.url)).append(",\n");
                    sb.append(jsonKey("bytes")).append(entry.bytes).append(",\n");
                    sb.append(jsonKey("start")).append(json(sdf.format(entry.start))).append(",\n");
                    sb.append(jsonKey("end")).append(json(sdf.format(entry.end))).append(",\n");
                    sb.append(jsonKey("timeInMillis")).append((entry.end.getTime() - entry.start.getTime())).append(",\n");

                    sb.append(jsonKey("requestHeaders")).append("[");
                    jsonHeaders(sb, entry.requestHeaders);
                    sb.append("],\n");

                    sb.append(jsonKey("responseHeaders")).append("[");
                    jsonHeaders(sb, entry.responseHeaders);
                    sb.append("]\n");

                    sb.append("}");

                    if (iterator.hasNext()) {
                        sb.append(",\n");
                    }
                }
            }

            sb.append("]");
        } else if ("xml".equalsIgnoreCase(type)) {
            /*
            <traffic>
             <entry statusCode="200" method="GET" url="http://foo.com/index.html" bytes="12422" start="2009-03-15T14:23:00.000-0700" end="2009-03-15T14:23:00.102-0700" timeInMillis="102">
              <requestHeaders>

              </requestHeaders>
              <responseHeaders>

              </responseHeaders>
             </entry>
            </traffic>
             */
            sb.append("<traffic>\n");

            synchronized(entries) {
                for (final Entry entry : entries) {
                    sb.append("<entry ");

                    sb.append("statusCode=\"").append(entry.statusCode).append("\" ");
                    sb.append("method=\"").append(json(entry.method)).append("\" ");
                    sb.append("url=\"").append(xml(entry.url)).append("\" ");
                    sb.append("bytes=\"").append(entry.bytes).append("\" ");
                    sb.append("start=\"").append(sdf.format(entry.start)).append("\" ");
                    sb.append("end=\"").append(sdf.format(entry.end)).append("\" ");
                    sb.append("timeInMillis=\"").append((entry.end.getTime() - entry.start.getTime())).append("\">\n");

                    sb.append("    <requestHeaders>\n");
                    xmlHeaders(sb, entry.requestHeaders);
                    sb.append("    </requestHeaders>\n");

                    sb.append("    <responseHeaders>\n");
                    xmlHeaders(sb, entry.responseHeaders);
                    sb.append("    </responseHeaders>\n");

                    sb.append("</entry>\n");
                }
            }
            sb.append("</traffic>\n");
        } else {
            /*
             200 GET http://foo.com/index.html
             12422 bytes
             102ms (2009-03-15T14:23:00.000-0700 - 2009-03-15T14:23:00.102-0700)

             Request Headers
              - Foo => Bar
             Response Headers
              - Baz => Blah
             ================================================================

             */

            synchronized(entries) {
                for (final Entry entry : entries) {
                    sb.append(entry.statusCode).append(" ").append(entry.method).append(" ").append(entry.url).append("\n");
                    sb.append(entry.bytes).append(" bytes\n");
                    sb.append(entry.end.getTime() - entry.start.getTime()).append("ms (").append(sdf.format(entry.start)).append(" - ").append(sdf.format(entry.end)).append("\n");
                    sb.append("\n");
                    sb.append("Request Headers\n");
                    for (Header header : entry.requestHeaders) {
                        sb.append(" - ").append(header.name).append(" => ").append(header.value).append("\n");
                    }
                    sb.append("Response Headers\n");
                    for (Header header : entry.responseHeaders) {
                        sb.append(" - ").append(header.name).append(" => ").append(header.value).append("\n");
                    }
                    sb.append("================================================================\n");
                    sb.append("\n");
                }
            }
        }

        clear();

        return "OK," + sb.toString();
    }

    private void xmlHeaders(final StringBuilder sb, final List headers) {
        for (final Header header : headers) {
            sb.append("        ").append(xml(header.value)).append("\n");
        }
    }

    private void jsonHeaders(final StringBuilder sb, final List headers) {
        for (final Iterator headItr = headers.iterator(); headItr.hasNext();) {
            final Header header = headItr.next();

            sb.append("{\n");
            sb.append("    ").append(jsonKey("name")).append(json(header.name)).append(",\n");
            sb.append("    ").append(jsonKey("value")).append(json(header.value)).append("\n");
            if (headItr.hasNext()) {
                sb.append("    },");
            }
            else {
                sb.append("  }");
            }

        }
    }

    private String xml(String s) {
        s = s.replaceAll("&", "&");
        s = s.replaceAll("\"", """);
        s = s.replaceAll("\\<", "<");
        s = s.replaceAll("\\>", ">");

        return s;
    }

    private String jsonKey(final String key) {
        final StringBuilder ret = new StringBuilder();

        ret.append("  \"").append(key).append("\"").append(":");

        return ret.toString();
    }

    private Object json(String s) {
        s = s.replaceAll("\\'", "\\\\'");
        s = s.replaceAll("\\\"", "\\\\\"");
        s = s.replaceAll("\n", "\\\\n");

        final StringBuilder ret = new StringBuilder();
        ret.append("\"").append(s).append("\"");

        return ret.toString();
    }

    public static class Entry {
        private String method;
        private String url;
        private int statusCode;
        private Date start;
        private Date end;
        private long bytes;
        private List requestHeaders = new ArrayList();
        private List responseHeaders = new ArrayList();

        public Entry(String method, String url) {
            this.method = method;
            this.url = url;
            this.start = new Date();
        }

        public void finish(int statusCode, long bytes) {
            this.statusCode = statusCode;
            this.bytes = bytes;
            this.end = new Date();
        }

        public void addRequestHeaders(HttpRequest request) {
            Enumeration names = request.getFieldNames();
            while (names.hasMoreElements()) {
                String name = (String) names.nextElement();
                String value = request.getField(name);

                requestHeaders.add(new Header(name, value));
            }
        }

        public void addResponseHeader(HttpResponse response) {
            Enumeration names = response.getFieldNames();
            while (names.hasMoreElements()) {
                String name = (String) names.nextElement();
                String value = response.getField(name);

                responseHeaders.add(new Header(name, value));
            }
        }

        public void setStart(Date start) {
            this.start = start;
        }

        public void setEnd(Date end) {
            this.end = end;
        }

        @Override
        public String toString() {
            return method + "|" + statusCode + "|" + url + "|" + requestHeaders.size() + "|" + responseHeaders.size() + "\n";
        }

        public void addRequestHeader(String key, String value) {
            this.requestHeaders.add(new Header(key, value));
        }
    }

    public static class Header {
        private String name;
        private String value;

        public Header(String name, String value) {
            this.name = name;
            this.value = value;
        }
    }
}