text:
This sample application demonstrates creating and deploying a Shipped project from an existing GitHub repository.

Summary
-------

Spree is a complete open source e-commerce solution built with Ruby on Rails. It
was originally developed by Sean Schofield and is now maintained by a dedicated
[core team](https://github.com/spree/spree/wiki/Core-Team). You can find out more by
visiting the [Spree e-commerce project page](http://spreecommerce.com).

Spree actually consists of several different gems, each of which are maintained
in a single repository and documented in a single set of
[online documentation](http://spreecommerce.com/documentation). By requiring the
Spree gem you automatically require all of the necessary gem dependencies which are:

* spree_api (RESTful API)
* spree_frontend (User-facing components)
* spree_backend (Admin area)
* spree_cmd (Command-line tools)
* spree_core (Models & Mailers, the basic components of Spree that it can't run without)
* spree_sample (Sample data)

All of the gems are designed to work together to provide a fully functional
e-commerce platform. It is also possible, however, to use only the pieces you are
interested in. For example, you could use just the barebones spree\_core gem
and perhaps combine it with your own custom backend admin instead of using
spree_api.

Further Documentation
------------
Spree has a number of really useful guides online at [http://guides.spreecommerce.com](http://guides.spreecommerce.com).

## Setting Up on Shipped

### Step 1. Get a GitHub Account
[Git](https://git-scm.com/) is a source and version control system hosted on the web, and [GitHub](https://github.com/) is a repository of Git projects. Shipped stores your projects on GitHub, and you'll need a GitHub account to use Shipped. If you already have a GitHub account, skip to step 2. Otherwise, navigate to the [GitHub home page](https://github.com/) using any modern browser (we recommend Chrome), click on [Sign up](https://github.com/join) and follow the instructions to create a free account. You don't need to do anything more with GitHub at this time; Shipped will do it all for you.

### Step 2 Fork the spree project
Fork CiscoCloud/spree as your repository master project branch.  This sets up spree as the sample repository that you'll use for your Shipped project.

![](https://github.com/CiscoCloud/spree/blob/master/shipped/images/fork.Png)

### Step 3 Download the Shipped CLI
You can compose a Shipped project either with the Shipped web UI at [http://shipped-cisco.com](http://shipped-cisco.com) or with the Shipped CLI.  However, even if you compose your project online, you'll still need the CLI to bootstrap it to your local laptop, so the first step in using Shipped is to download the CLI.  Download from the appropriate link below:

OS | Download URL
---- | -------------------
linux | https://bintray.com/artifact/download/shippedrepos/shipped-cli/linux/shipped (5.9 MB)
linux (compressed) | https://bintray.com/artifact/download/shippedrepos/shipped-cli/linux/shipped.gz (1.7 MB)
mac | https://bintray.com/artifact/download/shippedrepos/shipped-cli/mac/shipped (6.3 MB)
mac (compressed) | https://bintray.com/artifact/download/shippedrepos/shipped-cli/mac/shipped.gz (1.8 MB)
windows | https://bintray.com/artifact/download/shippedrepos/shipped-cli/windows/shipped.exe (6 MB)
windows (compressed) | https://bintray.com/artifact/download/shippedrepos/shipped-cli/windows/shipped.zip (1.7 MB)

The compressed links contain the same executables as the standard links, but may take less time to download (though you'll need to decompress them after the download). Once you've downloaded an executable, copy it to a directory in your path.   Issue the command:

    shipped -v

to verify you've successfully downloaded and deployed the Shipped CLI.  You should see a response similar to:

> Cisco Shipped 1.0 b103 20150919 001714

### Step 4 Compose and Deploy your Project with the Shipped CLI
This step explains how to compose and deploy your project entirely with the Shipped CLI.  If you'd prefer to use the web UI, skip this step and go to Step 5.

To compose your project with the Shipped CLI, first obtain a terminal window:

| Os Type | Action          |
| ------------------- | -------------------- |
| OS X (Mac)|	Press Command + Space to open Spotlight Search. Type Terminal and double-click the Terminal Application. Menu option Shell -> New Window will open a new window for you. |
| Ubuntu |	Press Ctrl+Alt+T |
| Windows |	Click Start, type "cmd", and press Enter for a normal terminal window, or Ctrl+Shift+Enter for an Administrator terminal window. You will need an Administrator window if the bootstrap process needs to install Vagrant and VirtualBox. If you already have this software installed, you can use a normal terminal window. |

Once you have the terminal window open, enter the following command:

    shipped run create-and-deploy project=MyProject service=spree framework=express [fast="--fast"]

This command is all you need to create your project and deploy it to the Cloud!  Use the **project** argument to provide a name for your project (you can call it anything you want); specify the **service** and **framework** arguments exactly as shown; and specify the optional **fast="--fast"** argument to suppress building a VM on your laptop for local deployment (which saves two or three minutes of bootstrap time, but doesn't run the application locally).

This command does the following:

* Creates the project and service in the Shipped database
* Sets up a remote GitHub repository in the Cloud
* Sets up a continuous integration (CI) build that rebuilds your project automatically after every commit
* Downloads project source code into a local Git repository on your laptop
* If necessary, installs prerequisite software (Vagrant and Virtualbox)
* Optionally creates a VM on your laptop to build and run the service
* Makes a commit to the Git repository that starts the first build
* Sets up a cloud environment where you can deploy your project
* Waits for the build to complete and deploys the project to the cloud

Once it completes, you'll have your application running both on your laptop and in the cloud.  That's how easy it is to get started with Shipped!

Create-and-deploy is an example of a Shipped CLI script that runs several CLI commands in succession.  You can see the contents of the script with the command:

    shipped script list create-and-deploy

The commands in the script perform the same tasks as the Shipped UI actions described in the next step.  You can get an overview of some CLI commands by following along with the script as you read through the next step.  For more detailed documentation on the CLI, use its help command,

    shipped help

### Step 5. Compose and Deploy Your Project with the Shipped UI
If you've composed your project with the CLI, you can skip this step.  However, if you prefer to compose your project online - or would just like to see how it's done - just use any modern browser (we recommend Chrome) to navigate to the [Shipped welcome page](http://shipped-cisco.com).

![](https://github.com/CiscoCloud/spree/blob/master/shipped/images/home.Png)
#### Step 5.1 Login to Shipped
Your GitHub account is all you need to login to Shipped, so click on the big green "Sign up with GitHub" button.

If this is your first project, Shipped automatically pops up a Create New Project form; if not, select Create New Project from the Your Projects dropdown to get the popup:

![](https://github.com/CiscoCloud/spree/blob/master/shipped/images/createproject.Png)

Enter a name for your project (we'll use "Sample" for this project) and press Start Composing. Shipped displays a list of development services:

#### Step 5.2 Add a service
The development services listed are examples of what Shipped calls "microservices" - supporting services used by a project. We can choose as many microservices as needed for a project. Shipped installs whatever is needed to deploy the selected microservices on one of the VMs it creates for you.

For this project we'll select **Ruby on Rails** which create a Ruby on Rails VM with everything needed to build and run an Rails project like Spree.

![](https://github.com/CiscoCloud/spree/blob/master/shipped/images/selectservice.Png)

Click on the Select button to the right of this service. Shipped pops up the Service Configuration form that you'll use to specify the GitHub repository where Shipped stores the source code using the service:

#### Step 5.3 Configure the Service
![](https://github.com/CiscoCloud/spree/blob/master/shipped/images/selectrepo.Png)

This form allow us to specify:

| Name | Description          |
| ------------------- | -------------------- |
| Name of GitHub Repository|	The name of the GitHub repository where Shipped stores the source code using this service. Shipped automatically creates the repository if necessary.  *For this example, we'll use the repository you forked in Step 2 and specify* spree *for the repository name.* |
| GitHub Organization|	The GitHub account owning the repository. This can be your personal account, or the account of a company or organization associated with your account.  *For this example, specify the account where you forked the spree repository.* |
| Private Public |	The type of repository to create.  Private repositories are available only to specific GitHub users; public repositories are viewable by any web user. You need a paid GitHub account to create a private repository.  *For this example, specify Public, as your fork of a public repository must also be public.*  |

#### Step 5.4 Build Your Project

Specify "spree" for the repository name and press Add Service. Shipped re-displays the Compose Your Project form with the repository name for the selected service above the Build Project button.

![](https://github.com/CiscoCloud/spree/blob/master/shipped/images/buildproject.Png)

To build your project, press the Build Project button. The button label changes to Building, and a status bar moves across the button while Shipped creates your GitHub repository and stores the description of your project in its database. When it's finished, it pops up the Let's Get Set Up form containing the command to bootstrap the project on your computer:

![](https://github.com/CiscoCloud/spree/blob/master/shipped/images/buildlocal.Png)

#### Step 5.5 Bootstrap Your Local Development Environment
Bootstrapping a Shipped project means:

-  Downloads the project's source code to your machine
-  Sets up a local Git repository tied to the cloud-based repository created by Shipped
-  If necessary, installs the prerequisite software Vagrant and VirtualBox
-  Optionally creates the virtual machines that host your development environment

The process is fully automatic; you just need to copy and paste the command presented by Shipped when you created the project.

The bootstrap process runs in a command-line terminal window, so the first step in bootstrapping your project is opening a terminal window. The way you do this depends on your operating system:

| Os Type | Action          |
| ------------------- | -------------------- |
| OS X (Mac)|	Press Command + Space to open Spotlight Search. Type Terminal and double-click the Terminal Application. Menu option Shell -> New Window will open a new window for you. |
| Ubuntu |	Press Ctrl+Alt+T |
| Windows |	Click Start, type "cmd", and press Enter for a normal terminal window, or Ctrl+Shift+Enter for an Administrator terminal window. You will need an Administrator window if the bootstrap process needs to install Vagrant and VirtualBox. If you already have this software installed, you can use a normal terminal window. |

When you completed creating your project in the previous step, Shipped popped up the Let's Get Set Up form containing commands to download the CLI and bootstrap your project:

![](https://github.com/CiscoCloud/spree/blob/master/shipped/images/buildlocal.Png)

Since you already installed the Shipped CLI in Step 3, you only need to copy the second command and paste it into your terminal window.  This command looks something like this:

    shipped -t wxkOzQgIgoxSuekHjuyMdMjCIbrKJAcO local bootstrap 65a1fcb4-6141-11e5-befb-0242ac113ce8

If you don't want to create a VM hosting your development environment, append the argument **--fast** to the end of this line.  This saves two or three minutes of bootstrap time, but skips local deployment of the project.  If you choose this option, you can create the VM at a later time by rerunning the bootstrap command without **--fast**.

Press Enter to start the bootstrap process.  While bootstrap runs, the Shipped UI displays a circular animation ticking off each step in the bootstrap process as it happens:

![](https://github.com/CiscoCloud/spree/blob/master/shipped/images/buildstatus.Png)

#### Step 5.6 Run a Build

When you created the project, Shipped set up both a GitHub repository in the cloud and a continuous integration (CI) build, so that any commit to the repository automatically triggers a build.  When you bootstrapped the project, Shipped stored the application's source code in a local Git repository tied to the GitHub repository.  To start a build, all you need to is commit changes to the GitHub repository.  When the bootstrap process completes, the Shipped browser window displays the commit command you need to run your first build:

![](https://github.com/CiscoCloud/spree/blob/master/shipped/images/pushbuild.Png)

Once again, select the command by clicking on it and copy and paste it into your terminal window. The command changes the directory to the one containing your new local Git repository and commits the initial copy of the application source to your cloud-based remote Git repository.

This automatically triggers a build, as you can in the event section of your browser window

#### Step 5.7 Create an Environment to Deploy Your Project to the Cloud

The last step in the bootstrap process is deploying your project's application to the Cisco cloud. To do this, click on the Deploy tab at the top left of the screen. Shipped displays the Deploy tab with a message that there are currently no deployed environments:

Create a new Environment by clicking on the New Environment button in the upper right corner of the form.  Shipped displays the New Environment form:

![](https://github.com/CiscoCloud/spree/blob/master/shipped/images/newenv.Png)

Specify a name for your environment and click Add Environment.

#### Step 5.8 Deploy Your Project to the  Environment.
Click on the build in the Select Build column, the environment in the Select Environment column, and then on the Deploy Build button.  Shipped shows the message "Deploying to environment..." under the environment name, and a short time later replaces it with a "Deployed successfully" message:
![](https://github.com/CiscoCloud/spree/blob/master/shipped/images/deploy.Png)

Congratulations! You've deployed your spree application to the cloud. Click on the URL in the "Deployed successfully" message to see the application running in its new environment

### Spree
[![Circle CI](https://circleci.com/gh/spree/spree.svg?style=svg)](https://circleci.com/gh/spree/spree)
[![Code Climate](https://codeclimate.com/github/spree/spree.png)](https://codeclimate.com/github/spree/spree)
[![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/spree/spree)
[![Issue Stats](http://issuestats.com/github/spree/spree/badge/pr)](http://issuestats.com/github/spree/spree)
[![Issue Stats](http://issuestats.com/github/spree/spree/badge/issue)](http://issuestats.com/github/spree/spree)

Request for Comments
------------
Spree feature and change request for comments can be found at [https://github.com/spree-contrib/rfcs](https://github.com/spree-contrib/rfcs).

Contributing
------------

Spree is an open source project and we encourage contributions. Please review the
[contributing guidelines](http://guides.spreecommerce.com/developer/contributing.html)
before contributing.

In the spirit of [free software](http://www.fsf.org/licensing/essays/free-sw.html), **everyone** is encouraged to help improve this project.

Here are some ways **you** can contribute:

* by using prerelease versions / master branch
* by reporting [bugs](https://github.com/spree/spree/issues/new)
* by [translating to a new language](https://github.com/spree/spree_i18n/tree/master/config/locales)
* by writing or editing [documentation](http://guides.spreecommerce.com/developer/contributing.html#contributing-to-the-documentation)
* by writing [specs](https://github.com/spree/spree/labels/need_specs)
* by writing [needed code](https://github.com/spree/spree/labels/feature_request) or [finishing code](https://github.com/spree/spree/labels/address_feedback)
* by [refactoring code](https://github.com/spree/spree/labels/address_feedback)
* by reviewing [pull requests](https://github.com/spree/spree/pulls)
* by verifying [issues](https://github.com/spree/spree/labels/unverified)

License
-------

Spree is released under the [New BSD License](https://github.com/spree/spree/blob/master/license.md).


text:
SQLKit
=======

SQLKit is a library for iOS that helps to store objects that may be temporary and have depend on other temporary objects.

A typical use-case would be a mobile application that needs to fetch different sets of data from the server and store offline.
The same data may be returned in different views. Sometimes temporary data should become persistent and vice versa.
And to even complicate matters: data, that may be out of date, but is still shown to the user should not be deleted.

Lets say the application has N feeds that contain M posts that contain X comments.
Most feeds could have a limited lifespan in cache, but if users can bookmark posts then these posts should be moved to a special
persistent feed and never be deleted from the cache. So the post along with comments gets deleted only if it's marked as
temporary and there are no feeds that depend on it.

# Features

* sqlite back-end
* Key-value object store
* Tables
* Assocications between tables and objects
* Global table (properties)
* Search
* Object locking
* Model classes don't require a special superclass
* No CoreData. Easier to port.

# Example

	// Create a Store object
	SQLObjectStore *store = [[SQLObjectStore alloc] initWithPath:path];

	// Read and write properties
	[store setProperty:[NSArray arrayWithObject:@"foo"] forKey:@"bar"];
	NSArray *foo = [store propertyForKey:@"bar"];

	// Remove expired objects from a table
	[store invalidateObjectsInTable:@"posts" usingBlock:^(NSString *table, NSString *key) {
        // If not NULL, then is called for every object that will be removed
    }];

    // Add or replace an object
    [store setObject:[post jsonData] expires:expires forKey:post.identifier inTable:@"posts"];

    // Find all the keys and values in a table. Optional block parameter allows automatic conversion and filtering.
    NSMutableArray *posts = [[NSMutableArray alloc] init];

    for(Post *post in [m_store allObjectsInTable:@"posts" usingBlock:^id (NSString *key, NSData *value) {
        return [[Post alloc] initWithJsonData:value];
    }].objectEnumerator) {
        [posts addObject:post];
    }

    // Add a bookmark
    [store associateKey:@"bookmarks" inTable:@"feeds" withKey:post.identifier inTable:@"posts"];

    // Remove a bookmark
    [store dissociateKey:@"bookmarks" inTable:@"feeds" withKey:post.identifier inTable:@"posts"];

    // Find all the associations. Optional block parameter allows automatic conversion and filtering.
    NSArray *posts = [store associationsForKey:@"bookmarks" inTable:@"feeds" forTable:@"posts" usingBlock:^id (NSString *key, NSData *value) {
        return [[Post alloc] initWithJsonData:value];
    }];

redpajama_set_name: RedPajamaGithub


text:
package io.crnk.core.engine.internal.jackson.mock.models;

import java.util.Collections;
import java.util.List;

import io.crnk.core.resource.annotations.JsonApiId;
import io.crnk.core.resource.annotations.JsonApiRelation;
import io.crnk.core.resource.annotations.JsonApiResource;
import io.crnk.core.resource.annotations.LookupIncludeBehavior;
import io.crnk.core.resource.annotations.SerializeType;

@JsonApiResource(type = "classCsWithInclusion")
public class ClassCWithInclusion {
	@JsonApiId
	private Long id;

	@JsonApiRelation(serialize = SerializeType.EAGER, lookUp = LookupIncludeBehavior.AUTOMATICALLY_WHEN_NULL)
	private List<ClassCWithInclusion> classCsWithInclusion;

	public ClassCWithInclusion() {
	}

	public ClassCWithInclusion(ClassCWithInclusion classCsWithInclusion) {
		this.classCsWithInclusion = Collections.singletonList(classCsWithInclusion);
	}

	public Long getId() {
		return id;
	}

	public ClassCWithInclusion setId(Long id) {
		this.id = id;
		return this;
	}

	public List<ClassCWithInclusion> getClassCsWithInclusion() {
		return classCsWithInclusion;
	}

	public void setClassCsWithInclusion(List<ClassCWithInclusion> classCsWithInclusion) {
		this.classCsWithInclusion = classCsWithInclusion;
	}
}


text:
class Settings {
    closed = true;
    options = {
        blockFromNewLine: true,
        blockSeparatorText: "\\n",
        blockSeparator: ko.es5.mapping.computed(() => {
            return this.options.blockSeparatorText.replace("\\n", String.fromCharCode(13));
        }),
        combineVariables: false,
        indentSize: 4,
        indentSymbol: " ",
        rulesList: [
            "font-size",
            "background-color",
        ],
        selectorSeparatorText: ",\\n",
        selectorSeparator: ko.es5.mapping.computed(() => {
            return this.options.selectorSeparatorText.replace("\\n", String.fromCharCode(13));
        }),
        vendorPrefixesListText: "-moz,-o,-ms,-webkit",
        vendorPrefixesList: ko.es5.mapping.computed(() => {
            return this.options.vendorPrefixesListText.split(",");
        })
    };
    rulesList: UI.ListBox = null;
    subscriptions = new SubscriptionList();
    width = 200;

    close = () => {
        this.closed = true;
        $("#settings").animate({ width: 'toggle' });
        $("#settingsCell").width($("#settingsLabel").height());
        $("#settingsLabel").fadeIn();
    };

    show = () => {
        this.closed = false;
        $("#settingsLabel").fadeOut();
        $("#settings").animate({ width: 'toggle' });
        $("#settingsCell").width($("#settings").width());
    }

    clearCookies = () => {
        eraseAllCookies();
    };

    displayContents = ko.es5.mapping.computed<string>(() => {
        return this.closed ? "none" : "block";
    });

    displayLabel = ko.es5.mapping.computed<string>(() => {
        // Label must be displayed block, not inline
        return this.closed ? "block" : "none";
    });

    load = () => {
        this.closed = getCookie("settings", "closed", this.closed);
        this.width = getCookie("settings", "closedwidth", this.width);
        this.options = getCookie("settings", "options", this.options);
    }

    save = () => {
        var data = {
            closed: this.closed,
            //width: this.width, // not resizable yet
            options: this.options,
        };
        $.cookie("settings", data, { expires: 365 });
    }

    constructor() {
        // TODO: Clear cookies UI
        //$.removeCookie("settings");
        this.load();
        if (this.closed)
            $("#settingsLabel").show();
        else
            $("#settings").show();
        this.rulesList = new UI.ListBox(this.options.rulesList);

        ko.es5.mapping.track(this);

        this.subscriptions.add(ko.getObservable(this, "width"), (data) => {
            if (this.closed)
                // don't save the closed width
                return;

            this.save();
        }, true, true);

        this.subscriptions.add(ko.getObservable(this, "closed"), (data) => {
            this.save();
        }, true, true);
        this.subscriptions.add(this.options, (data) => {
            if (typeof (this.options.indentSize) == "string") {
                this.options.indentSize = parseInt(<any> this.options.indentSize);
            }
            this.save();
        }, true, true);
    }
}


text:
/*************************
*   Precompiled Header   *
**************************/
#include "precomp_gamecomponents.h"

/**********************
*   System Includes   *
***********************/

/*************************
*   3rd Party Includes   *
**************************/

/***************************
*   Game Engine Includes   *
****************************/
#include "Models\Mesh.h"
#include "Camera\Camera.h"
#include "Models\MeshPart.h"
#include "Vertex\IndexBuffer.h"
#include "GameObjectRenderTest.h"
#include "GameObject\Components\MeshGOC.h"
#include "Shaders\Buffers\ConstantBuffer.h"
#include "GameObject\Components\MeshMaterialGOC.h"
#include "Graphic Extensions\Shader Extensions\Properties\ShaderProperties.h"

//Always include last
#include "Memory\MemLeaks.h"

/********************
*   Function Defs   *
*********************/
GameObjectRenderTest::GameObjectRenderTest(GameApp& gameApp, const std::string& gameComponentName)
    : DrawableGameComponent(gameApp, gameComponentName)
    , m_GameObjectManager(m_GameApp.GetGameObjectManager())
{
}

GameObjectRenderTest::~GameObjectRenderTest()
{
}

void GameObjectRenderTest::Initialize()
{
    m_Camera = m_GameApp.GetGameService<Camera>("Camera");
}

void GameObjectRenderTest::LoadContent()
{
}

void GameObjectRenderTest::Update(const TimerParams& timerParams)
{
}

void GameObjectRenderTest::Render(const TimerParams& timerParams)
{
    for(auto goIt : m_GameObjectManager)
    {
        DrawGameObject(goIt.second);
    }
}

void GameObjectRenderTest::DrawGameObject(GameObject* gameObject)
{
    AEAssert(gameObject != nullptr);
    if(gameObject == nullptr)
    {
        return;
    }

    if(gameObject->HasMeshGOC() && gameObject->HasMaterialGOCs())
    {
        Mesh* mesh = gameObject->GetMeshGOC()->GetMeshResource();

        if(mesh != nullptr)
        {
            const MeshMaterialsGOCList& matList = gameObject->GetMeshMaterialsGOCList();
            auto matListIt = matList.begin();

            for(uint32_t i = 0; i < mesh->GetNumberMeshParts() && i < matList.size(); i++, matListIt++)
            {
                MeshPart* meshPart = mesh->GetMeshPart(i);

                MeshMaterialGOC* meshMat = *matListIt;

                ShaderProperties* vsProps = meshMat->GetVertexShaderProperties();

                if(vsProps != nullptr)
                {
                    ConstantBuffer* cb = vsProps->GetConstantBuffer("_AE_CB_World_View_Proj");

                    cb->SetValueT<glm::mat4>("_AE_View", m_Camera->GetViewMatrix());
                    cb->SetValueT<glm::mat4>("_AE_PROJection", m_Camera->GetProjectionMatrix());
                    cb->SetValueT<glm::mat4>("_AE_World", gameObject->GetWorldTransform());
                }

                meshMat->ApplyShaders(m_GraphicDevice);

                m_GraphicDevice.SetVertexBuffer(meshPart->GetVertexBuffer());
                m_GraphicDevice.SetIndexBuffer(meshPart->GetIndexBuffer());

                m_GraphicDevice.SetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);

                m_GraphicDevice.DrawIndexed(0, 0, meshPart->GetIndexBuffer()->GetSize());
            }
        }

    }

    for(auto goIt : *gameObject)
    {
        DrawGameObject(goIt.second);
    }
}

void GameObjectRenderTest::OnLostDevice()
{
}

void GameObjectRenderTest::OnResetDevice()
{
}


text:
const request = require('request');
const config = require('config');
const crypto = require('crypto');
const qs = require('querystring');

const buyLimit = (market, quantity, rate) => new Promise(
  async (resolveBuyLimit, rejectBuyLimit) => {
    const query = {
      apikey: config.get('bittrexApiKey'),
      nonce: new Date().getTime(),
      market,
      quantity,
      rate,
    };

    const url = `${config.get('bittrex.buylimiturl')}?${qs.stringify(query)}`;
    const apisign = crypto.createHmac('sha512', config.get('bittrexApiSecret')).update(url).digest('hex');

    try {
      const order = await (
        new Promise((resolve, reject) => request({ url, headers: { apisign } },
          (error, response) => {
            if (error) {
              return reject(error);
            }

            if (response.body === undefined) {
              return reject(new Error('Empty body'));
            }

            let jsonBody;
            try {
              jsonBody = JSON.parse(response.body);
            } catch (jsonParseError) {
              return reject(jsonParseError);
            }

            if (jsonBody.success !== true) {
              return reject(new Error(jsonBody.message || 'Unknown error'));
            }

            return resolve(jsonBody.result);
          })));

      return resolveBuyLimit(order);
    } catch (error) {
      return rejectBuyLimit(error);
    }
  });

module.exports = buyLimit;


text:
package noderedis;

import org.stjs.javascript.Array;
import org.stjs.javascript.Map;
import org.stjs.javascript.Promise;
import org.stjs.javascript.annotation.Native;
import org.stjs.javascript.annotation.STJSBridge;
import org.stjs.javascript.functions.Callback2;

@STJSBridge
public class NodeRedis {
    @Native
    public static NodeRedis createClient() {
        return null;
    }

    @Native
    public static NodeRedis createClient(String url) {
        return null;
    }

    @Native
    public void exists(String key, Callback2<Object, Integer> responseCallback) {
    }

    @Native
    public Promise<Integer> existsAsync(String key) {
        return null;
    }

    @Native
    public Multi multi() {
        return null;
    }

    @Native
    public void hget(String key, String field, Callback2<Object, String> cb) {
        throw new RuntimeException("TODO NodeRedis.hget");
    }

    @Native
    public Promise<String> hgetAsync(String key, String field) {
        return null;
    }

    @Native
    public Promise<Double> zcardAsync(String kReadyQueue) {
        throw new RuntimeException("TODO NodeRedis.zcardAsync");
    }

    @Native
    public Promise<Array<String>> zrangeAsync(String key, double min, double max) {
        throw new RuntimeException("TODO NodeRedis.zrangeAsync");
    }

    @Native
    public Promise<Map<String, String>> hgetallAsync(String kJob) {
        throw new RuntimeException("TODO NodeRedis.hgetAllAsync");
    }

    @Native
    public Promise<Double> zscoreAsync(String kDelayQueue, String id) {
        return null;
    }

    @Native
    public Promise<Array<String>> zrangebyscoreAsync(String kDelayQueue, double min, double max) {
        throw new RuntimeException("TODO NodeRedis.zrangeByScoreAsync");
    }

    @Native
    public Promise<Integer> zaddAsync(String kReadyQueue, Array scoreMember) {
        throw new RuntimeException("TODO NodeRedis.zaddAsync");
    }

    @Native
    public Promise<Array<String>> zrangebyscoreAsync(String kDelayQueue, double d, double positiveInfinity,
            String limit, int offset, int count) {
        throw new RuntimeException("TODO NodeRedis.zrangebyscoreAsync");
    }

    @Native
    public Promise<Integer> zcountAsync(String kDelayQueue, int i, long now) {
        throw new RuntimeException("TODO NodeRedis.zcountAsync");
    }

    @Native
    public Promise<String> getAsync(String k) {
        throw new RuntimeException("TODO NodeRedis.getAsync");
    }

    @Native
    public void quit() {
        throw new RuntimeException("TODO NodeRedis.quit");
    }

}


text:
using Esri.ArcGISRuntime.Controls;
using Esri.ArcGISRuntime.Data;
using Esri.ArcGISRuntime.Layers;
using Esri.ArcGISRuntime.Tasks.Query;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace ArcGISRuntimeSDKDotNet_StoreSamples.Samples
{
    /// <summary>
    /// Demonstrates how to query and edit related records.
    /// </summary>
    /// <title>Edit Related Data</title>
    /// <category>Editing</category>
    public partial class EditRelatedData : Page
    {
        // Query is done through this relationship.
        Esri.ArcGISRuntime.ArcGISServices.Relationship relationship;
        // Editing is done through this table.
        ServiceFeatureTable table;

        public EditRelatedData()
        {
            InitializeComponent();
            var layer = MyMapView.Map.Layers["ServiceRequests"] as ArcGISDynamicMapServiceLayer;
            layer.VisibleLayers = new ObservableCollection<int>(new int[] { 0 });
        }

        /// <summary>
        /// Identifies graphic to highlight and query its related records.
        /// </summary>
        private async void MyMapView_MapViewTapped(object sender, MapViewInputEventArgs e)
        {
            var layer = MyMapView.Map.Layers["ServiceRequests"] as ArcGISDynamicMapServiceLayer;
            var task = new IdentifyTask(new Uri(layer.ServiceUri));
            var mapPoint = MyMapView.ScreenToLocation(e.Position);
            var parameter = new IdentifyParameters(mapPoint, MyMapView.Extent, 2, (int)MyMapView.ActualHeight, (int)MyMapView.ActualWidth);

            // Clears map of any highlights.
            var overlay = MyMapView.GraphicsOverlays["Highlighter"] as GraphicsOverlay;
            overlay.Graphics.Clear();

            SetRelatedRecordEditor();

            string message = null;
            try
            {
                // Performs an identify and adds graphic result into overlay.
                var result = await task.ExecuteAsync(parameter);
                if (result == null || result.Results == null || result.Results.Count < 1)
                    return;
                var graphic = (Graphic)result.Results[0].Feature;
                overlay.Graphics.Add(graphic);

                // Prepares related records editor.
                var featureID = Convert.ToInt64(graphic.Attributes["OBJECTID"], CultureInfo.InvariantCulture);
                string requestID = null;
                if (graphic.Attributes["Service Request ID"] != null)
                    requestID = Convert.ToString(graphic.Attributes["Service Request ID"], CultureInfo.InvariantCulture);
                SetRelatedRecordEditor(featureID, requestID);

                await QueryRelatedRecordsAsync();
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            if (!string.IsNullOrWhiteSpace(message))
                await new MessageDialog(message).ShowAsync();
        }

        /// <summary>
        /// Prepares related record editor for add and query.
        /// </summary>
        private void SetRelatedRecordEditor(long featureID = 0, string requestID = null)
        {
            AddButton.Tag = featureID;
            AddButton.IsEnabled = featureID > 0 && !string.IsNullOrWhiteSpace(requestID);
            RelatedRecords.Tag = requestID;
            if (featureID == 0)
            {
                Records.IsEnabled = false;
                RelatedRecords.ItemsSource = null;
                RelatedRecords.SelectedItem = null;
            }
            SetAttributeEditor();
        }

        /// <summary>
        /// Prepares attribute editor for update or delete of existing related record.
        /// </summary>
        private void SetAttributeEditor(Feature feature = null)
        {
            if (ChoiceList.ItemsSource == null && table != null && table.ServiceInfo != null && table.ServiceInfo.Fields != null)
            {
                var rangeDomain = (RangeDomain<IComparable>)table.ServiceInfo.Fields.FirstOrDefault(f => f.Name == "rank").Domain;
                ChoiceList.ItemsSource = GetRangeValues((int)rangeDomain.MinValue, (int)rangeDomain.MaxValue);
            }
            AttributeEditor.Tag = feature;
            if (feature != null)
            {
                if (feature.Attributes.ContainsKey("rank") && feature.Attributes["rank"] != null)
                    ChoiceList.SelectedItem = Convert.ToInt32(feature.Attributes["rank"], CultureInfo.InvariantCulture);
                if (feature.Attributes.ContainsKey("comments") && feature.Attributes["comments"] != null)
                    Comments.Text = Convert.ToString(feature.Attributes["comments"], CultureInfo.InvariantCulture);
                AttributeEditor.Visibility = Visibility.Visible;
                Records.Flyout.ShowAt(Records);
            }
            else
            {
                ChoiceList.SelectedItem = null;
                Comments.Text = string.Empty;
                AttributeEditor.Visibility = Visibility.Collapsed;
            }
        }

        /// <summary>
        /// Gets exclusive values between minimum and maximum values.
        /// </summary>
        private IEnumerable<int> GetRangeValues(int min, int max)
        {
            for (int i = min; i <= max; i++)
                yield return i;
        }

        /// <summary>
        /// Gets relationship information using service metadata.
        /// </summary>
        private async Task<Esri.ArcGISRuntime.ArcGISServices.Relationship> GetRelationshipAsync()
        {
            var layer = MyMapView.Map.Layers["ServiceRequests"] as ArcGISDynamicMapServiceLayer;
            if (layer == null || layer.VisibleLayers == null)
                return null;
            var id = layer.VisibleLayers.FirstOrDefault();
            var details = await layer.GetDetailsAsync(id);
            if (details != null && details.Relationships != null)
                return details.Relationships.FirstOrDefault();
            return null;
        }

        /// <summary>
        /// Queries related records for specified feature ID.
        /// </summary>
        private async Task QueryRelatedRecordsAsync()
        {
            var featureID = (Int64)AddButton.Tag;
            var layer = MyMapView.Map.Layers["ServiceRequests"] as ArcGISDynamicMapServiceLayer;
            var id = layer.VisibleLayers.FirstOrDefault();
            var task = new QueryTask(new Uri(string.Format("{0}/{1}", layer.ServiceUri, id)));
            if (relationship == null)
                relationship = await GetRelationshipAsync();
            var parameters = new RelationshipParameters(new List<long>(new long[] { featureID }), relationship.ID);
            parameters.OutFields = new OutFields(new string[] { "objectid" });
            var result = await task.ExecuteRelationshipQueryAsync(parameters);
            if (result != null && result.RelatedRecordGroups != null && result.RelatedRecordGroups.ContainsKey(featureID))
            {
                RelatedRecords.ItemsSource = result.RelatedRecordGroups[featureID];
                Records.IsEnabled = true;
            }
        }

        /// <summary>
        /// Submits related record edits back to server.
        /// </summary>
        private async Task SaveEditsAsync()
        {
            if (table == null || !table.HasEdits)
                return;
            if (table is ServiceFeatureTable)
            {
                var serviceTable = (ServiceFeatureTable)table;
                // Pushes new graphic back to the server.
                var result = await serviceTable.ApplyEditsAsync();
                if (result.AddResults == null || result.AddResults.Count < 1)
                    return;
                var addResult = result.AddResults[0];
                if (addResult.Error != null)
                    throw addResult.Error;
            }
        }

        /// <summary>
        /// Gets related table for editing.
        /// </summary>
        private async Task<ServiceFeatureTable> GetRelatedTableAsync()
        {
            var layer = MyMapView.Map.Layers["ServiceRequests"] as ArcGISDynamicMapServiceLayer;
            // Creates table based on related table ID of the visible layer in dynamic layer
            // using FeatureServer specifying rank and comments fields to enable editing.
            var id = relationship.RelatedTableID.Value;
            var url = layer.ServiceUri.Replace("MapServer", "FeatureServer");
            url = string.Format("{0}/{1}", url, id);
            var table = await ServiceFeatureTable.OpenAsync(new Uri(url), null, MyMapView.SpatialReference);
            table.OutFields = new OutFields(new string[] { relationship.KeyField, "rank", "comments", "submitdt" });
            return table;
        }

        /// <summary>
        /// Displays current attribute values of related record.
        /// </summary>
        private async void RelatedRecords_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (RelatedRecords.SelectedItem == null)
                return;
            var graphic = (Graphic)RelatedRecords.SelectedItem;
            SetAttributeEditor();
            string message = null;
            try
            {
                if (table == null)
                    table = await GetRelatedTableAsync();
                var featureID = Convert.ToInt64(graphic.Attributes[table.ObjectIDField], CultureInfo.InvariantCulture);
                var feature = await table.QueryAsync(featureID);
                SetAttributeEditor(feature);
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            if (!string.IsNullOrWhiteSpace(message))
                await new MessageDialog(message).ShowAsync();
        }

        /// <summary>
        /// Adds a new related record to highlighted feature.
        /// </summary>
        private async void AddButton_Click(object sender, RoutedEventArgs e)
        {
            SetAttributeEditor();
            var featureID = (Int64)AddButton.Tag;
            var requestID = (string)RelatedRecords.Tag;
            string message = null;
            try
            {
                if (table == null)
                    table = await GetRelatedTableAsync();
                var feature = new GeodatabaseFeature(table.Schema);
                feature.Attributes[relationship.KeyField] = requestID;
                feature.Attributes["rank"] = 5;
                feature.Attributes["comments"] = "Describe service requirement here.";
                feature.Attributes["submitdt"] = DateTime.UtcNow;
                var relatedFeatureID = await table.AddAsync(feature);
                await SaveEditsAsync();
                await QueryRelatedRecordsAsync();
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            if (!string.IsNullOrWhiteSpace(message))
                await new MessageDialog(message).ShowAsync();
        }

        /// <summary>
        /// Updates attributes of related record.
        /// </summary>
        private async void EditButton_Click(object sender, RoutedEventArgs e)
        {
            if (AttributeEditor.Tag == null) return;
            var feature = (GeodatabaseFeature)AttributeEditor.Tag;
            string message = null;
            try
            {
                if (ChoiceList.SelectedItem != null)
                    feature.Attributes["rank"] = (int)ChoiceList.SelectedItem;
                feature.Attributes["comments"] = Comments.Text.Trim();
                await table.UpdateAsync(feature);
                await SaveEditsAsync();
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            if (!string.IsNullOrWhiteSpace(message))
                await new MessageDialog(message).ShowAsync();
        }

        /// <summary>
        /// Deletes related record.
        /// </summary>
        private async void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            if (RelatedRecords.SelectedItem == null) return;
            var graphic = (Graphic)RelatedRecords.SelectedItem;
            string message = null;
            try
            {
                if (table == null)
                    table = await GetRelatedTableAsync();
                var featureID = Convert.ToInt64(graphic.Attributes[table.ObjectIDField], CultureInfo.InvariantCulture);
                await table.DeleteAsync(featureID);
                await SaveEditsAsync();
                await QueryRelatedRecordsAsync();
                SetAttributeEditor();
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            if (!string.IsNullOrWhiteSpace(message))
                await new MessageDialog(message).ShowAsync();
        }
    }
}


text:
package main

import (
	"flag"
	//"strconv"
	//"strings"

	. "github.com/strickyak/rxtx"
)

var bind = flag.String("bind", ":44144", "port to bind to")
var hub = flag.String("hub", "localhost:44144", "hub to use")
var cmd = flag.String("cmd", "h", "what to do")
var audio = flag.String("audio", "/dev/audio", "muLaw audio device")
var junk = flag.String("junk", "UUU", "junk to write on usb")

func main() {
	flag.Parse()
	e := NewEngine(*hub)
	e.InitSocket(*bind)
	switch *cmd {

	case "x": // hub
		e.HubCommand()

	case "h": // human
		e.InitAudio(*audio)
		e.HumanCommand()

	case "r": // radio
		e.InitAudio(*audio)
		e.RadioCommand(*junk)

	default:
		panic(*cmd)
	}
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>mediabot</groupId>
		<artifactId>mediabot-core</artifactId>
		<version>0.0.1-SNAPSHOT</version>
		<relativePath>../pom.xml</relativePath>
	</parent>
	<artifactId>mediabot-business</artifactId>

	<dependencies>
		<!-- internal dependencies -->
		<dependency>
			<groupId>mediabot</groupId>
			<artifactId>mediabot-model</artifactId>
		</dependency>
		<!-- spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		<!-- tests -->
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
		</dependency>
		<dependency>
			<groupId>org.mockito</groupId>
			<artifactId>mockito-all</artifactId>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-core</artifactId>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-api-mockito</artifactId>
		</dependency>
		<dependency>
			<groupId>org.powermock</groupId>
			<artifactId>powermock-module-junit4</artifactId>
		</dependency>
		<!-- logger -->
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.velocity</groupId>
			<artifactId>velocity</artifactId>
		</dependency>
	</dependencies>
</project>


text:
package org.apache.lucene.index;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;

import org.apache.lucene.codecs.Codec;
import org.apache.lucene.codecs.FieldsConsumer;
import org.apache.lucene.codecs.FieldsProducer;
import org.apache.lucene.codecs.PostingsConsumer;
import org.apache.lucene.codecs.TermStats;
import org.apache.lucene.codecs.TermsConsumer;
import org.apache.lucene.index.FieldInfo.DocValuesType;
import org.apache.lucene.index.FieldInfo.IndexOptions;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FlushInfo;
import org.apache.lucene.store.IOContext;
import org.apache.lucene.util.Bits;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.Constants;
import org.apache.lucene.util.FixedBitSet;
import org.apache.lucene.util.LuceneTestCase;
import org.apache.lucene.util._TestUtil;
import org.junit.AfterClass;
import org.junit.BeforeClass;

/**
 * Abstract class to do basic tests for a postings format.
 * NOTE: This test focuses on the postings
 * (docs/freqs/positions/payloads/offsets) impl, not the
 * terms dict.  The [stretch] goal is for this test to be
 * so thorough in testing a new PostingsFormat that if this
 * test passes, then all Lucene/Solr tests should also pass.  Ie,
 * if there is some bug in a given PostingsFormat that this
 * test fails to catch then this test needs to be improved! */

// TODO can we make it easy for testing to pair up a "random terms dict impl" with your postings base format...

// TODO test when you reuse after skipping a term or two, eg the block reuse case

// TODO hmm contract says .doc() can return NO_MORE_DOCS
// before nextDoc too...?

/* TODO
  - threads
  - assert doc=-1 before any nextDoc
  - if a PF passes this test but fails other tests then this
    test has a bug!!
  - test tricky reuse cases, eg across fields
  - verify you get null if you pass needFreq/needOffset but
    they weren't indexed
*/

public abstract class BasePostingsFormatTestCase extends LuceneTestCase {

  /**
   * Returns the Codec to run tests against
   */
  protected abstract Codec getCodec();

  private enum Option {
    // Sometimes use .advance():
    SKIPPING,

    // Sometimes reuse the Docs/AndPositionsEnum across terms:
    REUSE_ENUMS,

    // Sometimes pass non-null live docs:
    LIVE_DOCS,

    // Sometimes seek to term using previously saved TermState:
    TERM_STATE,

    // Sometimes don't fully consume docs from the enum
    PARTIAL_DOC_CONSUME,

    // Sometimes don't fully consume positions at each doc
    PARTIAL_POS_CONSUME,

    // Sometimes check payloads
    PAYLOADS,

    // Test w/ multiple threads
    THREADS
  };

  /** Given the same random seed this always enumerates the
   *  same random postings */
  private static class SeedPostings extends DocsAndPositionsEnum {
    // Used only to generate docIDs; this way if you pull w/
    // or w/o positions you get the same docID sequence:
    private final Random docRandom;
    private final Random random;
    public int docFreq;
    private final int maxDocSpacing;
    private final int payloadSize;
    private final boolean fixedPayloads;
    private final Bits liveDocs;
    private final BytesRef payload;
    private final IndexOptions options;
    private final boolean doPositions;

    private int docID;
    private int freq;
    public int upto;

    private int pos;
    private int offset;
    private int startOffset;
    private int endOffset;
    private int posSpacing;
    private int posUpto;

    public SeedPostings(long seed, int minDocFreq, int maxDocFreq, Bits liveDocs, IndexOptions options) {
      random = new Random(seed);
      docRandom = new Random(random.nextLong());
      docFreq = _TestUtil.nextInt(random, minDocFreq, maxDocFreq);
      this.liveDocs = liveDocs;

      // TODO: more realistic to inversely tie this to numDocs:
      maxDocSpacing = _TestUtil.nextInt(random, 1, 100);

      if (random.nextInt(10) == 7) {
        // 10% of the time create big payloads:
        payloadSize = 1 + random.nextInt(3);
      } else {
        payloadSize = 1 + random.nextInt(1);
      }

      fixedPayloads = random.nextBoolean();
      byte[] payloadBytes = new byte[payloadSize];
      payload = new BytesRef(payloadBytes);
      this.options = options;
      doPositions = IndexOptions.DOCS_AND_FREQS_AND_POSITIONS.compareTo(options) <= 0;
    }

    @Override
    public int nextDoc() {
      while(true) {
        _nextDoc();
        if (liveDocs == null || docID == NO_MORE_DOCS || liveDocs.get(docID)) {
          return docID;
        }
      }
    }

    private int _nextDoc() {
      // Must consume random:
      while(posUpto < freq) {
        nextPosition();
      }

      if (upto < docFreq) {
        if (upto == 0 && docRandom.nextBoolean()) {
          // Sometimes index docID = 0
        } else if (maxDocSpacing == 1) {
          docID++;
        } else {
          // TODO: sometimes have a biggish gap here!
          docID += _TestUtil.nextInt(docRandom, 1, maxDocSpacing);
        }

        if (random.nextInt(200) == 17) {
          freq = _TestUtil.nextInt(random, 1, 1000);
        } else if (random.nextInt(10) == 17) {
          freq = _TestUtil.nextInt(random, 1, 20);
        } else {
          freq = _TestUtil.nextInt(random, 1, 4);
        }

        pos = 0;
        offset = 0;
        posUpto = 0;
        posSpacing = _TestUtil.nextInt(random, 1, 100);

        upto++;
        return docID;
      } else {
        return docID = NO_MORE_DOCS;
      }
    }

    @Override
    public int docID() {
      return docID;
    }

    @Override
    public int freq() {
      return freq;
    }

    @Override
    public int nextPosition() {
      if (!doPositions) {
        posUpto = freq;
        return 0;
      }
      assert posUpto < freq;

      if (posUpto == 0 && random.nextBoolean()) {
        // Sometimes index pos = 0
      } else if (posSpacing == 1) {
        pos++;
      } else {
        pos += _TestUtil.nextInt(random, 1, posSpacing);
      }

      if (payloadSize != 0) {
        if (fixedPayloads) {
          payload.length = payloadSize;
          random.nextBytes(payload.bytes);
        } else {
          int thisPayloadSize = random.nextInt(payloadSize);
          if (thisPayloadSize != 0) {
            payload.length = payloadSize;
            random.nextBytes(payload.bytes);
          } else {
            payload.length = 0;
          }
        }
      } else {
        payload.length = 0;
      }

      startOffset = offset + random.nextInt(5);
      endOffset = startOffset + random.nextInt(10);
      offset = endOffset;

      posUpto++;
      return pos;
    }

    @Override
    public int startOffset() {
      return startOffset;
    }

    @Override
    public int endOffset() {
      return endOffset;
    }

    @Override
    public BytesRef getPayload() {
      return payload.length == 0 ? null : payload;
    }

    @Override
    public int advance(int target) {
      while(nextDoc() < target) {
      }
      return docID;
    }
  }

  private static class FieldAndTerm {
    String field;
    BytesRef term;

    public FieldAndTerm(String field, BytesRef term) {
      this.field = field;
      this.term = BytesRef.deepCopyOf(term);
    }
  }

  // Holds all postings:
  private static Map<String,Map<BytesRef,Long>> fields;

  private static FieldInfos fieldInfos;

  private static FixedBitSet globalLiveDocs;

  private static List<FieldAndTerm> allTerms;
  private static int maxDoc;

  private static long totalPostings;
  private static long totalPayloadBytes;

  private static SeedPostings getSeedPostings(String term, long seed, boolean withLiveDocs, IndexOptions options) {
    int minDocFreq, maxDocFreq;
    if (term.startsWith("big_")) {
      minDocFreq = RANDOM_MULTIPLIER * 50000;
      maxDocFreq = RANDOM_MULTIPLIER * 70000;
    } else if (term.startsWith("medium_")) {
      minDocFreq = RANDOM_MULTIPLIER * 3000;
      maxDocFreq = RANDOM_MULTIPLIER * 6000;
    } else if (term.startsWith("low_")) {
      minDocFreq = RANDOM_MULTIPLIER;
      maxDocFreq = RANDOM_MULTIPLIER * 40;
    } else {
      minDocFreq = 1;
      maxDocFreq = 3;
    }

    return new SeedPostings(seed, minDocFreq, maxDocFreq, withLiveDocs ? globalLiveDocs : null, options);
  }

  @BeforeClass
  public static void createPostings() throws IOException {
    totalPostings = 0;
    totalPayloadBytes = 0;
    fields = new TreeMap<String,Map<BytesRef,Long>>();

    final int numFields = _TestUtil.nextInt(random(), 1, 5);
    if (VERBOSE) {
      System.out.println("TEST: " + numFields + " fields");
    }
    maxDoc = 0;

    FieldInfo[] fieldInfoArray = new FieldInfo[numFields];
    int fieldUpto = 0;
    while (fieldUpto < numFields) {
      String field = _TestUtil.randomSimpleString(random());
      if (fields.containsKey(field)) {
        continue;
      }

      fieldInfoArray[fieldUpto] = new FieldInfo(field, true, fieldUpto, false, false, true,
                                                IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS,
                                                null, DocValuesType.NUMERIC, null);
      fieldUpto++;

      Map<BytesRef,Long> postings = new TreeMap<BytesRef,Long>();
      fields.put(field, postings);
      Set<String> seenTerms = new HashSet<String>();

      // TODO:
      //final int numTerms = atLeast(10);
      final int numTerms = 4;

      for(int termUpto=0;termUpto<numTerms;termUpto++) {
        String term = _TestUtil.randomSimpleString(random());
        if (seenTerms.contains(term)) {
          continue;
        }
        seenTerms.add(term);

        if (TEST_NIGHTLY && termUpto == 0 && fieldUpto == 1) {
          // Make 1 big term:
          term = "big_" + term;
        } else if (termUpto == 1 && fieldUpto == 1) {
          // Make 1 medium term:
          term = "medium_" + term;
        } else if (random().nextBoolean()) {
          // Low freq term:
          term = "low_" + term;
        } else {
          // Very low freq term (don't multiply by RANDOM_MULTIPLIER):
          term = "verylow_" + term;
        }

        long termSeed = random().nextLong();
        postings.put(new BytesRef(term), termSeed);

        // NOTE: sort of silly: we enum all the docs just to
        // get the maxDoc
        DocsEnum docsEnum = getSeedPostings(term, termSeed, false, IndexOptions.DOCS_ONLY);
        int doc;
        int lastDoc = 0;
        while((doc = docsEnum.nextDoc()) != DocsEnum.NO_MORE_DOCS) {
          lastDoc = doc;
        }
        maxDoc = Math.max(lastDoc, maxDoc);
      }
    }

    fieldInfos = new FieldInfos(fieldInfoArray);

    // It's the count, not the last docID:
    maxDoc++;

    globalLiveDocs = new FixedBitSet(maxDoc);
    double liveRatio = random().nextDouble();
    for(int i=0;i<maxDoc;i++) {
      if (random().nextDouble() <= liveRatio) {
        globalLiveDocs.set(i);
      }
    }

    allTerms = new ArrayList<FieldAndTerm>();
    for(Map.Entry<String,Map<BytesRef,Long>> fieldEnt : fields.entrySet()) {
      String field = fieldEnt.getKey();
      for(Map.Entry<BytesRef,Long> termEnt : fieldEnt.getValue().entrySet()) {
        allTerms.add(new FieldAndTerm(field, termEnt.getKey()));
      }
    }

    if (VERBOSE) {
      System.out.println("TEST: done init postings; " + allTerms.size() + " total terms, across " + fieldInfos.size() + " fields");
    }
  }

  @AfterClass
  public static void afterClass() throws Exception {
    allTerms = null;
    fieldInfos = null;
    fields = null;
    globalLiveDocs = null;
  }

  // TODO maybe instead of @BeforeClass just make a single test run: build postings & index & test it?

  private FieldInfos currentFieldInfos;

  // maxAllowed = the "highest" we can index, but we will still
  // randomly index at lower IndexOption
  private FieldsProducer buildIndex(Directory dir, IndexOptions maxAllowed, boolean allowPayloads, boolean alwaysTestMax) throws IOException {
    Codec codec = getCodec();
    SegmentInfo segmentInfo = new SegmentInfo(dir, Constants.LUCENE_MAIN_VERSION, "_0", maxDoc, false, codec, null, null);

    int maxIndexOption = Arrays.asList(IndexOptions.values()).indexOf(maxAllowed);
    if (VERBOSE) {
      System.out.println("\nTEST: now build index");
    }

    int maxIndexOptionNoOffsets = Arrays.asList(IndexOptions.values()).indexOf(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS);

    // TODO use allowPayloads

    FieldInfo[] newFieldInfoArray = new FieldInfo[fields.size()];
    for(int fieldUpto=0;fieldUpto<fields.size();fieldUpto++) {
      FieldInfo oldFieldInfo = fieldInfos.fieldInfo(fieldUpto);

      String pf = _TestUtil.getPostingsFormat(codec, oldFieldInfo.name);
      int fieldMaxIndexOption;
      if (doesntSupportOffsets.contains(pf)) {
        fieldMaxIndexOption = Math.min(maxIndexOptionNoOffsets, maxIndexOption);
      } else {
        fieldMaxIndexOption = maxIndexOption;
      }

      // Randomly picked the IndexOptions to index this
      // field with:
      IndexOptions indexOptions = IndexOptions.values()[alwaysTestMax ? fieldMaxIndexOption : random().nextInt(1+fieldMaxIndexOption)];
      boolean doPayloads = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 && allowPayloads;

      newFieldInfoArray[fieldUpto] = new FieldInfo(oldFieldInfo.name,
                                                   true,
                                                   fieldUpto,
                                                   false,
                                                   false,
                                                   doPayloads,
                                                   indexOptions,
                                                   null,
                                                   DocValuesType.NUMERIC,
                                                   null);
    }

    FieldInfos newFieldInfos = new FieldInfos(newFieldInfoArray);

    // Estimate that flushed segment size will be 25% of
    // what we use in RAM:
    long bytes =  totalPostings * 8 + totalPayloadBytes;

    SegmentWriteState writeState = new SegmentWriteState(null, dir,
                                                         segmentInfo, newFieldInfos,
                                                         32, null, new IOContext(new FlushInfo(maxDoc, bytes)));
    FieldsConsumer fieldsConsumer = codec.postingsFormat().fieldsConsumer(writeState);

    for(Map.Entry<String,Map<BytesRef,Long>> fieldEnt : fields.entrySet()) {
      String field = fieldEnt.getKey();
      Map<BytesRef,Long> terms = fieldEnt.getValue();

      FieldInfo fieldInfo = newFieldInfos.fieldInfo(field);

      IndexOptions indexOptions = fieldInfo.getIndexOptions();

      if (VERBOSE) {
        System.out.println("field=" + field + " indexOtions=" + indexOptions);
      }

      boolean doFreq = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
      boolean doPos = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
      boolean doPayloads = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 && allowPayloads;
      boolean doOffsets = indexOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;

      TermsConsumer termsConsumer = fieldsConsumer.addField(fieldInfo);
      long sumTotalTF = 0;
      long sumDF = 0;
      FixedBitSet seenDocs = new FixedBitSet(maxDoc);
      for(Map.Entry<BytesRef,Long> termEnt : terms.entrySet()) {
        BytesRef term = termEnt.getKey();
        SeedPostings postings = getSeedPostings(term.utf8ToString(), termEnt.getValue(), false, maxAllowed);
        if (VERBOSE) {
          System.out.println("  term=" + field + ":" + term.utf8ToString() + " docFreq=" + postings.docFreq + " seed=" + termEnt.getValue());
        }

        PostingsConsumer postingsConsumer = termsConsumer.startTerm(term);
        long totalTF = 0;
        int docID = 0;
        while((docID = postings.nextDoc()) != DocsEnum.NO_MORE_DOCS) {
          final int freq = postings.freq();
          if (VERBOSE) {
            System.out.println("    " + postings.upto + ": docID=" + docID + " freq=" + postings.freq);
          }
          postingsConsumer.startDoc(docID, doFreq ? postings.freq : -1);
          seenDocs.set(docID);
          if (doPos) {
            totalTF += postings.freq;
            for(int posUpto=0;posUpto<freq;posUpto++) {
              int pos = postings.nextPosition();
              BytesRef payload = postings.getPayload();

              if (VERBOSE) {
                if (doPayloads) {
                  System.out.println("      pos=" + pos + " payload=" + (payload == null ? "null" : payload.length + " bytes"));
                } else {
                  System.out.println("      pos=" + pos);
                }
              }
              postingsConsumer.addPosition(pos, doPayloads ? payload : null,
                                           doOffsets ? postings.startOffset() : -1,
                                           doOffsets ? postings.endOffset() : -1);
            }
          } else if (doFreq) {
            totalTF += freq;
          } else {
            totalTF++;
          }
          postingsConsumer.finishDoc();
        }
        termsConsumer.finishTerm(term, new TermStats(postings.docFreq, doFreq ? totalTF : -1));
        sumTotalTF += totalTF;
        sumDF += postings.docFreq;
      }

      termsConsumer.finish(doFreq ? sumTotalTF : -1, sumDF, seenDocs.cardinality());
    }

    fieldsConsumer.close();

    if (VERBOSE) {
      System.out.println("TEST: after indexing: files=");
      for(String file : dir.listAll()) {
        System.out.println("  " + file + ": " + dir.fileLength(file) + " bytes");
      }
    }

    currentFieldInfos = newFieldInfos;

    SegmentReadState readState = new SegmentReadState(dir, segmentInfo, newFieldInfos, IOContext.DEFAULT, 1);

    return codec.postingsFormat().fieldsProducer(readState);
  }

  private static class ThreadState {
    // Only used with REUSE option:
    public DocsEnum reuseDocsEnum;
    public DocsAndPositionsEnum reuseDocsAndPositionsEnum;
  }

  private void verifyEnum(ThreadState threadState,
                          String field,
                          BytesRef term,
                          TermsEnum termsEnum,

                          // Maximum options (docs/freqs/positions/offsets) to test:
                          IndexOptions maxTestOptions,

                          IndexOptions maxIndexOptions,

                          EnumSet<Option> options,
                          boolean alwaysTestMax) throws IOException {

    if (VERBOSE) {
      System.out.println("  verifyEnum: options=" + options + " maxTestOptions=" + maxTestOptions);
    }

    // 50% of the time time pass liveDocs:
    boolean useLiveDocs = options.contains(Option.LIVE_DOCS) && random().nextBoolean();
    Bits liveDocs;
    if (useLiveDocs) {
      liveDocs = globalLiveDocs;
      if (VERBOSE) {
        System.out.println("  use liveDocs");
      }
    } else {
      liveDocs = null;
      if (VERBOSE) {
        System.out.println("  no liveDocs");
      }
    }

    FieldInfo fieldInfo = currentFieldInfos.fieldInfo(field);

    // NOTE: can be empty list if we are using liveDocs:
    SeedPostings expected = getSeedPostings(term.utf8ToString(),
                                            fields.get(field).get(term),
                                            useLiveDocs,
                                            maxIndexOptions);
    assertEquals(expected.docFreq, termsEnum.docFreq());

    boolean allowFreqs = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS) >= 0 &&
      maxTestOptions.compareTo(IndexOptions.DOCS_AND_FREQS) >= 0;
    boolean doCheckFreqs = allowFreqs && (alwaysTestMax || random().nextInt(3) <= 2);

    boolean allowPositions = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0 &&
      maxTestOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS) >= 0;
    boolean doCheckPositions = allowPositions && (alwaysTestMax || random().nextInt(3) <= 2);

    boolean allowOffsets = fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0 &&
      maxTestOptions.compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) >= 0;
    boolean doCheckOffsets = allowOffsets && (alwaysTestMax || random().nextInt(3) <= 2);

    boolean doCheckPayloads = options.contains(Option.PAYLOADS) && allowPositions && fieldInfo.hasPayloads() && (alwaysTestMax || random().nextInt(3) <= 2);

    DocsEnum prevDocsEnum = null;

    DocsEnum docsEnum;
    DocsAndPositionsEnum docsAndPositionsEnum;

    if (!doCheckPositions) {
      if (allowPositions && random().nextInt(10) == 7) {
        // 10% of the time, even though we will not check positions, pull a DocsAndPositions enum

        if (options.contains(Option.REUSE_ENUMS) && random().nextInt(10) < 9) {
          prevDocsEnum = threadState.reuseDocsAndPositionsEnum;
        }

        int flags = 0;
        if (alwaysTestMax || random().nextBoolean()) {
          flags |= DocsAndPositionsEnum.FLAG_OFFSETS;
        }
        if (alwaysTestMax || random().nextBoolean()) {
          flags |= DocsAndPositionsEnum.FLAG_PAYLOADS;
        }

        if (VERBOSE) {
          System.out.println("  get DocsAndPositionsEnum (but we won't check positions) flags=" + flags);
        }

        threadState.reuseDocsAndPositionsEnum = termsEnum.docsAndPositions(liveDocs, (DocsAndPositionsEnum) prevDocsEnum, flags);
        docsEnum = threadState.reuseDocsAndPositionsEnum;
        docsAndPositionsEnum = threadState.reuseDocsAndPositionsEnum;
      } else {
        if (VERBOSE) {
          System.out.println("  get DocsEnum");
        }
        if (options.contains(Option.REUSE_ENUMS) && random().nextInt(10) < 9) {
          prevDocsEnum = threadState.reuseDocsEnum;
        }
        threadState.reuseDocsEnum = termsEnum.docs(liveDocs, prevDocsEnum, doCheckFreqs ? DocsEnum.FLAG_FREQS : DocsEnum.FLAG_NONE);
        docsEnum = threadState.reuseDocsEnum;
        docsAndPositionsEnum = null;
      }
    } else {
      if (options.contains(Option.REUSE_ENUMS) && random().nextInt(10) < 9) {
        prevDocsEnum = threadState.reuseDocsAndPositionsEnum;
      }

      int flags = 0;
      if (alwaysTestMax || doCheckOffsets || random().nextInt(3) == 1) {
        flags |= DocsAndPositionsEnum.FLAG_OFFSETS;
      }
      if (alwaysTestMax || doCheckPayloads|| random().nextInt(3) == 1) {
        flags |= DocsAndPositionsEnum.FLAG_PAYLOADS;
      }

      if (VERBOSE) {
        System.out.println("  get DocsAndPositionsEnum flags=" + flags);
      }

      threadState.reuseDocsAndPositionsEnum = termsEnum.docsAndPositions(liveDocs, (DocsAndPositionsEnum) prevDocsEnum, flags);
      docsEnum = threadState.reuseDocsAndPositionsEnum;
      docsAndPositionsEnum = threadState.reuseDocsAndPositionsEnum;
    }

    assertNotNull("null DocsEnum", docsEnum);
    int initialDocID = docsEnum.docID();
    assertTrue("inital docID should be -1 or NO_MORE_DOCS: " + docsEnum, initialDocID == -1 || initialDocID == DocsEnum.NO_MORE_DOCS);

    if (VERBOSE) {
      if (prevDocsEnum == null) {
        System.out.println("  got enum=" + docsEnum);
      } else if (prevDocsEnum == docsEnum) {
        System.out.println("  got reuse enum=" + docsEnum);
      } else {
        System.out.println("  got enum=" + docsEnum + " (reuse of " + prevDocsEnum + " failed)");
      }
    }

    // 10% of the time don't consume all docs:
    int stopAt;
    if (!alwaysTestMax && options.contains(Option.PARTIAL_DOC_CONSUME) && expected.docFreq > 1 && random().nextInt(10) == 7) {
      stopAt = random().nextInt(expected.docFreq-1);
      if (VERBOSE) {
        System.out.println("  will not consume all docs (" + stopAt + " vs " + expected.docFreq + ")");
      }
    } else {
      stopAt = expected.docFreq;
      if (VERBOSE) {
        System.out.println("  consume all docs");
      }
    }

    double skipChance = alwaysTestMax ? 0.5 : random().nextDouble();
    int numSkips = expected.docFreq < 3 ? 1 : _TestUtil.nextInt(random(), 1, Math.min(20, expected.docFreq/3));
    int skipInc = expected.docFreq/numSkips;
    int skipDocInc = maxDoc/numSkips;

    // Sometimes do 100% skipping:
    boolean doAllSkipping = options.contains(Option.SKIPPING) && random().nextInt(7) == 1;

    double freqAskChance = alwaysTestMax ? 1.0 : random().nextDouble();
    double payloadCheckChance = alwaysTestMax ? 1.0 : random().nextDouble();
    double offsetCheckChance = alwaysTestMax ? 1.0 : random().nextDouble();

    if (VERBOSE) {
      if (options.contains(Option.SKIPPING)) {
        System.out.println("  skipChance=" + skipChance + " numSkips=" + numSkips);
      } else {
        System.out.println("  no skipping");
      }
      if (doCheckFreqs) {
        System.out.println("  freqAskChance=" + freqAskChance);
      }
      if (doCheckPayloads) {
        System.out.println("  payloadCheckChance=" + payloadCheckChance);
      }
      if (doCheckOffsets) {
        System.out.println("  offsetCheckChance=" + offsetCheckChance);
      }
    }

    while (expected.upto <= stopAt) {
      if (expected.upto == stopAt) {
        if (stopAt == expected.docFreq) {
          assertEquals("DocsEnum should have ended but didn't", DocsEnum.NO_MORE_DOCS, docsEnum.nextDoc());

          // Common bug is to forget to set this.doc=NO_MORE_DOCS in the enum!:
          assertEquals("DocsEnum should have ended but didn't", DocsEnum.NO_MORE_DOCS, docsEnum.docID());
        }
        break;
      }

      if (options.contains(Option.SKIPPING) && (doAllSkipping || random().nextDouble() <= skipChance)) {
        int targetDocID = -1;
        if (expected.upto < stopAt && random().nextBoolean()) {
          // Pick target we know exists:
          final int skipCount = _TestUtil.nextInt(random(), 1, skipInc);
          for(int skip=0;skip<skipCount;skip++) {
            if (expected.nextDoc() == DocsEnum.NO_MORE_DOCS) {
              break;
            }
          }
        } else {
          // Pick random target (might not exist):
          final int skipDocIDs = _TestUtil.nextInt(random(), 1, skipDocInc);
          if (skipDocIDs > 0) {
            targetDocID = expected.docID() + skipDocIDs;
            expected.advance(targetDocID);
          }
        }

        if (expected.upto >= stopAt) {
          int target = random().nextBoolean() ? maxDoc : DocsEnum.NO_MORE_DOCS;
          if (VERBOSE) {
            System.out.println("  now advance to end (target=" + target + ")");
          }
          assertEquals("DocsEnum should have ended but didn't", DocsEnum.NO_MORE_DOCS, docsEnum.advance(target));
          break;
        } else {
          if (VERBOSE) {
            if (targetDocID != -1) {
              System.out.println("  now advance to random target=" + targetDocID + " (" + expected.upto + " of " + stopAt + ") current=" + docsEnum.docID());
            } else {
              System.out.println("  now advance to known-exists target=" + expected.docID() + " (" + expected.upto + " of " + stopAt + ") current=" + docsEnum.docID());
            }
          }
          int docID = docsEnum.advance(targetDocID != -1 ? targetDocID : expected.docID());
          assertEquals("docID is wrong", expected.docID(), docID);
        }
      } else {
        expected.nextDoc();
        if (VERBOSE) {
          System.out.println("  now nextDoc to " + expected.docID() + " (" + expected.upto + " of " + stopAt + ")");
        }
        int docID = docsEnum.nextDoc();
        assertEquals("docID is wrong", expected.docID(), docID);
        if (docID == DocsEnum.NO_MORE_DOCS) {
          break;
        }
      }

      if (doCheckFreqs && random().nextDouble() <= freqAskChance) {
        if (VERBOSE) {
          System.out.println("    now freq()=" + expected.freq());
        }
        int freq = docsEnum.freq();
        assertEquals("freq is wrong", expected.freq(), freq);
      }

      if (doCheckPositions) {
        int freq = docsEnum.freq();
        int numPosToConsume;
        if (!alwaysTestMax && options.contains(Option.PARTIAL_POS_CONSUME) && random().nextInt(5) == 1) {
          numPosToConsume = random().nextInt(freq);
        } else {
          numPosToConsume = freq;
        }

        for(int i=0;i<numPosToConsume;i++) {
          int pos = expected.nextPosition();
          if (VERBOSE) {
            System.out.println("    now nextPosition to " + pos);
          }
          assertEquals("position is wrong", pos, docsAndPositionsEnum.nextPosition());

          if (doCheckPayloads) {
            BytesRef expectedPayload = expected.getPayload();
            if (random().nextDouble() <= payloadCheckChance) {
              if (VERBOSE) {
                System.out.println("      now check expectedPayload length=" + (expectedPayload == null ? 0 : expectedPayload.length));
              }
              if (expectedPayload == null || expectedPayload.length == 0) {
                assertNull("should not have payload", docsAndPositionsEnum.getPayload());
              } else {
                BytesRef payload = docsAndPositionsEnum.getPayload();
                assertNotNull("should have payload but doesn't", payload);

                assertEquals("payload length is wrong", expectedPayload.length, payload.length);
                for(int byteUpto=0;byteUpto<expectedPayload.length;byteUpto++) {
                  assertEquals("payload bytes are wrong",
                               expectedPayload.bytes[expectedPayload.offset + byteUpto],
                               payload.bytes[payload.offset+byteUpto]);
                }

                // make a deep copy
                payload = BytesRef.deepCopyOf(payload);
                assertEquals("2nd call to getPayload returns something different!", payload, docsAndPositionsEnum.getPayload());
              }
            } else {
              if (VERBOSE) {
                System.out.println("      skip check payload length=" + (expectedPayload == null ? 0 : expectedPayload.length));
              }
            }
          }

          if (doCheckOffsets) {
            if (random().nextDouble() <= offsetCheckChance) {
              if (VERBOSE) {
                System.out.println("      now check offsets: startOff=" + expected.startOffset() + " endOffset=" + expected.endOffset());
              }
              assertEquals("startOffset is wrong", expected.startOffset(), docsAndPositionsEnum.startOffset());
              assertEquals("endOffset is wrong", expected.endOffset(), docsAndPositionsEnum.endOffset());
            } else {
              if (VERBOSE) {
                System.out.println("      skip check offsets");
              }
            }
          } else if (fieldInfo.getIndexOptions().compareTo(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS) < 0) {
            if (VERBOSE) {
              System.out.println("      now check offsets are -1");
            }
            assertEquals("startOffset isn't -1", -1, docsAndPositionsEnum.startOffset());
            assertEquals("endOffset isn't -1", -1, docsAndPositionsEnum.endOffset());
          }
        }
      }
    }
  }

  private static class TestThread extends Thread {
    private Fields fieldsSource;
    private EnumSet<Option> options;
    private IndexOptions maxIndexOptions;
    private IndexOptions maxTestOptions;
    private boolean alwaysTestMax;
    private BasePostingsFormatTestCase testCase;

    public TestThread(BasePostingsFormatTestCase testCase, Fields fieldsSource, EnumSet<Option> options, IndexOptions maxTestOptions,
                      IndexOptions maxIndexOptions, boolean alwaysTestMax) {
      this.fieldsSource = fieldsSource;
      this.options = options;
      this.maxTestOptions = maxTestOptions;
      this.maxIndexOptions = maxIndexOptions;
      this.alwaysTestMax = alwaysTestMax;
      this.testCase = testCase;
    }

    @Override
    public void run() {
      try {
        try {
          testCase.testTermsOneThread(fieldsSource, options, maxTestOptions, maxIndexOptions, alwaysTestMax);
        } catch (Throwable t) {
          throw new RuntimeException(t);
        }
      } finally {
        fieldsSource = null;
        testCase = null;
      }
    }
  }

  private void testTerms(final Fields fieldsSource, final EnumSet<Option> options,
                         final IndexOptions maxTestOptions,
                         final IndexOptions maxIndexOptions,
                         final boolean alwaysTestMax) throws Exception {

    if (options.contains(Option.THREADS)) {
      int numThreads = _TestUtil.nextInt(random(), 2, 5);
      Thread[] threads = new Thread[numThreads];
      for(int threadUpto=0;threadUpto<numThreads;threadUpto++) {
        threads[threadUpto] = new TestThread(this, fieldsSource, options, maxTestOptions, maxIndexOptions, alwaysTestMax);
        threads[threadUpto].start();
      }
      for(int threadUpto=0;threadUpto<numThreads;threadUpto++) {
        threads[threadUpto].join();
      }
    } else {
      testTermsOneThread(fieldsSource, options, maxTestOptions, maxIndexOptions, alwaysTestMax);
    }
  }

  private void testTermsOneThread(Fields fieldsSource, EnumSet<Option> options,
                                  IndexOptions maxTestOptions,
                                  IndexOptions maxIndexOptions, boolean alwaysTestMax) throws IOException {

    ThreadState threadState = new ThreadState();

    // Test random terms/fields:
    List<TermState> termStates = new ArrayList<TermState>();
    List<FieldAndTerm> termStateTerms = new ArrayList<FieldAndTerm>();

    Collections.shuffle(allTerms, random());
    int upto = 0;
    while (upto < allTerms.size()) {

      boolean useTermState = termStates.size() != 0 && random().nextInt(5) == 1;
      FieldAndTerm fieldAndTerm;
      TermsEnum termsEnum;

      TermState termState = null;

      if (!useTermState) {
        // Seek by random field+term:
        fieldAndTerm = allTerms.get(upto++);
        if (VERBOSE) {
          System.out.println("\nTEST: seek to term=" + fieldAndTerm.field + ":" + fieldAndTerm.term.utf8ToString() );
        }
      } else {
        // Seek by previous saved TermState
        int idx = random().nextInt(termStates.size());
        fieldAndTerm = termStateTerms.get(idx);
        if (VERBOSE) {
          System.out.println("\nTEST: seek using TermState to term=" + fieldAndTerm.field + ":" + fieldAndTerm.term.utf8ToString());
        }
        termState = termStates.get(idx);
      }

      Terms terms = fieldsSource.terms(fieldAndTerm.field);
      assertNotNull(terms);
      termsEnum = terms.iterator(null);

      if (!useTermState) {
        assertTrue(termsEnum.seekExact(fieldAndTerm.term, true));
      } else {
        termsEnum.seekExact(fieldAndTerm.term, termState);
      }

      boolean savedTermState = false;

      if (options.contains(Option.TERM_STATE) && !useTermState && random().nextInt(5) == 1) {
        // Save away this TermState:
        termStates.add(termsEnum.termState());
        termStateTerms.add(fieldAndTerm);
        savedTermState = true;
      }

      verifyEnum(threadState,
                 fieldAndTerm.field,
                 fieldAndTerm.term,
                 termsEnum,
                 maxTestOptions,
                 maxIndexOptions,
                 options,
                 alwaysTestMax);

      // Sometimes save term state after pulling the enum:
      if (options.contains(Option.TERM_STATE) && !useTermState && !savedTermState && random().nextInt(5) == 1) {
        // Save away this TermState:
        termStates.add(termsEnum.termState());
        termStateTerms.add(fieldAndTerm);
        useTermState = true;
      }

      // 10% of the time make sure you can pull another enum
      // from the same term:
      if (alwaysTestMax || random().nextInt(10) == 7) {
        // Try same term again
        if (VERBOSE) {
          System.out.println("TEST: try enum again on same term");
        }

        verifyEnum(threadState,
                   fieldAndTerm.field,
                   fieldAndTerm.term,
                   termsEnum,
                   maxTestOptions,
                   maxIndexOptions,
                   options,
                   alwaysTestMax);
      }
    }
  }

  private void testFields(Fields fields) throws Exception {
    Iterator<String> iterator = fields.iterator();
    while (iterator.hasNext()) {
      iterator.next();
      try {
        iterator.remove();
        fail("Fields.iterator() allows for removal");
      } catch (UnsupportedOperationException expected) {
        // expected;
      }
    }
    assertFalse(iterator.hasNext());
    try {
      iterator.next();
      fail("Fields.iterator() doesn't throw NoSuchElementException when past the end");
    } catch (NoSuchElementException expected) {
      // expected
    }
  }

  /** Indexes all fields/terms at the specified
   *  IndexOptions, and fully tests at that IndexOptions. */
  private void testFull(IndexOptions options, boolean withPayloads) throws Exception {
    File path = _TestUtil.getTempDir("testPostingsFormat.testExact");
    Directory dir = newFSDirectory(path);

    // TODO test thread safety of buildIndex too
    FieldsProducer fieldsProducer = buildIndex(dir, options, withPayloads, true);

    testFields(fieldsProducer);

    IndexOptions[] allOptions = IndexOptions.values();
    int maxIndexOption = Arrays.asList(allOptions).indexOf(options);

    for(int i=0;i<=maxIndexOption;i++) {
      testTerms(fieldsProducer, EnumSet.allOf(Option.class), allOptions[i], options, true);
      if (withPayloads) {
        // If we indexed w/ payloads, also test enums w/o accessing payloads:
        testTerms(fieldsProducer, EnumSet.complementOf(EnumSet.of(Option.PAYLOADS)), allOptions[i], options, true);
      }
    }

    fieldsProducer.close();
    dir.close();
    _TestUtil.rmDir(path);
  }

  public void testDocsOnly() throws Exception {
    testFull(IndexOptions.DOCS_ONLY, false);
  }

  public void testDocsAndFreqs() throws Exception {
    testFull(IndexOptions.DOCS_AND_FREQS, false);
  }

  public void testDocsAndFreqsAndPositions() throws Exception {
    testFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, false);
  }

  public void testDocsAndFreqsAndPositionsAndPayloads() throws Exception {
    testFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS, true);
  }

  public void testDocsAndFreqsAndPositionsAndOffsets() throws Exception {
    testFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, false);
  }

  public void testDocsAndFreqsAndPositionsAndOffsetsAndPayloads() throws Exception {
    testFull(IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, true);
  }

  public void testRandom() throws Exception {

    int iters = 5;

    for(int iter=0;iter<iters;iter++) {
      File path = _TestUtil.getTempDir("testPostingsFormat");
      Directory dir = newFSDirectory(path);

      boolean indexPayloads = random().nextBoolean();
      // TODO test thread safety of buildIndex too
      FieldsProducer fieldsProducer = buildIndex(dir, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, indexPayloads, false);

      testFields(fieldsProducer);

      // NOTE: you can also test "weaker" index options than
      // you indexed with:
      testTerms(fieldsProducer, EnumSet.allOf(Option.class), IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS, false);

      fieldsProducer.close();
      fieldsProducer = null;

      dir.close();
      _TestUtil.rmDir(path);
    }
  }
}


text:
#pragma once
#include <aws/cloudformation/CloudFormation_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/cloudformation/model/StackStatus.h>

namespace Aws
{
namespace Utils
{
namespace Xml
{
  class XmlNode;
} // namespace Xml
} // namespace Utils
namespace CloudFormation
{
namespace Model
{
  /*

The StackSummary Data Type

  */
  class AWS_CLOUDFORMATION_API StackSummary
  {
  public:
    StackSummary();
    StackSummary(const Aws::Utils::Xml::XmlNode& xmlNode);
    StackSummary& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);

    void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
    void OutputToStream(Aws::OStream& oStream, const char* location) const;

    /*

Unique stack identifier.

    */
    inline const Aws::String& GetStackId() const{ return m_stackId; }

    /*

Unique stack identifier.

    */
    inline void SetStackId(const Aws::String& value) { m_stackIdHasBeenSet = true; m_stackId = value; }

    /*

Unique stack identifier.

    */
    inline void SetStackId(Aws::String&& value) { m_stackIdHasBeenSet = true; m_stackId = value; }

    /*

Unique stack identifier.

    */
    inline void SetStackId(const char* value) { m_stackIdHasBeenSet = true; m_stackId.assign(value); }

    /*

Unique stack identifier.

    */
    inline StackSummary& WithStackId(const Aws::String& value) { SetStackId(value); return *this;}

    /*

Unique stack identifier.

    */
    inline StackSummary& WithStackId(Aws::String&& value) { SetStackId(value); return *this;}

    /*

Unique stack identifier.

    */
    inline StackSummary& WithStackId(const char* value) { SetStackId(value); return *this;}

    /*

The name associated with the stack.

    */
    inline const Aws::String& GetStackName() const{ return m_stackName; }

    /*

The name associated with the stack.

    */
    inline void SetStackName(const Aws::String& value) { m_stackNameHasBeenSet = true; m_stackName = value; }

    /*

The name associated with the stack.

    */
    inline void SetStackName(Aws::String&& value) { m_stackNameHasBeenSet = true; m_stackName = value; }

    /*

The name associated with the stack.

    */
    inline void SetStackName(const char* value) { m_stackNameHasBeenSet = true; m_stackName.assign(value); }

    /*

The name associated with the stack.

    */
    inline StackSummary& WithStackName(const Aws::String& value) { SetStackName(value); return *this;}

    /*

The name associated with the stack.

    */
    inline StackSummary& WithStackName(Aws::String&& value) { SetStackName(value); return *this;}

    /*

The name associated with the stack.

    */
    inline StackSummary& WithStackName(const char* value) { SetStackName(value); return *this;}

    /*

The template description of the template used to create the stack.

    */
    inline const Aws::String& GetTemplateDescription() const{ return m_templateDescription; }

    /*

The template description of the template used to create the stack.

    */
    inline void SetTemplateDescription(const Aws::String& value) { m_templateDescriptionHasBeenSet = true; m_templateDescription = value; }

    /*

The template description of the template used to create the stack.

    */
    inline void SetTemplateDescription(Aws::String&& value) { m_templateDescriptionHasBeenSet = true; m_templateDescription = value; }

    /*

The template description of the template used to create the stack.

    */
    inline void SetTemplateDescription(const char* value) { m_templateDescriptionHasBeenSet = true; m_templateDescription.assign(value); }

    /*

The template description of the template used to create the stack.

    */
    inline StackSummary& WithTemplateDescription(const Aws::String& value) { SetTemplateDescription(value); return *this;}

    /*

The template description of the template used to create the stack.

    */
    inline StackSummary& WithTemplateDescription(Aws::String&& value) { SetTemplateDescription(value); return *this;}

    /*

The template description of the template used to create the stack.

    */
    inline StackSummary& WithTemplateDescription(const char* value) { SetTemplateDescription(value); return *this;}

    /*

The time the stack was created.

    */
    inline double GetCreationTime() const{ return m_creationTime; }

    /*

The time the stack was created.

    */
    inline void SetCreationTime(double value) { m_creationTimeHasBeenSet = true; m_creationTime = value; }

    /*

The time the stack was created.

    */
    inline StackSummary& WithCreationTime(double value) { SetCreationTime(value); return *this;}

    /*

The time the stack was last updated. This field will only be returned if the stack has been updated at least once.

    */
    inline double GetLastUpdatedTime() const{ return m_lastUpdatedTime; }

    /*

The time the stack was last updated. This field will only be returned if the stack has been updated at least once.

    */
    inline void SetLastUpdatedTime(double value) { m_lastUpdatedTimeHasBeenSet = true; m_lastUpdatedTime = value; }

    /*

The time the stack was last updated. This field will only be returned if the stack has been updated at least once.

    */
    inline StackSummary& WithLastUpdatedTime(double value) { SetLastUpdatedTime(value); return *this;}

    /*

The time the stack was deleted.

    */
    inline double GetDeletionTime() const{ return m_deletionTime; }

    /*

The time the stack was deleted.

    */
    inline void SetDeletionTime(double value) { m_deletionTimeHasBeenSet = true; m_deletionTime = value; }

    /*

The time the stack was deleted.

    */
    inline StackSummary& WithDeletionTime(double value) { SetDeletionTime(value); return *this;}

    /*

The current status of the stack.

    */
    inline const StackStatus& GetStackStatus() const{ return m_stackStatus; }

    /*

The current status of the stack.

    */
    inline void SetStackStatus(const StackStatus& value) { m_stackStatusHasBeenSet = true; m_stackStatus = value; }

    /*

The current status of the stack.

    */
    inline void SetStackStatus(StackStatus&& value) { m_stackStatusHasBeenSet = true; m_stackStatus = value; }

    /*

The current status of the stack.

    */
    inline StackSummary& WithStackStatus(const StackStatus& value) { SetStackStatus(value); return *this;}

    /*

The current status of the stack.

    */
    inline StackSummary& WithStackStatus(StackStatus&& value) { SetStackStatus(value); return *this;}

    /*

Success/Failure message associated with the stack status.

    */
    inline const Aws::String& GetStackStatusReason() const{ return m_stackStatusReason; }

    /*

Success/Failure message associated with the stack status.

    */
    inline void SetStackStatusReason(const Aws::String& value) { m_stackStatusReasonHasBeenSet = true; m_stackStatusReason = value; }

    /*

Success/Failure message associated with the stack status.

    */
    inline void SetStackStatusReason(Aws::String&& value) { m_stackStatusReasonHasBeenSet = true; m_stackStatusReason = value; }

    /*

Success/Failure message associated with the stack status.

    */
    inline void SetStackStatusReason(const char* value) { m_stackStatusReasonHasBeenSet = true; m_stackStatusReason.assign(value); }

    /*

Success/Failure message associated with the stack status.

    */
    inline StackSummary& WithStackStatusReason(const Aws::String& value) { SetStackStatusReason(value); return *this;}

    /*

Success/Failure message associated with the stack status.

    */
    inline StackSummary& WithStackStatusReason(Aws::String&& value) { SetStackStatusReason(value); return *this;}

    /*

Success/Failure message associated with the stack status.

    */
    inline StackSummary& WithStackStatusReason(const char* value) { SetStackStatusReason(value); return *this;}

  private:
    Aws::String m_stackId;
    bool m_stackIdHasBeenSet;
    Aws::String m_stackName;
    bool m_stackNameHasBeenSet;
    Aws::String m_templateDescription;
    bool m_templateDescriptionHasBeenSet;
    double m_creationTime;
    bool m_creationTimeHasBeenSet;
    double m_lastUpdatedTime;
    bool m_lastUpdatedTimeHasBeenSet;
    double m_deletionTime;
    bool m_deletionTimeHasBeenSet;
    StackStatus m_stackStatus;
    bool m_stackStatusHasBeenSet;
    Aws::String m_stackStatusReason;
    bool m_stackStatusReasonHasBeenSet;
  };

} // namespace Model
} // namespace CloudFormation
} // namespace Aws


text:
var Class  = require('js-class'),
    elements = require('evo-elements'),
    CliBase = elements.Cli,
    Config  = elements.Config,
    Logger  = elements.Logger;

var Cli = Class(CliBase, {
    constructor: function () {
        CliBase.prototype.constructor.call(this, 'pcloud');
        this.services = components.services;
        this.logdir = '/var/log/cloud';
        this.rundir = '/var/run/cloud';
        this.datdir = '/var/lib/cloud';
        this.cfgdir = '/etc/cloud.d';

        this.options
            .option('logdir', {
                type: 'string',
                default: this.logdir,
                help: 'Directory for log files',
                callback: function (val) {
                    this.logdir = val;
                }.bind(this)
            })
            .option('loglevel', {
                type: 'string',
                default: 'notice',
                help: 'Set log level with --logdir specified',
                callback: function (val) {
                    this.loglevel = val;
                }.bind(this)
            })
            .option('rundir', {
                type: 'string',
                default: this.rundir,
                help: 'Directory for runtime files',
                callback: function (val) {
                    this.rundir = val;
                }.bind(this)
            })
            .option('datadir', {
                type: 'string',
                default: this.datdir,
                help: 'Directory for data files',
                callback: function (val) {
                    this.datdir = val;
                }.bind(this)
            })
            .option('confdir', {
                type: 'string',
                default: this.cfgdir,
                help: 'Directory for configuration files',
                callback: function (val) {
                    this.cfgdir = val;
                }.bind(this)
            })
        ;
    }
});

module.exports = Cli;


text:
import Ember from 'ember';
import { module, test } from 'qunit';
import startApp from '../../helpers/start-app';

export function executeTest(testName, callback) {
  let app;
  let store;
  let userSettingsService;

  module('Acceptance | flexberry-validation | ' + testName, {
    beforeEach() {

      // Start application.
      app = startApp();

      // Enable acceptance test mode in application controller (to hide unnecessary markup from application.hbs).
      let applicationController = app.__container__.lookup('controller:application');
      applicationController.set('isInAcceptanceTestMode', true);
      store = app.__container__.lookup('service:store');

      userSettingsService = app.__container__.lookup('service:user-settings');
      let getCurrentPerPage = function() {
        return 5;
      };

      userSettingsService.set('getCurrentPerPage', getCurrentPerPage);
    },

    afterEach() {
      Ember.run(app, 'destroy');
      let daterangepicker = Ember.$('.daterangepicker');
      daterangepicker.remove();
    }
  });

  test(testName, (assert) => callback(store, assert, app));
}


text:
{% extends "base.html" %}
{% block description %}The Tags page lists all tags used to classify the posts. Each post has at least one tag helping readers find out easily what they are looking for.{% endblock %}
{% block title %}Tags — {{ SITENAME }}{% endblock %}
{% block head %}

{% endblock %}
{% block content %}

Tags

	{% for tag in tag_cloud %}

{{ tag.0 }}

	{% endfor %}

{% endblock %}