text:
[![Version](https://img.shields.io/npm/v/react-lazy.svg)](https://www.npmjs.com/package/react-lazy)
[![Build Status](https://travis-ci.org/Merri/react-lazy.svg)](https://travis-ci.org/Merri/react-lazy)

> Lazy load your content without breaking the internet!

Supports universal rendering including disabled JavaScript by using `noscript` elements that are also friendly to all
search engines. Uses modern IntersectionObserver API using the excellent
[@researchgate/react-intersection-observer](https://github.com/researchgate/react-intersection-observer).

Also optionally supports displaying the content on IE8 and earlier by adding conditional comments to skip `noscript`
elements.

[View lazy loading demo](https://merri.github.io/react-lazy/)

```js
npm install react-lazy

import { Lazy } from 'react-lazy'
// or
import { LazyGroup } from 'react-lazy'
```

You also need to polyfill `intersection-observer`! Use polyfill.io or `require('intersection-observer')`. Check
[Can I use](https://caniuse.com/#feat=intersectionobserver) for browser support status. `Map` and `Set` are also
required, but these are required by React as well.

----

## Why `react-lazy`?

1. Minimalistic and performant implementation with less dependencies than other solutions
2. You can choose between ease-of-use (LazyGroup) and do-it-yourself (Lazy)
3. The hard part of handling `noscript` is done for you

----

### Why lazy load content such as images?

You want to save your bandwidth and/or server load. As a side effect you may also gain some performance benefits on
client side, especially on mobile devices. However the main benefit (and main purpose) for you should always be the
reduction of bandwidth/server load.

Likely side effect of lazy loading is that user may see content flashing as it comes into view; sometimes with a lot of
delay as it depends on connectivity. You can make the experience less flickery by adding a transition when image is
loaded (a bit harder to develop) or by giving `Lazy` a large cushion (500 pixels or more) to load image before it is
actually in the viewport. Using both strategies together is recommended. You can test the experience on your own site by
dropping mobile connection to slow 3G.

Chrome developer tools also has network throttling so you don't need to get yourself into a train to nowhere to test how
well or poorly your site works in high latency conditions. However it is also recommended you do get yourself into a
train to nowhere as it does good for your mind and soul to abandon the hectic although convenient city lifestyle every
once in a while.

----

## Usage: `<Lazy />`

```jsx
// curly brackets are required
import { Lazy } from 'react-lazy'

...

    <Lazy component="a" href="/" className="image-link image-link--100px" ltIE9>
        <img alt="My Lazy Loaded Image" className="image-link__image" src="my-lazy-loaded-image.png" />
    </Lazy>
```

```html
<!-- server render and render before component is in viewport -->
<a href="/" class="image-link image-link--100px">
    <!--[if IE 9]><!--><noscript><!--<![endif]-->
        <img alt="My Lazy Loaded Image" class="image-link__image" src="my-lazy-loaded-image.png" />
    <!--[if IE 9]><!--></noscript><!--<![endif]-->
</a>

<!-- client DOM after component is in viewport -->
<a href="/" class="image-link image-link--100px">
    <img alt="My Lazy Loaded Image" class="image-link__image" src="my-lazy-loaded-image.png" />
</a>
```

----

## Component introduction

There are two components: `<Lazy />` and `<LazyGroup />`.

**Lazy** provides basic functionality for lazy loading: it keeps render in `noscript` element until it has come into
viewport and then simply swaps render. **Everything** inside the component is wrapped into `noscript`. As the component
is quite simple and generic it doesn't support many other things that provide convenience; for example, with images you
have to write your own logic for handling `onError` and `onLoad` so that you can do things like trigger transitions as
images are loaded, or change what to render instead of the image if loading the image fails.

**LazyGroup** extends `Lazy` functionality by wrapping only specified component types inside `noscript`. So only the
specified components like `img` or `iframe` elements are wrapped to `noscript`. Other elements are simply rendered
as-is.

The wrappable components (`img`s and `iframe`s by default) are also always wrapped inside another component. This custom
component will receive information on whether loading the `img` or `iframe` has succeeded or failed, thus allowing a
single place to control lifecycles as images or other content is loaded.

## Shared features

These features are supported by both `<Lazy />` and `<LazyGroup />`.

### IntersectionObserver props

- `viewport` (= `root` option)
- `cushion` (= `rootMargin` option)
- `threshold`

These props work like you would expect them to work with IntersectionObserver.

### `clientOnly` prop

Disables `noscript` element rendering, instead rendering no HTML for the contents in server side. This gives behavior
similar to most other lazy loaders, which is why it is not enabled by default in `react-lazy`.

### `ltIE9` prop

Renders Internet Explorer 8 friendly syntax by adding conditional comments around `noscript`, effectively hiding
existance of the tag from IE8 and earlier. This allows for minimal legacy browser support, since it is highly unlikely
anyone writes their JS to execute on IE8 anymore.

Essentially this feature allows to render a visually non-broken page to users of legacy browsers, making it possible to
give minimally acceptable user experience to users of browsers that should be dead.

This means there is no lazy rendering on legacy browsers, images load immediately.

This prop has no effect if `clientOnly` is enabled.

### `onLoad`

- On `Lazy` triggers after removing `noscript` element.
- On `LazyGroup` triggers after **all** wrapped child components `onLoad` or `onError` events have triggered.

```jsx
<Lazy onLoad={yourCustomFunction}>...</Lazy>
```

### `onViewport`

Triggers before removing `noscript` elements. Given function receives IntersectionObserver event object.

### `visible`

Allows you to manually tell if the element is actually visible to the user or not.

----

## `<LazyGroup />`

`Lazy` works fine with single images, but sometimes you may want to have slightly more control or better performance
when you know multiple images load at the same time (for example, a row of thumbnails). In this case it makes no sense
to check each individual image's position in viewport when checking for just the container component will be good enough
— and also less for a browser to execute.

You can also use `Lazy` for multiple images, but there are some practical limitations such as the fact that everything
inside `Lazy` is within `noscript` element, thus there is nothing rendered inside. `LazyGroup` solves this issue by
rendering `noscript` only around specific wrapped elements (`img` and `iframe` by default). Also, further control is
given with `childWrapper` component that will receive a set of props to make life easier.

Use cases:

1. You want all contained images/iframes to be transitioned at the exact same time after everything is loaded.
2. You want to use the abstraction provided by `childWrapper` instead of writing custom logic.
3. You want to have slightly better performance by only checking the container element's location relative to the view.

### Usage

```jsx
// curly brackets are required
import { LazyGroup } from 'react-lazy'

function ImageContainer({ childProps, children, isFailed, isLoaded, ...props }) {
    return (
        // usually the other props include `dangerouslySetInnerHtml` when rendering `noscript` element
        <div {...props}>
            {isFailed ? 'The image did not load :( ' + childProps.src : children}
        </div>
    )
}

...

    <LazyGroup component="ul" className="image-list" childWrapper={ImageContainer}>
        {this.props.images.map((image, index) =>
            <li key={index} className="image-list__item">
                <img {...image} />
            </li>
        )}
    </LazyGroup>
```

### `childWrapper` lifecycle

1. On server side render and before the `LazyGroup` container is in viewport in client `childWrapper` will receive
`dangerouslySetInnerHtml` prop (thus rendering `noscript` element that contains the lazily loaded content).
2. After coming into viewport `isFailed` and `isLoaded` are false. `childProps` also become available.
3. `isFailed` is set to true when `img`'s or `iframe`'s `onError` event triggers. You can use `childProps` to decide
what to render.
4. `isLoaded` is set to true when `img`'s or `iframe`'s `onLoad` event triggers.

### `childrenToWrap`

Use this array to decide which components are wrapped by `childWrapper`. Default value: `['iframe', 'img']`

**Note!** The components **must** support `onError` and `onLoad` events as these are used to detect loading.

----

## Other components

You can see these components via React developer tools, but as of 1.0.2 they have not been exposed.

### `DefaultWrapper`

This is the `childWrapper` used to render `LazyGroup`'s wrapped childs if no custom wrapper is given. The wrapper is a
simple div with a `className` of `react-lazy-wrapper`. BEM convention is used to tell about the lifecycle:

1. `react-lazy-wrapper--placeholder` is set on server render and client render before `LazyGroup` is in viewport.
2. `react-lazy-wrapper--loading` is set once `LazyGroup` is in viewport.
3. `react-lazy-wrapper--failed` is set if lazy loaded component's `onError` event has triggered.
4. `react-lazy-wrapper--loaded` is set if lazy loaded component's `onLoad` event has triggered.

### `LazyChild`

This is the component used by `LazyGroup` to handle rendering of the wrapped child components. It manages the `onLoad` /
`onError` handling. It takes two props: `callback` and `wrapper`. `callback` is called by `LazyChild` once loading
result has been resolved. `wrapper` is the component rendered around wrapped child element.


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

<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>stylesheet_test</title>
    <meta name="generator" content="TextMate http://macromates.com/" />
    <meta name="author" content="John McAliley" />
    <link
      rel="stylesheet"
      href="/charlotte-ruby/image_scraper/master/spec/support/unescaped_image.css"
      type="text/css"
      media="screen"
      title="no title"
      charset="utf-8"
    />
    <!-- Date: 2011-06-01 -->
  </head>
  <body></body>
</html>

redpajama_set_name: RedPajamaGithub


text:
/* This will automatically update any theme changes I make */
@import url("https://raw.githack.com/BakaTekku/Discord_Theme/master/theme.css");


text:
namespace cfsm {

template <class StateType>
class StateMachine;

template <class StateType, template <StateType, StateType> class TransitionType, StateType From>
class StateChanger {
public:
    template <StateType To>
    static void changeState(StateMachine<StateType> & stateMachine) {
        transitionValidityGuard<To>();
        stateMachine.setState(To);
    }

private:
    template <StateType To>
    static void transitionValidityGuard(TransitionType<From, To> const& = {}) { }
};

} // namespace cfsm


text:
import sys
import argparse

parser = argparse.ArgumentParser("Prints columns from a file as specified by the indices")
parser.add_argument("-file", help="initial file", required=True)
parser.add_argument("-indx", help="indices to print separated by commas. Ex: 0,2,4")
parser.add_argument("-sep", help="delimiter in the file", default="\t")
args = parser.parse_args()

indices = args.indx.split(",")
with open(args.file, 'r') as IN:
    for line in IN:
        elems = line[:-1].split(args.sep)

        to_print = []
        for indx in indices:
            to_print.append(elems[int(indx)])

        print(args.sep.join(to_print))


text:
<?xml version="1.0" encoding="utf-8"?>
<phpunit bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="Pop Shipping Component PHPUnit Test">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist addUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">src</directory>
            <exclude>
                <file>src/Adapter/Fedex.php</file>
                <file>src/Adapter/Ups.php</file>
                <file>src/Adapter/Usps.php</file>
            </exclude>
        </whitelist>
    </filter>
    <logging>
        <log type="coverage-html" target="/tmp/pop-shipping-cc" charset="UTF-8"
             yui="true" highlight="false" showUncoveredFiles="true"
             lowUpperBound="35" highLowerBound="70" />
    </logging>
</phpunit>


text:
package net.minidev.ovh.api.xdsl.eligibility;

import net.minidev.ovh.api.xdsl.OvhDeconsolidationEnum;
import net.minidev.ovh.api.xdsl.OvhDslTypeEnum;
import net.minidev.ovh.api.xdsl.OvhGtrEnum;

/**
 * An offer
 */
public class OvhOffer {
	/**
	 * Estimated or guaranteed upload rate in Mbit/s, if applicable
	 *
	 * canBeNull
	 */
	public Double uploadRate;

	/**
	 * Is copper lines desaturation needed and available for this offer ?
	 *
	 * canBeNull
	 */
	public Boolean desaturation;

	/**
	 * Estimated or guaranteed download rate in Mbit/s, if applicable
	 *
	 * canBeNull
	 */
	public Double downloadRate;

	/**
	 * Allowed GTR (none, 4ho : 4 work hours, 4hno : 4 unworked hours)
	 *
	 * canBeNull
	 */
	public OvhGtrEnum[] gtr;

	/**
	 * Allowed unbundling methods
	 *
	 * canBeNull
	 */
	public OvhDeconsolidationEnum[] unbundling;

	/**
	 * DEPRECATED Please use downloadRate instead /DEPRECATED - Estimated or guaranteed rate in Mbit/s, if applicable
	 *
	 * canBeNull
	 */
	public Double rate;

	/**
	 * Provider, if applicable
	 *
	 * canBeNull
	 */
	public OvhProviderEnum provider;

	/**
	 * Is the rate guaranteed ?
	 *
	 * canBeNull
	 */
	public Boolean guaranteed;

	/**
	 * Offer label
	 *
	 * canBeNull
	 */
	public String label;

	/**
	 * DSL technology
	 *
	 * canBeNull
	 */
	public OvhDslTypeEnum type;

	/**
	 * Number of pairs to use
	 *
	 * canBeNull
	 */
	public Long pairs;
}


text:
import treeano.nodes as tn
from treeano.sandbox.nodes import equilibrated_sgd

def test_equilibrated_sgd_node_serialization():
    tn.check_serialization(equilibrated_sgd.EquilibratedSGDNode("a"))

def test_equilibrated_sgd_node():
    tn.test_utils.check_updates_node(equilibrated_sgd.EquilibratedSGDNode,
                                     activation="sigmoid")


text:
<PackageItem xmlns:tcm="http://www.tridion.com/ContentManager/5.0" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.sdltridion.com/ContentManager/ImportExport/Package/2013">
  <Dependencies>
    <Dependency dependencyType="Publication" itemUrl="/webdav/401%20Automated%20Test%20Parent" linkName="LocationInfo/ContextRepository" />
    <Dependency dependencyType="BluePrintParent" itemUrl="/webdav/100%20Master/Building%20Blocks/Framework/Developer/Templates/DXA%2ER2/Render%20Component%20Content.tbbcmp" linkName="" />
  </Dependencies>
</PackageItem>


text:
package sbt

trait PackagePaths extends NotNull
{
	def jarPath: Path
	def packageTestJar: Path
	def packageDocsJar: Path
	def packageSrcJar: Path
	def packageTestSrcJar: Path
	def packageProjectZip: Path
}
/** These are the paths required by BasicScalaProject.*/
trait ScalaPaths extends PackagePaths
{
	/** A PathFinder that selects all main sources.*/
	def mainSources: PathFinder
	/** A PathFinder that selects all test sources.*/
	def testSources: PathFinder
	def mainSourceRoots: PathFinder
	def testSourceRoots: PathFinder
	/** A PathFinder that selects all main resources.*/
	def mainResources: PathFinder
	/** A PathFinder that selects all test resources. */
	def testResources: PathFinder

	def mainCompilePath: Path
	def testCompilePath: Path
	def mainAnalysisPath: Path
	def testAnalysisPath: Path
	def mainDocPath: Path
	def testDocPath: Path
	def graphSourcesPath: Path
	def graphPackagesPath: Path
	def mainResourcesOutputPath: Path
	def testResourcesOutputPath: Path

	/** A PathFinder that selects all the classes compiled from the main sources.*/
	def mainClasses: PathFinder
	/** A PathFinder that selects all the classes compiled from the test sources.*/
	def testClasses: PathFinder

	/** Declares all paths to be packaged by the package action.*/
	def packagePaths: PathFinder
	/** Declares all paths to be packaged by the package-test action.*/
	def packageTestPaths: PathFinder
	/** Declares all sources to be packaged by the package-src action.*/
	def packageSourcePaths: PathFinder
	/** Declares all sources to be packaged by the package-test-src action.*/
	def packageTestSourcePaths: PathFinder
	/** Declares all paths to be packaged by the package-project action.*/
	def packageProjectPaths: PathFinder

	/** These are the directories that are created when a user makes a new project from sbt.*/
	protected def directoriesToCreate: List[Path]
	/** The directories to which a project writes are listed here and is used
	* to check a project and its dependencies for collisions.*/
	def outputDirectories: Iterable[Path]

	def artifactBaseName: String
}

trait BasicScalaPaths extends Project with ScalaPaths
{
	def mainResourcesPath: PathFinder
	def testResourcesPath: PathFinder
	def managedDependencyPath: Path
	def managedDependencyRootPath: Path
	def dependencyPath: Path

	protected def sources(base: PathFinder) = descendents(base, sourceExtensions)
	protected def sourceExtensions = "*.scala" | "*.java"

	def mainSources =
	{
		val normal = sources(mainSourceRoots)
		if(scratch)
			normal +++ (info.projectPath * sourceExtensions)
		else
			normal
	}
	def testSources = sources(testSourceRoots)

	def mainResources = descendents(mainResourcesPath ##, "*")
	def testResources = descendents(testResourcesPath ##, "*")

	def mainClasses = (mainCompilePath ##) ** "*.class"
	def testClasses = (testCompilePath ##) ** "*.class"

	def packagePaths = mainClasses +++ mainResources
	def packageTestPaths = testClasses +++ testResources
	def packageSourcePaths = mainSources +++ mainResources
	def packageTestSourcePaths = testSources +++ testResources
	def packageProjectPaths = descendents( (info.projectPath ##), "*") --- (packageProjectExcludes ** "*")
	protected def packageProjectExcludes: PathFinder =
		outputRootPath +++ managedDependencyRootPath +++
		info.bootPath +++ info.builderProjectOutputPath +++
		info.pluginsOutputPath +++ info.pluginsManagedSourcePath +++ info.pluginsManagedDependencyPath

	override def outputDirectories = outputPath :: managedDependencyPath :: Nil
}

@deprecated trait BasicProjectPaths extends MavenStyleScalaPaths
trait MavenStyleScalaPaths extends BasicScalaPaths with BasicPackagePaths
{
	import BasicProjectPaths._

	def outputPath: Path

	def sourceDirectoryName = DefaultSourceDirectoryName
	def mainDirectoryName = DefaultMainDirectoryName
	def scalaDirectoryName = DefaultScalaDirectoryName
	def javaDirectoryName = DefaultJavaDirectoryName
	def resourcesDirectoryName = DefaultResourcesDirectoryName
	def testDirectoryName = DefaultTestDirectoryName
	def mainCompileDirectoryName = DefaultMainCompileDirectoryName
	def testCompileDirectoryName = DefaultTestCompileDirectoryName
	def docDirectoryName = DefaultDocDirectoryName
	def apiDirectoryName = DefaultAPIDirectoryName
	def graphDirectoryName = DefaultGraphDirectoryName
	def mainAnalysisDirectoryName = DefaultMainAnalysisDirectoryName
	def testAnalysisDirectoryName = DefaultTestAnalysisDirectoryName
	def mainResourcesOutputDirectoryName = DefautMainResourcesOutputDirectoryName
	def testResourcesOutputDirectoryName = DefautTestResourcesOutputDirectoryName

	def sourcePath = path(sourceDirectoryName)

	def mainSourcePath = sourcePath / mainDirectoryName
	def mainScalaSourcePath = mainSourcePath / scalaDirectoryName
	def mainJavaSourcePath = mainSourcePath / javaDirectoryName
	def mainResourcesPath = mainSourcePath / resourcesDirectoryName
	def mainDocPath = docPath / mainDirectoryName / apiDirectoryName
	def mainCompilePath = outputPath / mainCompileDirectoryName
	def mainResourcesOutputPath = outputPath / mainResourcesOutputDirectoryName
	def mainAnalysisPath = outputPath / mainAnalysisDirectoryName

	def testSourcePath = sourcePath / testDirectoryName
	def testJavaSourcePath = testSourcePath / javaDirectoryName
	def testScalaSourcePath = testSourcePath / scalaDirectoryName
	def testResourcesPath = testSourcePath / resourcesDirectoryName
	def testDocPath = docPath / testDirectoryName / apiDirectoryName
	def testCompilePath = outputPath / testCompileDirectoryName
	def testResourcesOutputPath = outputPath / testResourcesOutputDirectoryName
	def testAnalysisPath = outputPath / testAnalysisDirectoryName

	def docPath = outputPath / docDirectoryName
	def graphPath = outputPath / graphDirectoryName
	def graphPackagesPath = graphPath / "packages"
	def graphSourcesPath = graphPath / "sources"

	/** These are the directories that are created when a user makes a new project from sbt.*/
	protected def directoriesToCreate: List[Path] =
		dependencyPath ::
		mainScalaSourcePath ::
		mainResourcesPath ::
		testScalaSourcePath ::
		testResourcesPath ::
		Nil

	def mainSourceRoots = (mainJavaSourcePath##) +++ (mainScalaSourcePath##)
	def testSourceRoots = (testJavaSourcePath##) +++ (testScalaSourcePath##)
}

trait BasicPackagePaths extends ScalaPaths with PackagePaths
{
	def outputPath: Path

	def defaultJarBaseName: String = artifactBaseName
	def defaultJarName = defaultJarBaseName + ".jar"
	def jarPath = outputPath / defaultJarName
	def packageTestJar = defaultJarPath("-test.jar")
	def packageDocsJar = defaultJarPath("-docs.jar")
	def packageSrcJar= defaultJarPath("-src.jar")
	def packageTestSrcJar = defaultJarPath("-test-src.jar")
	def packageProjectZip = defaultJarPath("-project.zip")
	def defaultJarPath(extension: String) = outputPath / (artifactBaseName + extension)
}

object BasicProjectPaths
{
	val DefaultSourceDirectoryName = "src"
	val DefaultMainCompileDirectoryName = "classes"
	val DefaultTestCompileDirectoryName = "test-classes"
	val DefaultDocDirectoryName = "doc"
	val DefaultAPIDirectoryName = "api"
	val DefaultGraphDirectoryName = "graph"
	val DefaultMainAnalysisDirectoryName = "analysis"
	val DefaultTestAnalysisDirectoryName = "test-analysis"
	val DefautMainResourcesOutputDirectoryName = "resources"
	val DefautTestResourcesOutputDirectoryName = "test-resources"

	val DefaultMainDirectoryName = "main"
	val DefaultScalaDirectoryName = "scala"
	val DefaultJavaDirectoryName = "java"
	val DefaultResourcesDirectoryName = "resources"
	val DefaultTestDirectoryName = "test"

	// forwarders to new locations
	def BootDirectoryName = Project.BootDirectoryName
	def DefaultManagedDirectoryName = BasicDependencyPaths.DefaultManagedDirectoryName
	def DefaultDependencyDirectoryName = BasicDependencyPaths.DefaultDependencyDirectoryName
}

trait WebScalaPaths extends ScalaPaths
{
	def temporaryWarPath: Path
	def webappResources: PathFinder
	def jettyContextPath: String
	def warPath: Path
}
@deprecated trait WebProjectPaths extends MavenStyleWebScalaPaths
trait MavenStyleWebScalaPaths extends WebScalaPaths with MavenStyleScalaPaths
{
	import WebProjectPaths._
	def temporaryWarPath = outputPath / webappDirectoryName
	def webappPath = mainSourcePath / webappDirectoryName
	def webappDirectoryName = DefaultWebappDirectoryName
	def jettyContextPath = DefaultJettyContextPath
	def defaultWarName = defaultJarBaseName + ".war"
	def warPath = outputPath / defaultWarName
	/** Additional files to include in the web application. */
	protected def extraWebappFiles: PathFinder = Path.emptyPathFinder
	def webappResources = descendents(webappPath ##, "*") +++ extraWebappFiles
}
object WebProjectPaths
{
	val DefaultWebappDirectoryName = "webapp"
	val DefaultJettyContextPath = "/"
}

/** Defines default paths for a webstart project.  It directly extends WebstartOptions to make
* it easy to implement and override webstart options in the common case of one webstartTask per
* project.*/
trait WebstartPaths extends ScalaPaths
{
	import WebstartPaths._

	def outputPath: Path
	def jnlpPath: Path

	def webstartOutputDirectory = outputPath / webstartDirectoryName

	def jnlpFile = webstartOutputDirectory / jnlpFileName
	def webstartLibDirectory = webstartOutputDirectory / webstartLibName
	def webstartZip: Option[Path] = Some(outputPath / webstartZipName)
	def jnlpResourcesPath = jnlpPath / BasicProjectPaths.DefaultResourcesDirectoryName

	def webstartLibName = DefaultWebstartLibName
	def webstartDirectoryName = DefaultWebstartDirectoryName

	def webstartZipName: String
	def jnlpFileName: String
}
object WebstartPaths
{
	val DefaultWebstartDirectoryName = "webstart"
	val DefaultJnlpName = "jnlp"
	val DefaultWebstartLibName = "lib"
}
trait MavenStyleWebstartPaths extends WebstartPaths with MavenStyleScalaPaths
{
	import WebstartPaths._
	def jnlpPath = mainSourcePath / DefaultJnlpName
	def webstartMainJar = jarPath
	def jnlpFileName = DefaultJnlpFileName
	def webstartZipName = artifactBaseName + ".zip"
	def DefaultJnlpFileName = artifactBaseName + ".jnlp"
}

trait IntegrationTestPaths extends NotNull
{
	def integrationTestSources: PathFinder
	def integrationTestScalaSourceRoots: PathFinder
	def integrationTestResourcesPath: Path

	def integrationTestCompilePath: Path
	def integrationTestAnalysisPath: Path
}
trait BasicIntegrationTestPaths extends IntegrationTestPaths
{
	def integrationTestScalaSourcePath: Path
	def integrationTestScalaSourceRoots: PathFinder = integrationTestScalaSourcePath
	def integrationTestSources = sources(integrationTestScalaSourceRoots)
	protected def sources(base: PathFinder): PathFinder
}
trait MavenStyleIntegrationTestPaths extends BasicIntegrationTestPaths with MavenStyleScalaPaths
{
	import IntegrationTestPaths._

	def integrationTestDirectoryName = DefaultIntegrationTestDirectoryName
	def integrationTestCompileDirectoryName = DefaultIntegrationTestCompileDirectoryName
	def integrationTestAnalysisDirectoryName = DefaultIntegrationTestAnalysisDirectoryName

	def integrationTestSourcePath = sourcePath / integrationTestDirectoryName
	def integrationTestScalaSourcePath = integrationTestSourcePath / scalaDirectoryName
	def integrationTestResourcesPath = integrationTestSourcePath / resourcesDirectoryName

	def integrationTestCompilePath = outputPath / integrationTestCompileDirectoryName
	def integrationTestAnalysisPath = outputPath / integrationTestAnalysisDirectoryName
}

object IntegrationTestPaths
{
	val DefaultIntegrationTestDirectoryName = "it"
	val DefaultIntegrationTestCompileDirectoryName = "it-classes"
	val DefaultIntegrationTestAnalysisDirectoryName = "it-analysis"
}


text:
#include "LegacyAlsaSubsystem.hpp"
#include "LegacyAmixerControl.hpp"
#include "LegacyAlsaCtlPortConfig.hpp"
#include "SubsystemObjectFactory.h"
#include "AlsaMappingKeys.hpp"
#include "AmixerMutableVolume.hpp"

LegacyAlsaSubsystem::LegacyAlsaSubsystem(const string &name) : AlsaSubsystem(name)
{
    // Provide creators to upper layer
    addSubsystemObjectFactory(
        new TSubsystemObjectFactory<LegacyAmixerControl>("Control", 1 << AlsaCard)
        );

    addSubsystemObjectFactory(
        new TSubsystemObjectFactory<LegacyAmixerControl>(
            "ByteControl", 1 << AlsaCard)
        );

    addSubsystemObjectFactory(
        new TSubsystemObjectFactory<
            AmixerMutableVolume<LegacyAmixerControl> >("Volume", 1 << AlsaCard)
        );

    addSubsystemObjectFactory(
        new TSubsystemObjectFactory<LegacyAlsaCtlPortConfig>(
            "PortConfig", (1 << AlsaCard) | (1 << AlsaCtlDevice))
        );
}


text:
namespace wasp {

using absl::flat_hash_map;
using absl::flat_hash_set;
using absl::node_hash_map;
using absl::node_hash_set;

}  // namespace wasp

#endif  // WASP_BASE_HASHMAP_H_


text:
from django import forms

class AnswerForm(forms.Form):
    answer = forms.ChoiceField(widget=forms.RadioSelect, choices=((True, 'True'), (False, 'False')))
    question = forms.IntegerField(widget=forms.HiddenInput)


text:
from streamlink.plugins.tv3cat import TV3Cat
from tests.plugins import PluginCanHandleUrl

class TestPluginCanHandleUrlTV3Cat(PluginCanHandleUrl):
    __plugin__ = TV3Cat

    should_match_groups = [
        ("https://ccma.cat/tv3/directe/tv3/", {"ident": "tv3"}),
        ("https://ccma.cat/tv3/directe/324/", {"ident": "324"}),
        ("https://www.ccma.cat/tv3/directe/tv3/", {"ident": "tv3"}),
        ("https://www.ccma.cat/tv3/directe/324/", {"ident": "324"}),
    ]


text:
**1. Structural:**
* Total number of tokens
* Total number of sentences
* Average length of sentences
* Number of exclamations.
* Percentage of Question sentences.

**2. Lexical:**
* Unigrams and Bigrams after removing stop-words, subsequent tf-idf weighting

**3. LIWC:**  A dictionary which helps users to determine the degree that any text uses positive or negative emotions, self-references
and other language dimensions.

**4. INQUIRER:**  A dictionary in which words are grouped in categories. It is basically a mapping tool which maps each word to some semantic tags, e.g., absurd
is mapped to tags NEG and VICE.

**5. Features that represent informativeness:**
* Features of a product that appear in the review.
* *TODO*

**6. Meta Data: (???)**

*If we use this, we are moving away from representing helpfulness purely as a property of text.*
* Stars of a review


text:
GV.Viewer = GV.Viewer || {};

GV.Viewer.Main = function() {

	var gl;
	var width = 0;
	var height = 0;

	var panodraw;
	var polydraw;

	// utils
	var screenToCartesian = function(screen) {
		var tz = Math.tan(GV.setting.getZoom());
		var x = 2*tz* ((1.0*screen.getX()/(width-1))-0.5) ;
		var y = 2*tz* (0.5-(1.0*screen.getY()/(height-1))) *height/width;

		var sv = Math.sin(GV.setting.getElev());
		var cv = Math.cos(GV.setting.getElev());
		var sh = Math.sin(GV.setting.getAzim());
		var ch = Math.cos(GV.setting.getAzim());
		var matrix = new mat3();
		matrix.a00 = sh;  matrix.a01 = -cv*ch; matrix.a02 = sv*ch;
		matrix.a10 = -ch; matrix.a11 = -cv*sh; matrix.a12 = sv*sh;
		matrix.a20 = 0;   matrix.a21 = sv;     matrix.a22 = cv;

		var point = new vec3(x,y,1);
		point.mulM(matrix);
		return point;
	}

	// repaint
	var draw = function() {
		gl.viewport(0, 0, width, height);
		gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
		var pMatrix = new Float32Array(GV.Math.projectionMatrix(width/height).toTransposedArray());
		var mvMatrix = new Float32Array(GV.Math.modelviewMatrix().toTransposedArray());
		panodraw.draw(pMatrix,mvMatrix);
		polydraw.draw(pMatrix,mvMatrix);
	}

	// init
	{
		var canvas = document.getElementById("viewer");

		// init webGL
		try {
			gl = canvas.getContext("webgl",{preserveDrawingBuffer: true}) || canvas.getContext("experimental-webgl",{preserveDrawingBuffer: true});
		}
		catch (exception) {
			alert("Sorry! Your browser doesn't support WebGL.");
			return;
		}
		if (!gl) {
			alert("Sorry! Your browser doesn't support WebGL.");
			return;
		}

		// init panorama and polygon drawer
		panodraw = new GV.Viewer.Panodraw(gl,draw);
		polydraw = new GV.Viewer.Polydraw(gl,draw);

		// init mouse
		GV.Viewer.addMouse(canvas,screenToCartesian);

		// clear canvas
		gl.clearColor(0.0,0.0,0.0,1.0);
		gl.enable(gl.BLEND);
		gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
	}

	this.changePanorama = function(panorama) {
		panodraw.changePanorama(panorama);
	}
	this.changeFeatures = function() {
		var spatialcontext = GV.setting.spatialstore.getSpatialcontext();
		var features = mapIntersect(spatialcontext.getViewpoint().getFeatures(),spatialcontext.getDisplayedFeatures());
		for (var i in features) {
			features[i].getGeometry().create();
			features[i].getGeometry().updateRadius();
		}
		polydraw.update(GV.setting.getMeasurement(),mapSubstract(features,spatialcontext.getSelectedFeatures()),mapIntersect(features,spatialcontext.getSelectedFeatures()));
		draw();
	}

	// set
	/*this.changeViewpoint = function(viewpoint) {
		var features = viewpoint.getFeatures();
		polydraw.clear();
		for (var fid in features)
			polydraw.addFeature(features[fid],viewpoint);
		draw();
	}
	this.addFeature = function(feature,viewpoint) {
		polydraw.addFeature(feature,viewpoint);
		draw();
	}
	this.removeFeature = function(fid) {
		polydraw.removeFeature(fid);
		draw();
	}
	this.changeFeatures = function(features) {
		var lookAt = polydraw.selectFeatures(features);
		if (lookAt) {
			var dir = lookAt.toSpherical();
			GV.master.setAngles(dir.getPhi(),dir.getTheta());
		}
		draw();
	}
	this.displayFeatures = function(fids) {
		polydraw.displayFeatures(fids);
	}*/
	this.update = function(zoom) {
		if (zoom) {
			var spatialcontext = GV.setting.spatialstore.getSpatialcontext();
			var features = mapIntersect(spatialcontext.getViewpoint().getFeatures(),spatialcontext.getDisplayedFeatures());
			for (var i in features) {
				features[i].getGeometry().updateRadius();
			}
			polydraw.update(GV.setting.getMeasurement(),mapSubstract(features,spatialcontext.getSelectedFeatures()),mapIntersect(features,spatialcontext.getSelectedFeatures()));
		}
		draw();
	}

	this.updateMeasurement = function() {
		polydraw.update(GV.setting.getMeasurement());
		draw();
	}

	// mouse
	/*var rotate = function(hStep,vStep) {
		var azim = GV.master.getAzim() + hStep*GV.master.getZoom();
		var elev = GV.master.getElev() - vStep*GV.master.getZoom();
		GV.master.setAngles(azim,elev);
	}
	var zoom = function(factor) {
		GV.master.setZoom(factor*GV.master.getZoom());
	}
	var click = function(screen,ctrlKey) {
		polydraw.click(screenToCartesian(screen),GV.master.getZoom(),ctrlKey);
		draw();
	}
	var dblclick = function(screen) {
		polydraw.dblclick(screenToCartesian(screen),GV.master.getZoom());
		draw();
	}
	var move = function(screen) {
		polydraw.mouseOver(screenToCartesian(screen));
		draw();
	}*/

	this.resize = function() {
		var canvas = document.getElementById("viewer");
		width = canvas.width;
		height = canvas.height;
		draw();
	}

	/*var save = function() {
		GV.master.addFeature(polydraw.getMeasurement().getPoints(),polydraw.getMode(),width*height);
		return false;
	}*/
	//document.getElementById("save").onclick = save;

}


text:
/*================================================================================
  code generated by: java2cpp
  author: Zoran Angelov, mailto://baldzar@gmail.com
  class: java.util.zip.GZIPInputStream
================================================================================*/

#ifndef J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_UTIL_ZIP_GZIPINPUTSTREAM_HPP_DECL
#define J2CPP_JAVA_UTIL_ZIP_GZIPINPUTSTREAM_HPP_DECL

namespace j2cpp { namespace java { namespace io { class InputStream; } } }
namespace j2cpp { namespace java { namespace util { namespace zip { class InflaterInputStream; } } } }

#include <java/io/InputStream.hpp>
#include <java/util/zip/InflaterInputStream.hpp>

namespace j2cpp {

namespace java { namespace util { namespace zip {

	class GZIPInputStream;
	class GZIPInputStream
		: public object<GZIPInputStream>
	{
	public:

		J2CPP_DECLARE_CLASS

		J2CPP_DECLARE_METHOD(0)
		J2CPP_DECLARE_METHOD(1)
		J2CPP_DECLARE_METHOD(2)
		J2CPP_DECLARE_METHOD(3)
		J2CPP_DECLARE_FIELD(0)
		J2CPP_DECLARE_FIELD(1)
		J2CPP_DECLARE_FIELD(2)

		explicit GZIPInputStream(jobject jobj)
		: object<GZIPInputStream>(jobj)
		{
		}

		operator local_ref<java::util::zip::InflaterInputStream>() const;

		GZIPInputStream(local_ref< java::io::InputStream > const&);
		GZIPInputStream(local_ref< java::io::InputStream > const&, jint);
		void close();
		jint read(local_ref< array<jbyte,1> >  const&, jint, jint);

		static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > GZIP_MAGIC;
	}; //class GZIPInputStream

} //namespace zip
} //namespace util
} //namespace java

} //namespace j2cpp

#endif //J2CPP_JAVA_UTIL_ZIP_GZIPINPUTSTREAM_HPP_DECL

#else //J2CPP_INCLUDE_IMPLEMENTATION

#ifndef J2CPP_JAVA_UTIL_ZIP_GZIPINPUTSTREAM_HPP_IMPL
#define J2CPP_JAVA_UTIL_ZIP_GZIPINPUTSTREAM_HPP_IMPL

namespace j2cpp {

java::util::zip::GZIPInputStream::operator local_ref<java::util::zip::InflaterInputStream>() const
{
	return local_ref<java::util::zip::InflaterInputStream>(get_jobject());
}

java::util::zip::GZIPInputStream::GZIPInputStream(local_ref< java::io::InputStream > const &a0)
: object<java::util::zip::GZIPInputStream>(
	call_new_object<
		java::util::zip::GZIPInputStream::J2CPP_CLASS_NAME,
		java::util::zip::GZIPInputStream::J2CPP_METHOD_NAME(0),
		java::util::zip::GZIPInputStream::J2CPP_METHOD_SIGNATURE(0)
	>(a0)
)
{
}

java::util::zip::GZIPInputStream::GZIPInputStream(local_ref< java::io::InputStream > const &a0, jint a1)
: object<java::util::zip::GZIPInputStream>(
	call_new_object<
		java::util::zip::GZIPInputStream::J2CPP_CLASS_NAME,
		java::util::zip::GZIPInputStream::J2CPP_METHOD_NAME(1),
		java::util::zip::GZIPInputStream::J2CPP_METHOD_SIGNATURE(1)
	>(a0, a1)
)
{
}

void java::util::zip::GZIPInputStream::close()
{
	return call_method<
		java::util::zip::GZIPInputStream::J2CPP_CLASS_NAME,
		java::util::zip::GZIPInputStream::J2CPP_METHOD_NAME(2),
		java::util::zip::GZIPInputStream::J2CPP_METHOD_SIGNATURE(2),
		void
	>(get_jobject());
}

jint java::util::zip::GZIPInputStream::read(local_ref< array<jbyte,1> > const &a0, jint a1, jint a2)
{
	return call_method<
		java::util::zip::GZIPInputStream::J2CPP_CLASS_NAME,
		java::util::zip::GZIPInputStream::J2CPP_METHOD_NAME(3),
		java::util::zip::GZIPInputStream::J2CPP_METHOD_SIGNATURE(3),
		jint
	>(get_jobject(), a0, a1, a2);
}

static_field<
	java::util::zip::GZIPInputStream::J2CPP_CLASS_NAME,
	java::util::zip::GZIPInputStream::J2CPP_FIELD_NAME(0),
	java::util::zip::GZIPInputStream::J2CPP_FIELD_SIGNATURE(0),
	jint
> java::util::zip::GZIPInputStream::GZIP_MAGIC;

J2CPP_DEFINE_CLASS(java::util::zip::GZIPInputStream,"java/util/zip/GZIPInputStream")
J2CPP_DEFINE_METHOD(java::util::zip::GZIPInputStream,0,"<init>","(Ljava/io/InputStream;)V")
J2CPP_DEFINE_METHOD(java::util::zip::GZIPInputStream,1,"<init>","(Ljava/io/InputStream;I)V")
J2CPP_DEFINE_METHOD(java::util::zip::GZIPInputStream,2,"close","()V")
J2CPP_DEFINE_METHOD(java::util::zip::GZIPInputStream,3,"read","([BII)I")
J2CPP_DEFINE_FIELD(java::util::zip::GZIPInputStream,0,"GZIP_MAGIC","I")
J2CPP_DEFINE_FIELD(java::util::zip::GZIPInputStream,1,"crc","Ljava/util/zip/CRC32;")
J2CPP_DEFINE_FIELD(java::util::zip::GZIPInputStream,2,"eos","Z")

} //namespace j2cpp

#endif //J2CPP_JAVA_UTIL_ZIP_GZIPINPUTSTREAM_HPP_IMPL

#endif //J2CPP_INCLUDE_IMPLEMENTATION


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/bg_accueil"
    android:fitsSystemWindows="false"
    android:orientation="vertical"
    android:weightSum="1.0" >

    <TextView
        android:id="@+id/WelcomeTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.25"
        android:gravity="top|left"
        android:padding="3dp"
        android:text="@string/welcomeMessage"
        android:textColor="#EEEEEE"
        android:textSize="17dp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/QuestiontextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:minLines="4"
        android:padding="3dp"
        android:layout_weight="0.25"
        android:layout_gravity="top|left"
        android:textColor="#EEEEEE"
        android:textSize="17dp"
        android:textStyle="bold"
        android:visibility="gone" >
    </TextView>

    <RadioGroup
        android:id="@+id/ChoicesRadioGroup"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="40dp"
        android:layout_weight="0.5"
        android:gravity="center"
        android:textSize="16dp"
        android:visibility="gone" >

        <RadioButton
            android:id="@+id/Choice1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0.16"
            android:textColor="#EEEEEE"
            android:textSize="16dp"
            android:textStyle="bold" />

        <RadioButton
            android:id="@+id/Choice2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0.16"
            android:textColor="#EEEEEE"
            android:textSize="16dp"
            android:textStyle="bold" />

        <RadioButton
            android:id="@+id/Choice3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="0.16"
            android:textColor="#EEEEEE"
            android:textSize="16dp"
            android:textStyle="bold" />
    </RadioGroup>

    <TableLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/menuLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="3dp"
        android:layout_weight="0.25"
        android:gravity="center_vertical|center_horizontal"
        android:orientation="horizontal" >

        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="30dp"
            android:gravity="center" >

            <Button
                android:id="@+id/buttonNewGame"
                android:layout_width="200dp"
                android:layout_height="wrap_content"
                android:background="@drawable/custom_button_grey"
                android:focusable="false"
                android:padding="10dip"
                android:text="@string/newGame"
                android:textColor="#eaeaea"
                android:textSize="16dp"
                android:textStyle="italic" />
        </TableRow>

        <TableRow
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:gravity="center" >

            <Button
                android:id="@+id/buttonResumeGame"
                android:layout_width="200dp"
                android:layout_height="wrap_content"
                android:background="@drawable/custom_button_grey"
                android:focusable="false"
                android:padding="10dip"
                android:text="@string/resumeGame"
                android:textColor="#eaeaea"
                android:textSize="16dp"
                android:textStyle="italic"
                android:visibility="gone"/>
        </TableRow>
    </TableLayout>

    <TableLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/footerTable"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.25"
        android:gravity="bottom"
        android:layout_marginBottom="5dp"
        android:orientation="horizontal"
        android:visibility="gone" >

        <TableRow
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:gravity="center" >

            <TextView
                android:id="@+id/ScoreTextView"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:capitalize="characters"
                android:gravity="center_horizontal"
                android:textColor="#EEEEEE"
                android:textSize="18dp"
                android:textStyle="bold" >
            </TextView>
        </TableRow>

        <TableRow
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_marginTop="10dp"
            android:gravity="center" >

            <Button
                android:id="@+id/button03"
                android:layout_width="100dp"
                android:layout_height="45dp"
                android:layout_marginRight="10dip"
                android:textColor="#eaeaea"
                android:background="@drawable/custom_button_grey"
                android:gravity="center_vertical|center_horizontal"
                android:padding="10dip"
                android:text="@string/usageStatistics"
                android:textStyle="italic" />

            <Button
                android:id="@+id/button02"
                android:layout_width="100dp"
                android:layout_height="45dp"
                android:layout_marginLeft="10dip"
                android:textColor="#eaeaea"
                android:background="@drawable/custom_button_grey"
                android:gravity="center_vertical|center_horizontal"
                android:padding="10dip"
                android:text="@string/quit"
                android:textStyle="italic" />
        </TableRow>
    </TableLayout>

</LinearLayout>


text:
package com.jcommerce.gwt.client.panels.promote;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.HorizontalPanel;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.TextArea;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.TextBox;
import com.jcommerce.gwt.client.ContentWidget;
import com.jcommerce.gwt.client.ModelNames;
import com.jcommerce.gwt.client.PageState;
import com.jcommerce.gwt.client.form.BeanObject;
import com.jcommerce.gwt.client.model.IGoods;
import com.jcommerce.gwt.client.model.IAuction;
import com.jcommerce.gwt.client.service.ListService;
import com.jcommerce.gwt.client.service.UpdateService;
import com.jcommerce.gwt.client.widgets.ColumnPanel;
import com.jcommerce.gwt.client.widgets.DateWidget;

public class ModifyAuctionPanel extends ContentWidget {

	private ColumnPanel contentPanel = new ColumnPanel();

	public static class State extends PageState {

		private BeanObject Auction = null;

		public BeanObject getAuction() {
			return Auction;
		}
		public void setAuction(BeanObject Auction) {
			this.Auction = Auction;
			setEditting(Auction != null);
		}
		public String getPageClassName() {
			return ModifyAuctionPanel.class.getName();
		}
		public String getMenuDisplayName() {
			return "编辑拍卖活动 ";
		}
	}

	public State getCurState() {
        if (curState == null ) {
            curState = new State();
        }
        return (State)curState;
	}

    public String getDescription() {
        return "cwBasicTextDescription";
    }

    public String getName() {
        return "编辑拍卖活动 ";
    }

    protected void onRender(Element parent, int index) {
		super.onRender(parent, index);

		ColumnPanel topPanel = new ColumnPanel();

		final TextBox snTextBox = new TextBox();
		snTextBox.setText(this.getCurState().getAuction().getString(IAuction.AUCTION_NAME));
		topPanel.createPanel(IAuction.AUCTION_NAME, "拍卖活动名称:", snTextBox);

		final TextArea descArea = new TextArea();
		descArea.setSize(300, 50);
		descArea.setValue(getCurState().getAuction().getString(IAuction.DESC));
		topPanel.createPanel("", "拍卖活动描述:", descArea);

		HorizontalPanel searchPanel = new HorizontalPanel();
		final TextBox searchTextBox = new TextBox();
		Button searchButton = new Button("搜索");
		searchPanel.add(searchTextBox);
		searchPanel.add(searchButton);
		topPanel.createPanel("", "根据商品编号、名称或货号搜索商品", searchPanel);

		HorizontalPanel selectPanel = new HorizontalPanel();
		final ListBox listGoods = new ListBox();
		listGoods.addItem("请先搜索商品");
		selectPanel.add(listGoods);
		topPanel.createPanel("", "拍卖商品名称:", selectPanel);

		final DateWidget startTime = new DateWidget();
		final DateWidget endTime = new DateWidget();
		topPanel.createPanel("", "拍卖开始时间:", startTime);
		topPanel.createPanel("", "拍卖结束时间:", endTime);

		final TextBox startBox = new TextBox();
		startBox.setText(getCurState().getAuction().getString(IAuction.START_PRICE));
		final TextBox dirBox = new TextBox();
		dirBox.setText(getCurState().getAuction().getString(IAuction.DIR_PRICE));
		final TextBox addRangeBox = new TextBox();
		addRangeBox.setText(getCurState().getAuction().getString(IAuction.ADD_RANGE));
		final TextBox secBox = new TextBox();
		secBox.setText(getCurState().getAuction().getString(IAuction.SEC_PRICE));

		topPanel.createPanel("", "起拍价:", startBox);
		topPanel.createPanel("", "一口价:", dirBox);
		topPanel.createPanel("", "加价幅度:", addRangeBox);
		topPanel.createPanel("", "保证金:", secBox);

		searchButton.addSelectionListener(new SelectionListener<ButtonEvent>(){
			public void componentSelected(ButtonEvent ce) {
				listGoods.clear();
				new ListService().listBeans(ModelNames.GOODS, new ListService.Listener() {

					public void onSuccess(List<BeanObject> beans) {
						List<String> goods = new ArrayList<String>();
						for(BeanObject bean : beans) {
							goods.add(bean.getString(IGoods.NAME));
							if(bean.getString(IGoods.NAME).equals(searchTextBox.getText()) || bean.getString(IGoods.NUMBER).equals(searchTextBox.getText())) {
								listGoods.addItem(bean.getString(IGoods.NAME));
							}
						}
						if(searchTextBox.getText().equals("")) {
							for(String str : goods) {
								listGoods.addItem(str);
							}
						}
					}
				});
			}});

		HorizontalPanel contentpanel = new HorizontalPanel();
		Button okButton = new Button("确定");
		Button resetButton = new Button("重置");
		contentpanel.setSpacing(30);
		contentpanel.add(okButton);
		contentpanel.add(resetButton);
		contentPanel.add(topPanel);
		contentPanel.add(contentpanel);
		add(contentPanel);

		okButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
			public void componentSelected(ButtonEvent ce) {
				Map<String,Object> map = new HashMap<String,Object>();
				map.put(IAuction.AUCTION_NAME, snTextBox.getText());
				map.put(IAuction.GOOD_NAME, listGoods.getItemText(listGoods.getSelectedIndex()));
				map.put(IAuction.START_TIME, startTime.getValue().getTime());
				map.put(IAuction.END_TIME, endTime.getValue().getTime());
				map.put(IAuction.START_PRICE, startBox.getText());
				map.put(IAuction.DIR_PRICE, dirBox.getText());
				map.put(IAuction.ADD_RANGE, addRangeBox.getText());
				map.put(IAuction.SEC_PRICE, secBox.getText());
				map.put(IAuction.DESC, descArea.getValue());
				BeanObject bean = new BeanObject(ModelNames.AUCTION,map);
				String id = getCurState().getAuction().getString(IAuction.ID);
				if(getCurState().isEditting()) {
					new UpdateService().updateBean(id, bean, null);
					AuctionListPanel.State state = new AuctionListPanel.State();
					state.execute();
				}
			}
		});
		resetButton.addSelectionListener(new SelectionListener<ButtonEvent>() {
			public void componentSelected(ButtonEvent ce) {
				snTextBox.setText("");
				startTime.setValue(new Date());
				endTime.setValue(new Date());
				startBox.setText("0.0");
				dirBox.setText("0.0");
				addRangeBox.setText("0.0");
				secBox.setText("");
				descArea.clear();
			}
		});
    }

}


text:
package org.openfs.component.truevfs;

import java.io.File;

import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.camel.util.FileUtil;
import org.junit.Before;
import org.junit.Test;

public class FilesExcludeTest extends CamelTestSupport {

	@EndpointInject(uri = "mock:result")
	MockEndpoint resultEndpoint;

	@Before
	public void setUp() throws Exception {
		super.setUp();
		cleanupDir("target/test");
		cleanupDir("target/archiver");
	}

	@Test
	public void testDirFilesTGZArchiver() throws Exception {
		context.addRoutes(new RouteBuilder() {
			@Override
			public void configure() throws Exception {
				from("timer://test?repeatCount=1")
						.to("truevfs://target/archiver?fileName=testDir.tbz&srcDir=target/test&exclude=.*dat")
						.to("mock:result");
			}
		});
		context.start();

		resultEndpoint.expectedMessageCount(1);
		resultEndpoint.expectedFileExists("target/archiver/testDir.tbz");
		resultEndpoint.expectedFileExists("target/test/1.dat");

		template.sendBodyAndHeader("file://target/test", "1",
				Exchange.FILE_NAME, "1.txt");
		template.sendBodyAndHeader("file://target/test", "1",
				Exchange.FILE_NAME, "2.txt");
		template.sendBodyAndHeader("file://target/test", "2",
				Exchange.FILE_NAME, "1.dat");

		resultEndpoint.assertIsSatisfied();
	}

	protected void cleanupDir (String dirname) {
		File d = new File(dirname);
		if (d.exists() && d.isDirectory())
			FileUtil.removeDir(d);
	}
}


text:
using System.Collections.Generic;
using SJP.Schematic.Core.Extensions;
using Superpower;
using Superpower.Model;

namespace SJP.Schematic.SqlServer.Parsing
{
    internal sealed class SqlServerTokenizer : Tokenizer<SqlServerToken>
    {
        static SqlServerTokenizer()
        {
            SimpleOps['+'] = SqlServerToken.Plus;
            SimpleOps['-'] = SqlServerToken.Minus;
            SimpleOps['*'] = SqlServerToken.Asterisk;
            SimpleOps['/'] = SqlServerToken.Divide;
            SimpleOps['%'] = SqlServerToken.Percent;
            SimpleOps['&'] = SqlServerToken.BitwiseAnd;
            SimpleOps['|'] = SqlServerToken.BitwiseOr;
            SimpleOps['^'] = SqlServerToken.BitwiseXor;
            SimpleOps['<'] = SqlServerToken.LessThan;
            SimpleOps['>'] = SqlServerToken.GreaterThan;
            SimpleOps['='] = SqlServerToken.Equal;
            SimpleOps[','] = SqlServerToken.Comma;
            SimpleOps['.'] = SqlServerToken.Period;
            SimpleOps['('] = SqlServerToken.LParen;
            SimpleOps[')'] = SqlServerToken.RParen;
            SimpleOps['['] = SqlServerToken.LBracket;
            SimpleOps[']'] = SqlServerToken.RBracket;
            SimpleOps['?'] = SqlServerToken.QuestionMark;
            SimpleOps[';'] = SqlServerToken.Semicolon;
        }

        protected override IEnumerable<Result<SqlServerToken>> Tokenize(TextSpan span)
        {
            var next = SkipWhiteSpace(span);
            if (!next.HasValue)
                yield break;

            do
            {
                if (next.Value.IsDigit())
                {
                    var hex = SqlServerTextParsers.SqlBlob(next.Location);
                    if (hex.HasValue)
                    {
                        next = hex.Remainder.ConsumeChar();
                        yield return Result.Value(SqlServerToken.Blob, hex.Location, hex.Remainder);
                    }
                    else
                    {
                        var real = SqlServerTextParsers.Real(next.Location);
                        if (!real.HasValue)
                            yield return Result.CastEmpty<TextSpan, SqlServerToken>(real);
                        else
                            yield return Result.Value(SqlServerToken.Number, real.Location, real.Remainder);

                        next = real.Remainder.ConsumeChar();
                    }

                    if (next.HasValue && !next.Value.IsPunctuation() && !next.Value.IsWhiteSpace())
                    {
                        yield return Result.Empty<SqlServerToken>(next.Location, new[] { "digit" });
                    }
                }
                else if (next.Value == '$')
                {
                    var money = SqlServerTextParsers.Money(next.Location);
                    if (!money.HasValue)
                        yield return Result.CastEmpty<TextSpan, SqlServerToken>(money);
                    else
                        yield return Result.Value(SqlServerToken.Money, money.Location, money.Remainder);

                    next = money.Remainder.ConsumeChar();
                }
                else if (next.Value == '\'')
                {
                    var str = SqlServerTextParsers.SqlString(next.Location);
                    if (!str.HasValue)
                        yield return Result.CastEmpty<string, SqlServerToken>(str);

                    next = str.Remainder.ConsumeChar();

                    yield return Result.Value(SqlServerToken.String, str.Location, str.Remainder);
                }
                else if (next.Value == '@')
                {
                    var beginIdentifier = next.Location;
                    var startOfName = next.Remainder;
                    do
                    {
                        next = next.Remainder.ConsumeChar();
                    }
                    while (next.HasValue && next.Value.IsLetterOrDigit());

                    if (next.Remainder == startOfName)
                    {
                        yield return Result.Empty<SqlServerToken>(startOfName, new[] { "built-in identifier name" });
                    }
                    else
                    {
                        yield return Result.Value(SqlServerToken.BuiltInIdentifier, beginIdentifier, next.Location);
                    }
                }
                else if (next.Value == '"' || next.Value == '[')
                {
                    var endChar = next.Value == '[' ? ']' : next.Value;

                    var beginIdentifier = next.Location;
                    do
                    {
                        next = next.Remainder.ConsumeChar();
                    }
                    while (next.HasValue && (next.Value != endChar));
                    next = next.Remainder.ConsumeChar(); // consume end char

                    yield return Result.Value(SqlServerToken.Identifier, beginIdentifier, next.Location);
                }
                else if (next.Value.IsLetter() || next.Value == '_')
                {
                    var beginIdentifier = next.Location;
                    do
                    {
                        next = next.Remainder.ConsumeChar();
                    }
                    while (next.HasValue && (next.Value.IsLetterOrDigit() || next.Value == '_'));

                    var str = SqlServerTextParsers.SqlString(beginIdentifier);
                    if (str.HasValue)
                    {
                        yield return Result.Value(SqlServerToken.String, str.Location, str.Remainder);
                        next = str.Remainder.ConsumeChar();
                    }
                    else if (TryGetKeyword(beginIdentifier.Until(next.Location), out var keyword))
                    {
                        yield return Result.Value(keyword, beginIdentifier, next.Location);
                    }
                    else
                    {
                        yield return Result.Value(SqlServerToken.Identifier, beginIdentifier, next.Location);
                    }
                }
                else if (next.Value == '-' || next.Value == '/')
                {
                    var sqlComment = SqlServerTextParsers.SqlComment(next.Location);
                    var compoundOp = SqlServerTextParsers.CompoundOperator(next.Location);
                    if (sqlComment.HasValue)
                    {
                        // don't return comments, assume they're filtered out as it makes parsing more difficult
                        next = sqlComment.Remainder.ConsumeChar();
                    }
                    else if (compoundOp.HasValue)
                    {
                        yield return Result.Value(compoundOp.Value, compoundOp.Location, compoundOp.Remainder);
                        next = compoundOp.Remainder.ConsumeChar();
                    }
                    else if (next.Value < SimpleOps.Length && SimpleOps[next.Value] != SqlServerToken.None)
                    {
                        yield return Result.Value(SimpleOps[next.Value], next.Location, next.Remainder);
                        next = next.Remainder.ConsumeChar();
                    }
                    else
                    {
                        yield return Result.Empty<SqlServerToken>(next.Location);
                        next = next.Remainder.ConsumeChar();
                    }
                }
                else
                {
                    var compoundOp = SqlServerTextParsers.CompoundOperator(next.Location);
                    if (compoundOp.HasValue)
                    {
                        yield return Result.Value(compoundOp.Value, compoundOp.Location, compoundOp.Remainder);
                        next = compoundOp.Remainder.ConsumeChar();
                    }
                    else if (next.Value < SimpleOps.Length && SimpleOps[next.Value] != SqlServerToken.None)
                    {
                        yield return Result.Value(SimpleOps[next.Value], next.Location, next.Remainder);
                        next = next.Remainder.ConsumeChar();
                    }
                    else
                    {
                        yield return Result.Empty<SqlServerToken>(next.Location);
                        next = next.Remainder.ConsumeChar();
                    }
                }

                next = SkipWhiteSpace(next.Location);
            } while (next.HasValue);
        }

        private static bool TryGetKeyword(TextSpan span, out SqlServerToken keyword)
        {
            foreach (var kw in SqlKeywords)
            {
                if (span.EqualsValueIgnoreCase(kw.Text))
                {
                    keyword = kw.Token;
                    return true;
                }
            }

            keyword = SqlServerToken.None;
            return false;
        }

        private static readonly SqlServerToken[] SimpleOps = new SqlServerToken[128];

        private static readonly SqlServerKeyword[] SqlKeywords =
        {
            new SqlServerKeyword("add", SqlServerToken.Add),
            new SqlServerKeyword("all", SqlServerToken.All),
            new SqlServerKeyword("alter", SqlServerToken.Alter),
            new SqlServerKeyword("and", SqlServerToken.And),
            new SqlServerKeyword("any", SqlServerToken.Any),
            new SqlServerKeyword("as", SqlServerToken.As),
            new SqlServerKeyword("asc", SqlServerToken.Ascending),
            new SqlServerKeyword("authorization", SqlServerToken.Authorization),
            new SqlServerKeyword("backup", SqlServerToken.Backup),
            new SqlServerKeyword("begin", SqlServerToken.Begin),
            new SqlServerKeyword("between", SqlServerToken.Between),
            new SqlServerKeyword("break", SqlServerToken.Break),
            new SqlServerKeyword("browse", SqlServerToken.Browse),
            new SqlServerKeyword("bulk", SqlServerToken.Bulk),
            new SqlServerKeyword("by", SqlServerToken.By),
            new SqlServerKeyword("cascade", SqlServerToken.Cascade),
            new SqlServerKeyword("case", SqlServerToken.Case),
            new SqlServerKeyword("check", SqlServerToken.Check),
            new SqlServerKeyword("checkpoint", SqlServerToken.Checkpoint),
            new SqlServerKeyword("close", SqlServerToken.Close),
            new SqlServerKeyword("clustered", SqlServerToken.Clustered),
            new SqlServerKeyword("coalesce", SqlServerToken.Coalesce),
            new SqlServerKeyword("collate", SqlServerToken.Collate),
            new SqlServerKeyword("column", SqlServerToken.Column),
            new SqlServerKeyword("commit", SqlServerToken.Commit),
            new SqlServerKeyword("compute", SqlServerToken.Compute),
            new SqlServerKeyword("constraint", SqlServerToken.Constraint),
            new SqlServerKeyword("contains", SqlServerToken.Contains),
            new SqlServerKeyword("containstable", SqlServerToken.ContainsTable),
            new SqlServerKeyword("continue", SqlServerToken.Continue),
            new SqlServerKeyword("convert", SqlServerToken.Convert),
            new SqlServerKeyword("create", SqlServerToken.Create),
            new SqlServerKeyword("cross", SqlServerToken.Cross),
            new SqlServerKeyword("current", SqlServerToken.Current),
            new SqlServerKeyword("current_date", SqlServerToken.CurrentDate),
            new SqlServerKeyword("current_time", SqlServerToken.CurrentTime),
            new SqlServerKeyword("current_timestamp", SqlServerToken.CurrentTimestamp),
            new SqlServerKeyword("current_user", SqlServerToken.CurrentUser),
            new SqlServerKeyword("cursor", SqlServerToken.Cursor),
            new SqlServerKeyword("database", SqlServerToken.Database),
            new SqlServerKeyword("dbcc", SqlServerToken.Dbcc),
            new SqlServerKeyword("deallocate", SqlServerToken.Deallocate),
            new SqlServerKeyword("declare", SqlServerToken.Declare),
            new SqlServerKeyword("default", SqlServerToken.Default),
            new SqlServerKeyword("delete", SqlServerToken.Delete),
            new SqlServerKeyword("deny", SqlServerToken.Deny),
            new SqlServerKeyword("desc", SqlServerToken.Descending),
            new SqlServerKeyword("disk", SqlServerToken.Disk),
            new SqlServerKeyword("distinct", SqlServerToken.Distinct),
            new SqlServerKeyword("distributed", SqlServerToken.Distributed),
            new SqlServerKeyword("double", SqlServerToken.Double),
            new SqlServerKeyword("drop", SqlServerToken.Drop),
            new SqlServerKeyword("dump", SqlServerToken.Dump),
            new SqlServerKeyword("else", SqlServerToken.Else),
            new SqlServerKeyword("end", SqlServerToken.End),
            new SqlServerKeyword("errlvl", SqlServerToken.ErrorLevel),
            new SqlServerKeyword("escape", SqlServerToken.Escape),
            new SqlServerKeyword("except", SqlServerToken.Except),
            new SqlServerKeyword("exec", SqlServerToken.Exec),
            new SqlServerKeyword("execute", SqlServerToken.Execute),
            new SqlServerKeyword("exists", SqlServerToken.Exists),
            new SqlServerKeyword("exit", SqlServerToken.Exit),
            new SqlServerKeyword("external", SqlServerToken.External),
            new SqlServerKeyword("fetch", SqlServerToken.Fetch),
            new SqlServerKeyword("file", SqlServerToken.File),
            new SqlServerKeyword("fillfactor", SqlServerToken.FillFactor),
            new SqlServerKeyword("for", SqlServerToken.For),
            new SqlServerKeyword("foreign", SqlServerToken.Foreign),
            new SqlServerKeyword("freetext", SqlServerToken.FreeText),
            new SqlServerKeyword("freetexttable", SqlServerToken.FreeTextTable),
            new SqlServerKeyword("from", SqlServerToken.From),
            new SqlServerKeyword("full", SqlServerToken.Full),
            new SqlServerKeyword("function", SqlServerToken.Function),
            new SqlServerKeyword("goto", SqlServerToken.Goto),
            new SqlServerKeyword("grant", SqlServerToken.Grant),
            new SqlServerKeyword("group", SqlServerToken.Group),
            new SqlServerKeyword("having", SqlServerToken.Having),
            new SqlServerKeyword("holdlock", SqlServerToken.HoldLock),
            new SqlServerKeyword("identity", SqlServerToken.Identity),
            new SqlServerKeyword("identity_insert", SqlServerToken.IdentityInsert),
            new SqlServerKeyword("identitycol", SqlServerToken.IdentityCol),
            new SqlServerKeyword("if", SqlServerToken.If),
            new SqlServerKeyword("in", SqlServerToken.In),
            new SqlServerKeyword("index", SqlServerToken.Index),
            new SqlServerKeyword("inner", SqlServerToken.Inner),
            new SqlServerKeyword("insert", SqlServerToken.Insert),
            new SqlServerKeyword("intersect", SqlServerToken.Intersect),
            new SqlServerKeyword("into", SqlServerToken.Into),
            new SqlServerKeyword("is", SqlServerToken.Is),
            new SqlServerKeyword("join", SqlServerToken.Join),
            new SqlServerKeyword("key", SqlServerToken.Key),
            new SqlServerKeyword("kill", SqlServerToken.Kill),
            new SqlServerKeyword("left", SqlServerToken.Left),
            new SqlServerKeyword("like", SqlServerToken.Like),
            new SqlServerKeyword("lineno", SqlServerToken.LineNumber),
            new SqlServerKeyword("load", SqlServerToken.Load),
            new SqlServerKeyword("merge", SqlServerToken.Merge),
            new SqlServerKeyword("national", SqlServerToken.National),
            new SqlServerKeyword("nocheck", SqlServerToken.NoCheck),
            new SqlServerKeyword("nonclustered", SqlServerToken.NonClustered),
            new SqlServerKeyword("not", SqlServerToken.Not),
            new SqlServerKeyword("null", SqlServerToken.Null),
            new SqlServerKeyword("nullif", SqlServerToken.Nullif),
            new SqlServerKeyword("of", SqlServerToken.Of),
            new SqlServerKeyword("off", SqlServerToken.Off),
            new SqlServerKeyword("offsets", SqlServerToken.Offsets),
            new SqlServerKeyword("on", SqlServerToken.On),
            new SqlServerKeyword("open", SqlServerToken.Open),
            new SqlServerKeyword("opendatasource", SqlServerToken.OpenDataSource),
            new SqlServerKeyword("openquery", SqlServerToken.OpenQuery),
            new SqlServerKeyword("openrowset", SqlServerToken.OpenRowSet),
            new SqlServerKeyword("openxml", SqlServerToken.OpenXml),
            new SqlServerKeyword("option", SqlServerToken.Option),
            new SqlServerKeyword("or", SqlServerToken.Or),
            new SqlServerKeyword("order", SqlServerToken.Order),
            new SqlServerKeyword("outer", SqlServerToken.Outer),
            new SqlServerKeyword("over", SqlServerToken.Over),
            new SqlServerKeyword("percent", SqlServerToken.Percent),
            new SqlServerKeyword("pivot", SqlServerToken.Pivot),
            new SqlServerKeyword("plan", SqlServerToken.Plan),
            new SqlServerKeyword("precision", SqlServerToken.Precision),
            new SqlServerKeyword("primary", SqlServerToken.Primary),
            new SqlServerKeyword("print", SqlServerToken.Print),
            new SqlServerKeyword("proc", SqlServerToken.Proc),
            new SqlServerKeyword("procedure", SqlServerToken.Procedure),
            new SqlServerKeyword("public", SqlServerToken.Public),
            new SqlServerKeyword("raiserror", SqlServerToken.Raiserror),
            new SqlServerKeyword("read", SqlServerToken.Read),
            new SqlServerKeyword("readtext", SqlServerToken.ReadText),
            new SqlServerKeyword("reconfigure", SqlServerToken.Reconfigure),
            new SqlServerKeyword("references", SqlServerToken.References),
            new SqlServerKeyword("replication", SqlServerToken.Replication),
            new SqlServerKeyword("restore", SqlServerToken.Restore),
            new SqlServerKeyword("restrict", SqlServerToken.Restrict),
            new SqlServerKeyword("return", SqlServerToken.Return),
            new SqlServerKeyword("revert", SqlServerToken.Revert),
            new SqlServerKeyword("revoke", SqlServerToken.Revoke),
            new SqlServerKeyword("right", SqlServerToken.Right),
            new SqlServerKeyword("rollback", SqlServerToken.Rollback),
            new SqlServerKeyword("rowcount", SqlServerToken.RowCount),
            new SqlServerKeyword("rowguidcol", SqlServerToken.RowGuidCol),
            new SqlServerKeyword("rule", SqlServerToken.Rule),
            new SqlServerKeyword("save", SqlServerToken.Save),
            new SqlServerKeyword("schema", SqlServerToken.Schema),
            new SqlServerKeyword("securityaudit", SqlServerToken.SecurityAudit),
            new SqlServerKeyword("select", SqlServerToken.Select),
            new SqlServerKeyword("semantickeyphrasetable", SqlServerToken.SemanticKeyPhraseTable),
            new SqlServerKeyword("semanticsimilaritydetailstable", SqlServerToken.SemanticSimilarityDetailsTable),
            new SqlServerKeyword("semanticsimilaritytable", SqlServerToken.SemanticSimilarityTable),
            new SqlServerKeyword("session_user", SqlServerToken.SessionUser),
            new SqlServerKeyword("set", SqlServerToken.Set),
            new SqlServerKeyword("setuser", SqlServerToken.SetUser),
            new SqlServerKeyword("shutdown", SqlServerToken.Shutdown),
            new SqlServerKeyword("some", SqlServerToken.Some),
            new SqlServerKeyword("statistics", SqlServerToken.Statistics),
            new SqlServerKeyword("system_user", SqlServerToken.SystemUser),
            new SqlServerKeyword("table", SqlServerToken.Table),
            new SqlServerKeyword("tablesample", SqlServerToken.TableSample),
            new SqlServerKeyword("textsize", SqlServerToken.TextSize),
            new SqlServerKeyword("then", SqlServerToken.Then),
            new SqlServerKeyword("to", SqlServerToken.To),
            new SqlServerKeyword("top", SqlServerToken.Top),
            new SqlServerKeyword("tran", SqlServerToken.Tran),
            new SqlServerKeyword("transaction", SqlServerToken.Transaction),
            new SqlServerKeyword("trigger", SqlServerToken.Trigger),
            new SqlServerKeyword("truncate", SqlServerToken.Truncate),
            new SqlServerKeyword("try_convert", SqlServerToken.TryConvert),
            new SqlServerKeyword("tsequal", SqlServerToken.Tsequal),
            new SqlServerKeyword("union", SqlServerToken.Union),
            new SqlServerKeyword("unique", SqlServerToken.Unique),
            new SqlServerKeyword("unpivot", SqlServerToken.Unpivot),
            new SqlServerKeyword("update", SqlServerToken.Update),
            new SqlServerKeyword("updatetext", SqlServerToken.UpdateText),
            new SqlServerKeyword("use", SqlServerToken.Use),
            new SqlServerKeyword("user", SqlServerToken.User),
            new SqlServerKeyword("values", SqlServerToken.Values),
            new SqlServerKeyword("varying", SqlServerToken.Varying),
            new SqlServerKeyword("view", SqlServerToken.View),
            new SqlServerKeyword("waitfor", SqlServerToken.WaitFor),
            new SqlServerKeyword("when", SqlServerToken.When),
            new SqlServerKeyword("where", SqlServerToken.Where),
            new SqlServerKeyword("while", SqlServerToken.While),
            new SqlServerKeyword("with", SqlServerToken.With),
            new SqlServerKeyword("within", SqlServerToken.Within),
            new SqlServerKeyword("writetext", SqlServerToken.WriteText)
        };
    }
}


text:
PhpBinaryReader
===
[![Build Status](https://travis-ci.org/mdurrant/php-binary-reader.svg)](https://travis-ci.org/mdurrant/php-binary-reader)
[![Code Coverage](https://scrutinizer-ci.com/g/mdurrant/php-binary-reader/badges/coverage.png?b=master)](https://scrutinizer-ci.com/g/mdurrant/php-binary-reader/?branch=master)
[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/mdurrant/php-binary-reader/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/mdurrant/php-binary-reader/?branch=master)

Why?
---
You probably wouldn't be here if you hadn't run into a scenario where you needed to leverage PHP to read a stream of
binary data. The honest truth is PHP really stinks at this stuff, but as long as we're going to be using it we may as
well do our best to make it as painless as possible.

The purpose of this binary reader is to accept a string of file contents or file resource and provide a set of methods
inspired by .NET to traverse it.

Note on Endians
---
The reader is designed to work on little endian machines, which is going to apply to most scenarios as all x86 and x86-64
machines are little endian. If you have somehow found yourself on a big endian machine, you need to inform the class or
you may not be able to properly read signed integers in the file you're parsing.
```php
$fileData = file_get_contents('somefile.bin');
$br = new BinaryReader($fileData);
$br->setMachineByteOrder(Endian::ENDIAN_BIG);
...
```

Example Usage
---

```php
$fileData = file_get_contents('somefile.bin');
$br = new BinaryReader($fileData, Endian::ENDIAN_LITTLE);
// or
$fileResource = fopen('somefile.bin', 'rb');
$br = new BinaryReader($fileResource, Endian::ENDIAN_LITTLE);

$magic = $br->readUInt32();
$offset = $br->readUInt16();
$length = $br->readUInt16();
...
```

Methods
---
**__construct($input, $endian)** a string or file resource must be provided to use this class, an endian is optional (string [big|little], or use the constants in the Endian class), it will default to little if not provided.

**readUInt8()** returns a single 8 bit byte as an unsigned integer

**readInt8()** returns a single 8 bit byte as a signed integer

**readUInt16()** returns a 16-bit short as an unsigned integer

**readInt16()** returns a 16-bit short as a signed integer

**readUInt32()** returns a 32-bit unsigned integer

**readInt32()** returns a 32-bit signed integer

**readUInt64()** returns a 64-bit unsigned integer

**readInt64()** returns a 64-bit signed integer

**readSingle()** returns a 4-bytes floating-point

**readUBits($length)** returns a variable length of bits (unsigned)

**readBits($length)** returns a variable length of bits (signed)

**readBytes($length)** returns a variable length of bytes

**readString($length)** returns a variable length string

**readAlignedString($length)** aligns the pointer to 0 bits and returns a variable length string

**align()** aligns the pointer back to 0 bits

**isEof()** returns true if the pointer is on the last byte of the file

**getPosition()** returns the current byte position in the file

**setPosition($position)** sets the current byte position

**getCurrentBit()** returns the current bit position in the file

**setCurrentBit($currentBit)** sets the current bit position

Contributing
---
Contributions must follow the PSR2 coding standards and must not degrade 100% coverage.

Acknowledgements
---
Significant portions of the work is based on Graylin Kim's Python bit/byte reader in `sc2reader`_

.. _sc2reader: https://github.com/GraylinKim/sc2reader


text:
package co.rc.smservice.api.infrastructure.acl.dtos

import co.rc.sessionmanager.{ EmptyData, SessionData }
import co.rc.smservice.api.infrastructure.translation.entities.StringData

/**
 * Class that represents a session dto
 * @param id Session id
 * @param data Session data to store - Optional
 * @param expirationTime Session expiration time - Optional
 */
case class SessionDTO( id: String,
    data: Option[ String ],
    expirationTime: Option[ ExpirationTimeDTO ] ) {

  require( !id.isEmpty, "Session id must not be empty" )
  if ( data.isDefined ) require( !data.get.isEmpty, "Data must not be empty" )

  /**
   * Method that converts string data to a valid SessionData class
   * @return Mapped data value. If data is it returns an instance of StringDataDTO with data value inside.
   *         Otherwise it returns EmptyData object
   */
  def dataToSessionData(): SessionData = data.map( d => StringData( d ) ).getOrElse( EmptyData )

}


text:
name: Запрос на улучшение
about: Предложите идею для Dollchan
title: "[Enhancement]"
labels: enhancement
assignees: ''

---
**Ваш запрос на улучшение функционала связан с проблемой?**
Пожалуйста, дайте чёткое описание проблемы.

**Опишите ваше решение, которое вы хотели бы увидеть в реализаци**
Дайте подробное описание того, что вы хотите, чтобы разработчик реализовал.
Если можете, предложите здесь свой вариант реализации, или отправьте Pull request вместо создания Issue.


text:
package org.junit.internal;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.SelfDescribing;
import org.hamcrest.StringDescription;

public class AssumptionViolatedException extends RuntimeException implements SelfDescribing {
	private static final long serialVersionUID= 1L;

	private final Object fValue;

	private final Matcher<?> fMatcher;

	public AssumptionViolatedException(Object value, Matcher<?> matcher) {
		super(value instanceof Throwable ? (Throwable) value : null);
		fValue= value;
		fMatcher= matcher;
	}

	public AssumptionViolatedException(String assumption) {
		this(assumption, null);
	}

	@Override
	public String getMessage() {
		return StringDescription.asString(this);
	}

	public void describeTo(Description description) {
		if (fMatcher != null) {
			description.appendText("got: ");
			description.appendValue(fValue);
			description.appendText(", expected: ");
			description.appendDescriptionOf(fMatcher);
		} else {
			description.appendText("failed assumption: " + fValue);
		}
	}
}


text:
from neutron_lib.api.definitions import bgpvpn as bgpvpn_def
from neutron_lib.api.definitions import bgpvpn_routes_control as bgpvpn_rc_def
from neutron_lib.api.definitions import bgpvpn_vni as bgpvpn_vni_def
from neutron_lib.plugins import directory

def rtrd_list2str(list):
    """Format Route Target list to string"""
    if not list:
        return ''

    if isinstance(list, str):
        return list

    return ','.join(list)

def rtrd_str2list(str):
    """Format Route Target string to list"""
    if not str:
        return []

    if isinstance(str, list):
        return str

    return str.split(',')

def filter_resource(resource, filters=None):
    if not filters:
        filters = {}
    for key, value in filters.items():
        if key in resource.keys():
            if not isinstance(value, list):
                value = [value]
            if isinstance(resource[key], list):
                resource_value = resource[key]
            else:
                resource_value = [resource[key]]
            if not set(value).issubset(set(resource_value)):
                return False
    return True

def filter_fields(resource, fields):
    if fields:
        return dict(((key, item) for key, item in resource.items()
                     if key in fields))
    return resource

def is_extension_supported(plugin, ext_alias):
    return ext_alias in plugin.supported_extension_aliases

def make_bgpvpn_dict(bgpvpn, fields=None):
    res = {
        'id': bgpvpn['id'],
        'tenant_id': bgpvpn['tenant_id'],
        'name': bgpvpn['name'],
        'type': bgpvpn['type'],
        'route_targets': rtrd_str2list(bgpvpn['route_targets']),
        'import_targets': rtrd_str2list(bgpvpn['import_targets']),
        'export_targets': rtrd_str2list(bgpvpn['export_targets']),
        'route_distinguishers': rtrd_str2list(bgpvpn['route_distinguishers']),
        'networks': bgpvpn.get('networks', []),
        'routers': bgpvpn.get('routers', []),
        'ports': bgpvpn.get('ports', []),
    }
    plugin = directory.get_plugin(bgpvpn_def.ALIAS)
    if is_extension_supported(plugin, bgpvpn_vni_def.ALIAS):
        res[bgpvpn_vni_def.VNI] = bgpvpn.get(bgpvpn_vni_def.VNI)
    if is_extension_supported(plugin, bgpvpn_rc_def.ALIAS):
        res[bgpvpn_rc_def.LOCAL_PREF_KEY] = bgpvpn.get(
            bgpvpn_rc_def.LOCAL_PREF_KEY)
    return filter_fields(res, fields)

def make_net_assoc_dict(id, tenant_id, bgpvpn_id, network_id, fields=None):
    res = {'id': id,
           'tenant_id': tenant_id,
           'bgpvpn_id': bgpvpn_id,
           'network_id': network_id}
    return filter_fields(res, fields)

def make_router_assoc_dict(id, tenant_id, bgpvpn_id, router_id, fields=None):
    res = {'id': id,
           'tenant_id': tenant_id,
           'bgpvpn_id': bgpvpn_id,
           'router_id': router_id}
    return filter_fields(res, fields)

def make_port_assoc_dict(id, tenant_id, bgpvpn_id, port_id, fields=None):
    # NOTE(tmorin): fields need to be added here, this isn't used yet
    res = {'id': id,
           'tenant_id': tenant_id,
           'bgpvpn_id': bgpvpn_id,
           'port_id': port_id}
    return filter_fields(res, fields)

def get_bgpvpn_differences(current_dict, old_dict):
    """Compare 2 BGP VPN

    - added keys
    - removed keys
    - changed values for keys in both dictionaries
    """
    set_current = set(current_dict.keys())
    set_old = set(old_dict.keys())
    intersect = set_current.intersection(set_old)

    added = set_current - intersect
    removed = set_old - intersect
    changed = set(
        key for key in intersect if old_dict[key] != current_dict[key]
    )

    return (added, removed, changed)


text:
@interface DribbbleDetailBoard_iPhone()
AS_SIGNAL( VIEW_PROFILE )
AS_SIGNAL( VIEW_URL )
@end

#pragma mark -

@implementation DribbbleDetailBoard_iPhone

DEF_SIGNAL( VIEW_PROFILE )
DEF_SIGNAL( VIEW_URL )

DEF_MODEL( ShotInfoModel,		info );
DEF_MODEL( ShotCommentsModel,	comments );

DEF_OUTLET( BeeUIScrollView,	list );

SUPPORT_AUTOMATIC_LAYOUT( YES );
SUPPORT_RESOURCE_LOADING( YES );

- (void)load
{
	self.info = [ShotInfoModel modelWithObserver:self];
	self.comments = [ShotCommentsModel modelWithObserver:self];
}

- (void)unload
{
	[self.comments removeAllObservers];
	self.comments = nil;

	[self.info removeAllObservers];
	self.info = nil;
}

#pragma mark -

ON_CREATE_VIEWS( signal )
{
	self.view.backgroundColor = SHORT_RGB( 0x444 );

//	self.allowedSwipeToBack = YES;

	self.navigationBarShown = YES;
	self.navigationBarTitle = @"Dribbble";
	self.navigationBarLeft  = [UIImage imageNamed:@"navigation-back.png"];

	self.list.headerClass = [PullLoader class];
	self.list.headerShown = YES;

	self.list.footerClass = [FootLoader class];
	self.list.footerShown = YES;

	self.list.lineCount = 1;
	self.list.vertical = YES;
	self.list.animationDuration = 0.25f;
	self.list.baseInsets = bee.ui.config.baseInsets;

	self.list.whenReloading = ^
	{
		self.list.total = 2 + self.comments.comments.count;

		BeeUIScrollItem * player = self.list.items[0];
		player.clazz = [DribbbleDetailBoardPlayer_iPhone class];
		player.data = self.info.shot;
		player.order = 0;
		player.size = CGSizeAuto;

		BeeUIScrollItem * photo = self.list.items[1];
		photo.clazz = [DribbbleDetailBoardPhoto_iPhone class];
		photo.data = self.info.shot;
		photo.order = 0;
		photo.size = CGSizeAuto;

		for ( NSUInteger i = 0; i < self.comments.comments.count; ++i )
		{
			BeeUIScrollItem * comment = self.list.items[2 + i];
			comment.clazz = [DribbbleDetailBoardComment_iPhone class];
			comment.data = self.comments.comments[i];
			comment.order = 0;
			comment.size = CGSizeAuto;
		}
	};

	self.list.whenHeaderRefresh = ^
	{
		[self.info reload];
		[self.comments firstPage];
	};

	self.list.whenFooterRefresh = ^
	{
		[self.comments nextPage];
	};

	self.list.whenReachBottom = ^
	{
		[self.comments nextPage];
	};
}

ON_DELETE_VIEWS( signal )
{
}

ON_LAYOUT_VIEWS( signal )
{
}

ON_WILL_APPEAR( signal )
{
	if ( NO == self.info.loaded )
	{
		[self.info reload];
	}

	if ( NO == self.comments.loaded )
	{
		[self.comments firstPage];
	}

	[self.list reloadData];
}

ON_DID_APPEAR( signal )
{
}

ON_WILL_DISAPPEAR( signal )
{
}

ON_DID_DISAPPEAR( signal )
{
}

#pragma mark -

ON_LEFT_BUTTON_TOUCHED( signal )
{
	[self.stack popBoardAnimated:YES];
}

ON_RIGHT_BUTTON_TOUCHED( signal )
{
}

#pragma mark -

ON_SIGNAL3( DribbbleDetailBoardPlayer_iPhone, mask, signal )
{
	DribbbleProfileBoard_iPhone * board = [DribbbleProfileBoard_iPhone board];
	board.player = self.info.shot.player;
	[self.stack pushBoard:board animated:YES];
}

#pragma mark -

ON_SIGNAL3( DribbbleDetailBoardPhoto_iPhone, mask, signal )
{
	DribbblePreviewBoard_iPhone * board = [DribbblePreviewBoard_iPhone board];
	board.shot = self.info.shot;
	[self.stack pushBoard:board animated:YES];
}

#pragma mark -

ON_SIGNAL3( DribbbleDetailBoardComment_iPhone, mask, signal )
{
	COMMENT * comment = signal.sourceCell.data;
	NSArray * urls = [comment.body allURLs];

	if ( urls.count )
	{
		BeeUIActionSheet * actionSheet = [[[BeeUIActionSheet alloc] init] autorelease];

		[actionSheet addButtonTitle:[NSString stringWithFormat:@"%@", comment.player.name]
							 signal:self.VIEW_PROFILE
							 object:comment.player];

		for ( NSString * url in urls )
		{
			[actionSheet addButtonTitle:url signal:self.VIEW_URL object:url];
		}

		[actionSheet addCancelTitle:@"Cancel"];

		[actionSheet showInViewController:self];
	}
	else
	{
		DribbbleProfileBoard_iPhone * board = [DribbbleProfileBoard_iPhone board];
		board.player = comment.player;
		[self.stack pushBoard:board animated:YES];
	}
}

#pragma mark -

ON_SIGNAL3( DribbbleDetailBoard_iPhone, VIEW_PROFILE, signal )
{
	DribbbleProfileBoard_iPhone * board = [DribbbleProfileBoard_iPhone board];
	board.player = signal.object;
	[self.stack pushBoard:board animated:YES];
}

ON_SIGNAL3( DribbbleDetailBoard_iPhone, VIEW_URL, signal )
{
	DribbbleWebBoard_iPhone * board = [DribbbleWebBoard_iPhone board];
	board.url = signal.object;
	[self.stack pushBoard:board animated:YES];
}

#pragma mark -

ON_SIGNAL3( ShotInfoModel, RELOADING, signal )
{
	self.list.headerLoading = self.info.loaded;
	self.list.footerLoading = YES;
}

ON_SIGNAL3( ShotInfoModel, RELOADED, signal )
{
	self.list.headerLoading = NO;
	self.list.footerLoading = NO;
	self.list.footerMore = self.comments.more;

//	[self transitionFade];

	[self.list reloadData];
}

ON_SIGNAL3( ShotCommentsModel, RELOADING, signal )
{
	self.list.headerLoading = self.info.loaded;
	self.list.footerLoading = YES;
}

ON_SIGNAL3( ShotCommentsModel, RELOADED, signal )
{
	self.list.headerLoading = NO;
	self.list.footerLoading = NO;
	self.list.footerMore = self.comments.more;

//	[self transitionFade];

	[self.list reloadData];
}

@end


text:
package com.submarine.gameservices;

/**
 * Created by sargis on 3/6/15.
 */
public interface GameServicesListener<T> {
    void onSignInFailed();

    void onSignInSucceeded();

    void savedGamesLoadFailed(T result);

    void savedGamesLoadSucceeded(T result);

    void savedGamesLoadConflicted(T result, int retryCount);

    void savedGamesUpdateSucceeded();

    void savedGamesUpdateFailed();

//    void savedGamesLoadDone();

    void savedGamesLoadContentsUnavailable(T result);
}


text:
'use strict';

// Declare app level module which depends on views, and components
    angular.module('makeYourOffer', [
        'ngRoute',
        'makeYourOffer.login',
        'makeYourOffer.setup-new-bidding',
        'makeYourOffer.bid-on-existing',
        'makeYourOffer.version',
        'ui.bootstrap'
    ]).
    run(function ($rootScope, $location, $window, $timeout) {

            $rootScope.$on('$routeChangeError', function (event, next, current) {
                if (!(next.templateUrl === "login/login.html")) {
                    $location.path('/login')
                }

            });

            $rootScope.user = {};
            $rootScope.loggedIn = false;
            $rootScope.fbInitialized = false;

            $window.fbAsyncInit = function() {
                FB.init({

                    appId: '361819630659077',

                    channelUrl: 'app/channel.html',

                    version    : 'v2.2',

                    status: true,

                    cookie: true,

                    xfbml: true
                });

                watchLoginChange();
                $rootScope.fbInitialized = true;

            };

            (function(d){
                // load the Facebook javascript SDK
                var js,
                    id = 'facebook-jssdk',
                    ref = d.getElementsByTagName('script')[0];

                if (d.getElementById(id)) {
                    return;
                }

                js = d.createElement('script');
                js.id = id;
                js.async = true;
                js.src = "//connect.facebook.net/en_US/all.js";

                ref.parentNode.insertBefore(js, ref);

            }(document));

            function watchLoginChange() {

                FB.Event.subscribe('auth.authResponseChange', function(response) {
                    if (response.status === 'connected') {
                        $rootScope.loggedIn = true;
                        getUserInfo();
                    }
                    else {

                    }

                });

            };

            function getUserInfo() {

                FB.api('/me', function(response) {

                    $rootScope.$apply(function() {

                        $rootScope.user = response;
                        console.log(response);
                    });
                });
            };

      }).
      config(['$routeProvider', function ($routeProvider) {
          $routeProvider.otherwise({
              redirectTo: '/setup-new-bidding'
          });
      }]);


text:
package com.amazonaws.services.workdocs.model;

import javax.annotation.Generated;

/**
 * Base exception for all service exceptions thrown by Amazon WorkDocs
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class AmazonWorkDocsException extends com.amazonaws.AmazonServiceException {

    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new AmazonWorkDocsException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public AmazonWorkDocsException(String message) {
        super(message);
    }

}


text:
module 'mock'

EnumGrowDirection = _ENUM_V{
	'x',
	'y'
}

CLASS: UIFormLayout ( UILayout )
	:MODEL{
		Field 'size' :type( 'vec2' ) :getset( 'Size' ) :meta{ decimals = 0 };
		Field 'rowHeight' :getset( 'RowHeight' );
		Field 'labelSize' :getset( 'LabelSize' );
		'----';
		Field 'margin' :type('vec4') :getset( 'Margin' );
		Field 'spacingX' :getset( 'SpacingX' );
	}

registerComponent( 'UIFormLayout', UIFormLayout )

-- function UIFormLayout:__init()
-- 	self.gridWidth, self.gridHeight = 50, 50
-- 	self.width, self.height = -1, -1
-- 	self.spacingX, self.spacingY = 5, 5
-- 	self.growDirection = 'y'
-- end

-- function UIFormLayout:getSize()
-- 	return self.width, self.height
-- end

-- function UIFormLayout:setSize( w, h )
-- 	self.width, self.height = w, h
-- 	self:invalidate()
-- end

-- function UIFormLayout:setSpacingX( s )
-- 	self.spacingX = s
-- 	self:invalidate()
-- end

-- function UIFormLayout:getSpacingX()
-- 	return self.spacingX
-- end

-- function UIFormLayout:setSpacingY( s )
-- 	self.spacingY = s
-- 	self:invalidate()
-- end

-- function UIFormLayout:getSpacingY()
-- 	return self.spacingY
-- end

-- function UIFormLayout:getSpacing()
-- 	return self.spacingX, self.spacingY
-- end

-- function UIFormLayout:setSpacing( x, y )
-- 	x = x or 0
-- 	y = y or x
-- 	self.spacingX = x
-- 	self.spacingY = y
-- 	self:invalidate()
-- end

-- function UIFormLayout:calcSize( count )
-- 	local cols, rows = self.width, self.height
-- 	local gw, gh = self.gridWidth, self.gridHeight
-- 	local sx, sy = self:getSpacing()
-- 	local growDir = self.growDirection
-- 	local maxAvailableWidth, maxAvailableHeight = self:getMaxAvailableSize()
-- 	local availableWidth, availableHeight = self:getAvailableSize()
-- 	gw = gw
-- 	gh = gh
-- 	local availableCols = math.floor( ( availableWidth + sx  )/ ( gw + sx ) )
-- 	local availableRows = math.floor( ( availableHeight + sy ) / ( gh + sy ) )
-- 	if cols <= 0 then
-- 		cols = availableCols
-- 	end
-- 	if rows <= 0 then
-- 		rows = availableRows
-- 	end
-- 	if cols <= 0 or rows <= 0 then return 0,0 end

-- 	if growDir == 'x' then
-- 		local cols1 = math.ceil( count/rows )
-- 		local maxCols =
-- 			maxAvailableWidth > 0 and math.floor( ( maxAvailableWidth + sx ) / ( gw + sx ) ) or -1
-- 		cols = maxCols > 0 and math.min( cols1, maxCols ) or cols1

-- 	elseif growDir == 'y' then
-- 		local rows1 = math.ceil( count/cols )
-- 		local maxRows =
-- 			maxAvailableHeight > 0 and math.floor( ( maxAvailableHeight + sy ) / ( gh + sy ) ) or -1
-- 		rows = maxRows > 0 and math.min( rows1, maxRows ) or rows1
-- 	else
-- 		return w, h
-- 	end
-- 	return cols, rows
-- end

-- function UIFormLayout:getGridSize()
-- 	return self.gridWidth, self.gridHeight
-- end

-- function UIFormLayout:setGridSize( w, h )
-- 	self.gridWidth, self.gridHeight = w, h
-- 	self:invalidate()
-- end

-- function UIFormLayout:onUpdate()
-- 	local owner = self:getOwner()
-- 	local info = owner:getLayoutableChildInfo()
-- 	local count = #info
-- 	--calculate grid
-- 	local cols, rows = self:calcSize( count )
-- 	local gw, gh = self:getGridSize()
-- 	local sx, sy = self:getSpacing()
-- 	local i = 1
-- 	local marginL, marginT, marginR, marginB = self:getMargin()
-- 	for y = 1, rows do
-- 		local py = ( y - 1 ) * ( gh + sy ) + marginT
-- 		for x = 1, cols do
-- 			local px = ( x - 1 ) * ( gw + sx ) + marginL
-- 			if i > count then return end
-- 			local entry = info[ i ]
-- 			local widget = entry.widget
-- 			local minW, minH = widget:getMinSize()
-- 			local w = math.max( minW, gw )
-- 			local h = math.max( minH, gh )
-- 			info.targetWidth  = w
-- 			info.targetHeight = h
-- 			widget:setLoc( px ,py )
-- 			widget:setSize( w, h, false, true )
-- 			i = i + 1
-- 		end
-- 	end
-- end


text:
'use strict';

/**
 * Posts controller for serving user posts.
 */

var qs = require('querystring'),
    route = require('koa-route'),
    parse = require('co-body'),
    mongo = require('../config/mongo');

// register koa routes
exports.init = function (app) {
    app.use(route.get('/api/playqueue', getQueue));
    app.use(route.post('/api/playqueue', queueItem));
};

/**
 * Lists last 15 posts with latest 15 comments in them.
 */
function *getQueue() {
    var items = yield mongo.playQueue.find(
            {user_id: this.user.id},
            {resource: 1}
        ).toArray();

    this.status = 201;
    this.body = items;
}

/**
 * Saves a new post in the database after proper validations.
 */
function *queueItem() {

    var data = yield parse(this);

    // delete item if already in queue
    yield mongo.playQueue.remove({
        user_id: this.user.id,
        resourceId: data.resource.resourceId
    });

    var results = yield mongo.playQueue.insert({
        user_id: this.user.id,
        createdTime: new Date(),
        resourceId: data.resource.resourceId,
        resource: data.resource
    });

    this.status = 201;
    this.body = {id: results[0]._id};
}