text:
<?php
/*
 * This work is hereby released into the Public Domain.
 * To view a copy of the public domain dedication,
 * visit http://creativecommons.org/licenses/publicdomain/ or send a letter to
 * Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.
 *
 */

require_once dirname(__FILE__)."/../Graph.class.php";

/**
 * To handle text
 *
 * @package Artichow
 */
class awText {

	/**
	 * Your text
	 *
	 * @var string
	 */
	private $text;

	/**
	 * Text font
	 *
	 * @var Font
	 */
	private $font;

	/**
	 * Text angle
	 * Can be 0 or 90
	 *
	 * @var int
	 */
	private $angle;

	/**
	 * Text color
	 *
	 * @var Color
	 */
	private $color;

	/**
	 * Text background
	 *
	 * @var Color, Gradient
	 */
	private $background;

	/**
	 * Padding
	 *
	 * @var array Array for left, right, top and bottom paddings
	 */
	private $padding;

	/**
	 * Text border
	 *
	 * @var Border
	 */
	public $border;

	/**
	 * Build a new awtext
	 *
	 * @param string $text Your text
	 */
	public function __construct($text, $font = NULL, $color = NULL, $angle = 0) {

		if(is_null($font)) {
			$font = new awFont2;
		}

		$this->setText($text);
		$this->setFont($font);

		// Set default color to black
		if($color === NULL) {
			$color = new awColor(0, 0, 0);
		}

		$this->setColor($color);
		$this->setAngle($angle);

		$this->border = new awBorder;
		$this->border->hide();

	}

	/**
	 * Get text
	 *
	 * @return string
	 */
	public function getText() {
		return $this->text;
	}

	/**
	 * Change text
	 *
	 * @param string $text New text
	 */
	public function setText($text) {
		$this->text = (string)$text;
		$this->text = str_replace("\r", "", $text);
	}

	/**
	 * Change text font
	 *
	 * @param Font
	 */
	public function setFont(awFont $font) {
		$this->font = $font;
	}

	/**
	 * Get text font
	 *
	 * @return int
	 */
	public function getFont() {
		return $this->font;
	}

	/**
	 * Change text angle
	 *
	 * @param int
	 */
	public function setAngle($angle) {
		$this->angle = (int)$angle;
	}

	/**
	 * Get text angle
	 *
	 * @return int
	 */
	public function getAngle() {
		return $this->angle;
	}

	/**
	 * Change text color
	 *
	 * @param Color
	 */
	public function setColor(awColor $color) {
		$this->color = $color;
	}

	/**
	 * Get text color
	 *
	 * @return Color
	 */
	public function getColor() {
		return $this->color;
	}

	/**
	 * Change text background
	 *
	 * @param mixed $background
	 */
	public function setBackground($background) {
		if($background instanceof awColor) {
			$this->setBackgroundColor($background);
		} elseif($background instanceof awGradient) {
			$this->setBackgroundGradient($background);
		}
	}

	/**
	 * Change text background color
	 *
	 * @param awColor $color
	 */
	public function setBackgroundColor(awColor $color) {
		$this->background = $color;
	}

	/**
	 * Change text background gradient
	 *
	 * @param awGradient $gradient
	 */
	public function setBackgroundGradient(awGradient $gradient) {
		$this->background = $gradient;
	}

	/**
	 * Get text background
	 *
	 * @return Color, Gradient
	 */
	public function getBackground() {
		return $this->background;
	}

	/**
	 * Change padding
	 *
	 * @param int $left Left padding
	 * @param int $right Right padding
	 * @param int $top Top padding
	 * @param int $bottom Bottom padding
	 */
	public function setPadding($left, $right, $top, $bottom) {
		$this->padding = array((int)$left, (int)$right, (int)$top, (int)$bottom);
	}

	/**
	 * Get current padding
	 *
	 * @return array
	 */
	public function getPadding() {
		return $this->padding;
	}

}

registerClass('Text');


text:
This project contains some very old code that does not reflect my standards anymore. I will be leaving
the project in an archived state in case it is still useful to someone.

[![Build Status](https://travis-ci.org/AkiKanellis/kata01-supermarket-pricing.svg?branch=develop)](https://travis-ci.org/AkiKanellis/kata01-supermarket-pricing)
# Kata01: Supermarket Pricing
A solution to [Kata01: Supermarket Pricing](http://codekata.com/kata/kata01-supermarket-pricing).

## Download
Download [the latest JAR][1].

## User stories
The Kata's description is fairly vague giving us the freedom to define the user stories as we see fit. We assume that
the supermarket has a stock of items that needs to be managed and that the *user* is the Stock Manager. Given that, our
user stories are like so:

 1. As a Stock Manager user, I can add a new item to the stock.
 - As a Stock Manager user, I can increase the quantity of an item so that I can update it in the arrival of more stock.
 - As a Stock Manager user, I can decrease the quantity of an item so that I can update it in the sale of stock.
 - As a Stock Manager user, I can see all the items in the stock.
 - As a Stock Manager user, I can add a new offer strategy for the stock so that the customers can have more discounts.
 - As a Stock Manager user, I can remove an offer strategy from the stock so that I can limit the customers' discounts.
 - As a Stock Manager user, I can see all the current offer strategies.
 - As a Stock Manager user, I can see all the applicable offers to the stock.
 - As a Stock Manager user, I can see the total value of the offers that are currently applicable.
 - As a Stock Manager user, I can see the total value of the stock, before the offers.
 - As a Stock Manager user, I can see the total value of the stock, after the offers.

## Design

### Architecture
The design of the supermarket follows a 3-layer [Clean Architecture](https://8thlight.com/blog/uncle-bob/2012/08/13/the-clean-architecture.html), the layers are:

- **Entities**, which includes our business POJOs and the repository contracts (interfaces).
- **Use Case**, with the main business rules of our application. Each Use Case maps to a user story.
- **Frameworks & Drivers**, where the concrete implementation of our repositories reside.

The repositories are implemented as in-memory repositories. If we were to implement them using persistence (like a
database) and we were to implement a UI (like a console application) then we could use two additional layers:

- **Interface adapters**, for converting the database rows to business entities and the business entities to View Models.
- **Presentation**, where the View Models are presented to the view. Preferably by leveraging a Design Pattern such as
Model-View-Presenter (MVP).

### Packaging
A [Package-By-Feature](http://www.javapractices.com/topic/TopicAction.do?Id=205) type of packaging is used.

### Branching model
The branching model used is [GitFlow](http://nvie.com/posts/a-successful-git-branching-model/).

### Notes
This project was made to be simple, readable and maintainable. To achieve that certain decisions have been made:

- There is no Dependency Injection framework used. If we were to create a production ready supermarket, then we would
  use a Dependency Injection framework such as [Dagger 2](https://google.github.io/dagger/). By taking advantage of such a framework we could reduce
  the visibility of certain internal classes (like the repository implementations) and we could also easily establish whichever
  resources we want as singletons.
- The supermarket does not support asynchronous operations, something that a real one should. This could be achieved
  by using a Reactive Extensions framework such as [RxJava](https://github.com/ReactiveX/RxJava) to manage multiple asynchronous streams. Additionally, we
  would have to make sure our reads and writes to the repositories are synchronized.
- All repositories are in-memory, meaning that no state is persisted. We would have to change that by making database
  implementations of the repositories.

## Modules

### Supermarket module
The supermarket can be found in the [supermarket module](supermarket).

### Scripts
If you want to build the whole project, run all the tests and the code analysis tools then run the file:

`scripts/build.sh`

## Libraries

### Production

#### [AutoValue](https://github.com/google/auto)
AutoValue provides us with an easy way to write immutable POJOs with generated `equals`, `hashcode` and `toString`
methods. It also provides a painless way to implement the Builder Pattern. These advantages allow us to have the
boilerplate code generated for us which lets us focus on the features we want to provide to the user.

### Testing

#### [JUnit](http://junit.org/junit4/)
The de facto framework when it comes to testing in Java. We use JUnit for both Unit and Integration testing.

#### [Mockito](http://site.mockito.org/)
This gives us a versatile and easy to use API for creating mocks, stubs and fakes for our tests. It makes the tests
very readable and easy to change.

#### [AssertJ](http://joel-costigliola.github.io/assertj/)
Provides a fluent API for assertions with better error messages than the default ones. The tests are more readable
and easy to understand.

#### [EqualsVerifier](http://jqno.nl/equalsverifier/)
An extensive tester for verifying whether the `equals` and `hashcode` contracts in a class are met.

### Code analysis

#### [CheckStyle](http://checkstyle.sourceforge.net/)
A tool for making sure our Java code adheres to the coding standard that has been defined. The coding standard used is
the Oracle standard along with some modifications.

#### [FindBugs](http://findbugs.sourceforge.net/)
A static analysis tool for finding bugs in Java code by analysing the generated bytecode.

#### [PMD](https://pmd.github.io/)
Same as FindBugs but works on the source code.

#### [Travis CI](https://travis-ci.org/)
Our Continuous Integration server for making sure errors are detected before they are merged.

## REST API
Instead of only having the backend exposed internally, we could expose it through a REST API.

Assuming that our supermarket's website is *supermarket.com* and we are in version v1.0, then the REST API could look
like this:

### Root
`api.supermarket.com`

### Stock
`api.supermarket.com/1.0/stock`

### Main Resources

- `/items`
- `/offerstrategies`
- `/applicableoffers`

### Supported verbs

#### For `/items`

| Verb                                      | Description                   |
|-------------------------------------------|-------------------------------|
| **GET** `/items`                          | Get all items                 |
| **POST** `/items`                         | Create new item               |
| **PUT** `/items/<id>/increase/<quantity>` | Increase item quantity        |
| **PUT** `/items/<id>/decrease/<quantity>` | Decrease item quantity        |
| **GET** `/items/valuebeforeoffers`        | Get stock value before offers |
| **GET** `/items/valueafteroffers`         | Get stock value after offers  |

#### For `/offerstrategies`

| Verb                                  | Description               |
|---------------------------------------|---------------------------|
| **GET** `/offerstrategies`            | Get all offer strategies  |
| **POST** `/offerstrategies`           | Create new offer strategy |
| **DELETE** `/offerstrategies/<id>`    | Delete offer strategy     |

#### For `/applicableoffers`

| Verb                              | Description                   |
|-----------------------------------|-------------------------------|
| **GET** `/applicableoffers`       | Get all applicable offers     |
| **GET** `/applicableoffers/value` | Get applicable offers value   |

## License
This application itself is released under **MIT** license, see [LICENSE](./LICENSE).

All 3rd party open sourced libs distributed with this application are still under their own license.

[1]: https://github.com/AkiKanellis/kata01-supermarket-pricing/releases/download/v1.0/supermarket-1.0.jar

redpajama_set_name: RedPajamaGithub


text:
/*	$NetBSD: filter.c,v 1.15 2009/08/13 05:53:58 dholland Exp $	*/

/*
 * Copyright (c) 1980, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <sys/cdefs.h>
#ifndef lint
#if 0
static char sccsid[] = "@(#)filter.c	8.1 (Berkeley) 6/6/93";
#endif
__RCSID("$NetBSD: filter.c,v 1.15 2009/08/13 05:53:58 dholland Exp $");
#endif /* not lint */

#include <sys/param.h>
#include <pwd.h>
#include <unistd.h>
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include "error.h"
#include "pathnames.h"

static const char *lint_libs[] = {
	IG_FILE1,
	IG_FILE2,
	IG_FILE3,
	IG_FILE4,
	0
};

static int lexsort(const void *, const void *);
static int search_ignore(const char *);

/*
 * Read the file ERRORNAME of the names of functions in lint
 * to ignore complaints about.
 */
void
getignored(const char *auxname)
{
	int i;
	FILE *fyle;
	char inbuffer[256];
	uid_t uid;
	char filename[MAXPATHLEN];
	const char *username;
	struct passwd *passwdentry;

	nignored = 0;
	if (auxname == 0) {	/* use the default */
		if ((username = getlogin()) == NULL) {
			username = "Unknown";
			uid = getuid();
			if ((passwdentry = getpwuid(uid)) == NULL) {
				return;
			}
		} else {
			if ((passwdentry = getpwnam(username)) == NULL)
				return;
		}
		strlcpy(filename, passwdentry->pw_dir, sizeof(filename));
		(void)strlcat(filename, ERRORNAME, sizeof(filename));
	} else
		(void)strlcpy(filename, auxname, sizeof(filename));
#ifdef FULLDEBUG
	printf("Opening file \"%s\" to read names to ignore.\n",
		filename);
#endif
	if ((fyle = fopen(filename, "r")) == NULL) {
#ifdef FULLDEBUG
		fprintf(stderr, "%s: Can't open file \"%s\"\n",
			processname, filename);
#endif
		return;
	}

	/*
	 * Make the first pass through the file, counting lines
	 */
	for (nignored = 0;
	     fgets(inbuffer, sizeof(inbuffer)-1, fyle) != NULL; nignored++)
		continue;
	names_ignored = Calloc(nignored+1, sizeof (char *));
	fclose(fyle);
	if (freopen(filename, "r", fyle) == NULL) {
#ifdef FULLDEBUG
		fprintf(stderr, "%s: Failure to open \"%s\" for second read.\n",
			processname, filename);
#endif
		nignored = 0;
		return;
	}
	for (i=0; i < nignored &&
	          (fgets (inbuffer, sizeof(inbuffer)-1, fyle) != NULL); i++) {
		names_ignored[i] = strdup(inbuffer);
		(void)substitute(names_ignored[i], '\n', '\0');
	}
	qsort(names_ignored, nignored, sizeof *names_ignored, lexsort);
#ifdef FULLDEBUG
	printf("Names to ignore follow.\n");
	for (i=0; i < nignored; i++) {
		printf("\tIgnore: %s\n", names_ignored[i]);
	}
#endif
}

static int
lexsort(const void *c1, const void *c2)
{
	const char *const *cpp1;
	const char *const *cpp2;

	cpp1 = c1;
	cpp2 = c2;
	return (strcmp(*cpp1, *cpp2));
}

static int
search_ignore(const char *key)
{
	int ub, lb;
	int halfway;
	int order;

	if (nignored == 0)
		return (-1);
	for (lb = 0, ub = nignored - 1; ub >= lb; ) {
		halfway = (ub + lb)/2;
		if ( (order = strcmp(key, names_ignored[halfway])) == 0)
			return (halfway);
		if (order < 0)	/* key is less than probe, throw away above */
			ub = halfway - 1;
		 else
			lb = halfway + 1;
	}
	return (-1);
}

/*
 * Tell if the error text is to be ignored.
 * The error must have been canonicalized, with
 * the file name the zeroth entry in the errorv,
 * and the linenumber the second.
 * Return the new categorization of the error class.
 */
Errorclass
discardit(Eptr errorp)
{
	int i;
	Errorclass errorclass = errorp->error_e_class;

	switch (errorclass) {
		case C_SYNC:
		case C_NONSPEC:
		case C_UNKNOWN: return (errorclass);
		default:	;
	}
	if (errorp->error_lgtext < 2) {
		return (C_NONSPEC);
	}
	if (errorp->error_language == INLINT) {
		if (errorclass != C_NONSPEC) {	/* no file */
			for (i=0; lint_libs[i] != 0; i++) {
				if (strcmp(errorp->error_text[0], lint_libs[i]) == 0) {
					return (C_DISCARD);
				}
			}
		}
		/* check if the argument to the error message is to be ignored */
		if (ispunct((unsigned char)lastchar(errorp->error_text[2])))
			clob_last(errorp->error_text[2], '\0');
		if (search_ignore(errorp->error_text[errorclass == C_NONSPEC ? 0 : 2]) >= 0) {
			return (C_NULLED);
		}
	}
	return (errorclass);
}


text:
package net.cyanwool.platform.management;

public interface WhitelistManager extends UserManager {

}


text:
package vg

import (
	"errors"
	"io/ioutil"
	"path/filepath"
	"sync"

	"gonum.org/v1/plot/vg/fonts"

	"golang.org/x/image/math/fixed"

	"github.com/golang/freetype"
	"github.com/golang/freetype/truetype"
)

var (
	// FontMap maps Postscript/PDF font names to compatible
	// free fonts (TrueType converted ghostscript fonts).
	// Fonts that are not keys of this map are not supported.
	FontMap = map[string]string{

		// We use fonts from RedHat's Liberation project:
		//  https://fedorahosted.org/liberation-fonts/

		"Courier":             "LiberationMono-Regular",
		"Courier-Bold":        "LiberationMono-Bold",
		"Courier-Oblique":     "LiberationMono-Italic",
		"Courier-BoldOblique": "LiberationMono-BoldItalic",

		"Helvetica":             "LiberationSans-Regular",
		"Helvetica-Bold":        "LiberationSans-Bold",
		"Helvetica-Oblique":     "LiberationSans-Italic",
		"Helvetica-BoldOblique": "LiberationSans-BoldItalic",

		"Times-Roman":      "LiberationSerif-Regular",
		"Times-Bold":       "LiberationSerif-Bold",
		"Times-Italic":     "LiberationSerif-Italic",
		"Times-BoldItalic": "LiberationSerif-BoldItalic",
	}

	// loadedFonts is indexed by a font name and it
	// caches the associated *truetype.Font.
	loadedFonts = make(map[string]*truetype.Font)

	// FontLock protects access to the loadedFonts map.
	fontLock sync.RWMutex
)

// A Font represents one of the supported font
// faces.
type Font struct {
	// Size is the size of the font.  The font size can
	// be used as a reasonable value for the vertical
	// distance between two successive lines of text.
	Size Length

	// name is the name of this font.
	name string

	// This is a little bit of a hack, but the truetype
	// font is currently only needed to determine the
	// dimensions of strings drawn in this font.
	// The actual drawing of the strings is handled
	// separately by different back-ends:
	// Both Postscript and PDF are capable of drawing
	// their own fonts and draw2d loads its own copy of
	// the truetype fonts for its own output.
	//
	// This isn't a necessity--some future backend is
	// free to use this field--however it is a consequence
	// of the fact that the current backends were
	// developed independently of this package.

	// font is the truetype font pointer for this
	// font.
	font *truetype.Font
}

// MakeFont returns a font object.  The name of the font must
// be a key of the FontMap.  The font file is located by searching
// the FontDirs slice for a directory containing the relevant font
// file.  The font file name is name mapped by FontMap with the
// .ttf extension.  For example, the font file for the font name
// Courier is LiberationMono-Regular.ttf.
func MakeFont(name string, size Length) (font Font, err error) {
	font.Size = size
	font.name = name
	font.font, err = getFont(name)
	return
}

// Name returns the name of the font.
func (f *Font) Name() string {
	return f.name
}

// Font returns the corresponding truetype.Font.
func (f *Font) Font() *truetype.Font {
	return f.font
}

// SetName sets the name of the font, effectively
// changing the font.  If an error is returned then
// the font is left unchanged.
func (f *Font) SetName(name string) error {
	font, err := getFont(name)
	if err != nil {
		return err
	}
	f.name = name
	f.font = font
	return nil
}

// FontExtents contains font metric information.
type FontExtents struct {
	// Ascent is the distance that the text
	// extends above the baseline.
	Ascent Length

	// Descent is the distance that the text
	// extends below the baseline.  The descent
	// is given as a negative value.
	Descent Length

	// Height is the distance from the lowest
	// descending point to the highest ascending
	// point.
	Height Length
}

// Extents returns the FontExtents for a font.
func (f *Font) Extents() FontExtents {
	bounds := f.font.Bounds(fixed.Int26_6(f.Font().FUnitsPerEm()))
	scale := f.Size / Points(float64(f.Font().FUnitsPerEm()))
	return FontExtents{
		Ascent:  Points(float64(bounds.Max.Y)) * scale,
		Descent: Points(float64(bounds.Min.Y)) * scale,
		Height:  Points(float64(bounds.Max.Y-bounds.Min.Y)) * scale,
	}
}

// Width returns width of a string when drawn using the font.
func (f *Font) Width(s string) Length {
	// scale converts truetype.FUnit to float64
	scale := f.Size / Points(float64(f.font.FUnitsPerEm()))

	width := 0
	prev, hasPrev := truetype.Index(0), false
	for _, rune := range s {
		index := f.font.Index(rune)
		if hasPrev {
			width += int(f.font.Kern(fixed.Int26_6(f.font.FUnitsPerEm()), prev, index))
		}
		width += int(f.font.HMetric(fixed.Int26_6(f.font.FUnitsPerEm()), index).AdvanceWidth)
		prev, hasPrev = index, true
	}
	return Points(float64(width)) * scale
}

// AddFont associates a truetype.Font with the given name.
func AddFont(name string, font *truetype.Font) {
	fontLock.Lock()
	loadedFonts[name] = font
	fontLock.Unlock()
}

// getFont returns the truetype.Font for the given font name or an error.
func getFont(name string) (*truetype.Font, error) {
	fontLock.RLock()
	f, ok := loadedFonts[name]
	fontLock.RUnlock()
	if ok {
		return f, nil
	}

	bytes, err := fontData(name)
	if err != nil {
		return nil, err
	}

	font, err := freetype.ParseFont(bytes)
	if err == nil {
		fontLock.Lock()
		loadedFonts[name] = font
		fontLock.Unlock()
	} else {
		err = errors.New("Failed to parse font file: " + err.Error())
	}

	return font, err
}

// fontData returns the []byte data for a font name or an error if it is not found.
func fontData(name string) ([]byte, error) {
	fname, err := fontFile(name)
	if err != nil {
		return nil, err
	}

	for _, d := range FontDirs {
		p := filepath.Join(d, fname)
		data, err := ioutil.ReadFile(p)
		if err != nil {
			continue
		}
		return data, nil
	}

	data, err := fonts.Asset(fname)
	if err == nil {
		return data, nil
	}

	return nil, errors.New("vg: failed to locate a font file " + fname + " for font name " + name)
}

// FontDirs is a slice of directories searched for font data files.
// If the first font file found is unreadable or cannot be parsed, then
// subsequent directories are not tried, and the font will fail to load.
//
// The default slice contains, in the following order, the values of the
// environment variable VGFONTPATH if it is defined, then the vg
// source fonts directory if it is found (i.e., if vg was installed by
// go get).  If the resulting FontDirs slice is empty then the current
// directory is added to it.  This slice may be changed to load fonts
// from different locations.
var FontDirs []string

// FontFile returns the font file name for a font name or an error
// if it is an unknown font (i.e., not in the FontMap).
func fontFile(name string) (string, error) {
	var err error
	n, ok := FontMap[name]
	if !ok {
		errStr := "Unknown font: " + name + ".  Available fonts are:"
		for n := range FontMap {
			errStr += " " + n
		}
		err = errors.New(errStr)
	}
	return n + ".ttf", err
}


text:
package com.taobao.api.internal.toplink.logging;

import org.apache.commons.logging.Log;

import com.taobao.api.internal.toplink.Logger;

public class CommonsLogger implements Logger {
	private Log logger;

	public CommonsLogger(Log log) {
		this.logger = log;
	}

	public boolean isDebugEnabled() {
		return this.logger.isDebugEnabled();
	}

	public boolean isInfoEnabled() {
		return this.logger.isInfoEnabled();
	}

	public boolean isWarnEnabled() {
		return this.logger.isWarnEnabled();
	}

	public boolean isErrorEnabled() {
		return this.logger.isErrorEnabled();
	}

	public boolean isFatalEnabled() {
		return this.logger.isFatalEnabled();
	}

	public void debug(String message) {
		this.logger.debug(message);
	}

	public void debug(Throwable exception) {
		this.logger.debug("", exception);
	}

	public void debug(String message, Throwable exception) {
		this.logger.debug(message, exception);
	}

	public void debug(String format, Object... args) {
		this.logger.debug(String.format(format, args));
	}

	public void info(String message) {
		this.logger.info(message);
	}

	public void info(Throwable exception) {
		this.logger.info("", exception);
	}

	public void info(String message, Throwable exception) {
		this.logger.info(message, exception);
	}

	public void info(String format, Object... args) {
		this.logger.info(String.format(format, args));
	}

	public void warn(String message) {
		this.logger.warn(message);
	}

	public void warn(Throwable exception) {
		this.logger.warn("", exception);
	}

	public void warn(String message, Throwable exception) {
		this.logger.warn(message, exception);
	}

	public void warn(String format, Object... args) {
		this.logger.warn(String.format(format, args));
	}

	public void error(String message) {
		this.logger.error(message);
	}

	public void error(Throwable exception) {
		this.logger.error("", exception);
	}

	public void error(String message, Throwable exception) {
		this.logger.error(message, exception);
	}

	public void error(String format, Object... args) {
		this.logger.error(String.format(format, args));
	}

	public void fatal(String message) {
		this.logger.fatal(message);
	}

	public void fatal(Throwable exception) {
		this.logger.fatal("", exception);
	}

	public void fatal(String message, Throwable exception) {
		this.logger.fatal(message, exception);
	}

	public void fatal(String format, Object... args) {
		this.logger.fatal(String.format(format, args));
	}

}


text:
module.exports = function(grunt) {

  grunt.util = grunt.util || grunt.utils;

  var async = grunt.util.async;
  var log = grunt.log;
  var _ = grunt.util._;
  var file = grunt.file;
  var fs = require('fs');
  var path = require('path');
  var util = require('util');
  var SSHConnection = require('ssh2');

  var toTransfer;
  var sftpConn;
  var sshConn;
  var localRoot;
  var remoteRoot;
  var remoteSep;
  var currPath;
  var remotePath;
  var authVals;
  var exclusions;

  // A method for parsing the source location and storing the information into a suitably formated object
  function dirParseSync(startDir, result) {
    var files;
    var i;
    var tmpPath;
    var currFile;

    // initialize the `result` object if it is the first iteration
    if (result === undefined) {
      result = {};
      result[path.sep] = [];
    }

    // check if `startDir` is a valid location
    if (!fs.existsSync(startDir)) {
      grunt.warn(startDir + ' is not an existing location');
    }

    // iterate throught the contents of the `startDir` location of the current iteration
    files = fs.readdirSync(startDir);
    for (i = 0; i < files.length; i++) {
      currFile = startDir + path.sep + files[i];
      if (!file.isMatch({matchBase: true}, exclusions, currFile)) {
        if (file.isDir(currFile)) {
          tmpPath = path.relative(localRoot, startDir + path.sep + files[i]);
          if (!_.has(result, tmpPath)) {
            result[tmpPath] = [];
          }
          dirParseSync(currFile, result);
        } else {
          tmpPath = path.relative(localRoot, startDir);
          if (!tmpPath.length) {
            tmpPath = path.sep;
          }
          result[tmpPath].push(files[i]);
        }
      }
    }

    return result;
  }

  // A method for uploading a single file
  function sftpPut(inFilename, cb) {
    var fromFile, toFile, from, to;

    if (inFilename == '.gitignore') {
      cb(null);
      return true;
    }

    if(currPath.indexOf(path.sep) !== -1){
      remotePath = currPath.split(path.sep).join(remoteSep);
    }else{
      remotePath = currPath;
    }

    if (currPath !== path.sep) {
      fromFile = localRoot + path.sep + currPath + path.sep + inFilename;
      toFile = remoteRoot + remoteSep + remotePath + remoteSep + inFilename;
    } else {
      fromFile = localRoot + path.sep + inFilename;
      toFile = remoteRoot + remoteSep + inFilename;
    }
    // console.log(fromFile + ' to ' + toFile);
    log.write(fromFile + ' to ' + toFile);

    sftpConn.fastPut( fromFile, toFile, function(err){
      if (err){
        log.write((' Error uploading file: ' + err.message).red + '\n');
        cb(false);
      } else {
        log.write(' done'.green + '\n' );
        cb(null);
      }
    } );

//    from = fs.createReadStream(fromFile);
//    to = sftpConn.createWriteStream(toFile, {
//      flags: 'w',
//      mode: 0644
//    });
//    // var to = process.stdout;
//
//    from.on('data', function(){
//      // console.log('fs.data ', inFilename);
//      process.stdout.write('.');
//    });
//
//    from.on('close', function(){
////       console.log('fs.close from', inFilename);
//      // sftpConn.end();
//    });
//
//    to.on('close', function(){
//      // console.log('sftp.close to', inFilename);
//      process.stdout.write(' done'+"\n");
//      // sftpConn.end();
//      cb(null);
//    });
//
//    from.pipe(to);
  }

  // A method that processes a location - changes to a folder and uploads all respective files
  function sftpProcessLocation (inPath, cb) {
    if (!toTransfer[inPath]) {
      cb(new Error('Data for ' + inPath + ' not found'));
    }
    var files;

    currPath = inPath;
    files = toTransfer[inPath];

    if(inPath.indexOf(path.sep) !== -1){
      remoteInPath = inPath.split(path.sep).join(remoteSep);
    }else{
      remoteInPath = inPath;
    }

    remotePath = remoteRoot + (remoteInPath == remoteSep ? remoteInPath : remoteSep + remoteInPath);

    sftpConn.mkdir(remotePath, {mode: 0755}, function(err) {
      console.log('mkdir ' + remotePath, err ? 'error or dir exists' : 'ok');

      // console.log(async);
      async.forEachLimit(files, 1, sftpPut, function (err) {
        // console.log('callback');
        cb(null);
      });
    });
  }

  function getAuthByKey (inKey) {
    var tmpStr;
    var retVal = null;

    if (fs.existsSync('.ftppass')) {
      tmpStr = grunt.file.read('.ftppass');
      if (inKey !== null && tmpStr.length) retVal = JSON.parse(tmpStr)[inKey];
    }
    return retVal;
  }

  function getKeyLocation(customKey) {
    var keyLocation = null;
    var defaultKeys = [
      process.env.HOME + '/.ssh/id_dsa',
      process.env.HOME + '/.ssh/id_rsa'
    ];

    if (customKey) {
      if (fs.existsSync(customKey)) keyLocation = customKey;
    } else {
      for (i = 0; i < defaultKeys.length; i++) {
        if (fs.existsSync(defaultKeys[i])) keyLocation = defaultKeys[i];
      }
    }

    if (keyLocation === null) grunt.warn('Could not find private key.');
    return keyLocation;
  }

  // The main grunt task
  grunt.registerMultiTask('sftp-deploy', 'Deploy code over SFTP', function() {
    var done = this.async();
    var connection = {};
    var keyLocation;

    // Init
    sshConn = new SSHConnection();

    localRoot = Array.isArray(this.data.src) ? this.data.src[0] : this.data.src;
    remoteRoot = Array.isArray(this.data.dest) ? this.data.dest[0] : this.data.dest;
    remoteSep = this.data.server_sep ? this.data.server_sep : path.sep;

    authVals = getAuthByKey(this.data.auth.authKey);
    exclusions = this.data.exclusions || [];

    toTransfer = dirParseSync(localRoot);

    connection = {
      host: this.data.auth.host,
      port: this.data.auth.port
    };

    // Use either password or key-based login
    if (authVals === null) {
      grunt.warn('.ftppass seems to be missing or incomplete');
    } else {

      connection.username = authVals.username;

      if (authVals.password === undefined) {
        keyLocation = getKeyLocation(authVals.keyLocation);
        connection.privateKey = fs.readFileSync(keyLocation);
        if (authVals.passphrase) connection.passphrase = authVals.passphrase;
        log.ok('Logging in with key at ' + keyLocation);
      } else {
        connection.password = authVals.password;
        log.ok('Logging in with username ' + authVals.username);
      }

    }

    sshConn.connect(connection);

    sshConn.on('connect', function () {
      // console.log('Connection :: connect');
    });
    sshConn.on('error', function (err) {
      console.log('Connection :: error ::', err);
    });
    sshConn.on('end', function () {
      // console.log('Connection :: end');
    });
    sshConn.on('close', function (had_error) {
      // console.log('Connection :: close', had_error);
    });

    sshConn.on('ready', function () {
      // console.log('Connection :: ready');

      sshConn.sftp(function (err, sftp) {
        if (err) throw err;

        sftpConn = sftp;

        sftp.on('end', function () {
          // console.log('SFTP :: SFTP session closed');
          // console.trace();
        });
        sftp.on('close', function () {
          // console.log('SFTP :: close');
          // console.trace();
          sshConn.end();
        });
        sftp.on('error', function (e) {
          console.log('SFTP :: error', e);
          sshConn.end();
        });
        sftp.on('open', function (e) {
          // console.log('SFTP :: open');
        });

        var locations = _.keys(toTransfer);
        // console.dir(locations);

        // Iterating through all location from the `localRoot` in parallel
        async.forEachSeries(locations, sftpProcessLocation, function() {
          log.ok('Uploads done.');
          sftp.end();
          done();
        });

      });
    });

    if (grunt.errors) {
      return false;
    }
  });
};


text:
package io.fabric8.patch.management;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.felix.utils.version.VersionCleaner;
import org.junit.Test;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Version;

import static io.fabric8.patch.management.Utils.*;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class UtilsTest {

    @Test
    public void fromNumericUnixPermissions() {
        assertThat(getPermissionsFromUnixMode(new File("target"), 0775), equalTo(PosixFilePermissions.fromString("rwxrwxr-x")));
        assertThat(getPermissionsFromUnixMode(new File("target"), 0641), equalTo(PosixFilePermissions.fromString("rw-r----x")));
        assertThat(getPermissionsFromUnixMode(new File("target"), 00), equalTo(PosixFilePermissions.fromString("rwxrwxr-x")));
        assertThat(getPermissionsFromUnixMode(new File("target/test-classes/logback-test.xml"), 00), equalTo(PosixFilePermissions.fromString("rw-rw-r--")));
    }

    @Test
    public void toNumericUnixPermissions() {
        assertThat(getUnixModeFromPermissions(new File("target"), PosixFilePermissions.fromString("rwxrwxr-x")), equalTo(0775));
        assertThat(getUnixModeFromPermissions(new File("target"), PosixFilePermissions.fromString("rw-rw-r--")), equalTo(0664));
        assertThat(getUnixModeFromPermissions(new File("target"), PosixFilePermissions.fromString("r--------")), equalTo(0400));
    }

    @Test
    public void relativePaths() {
        assertThat(relative(new File("target/karaf/patches"), new File("target/karaf/other")), equalTo("../other"));
        assertThat(relative(new File("target/karaf/patches"), new File("target/karaf/patches")), equalTo(""));
        assertThat(relative(new File("target/karaf/patches"), new File("target/karaf/patches/x")), equalTo("x"));
    }

    @Test
    public void pathToMvnUris() {
        assertThat(pathToMvnurl("a/b/c"), nullValue());
        assertThat(pathToMvnurl("a/b/c/d"), nullValue());
        assertThat(pathToMvnurl("a/b/c/d/e"), nullValue());

        assertThat(pathToMvnurl("a/b/c/b-c.jar"), equalTo("mvn:a/b/c"));
        assertThat(pathToMvnurl("a/b/b/c/b-c.jar"), equalTo("mvn:a.b/b/c"));
        assertThat(pathToMvnurl("a/b/b/c/b-c-d.jar"), equalTo("mvn:a.b/b/c/jar/d"));
        assertThat(pathToMvnurl("a/b/c/b-c.war"), equalTo("mvn:a/b/c/war"));

        assertThat(pathToMvnurl("a/b/c/b-c-x.war"), equalTo("mvn:a/b/c/war/x"));
        assertThat(pathToMvnurl("a/b/c/b-c-x-y.xml"), equalTo("mvn:a/b/c/xml/x-y"));
    }

    @Test
    public void mvnUrisToPaths() {
        assertThat(mvnurlToPath("mvn:a/b/c"), equalTo("a/b/c/b-c.jar"));
        assertThat(mvnurlToPath("mvn:a.b/b/c"), equalTo("a/b/b/c/b-c.jar"));
        assertThat(mvnurlToPath("mvn:a.b/b/c/jar/d"), equalTo("a/b/b/c/b-c-d.jar"));
        assertThat(mvnurlToPath("mvn:a/b/c/war"), equalTo("a/b/c/b-c.war"));
        assertThat(mvnurlToPath("mvn:a/b/c/war/x"), equalTo("a/b/c/b-c-x.war"));
        assertThat(mvnurlToPath("mvn:a/b/c/xml/x-y"), equalTo("a/b/c/b-c-x-y.xml"));
    }

    @Test
    public void testSymbolicNameStrip() {
        assertEquals("my.bundle", stripSymbolicName("my.bundle"));
        assertEquals("my.bundle", stripSymbolicName("my.bundle;singleton:=true"));
        assertEquals("my.bundle", stripSymbolicName("my.bundle;blueprint.graceperiod:=false;"));
        assertEquals("my.bundle", stripSymbolicName("my.bundle;blueprint.graceperiod:=false; blueprint.timeout=10000;"));
    }

    @Test
    public void canonicalVersionsFelix() {
        assertEquals("1.1.1.1", VersionCleaner.clean("1.1.1.1"));
        assertEquals("1.1.1", VersionCleaner.clean("1.1.1"));
        assertEquals("1.1.0", VersionCleaner.clean("1.1"));
        assertEquals("1.0.0", VersionCleaner.clean("1"));
        assertEquals("0.0.0", VersionCleaner.clean(""));
        assertEquals("0.0.0", VersionCleaner.clean(null));

        assertEquals("1.1.1.redhat-1", VersionCleaner.clean("1.1.1.redhat-1"));
        assertEquals("1.1.0.redhat-1", VersionCleaner.clean("1.1.redhat-1"));
        assertEquals("1.0.0.redhat-1", VersionCleaner.clean("1.redhat-1"));

        assertEquals("1.1.1.1_redhat-1", VersionCleaner.clean("1.1.1.1.redhat-1"));
        assertEquals("1.1.1.1_1_redhat-1", VersionCleaner.clean("1.1.1.1.1.redhat-1"));

        assertEquals("3.1.2.2", VersionCleaner.clean("3.1.2_2"));
        assertEquals("3.1.2.2", VersionCleaner.clean("3.1.2-2"));
        assertEquals("3.1.2.2", VersionCleaner.clean("3.1.2+2"));
        assertEquals("3.1.2.a+2", VersionCleaner.clean("3.1.2.a+2"));
    }

    @Test
    public void canonicalVersions() {
        assertEquals("1.1.1.1", Utils.getOsgiVersion("1.1.1.1").toString());
        assertEquals("1.1.1", Utils.getOsgiVersion("1.1.1").toString());
        assertEquals("1.1.0", Utils.getOsgiVersion("1.1").toString());
        assertEquals("1.0.0", Utils.getOsgiVersion("1").toString());
        assertEquals("0.0.0", Utils.getOsgiVersion("").toString());
        assertEquals("0.0.0", Utils.getOsgiVersion(null).toString());

        assertEquals("3.1.2.2", Utils.getOsgiVersion("3.1.2_2").toString());

        assertEquals("1.1.1.redhat-1", Utils.getOsgiVersion("1.1.1.redhat-1").toString());
        assertEquals("1.1.0.redhat-1", Utils.getOsgiVersion("1.1.redhat-1").toString());
        assertEquals("1.0.0.redhat-1", Utils.getOsgiVersion("1.redhat-1").toString());

        assertEquals("1.1.1.1_1_redhat-1", Utils.getOsgiVersion("1.1.1.1.1.redhat-1").toString());
        assertEquals("1.1.1.1_redhat-1", Utils.getOsgiVersion("1.1.1.1.redhat-1").toString());
    }

    @Test
    public void productBaselineLocations() throws IOException {
        BundleContext bc = mock(BundleContext.class);
        when(bc.getProperty("karaf.default.repository")).thenReturn("sys");
        File karafHome = new File("target/karaf-" + new Date().getTime());
        FileUtils.deleteDirectory(karafHome);

        FileUtils.write(new File(karafHome, "sys/a/b/1.2/b-1.2-baseline.zip"), "");
        when(bc.getProperty("fuse.patch.product")).thenReturn("a:b");
        assertThat(Utils.getBaselineLocationForProduct(karafHome, bc, "1.2"), equalTo("a/b/1.2/b-1.2-baseline.zip"));
        FileUtils.deleteQuietly(new File(karafHome, "sys/a/b/1.2/b-1.2-baseline.zip"));
        assertNull(Utils.getBaselineLocationForProduct(karafHome, bc, "1.2"));

        when(bc.getProperty("fuse.patch.product")).thenReturn(null);
        assertNull(Utils.getBaselineLocationForProduct(karafHome, bc, "1.2"));

        when(bc.getProperty("fuse.patch.product")).thenReturn("a");
        assertNull(Utils.getBaselineLocationForProduct(karafHome, bc, "1.2"));
    }

    @Test
    public void locationUpdates() throws IOException {
        List<BundleUpdate> updates = new LinkedList<>();

        updates.add(BundleUpdate.from("mvn:g/a/1.0").to("mvn:g/a/1.1"));
        updates.add(BundleUpdate.from("mvn:g/a2/1.0/jar").to("mvn:g/a2/1.1/jar"));
        updates.add(BundleUpdate.from("mvn:g/a3/1.0/jar/signed-secrets").to("mvn:g/a3/1.1/jar/signed-secrets"));
        updates.add(BundleUpdate.from("mvn:g2/a2/1.0/war").to("mvn:g2/a2/1.1/war"));
        updates.add(BundleUpdate.from("mvn:g2.g3/a2.a3/1.0/war").to("mvn:g2.g3/a2.a3/1.1/war"));
        updates.add(BundleUpdate.from("mvn:g2.g3/a2.a3/1.0/xml/sources").to("mvn:g2.g3/a2.a3/1.1/xml/sources"));
        updates.add(BundleUpdate.from("file:/fuse-6/system/org/ops4j/pax/url/pax-url-aether/2.4.0/pax-url-aether-2.4.0.jar")
                .to("file:/fuse-7.3/system/org/ops4j/pax/url/pax-url-aether/2.4.2/pax-url-aether-2.4.2.jar"));

        Map<String, String> map = Utils.collectLocationUpdates(updates);
        assertThat(map.get("g/a/1.0/a-1.0.jar"), equalTo("g/a/1.1/a-1.1.jar"));
        assertThat(map.get("g/a2/1.0/a2-1.0.jar"), equalTo("g/a2/1.1/a2-1.1.jar"));
        assertThat(map.get("g/a3/1.0/a3-1.0-signed-secrets.jar"), equalTo("g/a3/1.1/a3-1.1-signed-secrets.jar"));
        assertThat(map.get("g2/g3/a2.a3/1.0/a2.a3-1.0.war"), equalTo("g2/g3/a2.a3/1.1/a2.a3-1.1.war"));
        assertThat(map.get("g2/g3/a2.a3/1.0/a2.a3-1.0-sources.xml"), equalTo("g2/g3/a2.a3/1.1/a2.a3-1.1-sources.xml"));
        assertThat(map.get("org/ops4j/pax/url/pax-url-aether/2.4.0/pax-url-aether-2.4.0.jar"),
                equalTo("org/ops4j/pax/url/pax-url-aether/2.4.2/pax-url-aether-2.4.2.jar"));
    }

    @Test
    public void updateKarafPackages() throws IOException {
        File configProperties = new File("target/test-config.properties");
        StringWriter sw1 = new StringWriter();
        StringWriter sw2 = new StringWriter();

        sw1.write(" p.q;version=\"10.0\", \\\n");
        sw1.write(" p.q.r;version=\"10.0\", \\\n");
        sw1.write(" p.q.m;version=\"10.0\", \\\n");
        sw1.write(" x;version=\"10.0\", \\\n");
        sw1.write(" x;version=10.0, \\\n");
        sw1.write(" p.q = 3\n");
        sw1.write(" x = 3\n");

        sw2.write(" p.q;version=\"11.0\", \\\n");
        sw2.write(" p.q.r;version=\"11.0\", \\\n");
        sw2.write(" p.q.m;version=\"10.0\", \\\n");
        sw2.write(" x;version=\"12.0\", \\\n");
        sw2.write(" x;version=10.0, \\\n");
        sw2.write(" p.q = 3\n");
        sw2.write(" x = 3\n");

        FileUtils.write(configProperties, sw1.toString());

        Utils.updateKarafPackageVersion(configProperties, "11.0", "p.q", "p.q.r");
        Utils.updateKarafPackageVersion(configProperties, "12.0", "x");

        String newFile = FileUtils.readFileToString(configProperties);
        assertThat("etc/config.properties should be updated", newFile, equalTo(sw2.toString()));
    }

    @Test
    public void detectVersions() {
        assertThat(Utils.findVersionInName("ordinaryName"), equalTo(Version.emptyVersion));
        assertThat(Utils.findVersionInName("ordinary-name"), equalTo(Version.emptyVersion));
        assertThat(Utils.findVersionInName("ordinary-name-1"), equalTo(Version.parseVersion("1")));
        assertThat(Utils.findVersionInName("ordinary-name-1"), equalTo(Version.parseVersion("1.0")));
        assertThat(Utils.findVersionInName("ordinary-name-1"), equalTo(Version.parseVersion("1.0.0")));
        assertThat(Utils.findVersionInName("ordinary-name-1"), equalTo(new Version(1, 0, 0)));

        assertThat(Utils.findVersionInName("ordinary-name-1.2"), equalTo(new Version(1, 2, 0)));
        assertThat(Utils.findVersionInName("ordinary-name-1.2.3"), equalTo(new Version(1, 2, 3)));
        assertThat(Utils.findVersionInName("ordinary-name-1.2.3.4"), equalTo(new Version(1, 2, 3, "4")));
        assertThat(Utils.findVersionInName("ordinary-name-1.2.3.4.5"), equalTo(Version.emptyVersion)); // IllegalArgumentException
        assertThat(Utils.findVersionInName("ordinary-name-1.2.3.4-5"), equalTo(new Version(1, 2, 3, "4-5")));

        assertThat(Utils.findVersionInName("jboss-fuse-6.1.1.redhat-459-hf26"), equalTo(new Version(6, 1, 1, "redhat-459-hf26")));
    }

}


text:
[![browser support](https://ci.testling.com/itayw/describe-json.png)
](https://ci.testling.com/itayw/describe-json)

The library takes a JSON object and returns it's metadata in several useful ways.
I've developed this package as part of the [joola.io project][joola.io] to handle the transformation of JSON rich documents into NoSQL datastores.
This process requires some descriptive attributes for each of the JSON nodes and this library assists in this process.

**describe-json** uses two libraries for traversing the JSON and parsing its metadata, [traverse][traverse] which iterates over the JSON object and [kindof][kindof] which is used to determine the typeof the value.

```javascript
var djson = require('describe-json');
var obj = {
  number: 1,
  string: 'string',
  date: new Date(),
  array: [1, '2', [1, 2]],
  nested: {
    number: 1,
    string: 'string',
    date: new Date()
  }
};
console.log(djson.describe(obj));
```
Results with

```javascript
{ number: 'number',
  string: 'string',
  date: 'date',
  array: [ 'number', 'string', [ 'number', 'number' ] ],
  nested: { number: 'number', string: 'string', date: 'date' }
}
```

### Install

```bash
$ npm install describe-json
```

## API

### `describe-json.describe (obj)`
Generates a metadata representation of the provided JSON object.

Accepts `obj` which is a JSON object and traverses it to return another JSON object containing the metadata.

- Arrays are returned with their contents expanded and each replaced with the metadata of the array item value.
- Strings are parsed in attempt to cast them as a valid date.
- Root is not parsed and returned.

```javascript
var djson = require('describe-json');
var obj = {
  number: 1,
  string: 'string',
  date: new Date(),
  array: [1, '2', [1, 2]],
  nested: {
    number: 1,
    string: 'string',
    date: new Date()
  }
};
console.log(djson.describe(obj));
```
Results with

```javascript
{ number: 'number',
  string: 'string',
  date: 'date',
  array: [ 'number', 'string', [ 'number', 'number' ] ],
  nested: { number: 'number', string: 'string', date: 'date' }
}
```

### `describe-json.flatten (obj)`
Returns an `array` of `[key, value]` containing all leaf node values.

```js
var obj = {
  level0: 1,
  a: {
    b: {
      c: {
        d: 1
      }
    }
  },
  aa: {
    bb: ['cc']
  }
};
```
Results with:
```js
[
  [ 'level0', 1 ],
  [ 'a.b.c.d', 1 ],
  [ 'aa.bb', [ 'cc' ] ]
]
```

### Contributing
I would love to get your help and have outlined a simple Contribution Policy to support a transparent and easy merging of ideas, code, bug fixes and features.
If you're looking for a place to start, you can always go over the list of open issues, pick one and get started. If you're feeling lost or unsure, just let me know.

###License
Copyright (c) 2014 Itay Weinberger. MIT Licensed, see LICENSE for details.

[1]: https://coveralls.io/repos/itayw/describe-json/badge.png?branch=master
[2]: https://coveralls.io/r/itayw/describe-json?branch=master
[3]: https://travis-ci.org/itayw/describe-json.png?branch=master
[4]: https://travis-ci.org/itayw/describe-json?branch=master

[joola.io]: http://github.com/joola/joola.io
[traverse]: https://github.com/substack/js-traverse
[kindof]: https://github.com/moll/js-kindof


text:
export default function GridApiMock(gridOptions) {
  let elementMock = {
    css: jasmine.createSpy('css')
  };
  elementMock.find = jasmine.createSpy('find').and.returnValue(elementMock);

  return {
    grid: {
      id: '1234',
      element: elementMock,
      options: gridOptions
    },
    core: {
      getVisibleRows: jasmine.createSpy('rowsRendered').and.returnValue([]),
      on: {
        rowsRendered: jasmine.createSpy('rowsRendered'),
        sortChanged: jasmine.createSpy('sortChanged')
      }
    },
    selection: {
      on: {
        rowSelectionChanged: jasmine.createSpy('rowSelectionChanged'),
        rowSelectionChangedBatch: jasmine.createSpy('rowSelectionChangedBatch')
      },
      selectRow: jasmine.createSpy('selectRow')
    },
    draggableRows: {
      on: {
        rowDropped: jasmine.createSpy('rowDropped')
      }
    },
    pagination: {
      on: {
        paginationChanged: jasmine.createSpy('paginationChanged')
      }
    },
    colResizable: {
      on: {
        columnSizeChanged: jasmine.createSpy('columnSizeChanged')
      }
    }
  }
}


text:
<component name="libraryTable">
  <library name="Maven: org.hibernate:hibernate-search:4.2.0.Final">
    <CLASSES>
      <root url="jar://$MAVEN_REPOSITORY$/org/hibernate/hibernate-search/4.2.0.Final/hibernate-search-4.2.0.Final.jar!/" />
    </CLASSES>
    <JAVADOC>
      <root url="jar://$MAVEN_REPOSITORY$/org/hibernate/hibernate-search/4.2.0.Final/hibernate-search-4.2.0.Final-javadoc.jar!/" />
    </JAVADOC>
    <SOURCES>
      <root url="jar://$MAVEN_REPOSITORY$/org/hibernate/hibernate-search/4.2.0.Final/hibernate-search-4.2.0.Final-sources.jar!/" />
    </SOURCES>
  </library>
</component>


text:
// (c) Copyright 2018 Cloudera, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.cloudera.director.aws.ec2.allocation;

import com.amazonaws.services.ec2.model.BlockDeviceMapping;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.InstanceNetworkInterfaceSpecification;
import com.amazonaws.services.ec2.model.InstanceStateName;
import com.amazonaws.services.ec2.model.Tag;
import com.cloudera.director.aws.AWSTimeouts;
import com.cloudera.director.aws.ec2.EC2Instance;
import com.cloudera.director.aws.ec2.EC2InstanceTemplate;
import com.cloudera.director.aws.ec2.EC2TagHelper;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;

import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeoutException;

import org.joda.time.DateTime;

/**
 * Helper that allows instance allocators to delegate operations back to the provider.
 */
@SuppressWarnings("Guava")
public interface AllocationHelper {

  Set<InstanceStateName> UNALLOCATED_STATES = Collections
      .unmodifiableSet(EnumSet.of(InstanceStateName.Terminated, InstanceStateName.ShuttingDown));

  Predicate<Instance> INSTANCE_IS_TERMINAL =
      instance -> instance != null &&
          UNALLOCATED_STATES.contains(InstanceStateName.fromValue(instance.getState().getName()));

  /**
   * Returns the AWS timeouts.
   *
   * @return the AWS timeouts
   */
  AWSTimeouts getAWSTimeouts();

  /**
   * Returns the tag helper.
   *
   * @return the tag helper
   */
  EC2TagHelper getEC2TagHelper();

  /**
   * Creates an EC2 compute instance with the specified parameters.
   *
   * @param template        the template from which the instance was created
   * @param instanceId      the instance identifier
   * @param instanceDetails the provider-specific instance details
   * @throws IllegalArgumentException if the instance does not have a valid private IP address
   */
  EC2Instance createInstance(EC2InstanceTemplate template, String instanceId, Instance instanceDetails);

  /**
   * Waits until the instance has entered a running state.
   *
   * @param ec2InstanceId the EC2 instance id
   * @param timeout       the timeout in milliseconds
   * @return true if the instance has entered a running state, false if the instance is shutting
   * down/terminated or the function has timed out waiting for the instance to enter one of these
   * two states.
   */
  boolean waitUntilInstanceHasStarted(final String ec2InstanceId, DateTime timeout)
      throws InterruptedException, TimeoutException;

  /**
   * Returns current information for the specified instances, which are guaranteed to have
   * been created by this provider.
   *
   * @param template    the template that was used to create the instances
   * @param instanceIds the unique identifiers for the instances
   * @return the instances
   * @throws InterruptedException if the operation is interrupted
   */
  Collection<EC2Instance> find(final EC2InstanceTemplate template, Collection<String> instanceIds)
      throws InterruptedException;

  /**
   * Returns current information for the specified instances, which are guaranteed to have
   * been created by this provider.
   *
   * @param template    the template that was used to create the instances
   * @param instanceIds the unique identifiers for the instances
   * @return the instances
   * @throws InterruptedException if the operation is interrupted
   */
  default Iterable<Map.Entry<String, Instance>> doFind(
      EC2InstanceTemplate template, Iterable<String> instanceIds)
      throws InterruptedException {
    return doFind(template, instanceIds, Predicates.alwaysTrue());
  }

  /**
   * Returns current information for the specified instances, which are guaranteed to have
   * been created by this provider.
   *
   * @param template    the template that was used to create the instances
   * @param instanceIds the unique identifiers for the instances
   * @param predicate   a predicate used to filter the returned instances
   * @return the instances
   * @throws InterruptedException if the operation is interrupted
   */
  Iterable<Map.Entry<String, Instance>> doFind(
      EC2InstanceTemplate template, Iterable<String> instanceIds,
      Predicate<Instance> predicate)
      throws InterruptedException;

  /**
   * Deletes the specified instances, which are guaranteed to have been created by this provider.
   *
   * @param template    the template that was used to create the instances
   * @param instanceIds the unique identifiers for the instances
   * @throws InterruptedException if the operation is interrupted
   */
  void delete(EC2InstanceTemplate template, Collection<String> instanceIds)
      throws InterruptedException;

  /**
   * Deletes the specified EC2 instances.
   *
   * @param ec2InstanceIds the instance IDs
   * @throws InterruptedException if the operation is interrupted
   */
  void doDelete(Collection<String> ec2InstanceIds) throws InterruptedException;

  /**
   * Iterates through the instances in the specified {@code DescribeInstancesResult}
   * and calls the specified handler on each instance. This method will retrieve the
   * follow-on {@code DescribeInstanceResult}s if the result holds a {@code nextToken}.
   *
   * @param result          the {@code DescribeInstancesResult}
   * @param instanceHandler the instance handler
   */
  void forEachInstance(DescribeInstancesResult result, Function<Instance, Void> instanceHandler);

  /**
   * Determines the virtual instance ID from the specified list of tags.
   *
   * @param tags the tags
   * @param type the type of tagged object
   * @return the virtual instance ID
   * @throws IllegalStateException if the tags do not contain the virtual instance ID
   */
  String getVirtualInstanceId(List<Tag> tags, String type);

  /**
   * Creates block device mappings based on the specified instance template.
   *
   * @param template the instance template
   * @return the block device mappings
   */
  List<BlockDeviceMapping> getBlockDeviceMappings(EC2InstanceTemplate template);

  /**
   * Creates an instance network interface specification based on the specified instance template.
   *
   * @param template the instance template
   * @return instance network interface specification
   */
  InstanceNetworkInterfaceSpecification getInstanceNetworkInterfaceSpecification(
      EC2InstanceTemplate template);

  /**
   * Returns whether to associate public IP addresses with the allocated instances.
   *
   * @return whether to associate public IP addresses with the allocated instances
   */
  boolean isAssociatePublicIpAddresses();
}


text:
Discrete Decision Processes

@author : Daisuke Oyama, Spencer Lyon, Matthew McKay

@date: 24/Sep/2015

References
----------

http://quant-econ.net/jl/ddp.html

Notes
-----
1. This currently implements:
    a. Value Iteration,
    b. Policy Iteration, and
    c. Modified Policy Iteration
   For:
    a. Dense Matrices
    b. State-Action Pair Formulation

=#

import Base.*

#------------------------#
#-Types and Constructors-#
#------------------------#

"""
DiscreteDP type for specifying paramters for discrete dynamic programming model

##### Parameters

- `R::Array{T,NR}` : Reward Array
- `Q::Array{T,NQ}` : Transition Probability Array
- `beta::Float64`  : Discount Factor
- `s_indices::Nullable{Vector{Tind}}`: State Indices. Null unless using
  SA formulation
- `a_indices::Nullable{Vector{Tind}}`: Action Indices. Null unless using
  SA formulation
- `a_indptr::Nullable{Vector{Tind}}`: Action Index Pointers. Null unless using
  SA formulation

##### Returns

- `ddp::DiscreteDP` : DiscreteDP object

"""
type DiscreteDP{T<:Real,NQ,NR,Tbeta<:Real,Tind}
    R::Array{T,NR}                     # Reward Array
    Q::Array{T,NQ}                     # Transition Probability Array
    beta::Tbeta                        # Discount Factor
    s_indices::Nullable{Vector{Tind}}  # State Indices
    a_indices::Nullable{Vector{Tind}}  # Action Indices
    a_indptr::Nullable{Vector{Tind}}   # Action Index Pointers

    function DiscreteDP(R::Array, Q::Array, beta::Real)
        # verify input integrity 1
        if NQ != 3
            msg = "Q must be 3-dimensional without s-a formulation"
            throw(ArgumentError(msg))
        end
        if NR != 2
            msg = "R must be 2-dimensional without s-a formulation"
            throw(ArgumentError(msg))
        end
        (beta < 0 || beta >= 1) &&  throw(ArgumentError("beta must be [0, 1)"))

        # verify input integrity 2
        num_states, num_actions = size(R)
        if size(Q) != (num_states, num_actions, num_states)
            throw(ArgumentError("shapes of R and Q must be (n,m) and (n,m,n)"))
        end

        # check feasibility
        R_max = s_wise_max(R)
        if any(R_max .== -Inf)
            # First state index such that all actions yield -Inf
            s = find(R_max .== -Inf) #-Only Gives True
            throw(ArgumentError("for every state the reward must be finite for
                some action: violated for state $s"))
        end

        # here the indices and indptr are null.
        s_indices = Nullable{Vector{Int}}()
        a_indices = Nullable{Vector{Int}}()
        a_indptr = Nullable{Vector{Int}}()

        new(R, Q, beta, s_indices, a_indices, a_indptr)
    end

    # Note: We left R, Q as type Array to produce more helpful error message with regards to shape.
    # R and Q are dense Arrays
    function DiscreteDP(R::AbstractArray, Q::AbstractArray, beta::Real,
                        s_indices::Vector, a_indices::Vector)
        # verify input integrity 1
        if NQ != 2
            throw(ArgumentError("Q must be 2-dimensional with s-a formulation"))
        end
        if NR != 1
            throw(ArgumentError("R must be 1-dimensional with s-a formulation"))
        end
        (beta < 0 || beta >= 1) && throw(ArgumentError("beta must be [0, 1)"))

        # verify input integrity (same length)
        num_sa_pairs, num_states = size(Q)
        if length(R) != num_sa_pairs
            throw(ArgumentError("shapes of R and Q must be (L,) and (L,n)"))
        end
        if length(s_indices) != num_sa_pairs
            msg = "length of s_indices must be equal to the number of s-a pairs"
            throw(ArgumentError(msg))
        end
        if length(a_indices) != num_sa_pairs
            msg = "length of a_indices must be equal to the number of s-a pairs"
            throw(ArgumentError(msg))
        end

        if _has_sorted_sa_indices(s_indices, a_indices)
            a_indptr = Array(Int64, num_states+1)
            _generate_a_indptr!(num_states, s_indices, a_indptr)
        else
            # transpose matrix to use Julia's CSC; now rows are actions and
            # columns are states (this is why it's called as_ptr not sa_ptr)
            m = maximum(a_indices)
            n = maximum(s_indices)
            msg = "Duplicate s-a pair found"
            as_ptr = sparse(a_indices, s_indices, 1:num_sa_pairs, m, n,
                            (x,y)->throw(ArgumentError(msg)))
            a_indices = as_ptr.rowval
            a_indptr = as_ptr.colptr

            R = R[as_ptr.nzval]
            Q = Q[as_ptr.nzval, :]

            _s_indices = Array(eltype(a_indices), num_sa_pairs)
            for i in 1:num_states, j in a_indptr[i]:(a_indptr[i+1]-1)
                _s_indices[j] = i
            end
            copy!(s_indices, _s_indices)
        end

        # check feasibility
        aptr_diff = diff(a_indptr)
        if any(aptr_diff .== 0.0)
            # First state index such that no action is available
            s = find(aptr_diff .== 0.0)  # Only Gives True
            throw(ArgumentError("for every state at least one action
                must be available: violated for state $s"))
        end

        # package into nullables before constructing type
        s_indices = Nullable{Vector{Tind}}(s_indices)
        a_indices = Nullable{Vector{Tind}}(a_indices)
        a_indptr = Nullable{Vector{Tind}}(a_indptr)

        new(R, full(Q), beta, s_indices, a_indices, a_indptr)
    end
end

"""
DiscreteDP type for specifying parameters for discrete dynamic programming
model Dense Matrix Formulation

##### Parameters

- `R::Array{T,NR}` : Reward Array
- `Q::Array{T,NQ}` : Transition Probability Array
- `beta::Float64`  : Discount Factor

##### Returns

- `ddp::DiscreteDP` : Constructor for DiscreteDP object
"""
DiscreteDP{T,NQ,NR,Tbeta}(R::Array{T,NR}, Q::Array{T,NQ}, beta::Tbeta) =
    DiscreteDP{T,NQ,NR,Tbeta,Int}(R, Q, beta)

"""
DiscreteDP type for specifying parameters for discrete dynamic programming
model State-Action Pair Formulation

##### Parameters

- `R::Array{T,NR}` : Reward Array
- `Q::Array{T,NQ}` : Transition Probability Array
- `beta::Float64`  : Discount Factor
- `s_indices::Nullable{Vector{Tind}}`: State Indices. Null unless using
  SA formulation
- `a_indices::Nullable{Vector{Tind}}`: Action Indices. Null unless using
  SA formulation
- `a_indptr::Nullable{Vector{Tind}}`: Action Index Pointers. Null unless using
  SA formulation

##### Returns

- `ddp::DiscreteDP` : Constructor for DiscreteDP object

"""
function DiscreteDP{T,NQ,NR,Tbeta,Tind}(R::AbstractArray{T,NR},
                                        Q::AbstractArray{T,NQ},
                                        beta::Tbeta, s_indices::Vector{Tind},
                                        a_indices::Vector{Tind})
    DiscreteDP{T,NQ,NR,Tbeta,Tind}(R, Q, beta, s_indices, a_indices)
end

#--------------#
#-Type Aliases-#
#--------------#

typealias DDP{T,Tbeta,Tind} DiscreteDP{T,3,2,Tbeta,Tind}
typealias DDPsa{T,Tbeta,Tind} DiscreteDP{T,2,1,Tbeta,Tind}

#--------------------#
#-Property Functions-#
#--------------------#

num_states(ddp::DDP) = size(ddp.R, 1)
num_states(ddp::DDPsa) = size(ddp.Q, 2)
num_actions(ddp::DiscreteDP) = size(ddp.R, 2)

abstract DDPAlgorithm
immutable VFI <: DDPAlgorithm end
immutable PFI <: DDPAlgorithm end
immutable MPFI <: DDPAlgorithm end

"""
DPSolveResult is an object for retaining results and associated metadata after
solving the model

##### Parameters

- `ddp::DiscreteDP` : DiscreteDP object

##### Returns

- `ddpr::DPSolveResult` : DiscreteDP Results object

"""
type DPSolveResult{Algo<:DDPAlgorithm,Tval<:Real}
    v::Vector{Tval}
    Tv::Array{Tval}
    num_iter::Int
    sigma::Array{Int,1}
    mc::MarkovChain

    function DPSolveResult(ddp::DiscreteDP)
        v = s_wise_max(ddp, ddp.R) # Initialise v with v_init
        ddpr = new(v, similar(v), 0, similar(v, Int))

        # fill in sigma with proper values
        compute_greedy!(ddp, ddpr)
        ddpr
    end

    # method to pass initial value function (skip the s-wise max)
    function DPSolveResult(ddp::DiscreteDP, v::Vector)
        ddpr = new(v, similar(v), 0, similar(v, Int))

        # fill in sigma with proper values
        compute_greedy!(ddp, ddpr)
        ddpr
    end
end

# ------------------------ #
# Bellman operator methods #
# ------------------------ #

"""
The Bellman operator, which computes and returns the updated value function Tv
for a value function v.

##### Parameters

- `ddp::DiscreteDP` : Object that contains the model parameters
- `v::Vector{T<:AbstractFloat}`: The current guess of the value function
- `Tv::Vector{T<:AbstractFloat}`: A buffer array to hold the updated value
  function. Initial value not used and will be overwritten
- `sigma::Vector`: A buffer array to hold the policy function. Initial
  values not used and will be overwritten

##### Returns

- `Tv::Vector` : Updated value function vector
- `sigma::Vector` : Updated policiy function vector
"""
function bellman_operator!(ddp::DiscreteDP, v::Vector, Tv::Vector, sigma::Vector)
    vals = ddp.R + ddp.beta * ddp.Q * v
    s_wise_max!(ddp, vals, Tv, sigma)
    Tv, sigma
end

"""
Apply the Bellman operator using `v=ddpr.v`, `Tv=ddpr.Tv`, and `sigma=ddpr.sigma`

##### Notes

Updates `ddpr.Tv` and `ddpr.sigma` inplace

"""
bellman_operator!(ddp::DiscreteDP, ddpr::DPSolveResult) =
    bellman_operator!(ddp, ddpr.v, ddpr.Tv, ddpr.sigma)

"""
The Bellman operator, which computes and returns the updated value function Tv
for a given value function v.

This function will fill the input `v` with `Tv` and the input `sigma` with the
corresponding policy rule

##### Parameters

- `ddp::DiscreteDP`: The ddp model
- `v::Vector{T<:AbstractFloat}`: The current guess of the value function. This
  array will be overwritten
- `sigma::Vector`: A buffer array to hold the policy function. Initial
  values not used and will be overwritten

##### Returns

- `Tv::Vector`: Updated value function vector
- `sigma::Vector{T<:Integer}`: Policy rule
"""
bellman_operator!{T<:AbstractFloat}(ddp::DiscreteDP, v::Vector{T}, sigma::Vector) =
    bellman_operator!(ddp, v, v, sigma)

# method to allow dispatch on rationals
# TODO from albep: not sure how to update this to the state-action pair formulation
function bellman_operator!{T1<:Rational,T2<:Rational,NR,NQ,T3<:Rational}(ddp::DiscreteDP{T1,NR,NQ,T2},
                                                                         v::Vector{T3},
                                                                         sigma::Vector)
    bellman_operator!(ddp, v, v, sigma)
end

"""
The Bellman operator, which computes and returns the updated value function Tv
for a given value function v.

##### Parameters

- `ddp::DiscreteDP`: The ddp model
- `v::Vector`: The current guess of the value function

##### Returns

- `Tv::Vector` : Updated value function vector
"""
bellman_operator(ddp::DiscreteDP, v::Vector) =
    s_wise_max(ddp, ddp.R + ddp.beta * ddp.Q * v)

# ---------------------- #
# Compute greedy methods #
# ---------------------- #

"""
Compute the v-greedy policy

##### Parameters

- `ddp::DiscreteDP` : Object that contains the model parameters
- `ddpr::DPSolveResult` : Object that contains result variables

##### Returns

- `sigma::Vector{Int}` : Array containing `v`-greedy policy rule

##### Notes

modifies ddpr.sigma and ddpr.Tv in place

"""
compute_greedy!(ddp::DiscreteDP, ddpr::DPSolveResult) =
    (bellman_operator!(ddp, ddpr); ddpr.sigma)

function compute_greedy{TV<:Real}(ddp::DiscreteDP, v::Vector{TV})
    Tv = similar(v)
    sigma = ones(Int, length(v))
    bellman_operator!(ddp, v, Tv, sigma)
    sigma
end

# ----------------------- #
# Evaluate policy methods #
# ----------------------- #

"""
Method of `evaluate_policy` that extracts sigma from a `DPSolveResult`

See other docstring for details
"""
evaluate_policy(ddp::DiscreteDP, ddpr::DPSolveResult) =
    evaluate_policy(ddp, ddpr.sigma)

"""
Compute the value of a policy.

##### Parameters

- `ddp::DiscreteDP` : Object that contains the model parameters
- `sigma::Vector{T<:Integer}` : Policy rule vector

##### Returns

- `v_sigma::Array{Float64}` : Value vector of `sigma`, of length n.

"""
function evaluate_policy{T<:Integer}(ddp::DiscreteDP, sigma::Vector{T})
    R_sigma, Q_sigma = RQ_sigma(ddp, sigma)
    b = R_sigma
    A = I - ddp.beta * Q_sigma
    return A \ b
end

# ------------- #
# Solve methods #
# ------------- #

"""
Solve the dynamic programming problem.

##### Parameters

- `ddp::DiscreteDP` : Object that contains the Model Parameters
- `method::Type{T<Algo}(VFI)`: Type name specifying solution method. Acceptable
arguments are `VFI` for value function iteration or `PFI` for policy function
iteration or `MPFI` for modified policy function iteration
- `;max_iter::Int(250)` : Maximum number of iterations
- `;epsilon::Float64(1e-3)` : Value for epsilon-optimality. Only used if
`method` is `VFI`
- `;k::Int(20)` : Number of iterations for partial policy evaluation in modified
policy iteration (irrelevant for other methods).

##### Returns

- `ddpr::DPSolveResult{Algo}` : Optimization result represented as a
DPSolveResult. See `DPSolveResult` for details.
"""
function solve{Algo<:DDPAlgorithm,T}(ddp::DiscreteDP{T}, method::Type{Algo}=VFI;
                                     max_iter::Integer=250, epsilon::Real=1e-3,
                                     k::Integer=20)
    ddpr = DPSolveResult{Algo,T}(ddp)
    _solve!(ddp, ddpr, max_iter, epsilon, k)
    ddpr.mc = MarkovChain(ddp, ddpr)
    ddpr
end

function solve{Algo<:DDPAlgorithm,T}(ddp::DiscreteDP{T}, v_init::Vector{T},
                                   method::Type{Algo}=VFI; max_iter::Integer=250,
                                   epsilon::Real=1e-3, k::Integer=20)
    ddpr = DPSolveResult{Algo,T}(ddp, v_init)
    _solve!(ddp, ddpr, max_iter, epsilon, k)
    ddpr.mc = MarkovChain(ddp, ddpr)
    ddpr
end

# --------- #
# Other API #
# --------- #

"""
Returns the controlled Markov chain for a given policy `sigma`.

##### Parameters

- `ddp::DiscreteDP` : Object that contains the model parameters
- `ddpr::DPSolveResult` : Object that contains result variables

##### Returns

mc : MarkovChain
     Controlled Markov chain.
"""
QuantEcon.MarkovChain(ddp::DiscreteDP, ddpr::DPSolveResult) =
    MarkovChain(RQ_sigma(ddp, ddpr)[2])

"""
Method of `RQ_sigma` that extracts sigma from a `DPSolveResult`

See other docstring for details
"""
RQ_sigma(ddp::DiscreteDP, ddpr::DPSolveResult) = RQ_sigma(ddp, ddpr.sigma)

"""
Given a policy `sigma`, return the reward vector `R_sigma` and
the transition probability matrix `Q_sigma`.

##### Parameters

- `ddp::DiscreteDP` : Object that contains the model parameters
- `sigma::Vector{Int}`: policy rule vector

##### Returns

- `R_sigma::Array{Float64}`: Reward vector for `sigma`, of length n.

- `Q_sigma::Array{Float64}`: Transition probability matrix for `sigma`,
  of shape (n, n).

"""
function RQ_sigma{T<:Integer}(ddp::DDP, sigma::Array{T})
    R_sigma = [ddp.R[i, sigma[i]] for i in 1:length(sigma)]
    Q_sigma = hcat([getindex(ddp.Q, i, sigma[i], Colon())[:] for i=1:num_states(ddp)]...)
    return R_sigma, Q_sigma'
end

# TODO: express it in a similar way as above to exploit Julia's column major order
function RQ_sigma{T<:Integer}(ddp::DDPsa, sigma::Array{T})
    sigma_indices = Array(T, num_states(ddp))
    _find_indices!(get(ddp.a_indices), get(ddp.a_indptr), sigma, sigma_indices)
    R_sigma = ddp.R[sigma_indices]
    Q_sigma = ddp.Q[sigma_indices, :]
    return R_sigma, Q_sigma
end

# ---------------- #
# Internal methods #
# ---------------- #

## s_wise_max for DDP

s_wise_max(ddp::DiscreteDP, vals::AbstractMatrix) = s_wise_max(vals)

s_wise_max!(ddp::DiscreteDP, vals::AbstractMatrix, out::Vector, out_argmax::Vector) =
    s_wise_max!(vals, out, out_argmax)

"""
Return the `Vector` `max_a vals(s, a)`,  where `vals` is represented as a
`AbstractMatrix` of size `(num_states, num_actions)`.
"""
s_wise_max(vals::AbstractMatrix) = vec(maximum(vals, 2))

"""
Populate `out` with  `max_a vals(s, a)`,  where `vals` is represented as a
`AbstractMatrix` of size `(num_states, num_actions)`.
"""
s_wise_max!(vals::AbstractMatrix, out::Vector) = (println("calling this one! "); maximum!(out, vals))

"""
Populate `out` with  `max_a vals(s, a)`,  where `vals` is represented as a
`AbstractMatrix` of size `(num_states, num_actions)`.

Also fills `out_argmax` with the column number associated with the indmax in
each row
"""
function s_wise_max!(vals::AbstractMatrix, out::Vector, out_argmax::Vector)
    # naive implementation where I just iterate over the rows
    nr, nc = size(vals)
    for i_r in 1:nr
        # reset temporaries
        cur_max = -Inf
        out_argmax[i_r] = 1

        for i_c in 1:nc
            @inbounds v_rc = vals[i_r, i_c]
            if v_rc > cur_max
                out[i_r] = v_rc
                out_argmax[i_r] = i_c
                cur_max = v_rc
            end
        end

    end
    out, out_argmax
end

## s_wise_max for DDPsa

function s_wise_max(ddp::DDPsa, vals::Vector)
    s_wise_max!(get(ddp.a_indices), get(ddp.a_indptr), vals,
                 Array(Float64, num_states(ddp)))
end

s_wise_max!(ddp::DDPsa, vals::Vector, out::Vector, out_argmax::Vector) =
    s_wise_max!(get(ddp.a_indices), get(ddp.a_indptr), vals, out, out_argmax)

"""
Populate `out` with  `max_a vals(s, a)`,  where `vals` is represented as a
`Vector` of size `(num_sa_pairs,)`.
"""
function s_wise_max!(a_indices::Vector, a_indptr::Vector, vals::Vector,
                      out::Vector)
    n = length(out)
    for i in 1:n
        if a_indptr[i] != a_indptr[i+1]
            m = a_indptr[i]
            for j in a_indptr[i]+1:(a_indptr[i+1]-1)
                if vals[j] > vals[m]
                    m = j
                end
            end
            out[i] = vals[m]
        end
    end
    return out
end

"""
Populate `out` with  `max_a vals(s, a)`,  where `vals` is represented as a
`Vector` of size `(num_sa_pairs,)`.

Also fills `out_argmax` with the cartesiean index associated with the indmax in
each row
"""
function s_wise_max!(a_indices::Vector, a_indptr::Vector, vals::Vector,
                      out::Vector, out_argmax::Vector)
    n = length(out)
    for i in 1:n
        if a_indptr[i] != a_indptr[i+1]
            m = a_indptr[i]
            for j in a_indptr[i]+1:(a_indptr[i+1]-1)
                if vals[j] > vals[m]
                    m = j
                end
            end
            out[i] = vals[m]
            out_argmax[i] = a_indices[m]
        end
    end
    out, out_argmax
end

"""
Check whether `s_indices` and `a_indices` are sorted in lexicographic order.

Parameters
----------
s_indices, a_indices : Vectors

Returns
-------
bool: Whether `s_indices` and `a_indices` are sorted.
"""
function _has_sorted_sa_indices(s_indices::Vector, a_indices::Vector)
    L = length(s_indices)
    for i in 1:L-1
        if s_indices[i] > s_indices[i+1]
            return false
        end
        if s_indices[i] == s_indices[i+1]
            if a_indices[i] >= a_indices[i+1]
                return false
            end
        end
    end
    return true
end

"""
Generate `a_indptr`; stored in `out`. `s_indices` is assumed to be
in sorted order.

Parameters
----------
num_states : Int

s_indices : Vector{Int}

out : Vector{Int} with length = num_states+1
"""
function _generate_a_indptr!(num_states::Int, s_indices::Vector, out::Vector)
    idx = 1
    out[1] = 1
    for s in 1:num_states-1
        while(s_indices[idx] == s)
            idx += 1
        end
        out[s+1] = idx
    end
    # need this +1 to be consistent with Julia's sparse pointers:
    # colptr[i]:(colptr[i+1]-1)
    out[num_states+1] = length(s_indices)+1
    out
end

function _find_indices!(a_indices::Vector, a_indptr::Vector, sigma::Vector,
                        out::Vector)
    n = length(sigma)
    for i in 1:n, j in a_indptr[i]:(a_indptr[i+1]-1)
        if sigma[i] == a_indices[j]
            out[i] = j
        end
    end
end

"""
Define Matrix Multiplication between 3-dimensional matrix and a vector

Matrix multiplication over the last dimension of A

"""
function *{T}(A::Array{T,3}, v::Vector)
    shape = size(A)
    size(v, 1) == shape[end] || error("wrong dimensions")

    B = reshape(A, (prod(shape[1:end-1]), shape[end]))
    out = B * v

    return reshape(out, shape[1:end-1])
end

"""
Impliments Value Iteration
NOTE: See `solve` for further details
"""
function _solve!(ddp::DiscreteDP, ddpr::DPSolveResult{VFI}, max_iter::Integer,
                 epsilon::Real, k::Integer)
    if ddp.beta == 0.0
        tol = Inf
    else
        tol = epsilon * (1-ddp.beta) / (2*ddp.beta)
    end

    for i in 1:max_iter
        # updates Tv in place
        bellman_operator!(ddp, ddpr)

        # compute error and update the v inside ddpr
        err = maxabs(ddpr.Tv .- ddpr.v)
        copy!(ddpr.v, ddpr.Tv)
        ddpr.num_iter += 1

        if err < tol
            break
        end
    end

    ddpr
end

"""
Policy Function Iteration

NOTE: The epsilon is ignored in this method. It is only here so dispatch can
      go from `solve(::DiscreteDP, ::Type{Algo})` to any of the algorithms.
      See `solve` for further details
"""
function _solve!(ddp::DiscreteDP, ddpr::DPSolveResult{PFI}, max_iter::Integer,
                 epsilon::Real, k::Integer)
    old_sigma = copy(ddpr.sigma)

    for i in 1:max_iter
       ddpr.v = evaluate_policy(ddp, ddpr)
       compute_greedy!(ddp, ddpr)

       ddpr.num_iter += 1
       if all(old_sigma .== ddpr.sigma)
           break
       end
       copy!(old_sigma, ddpr.sigma)

    end

    ddpr
end

span(x::Vector) = maximum(x) - minimum(x)
midrange(x::Vector) = mean(extrema(x))

"""
Modified Policy Function Iteration
"""
function _solve!(ddp::DiscreteDP, ddpr::DPSolveResult{MPFI}, max_iter::Integer,
                 epsilon::Real, k::Integer)
    beta = ddp.beta
    fill!(ddpr.v, minimum(ddp.R[ddp.R .> -Inf]) / (1.0 - beta))
    old_sigma = copy(ddpr.sigma)

    tol = beta > 0 ? epsilon * (1-beta) / beta : Inf

    for i in 1:max_iter
        bellman_operator!(ddp, ddpr)  # updates Tv, sigma inplace
        dif = ddpr.Tv - ddpr.v

        ddpr.num_iter += 1

        # check convergence
        if span(dif) < tol
            ddpr.v = ddpr.Tv + midrange(dif) * beta / (1-beta)
            break
        end

        # now update v to use the output of the bellman step when entering
        # policy loop
        copy!(ddpr.v, ddpr.Tv)

        # now do k iterations of policy iteration
        R_sigma, Q_sigma = RQ_sigma(ddp, ddpr)
        for i in 1:k
            ddpr.Tv = R_sigma + beta * Q_sigma * ddpr.v
            copy!(ddpr.v, ddpr.Tv)
        end

    end

    ddpr
end


text:
require "resque/failure/multiple"
require "resque/failure/redis"
require "resque/rollbar"
require "resque-retry"
require "resque-retry/server"

# Enable resque-retry failure backend.
Resque::Failure::MultipleWithRetrySuppression.classes = [Resque::Failure::Rollbar, Resque::Failure::Redis]
Resque::Failure.backend = Resque::Failure::MultipleWithRetrySuppression

Resque.redis.namespace = "resque:Cyclescape"
Resque.inline = true if Rails.env.test?

Resque.after_fork do
  defined?(ActiveRecord::Base) && ActiveRecord::Base.establish_connection
end

Resque.before_fork do
  defined?(ActiveRecord::Base) && ActiveRecord::Base.connection.disconnect!
end

module ActionMailer
  class DeliveryJob
    retry_on StandardError, wait: :exponentially_longer, attempts: 5
  end
end

module ActiveJob
  class Base
    retry_on StandardError, wait: :exponentially_longer, attempts: 5
  end
end


text:
package com.huawei.esdk.ev3.common;

public class FoundPositionCmd implements NetMessage {

	/**
	 * UID
	 */
	private static final long serialVersionUID = -2603382574187963030L;

}


text:
/**
 * Grant.java
 *
 * This file was auto-generated from WSDL
 * by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
 */

package org.jets3t.service.impl.soap.axis._2006_03_01;

public class Grant  implements java.io.Serializable {
    private org.jets3t.service.impl.soap.axis._2006_03_01.Grantee grantee;

    private org.jets3t.service.impl.soap.axis._2006_03_01.Permission permission;

    public Grant() {
    }

    public Grant(
           org.jets3t.service.impl.soap.axis._2006_03_01.Grantee grantee,
           org.jets3t.service.impl.soap.axis._2006_03_01.Permission permission) {
           this.grantee = grantee;
           this.permission = permission;
    }

    /**
     * Gets the grantee value for this Grant.
     *
     * @return grantee
     */
    public org.jets3t.service.impl.soap.axis._2006_03_01.Grantee getGrantee() {
        return grantee;
    }

    /**
     * Sets the grantee value for this Grant.
     *
     * @param grantee
     */
    public void setGrantee(org.jets3t.service.impl.soap.axis._2006_03_01.Grantee grantee) {
        this.grantee = grantee;
    }

    /**
     * Gets the permission value for this Grant.
     *
     * @return permission
     */
    public org.jets3t.service.impl.soap.axis._2006_03_01.Permission getPermission() {
        return permission;
    }

    /**
     * Sets the permission value for this Grant.
     *
     * @param permission
     */
    public void setPermission(org.jets3t.service.impl.soap.axis._2006_03_01.Permission permission) {
        this.permission = permission;
    }

    private java.lang.Object __equalsCalc = null;
    public synchronized boolean equals(java.lang.Object obj) {
        if (!(obj instanceof Grant)) return false;
        Grant other = (Grant) obj;
        if (obj == null) return false;
        if (this == obj) return true;
        if (__equalsCalc != null) {
            return (__equalsCalc == obj);
        }
        __equalsCalc = obj;
        boolean _equals;
        _equals = true &&
            ((this.grantee==null && other.getGrantee()==null) ||
             (this.grantee!=null &&
              this.grantee.equals(other.getGrantee()))) &&
            ((this.permission==null && other.getPermission()==null) ||
             (this.permission!=null &&
              this.permission.equals(other.getPermission())));
        __equalsCalc = null;
        return _equals;
    }

    private boolean __hashCodeCalc = false;
    public synchronized int hashCode() {
        if (__hashCodeCalc) {
            return 0;
        }
        __hashCodeCalc = true;
        int _hashCode = 1;
        if (getGrantee() != null) {
            _hashCode += getGrantee().hashCode();
        }
        if (getPermission() != null) {
            _hashCode += getPermission().hashCode();
        }
        __hashCodeCalc = false;
        return _hashCode;
    }

    // Type metadata
    private static org.apache.axis.description.TypeDesc typeDesc =
        new org.apache.axis.description.TypeDesc(Grant.class, true);

    static {
        typeDesc.setXmlType(new javax.xml.namespace.QName("http://s3.amazonaws.com/doc/2006-03-01/", "Grant"));
        org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("grantee");
        elemField.setXmlName(new javax.xml.namespace.QName("http://s3.amazonaws.com/doc/2006-03-01/", "Grantee"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://s3.amazonaws.com/doc/2006-03-01/", "Grantee"));
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
        elemField = new org.apache.axis.description.ElementDesc();
        elemField.setFieldName("permission");
        elemField.setXmlName(new javax.xml.namespace.QName("http://s3.amazonaws.com/doc/2006-03-01/", "Permission"));
        elemField.setXmlType(new javax.xml.namespace.QName("http://s3.amazonaws.com/doc/2006-03-01/", "Permission"));
        elemField.setNillable(false);
        typeDesc.addFieldDesc(elemField);
    }

    /**
     * Return type metadata object
     */
    public static org.apache.axis.description.TypeDesc getTypeDesc() {
        return typeDesc;
    }

    /**
     * Get Custom Serializer
     */
    public static org.apache.axis.encoding.Serializer getSerializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanSerializer(
            _javaType, _xmlType, typeDesc);
    }

    /**
     * Get Custom Deserializer
     */
    public static org.apache.axis.encoding.Deserializer getDeserializer(
           java.lang.String mechType,
           java.lang.Class _javaType,
           javax.xml.namespace.QName _xmlType) {
        return
          new  org.apache.axis.encoding.ser.BeanDeserializer(
            _javaType, _xmlType, typeDesc);
    }

}


text:
import { NgModule }               from '@angular/core';
import { RouterModule, Routes }   from '@angular/router';
import { AuthGuard }              from './core/services/auth-guard.service';
import { PreloadSelectedModules } from './core/services/selective-preload-strategy';
import { NotFoundComponent }      from './shared/not-found.component';

const routes: Routes = [
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'news',
  },
  {
    path: 'dynamic',
    loadChildren: './dynamic-form/dynamic-form.module#DynamicFormModule',
    data: {
      title: 'My dynamic',
    }
  },
  {
    path: 'admin',
    loadChildren: './admin/admin.module#AdminModule',
    canLoad: [AuthGuard]
  },
  {
    path: 'user',
    loadChildren: './user/user.module#UserModule',
    data: {
      preload: true,
    }
  },
  {
    path: 'about',
    loadChildren: './about/about.module#AboutModule',
    data: {
      preload: true,
    }
  },
  {
    path: 'department',
    loadChildren: './department/department.module#DepartmentModule',
    data: {
      preload: true,
    }
  },
  {
    path: 'equipment',
    loadChildren: './equipment/equipment.module#EquipmentModule',
    data: {
      preload: true,
    }
  },
  {
    path: 'news',
    loadChildren: './news/news.module#NewsModule',
    data: {
      preload: true,
    }
  },
  {
    path: 'projects',
    loadChildren: './projects/projects.module#ProjectsModule',
    data: {
      preload: true,
    }
  },
  {
    path: 'publications',
    loadChildren: './publications/publications.module#PublicationsModule',
    data: {
      preload: true,
    }
  },
  {
    path: 'staff',
    loadChildren: './staff/staff.module#StaffModule',
    data: {
      preload: true,
    }
  },
  {
    path: 'notfound',
    component: NotFoundComponent,
  },
];

@NgModule({
  imports: [ RouterModule.forRoot(routes, { preloadingStrategy: PreloadSelectedModules }) ],
  exports: [ RouterModule ],
})
export class AppRoutingModule {}


text:
class Coupon < ApplicationRecord
end


text:
package io.craft.atom.nio;

import io.craft.atom.io.AbstractChannelEvent;
import io.craft.atom.io.Channel;
import io.craft.atom.io.ChannelEvent;
import io.craft.atom.io.ChannelEventType;
import lombok.ToString;

/**
 * @author mindwind
 * @version 1.0, Feb 26, 2013
 */
@ToString(callSuper = true, of = "channel")
abstract public class AbstractNioByteChannelEvent extends AbstractChannelEvent implements ChannelEvent<byte[]> {

	protected final NioByteChannel channel;

	// ~ --------------------------------------------------------------------------------------------------------------

	AbstractNioByteChannelEvent(ChannelEventType type, NioByteChannel channel) {
		super(type);
		if (channel == null) {
            throw new IllegalArgumentException("channel == null");
        }
		this.channel = channel;
	}

	// ~ --------------------------------------------------------------------------------------------------------------

	@Override
	public Channel<byte[]> getChannel() {
		return channel;
	}

}


text:
'use strict';

var fs = require('fs');
var path = require('path');

var Hapi = require('hapi');

var server = new Hapi.Server();
var InsultGenerator = require('../lib/InsultGenerator');

var insults = new InsultGenerator({
  file : path.resolve(__dirname, '../ext/words.tab')
});
var replaceRe = /{{insult}}/
var template;

server.connection({
    host: 'localhost',
    port: 9200
});

server.route({
    method: 'GET',
    path:'/',
    handler: function (request, reply) {
      insults.generate().then(function (insult) {
        reply(template.replace(replaceRe, insult));
      });
    }
});

server.route({
    method: 'GET',
    path:'/raw',
    handler: function (request, reply) {
      insults.generate().then(function (insult) {
        reply(insult);
      });
    }
});

// Preload stuff, then run
console.log("Loading template...");
fs.readFile(path.resolve(__dirname, '../ext/index.html'), {encoding: 'utf8'}, function (err, contents) {

  if (err) {
    console.error(err);
    process.exit(1)
  }

  template = contents;
  console.log("Setting up insults...")
  insults.generate().then(function (insult) {
    server.start(function() {
      console.log('Server running at:', server.info.uri);
    });
  }).catch(function (err) {
    console.error(err);
    console.log("Error running insults... bad augur");
    process.exit(1);
  });
});


text:
/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Soumyajit De, Heiko Strathmann, Bjoern Esser
 */

#ifndef LOG_RATIONAL_APPROXIMATION_INDIVIDUAL_H_
#define LOG_RATIONAL_APPROXIMATION_INDIVIDUAL_H_

#include <shogun/lib/config.h>
#include <shogun/mathematics/linalg/ratapprox/opfunc/RationalApproximation.h>

namespace shogun
{

template<class T> class SGVector;
template<class T> class CMatrixOperator;
template<class T, class ST> class CLinearSolver;

/** @brief Implementaion of rational approximation of a operator-function times
 * vector where the operator function is log of a dense-matrix. Each complex
 * system generated from the shifts due to rational approximation of opertor-
 * log times vector expression are solved individually with a complex linear
 * solver.
 */
class CLogRationalApproximationIndividual : public CRationalApproximation
{
public:
	/** default constructor */
	CLogRationalApproximationIndividual();

	/**
	 * Constructor. Number of shifts will be computed using a specified accuracy.
	 *
	 * @param linear_operator matrix linear operator of the log function
	 * @param eigen_solver eigen solver for computing min and max eigenvalues
	 * needed for computing shifts, weights and multiplier in the rational
	 * approximation
	 * @param linear_solver linear solver for solving complex systems
	 * @param desired_accuracy desired error bound on approximation. Computes
	 * the number of shifts automatically
	 */
	CLogRationalApproximationIndividual(
		CMatrixOperator<float64_t>* linear_operator,
		CEigenSolver* eigen_solver,
		CLinearSolver<complex128_t, float64_t>* linear_solver,
		float64_t desired_accuracy);

	/** destructor */
	virtual ~CLogRationalApproximationIndividual();

	/**
	 *method that solves the result for a sample
	 */
	virtual float64_t compute(SGVector<float64_t> sample) const;

	/** @return object name */
	virtual const char* get_name() const
	{
		return "LogRationalApproximationIndividual";
	}

private:
	/** the linear solver for solving complex systems */
	CLinearSolver<complex128_t, float64_t>* m_linear_solver;

	/** initialize with default values and register params */
	void init();
};

}

#endif // LOG_RATIONAL_APPROXIMATION_INDIVIDUAL_H_


text:
package org.eclipse.flux.sync;

/**
 * This is an operation to insert a number of characters at the given position
 *
 * @author Martin Lippert
 */
public class InsertOperation extends AbstractOperation {

	private final String characters;
	private final int position;

	/**
	 * create a new insert operation
	 * @param id The globally unique ID of this insertion, usually consists of the ID of the sync participant and an ID for the operation
	 * @param previousOperation The previous operation to this one
	 * @param characters The characters to be inserted into the document
	 * @param position The position at which the characters should be inserted
	 */
	public InsertOperation(final String id, final String previousOperation, final String characters, final int position) {
		super(id, previousOperation);
		this.characters = characters;
		this.position = position;
	}

	/**
	 * @return the characters
	 */
	public String getCharacters() {
		return characters;
	}

	/**
	 * @return the position
	 */
	public int getPosition() {
		return position;
	}

	/**
	 * @param historicOperation
	 * @return
	 */
	public InsertOperation transformForward(AbstractOperation historicOperation) {
		InsertOperation transformed = null;
		if (historicOperation instanceof InsertOperation) {
			InsertOperation insertOp = (InsertOperation) historicOperation;
			if (this.getPosition() < insertOp.getPosition()) {
				return this;
			}
			else if (this.getPosition() > insertOp.getPosition()) {
				return new InsertOperation(this.getId(), insertOp.getId(), this.getCharacters(), this.getPosition() + insertOp.getCharacters().length());
			}
		}
		else if (historicOperation instanceof DeleteOperation) {

		}
		return transformed;
	}

}


text:
chorus.views.PublishedWorkletList = chorus.views.Base.extend({
    constructorName: "PublishedWorkletListView",
    templateName: "published_worklet_list",

    collectionModelContext: function (model) {
        return {
            url: model.showUrl(),
            avatarUrl: model.url({workflow_action: 'image'})
        };
    },

    postRender: function() {
        // KT: a hack to adapt list_content_details.hbs to our needs:
        $(".list_content_details").find(".count").detach().prependTo('.list_content_details');
    }
});


text:
The classical introductory exercise. Just say "Hello, World!".

["Hello, World!"](http://en.wikipedia.org/wiki/%22Hello,_world!%22_program) is
the traditional first program for beginning programming in a new language
or environment.

The objectives are simple:

- Write a function that returns the string "Hello, World!".
- Run the test suite and make sure that it succeeds.
- Submit your solution and check it at the website.

If everything goes well, you will be ready to fetch your first real exercise.

### Project Structure

Clojure exercises in exercism use [leiningen](http://leiningen.org/) to configure and run your code
and use [leiningen standard directory structure](https://github.com/technomancy/leiningen/blob/master/doc/TUTORIAL.md#directory-layout).

You will find a test file named `hello_world_test.clj` inside `test` directory.
Write your code in `src/hello_world.clj`. It should use the namespace `hello-world` so that tests can pick it up.

### Running tests

Run the tests using `lein test` command and make them pass:

```
$ lein test

lein test hello-world-test

Ran 1 tests containing 1 assertions.
0 failures, 0 errors.
```

Then submit the exercise using:

```
$ exercism submit src/hello_world.clj
```

For more detailed instructions and learning resources refer [exercism's clojure language page](http://exercism.io/languages/clojure).

## Source

This is an exercise to introduce users to using Exercism [http://en.wikipedia.org/wiki/%22Hello,_world!%22_program](http://en.wikipedia.org/wiki/%22Hello,_world!%22_program)

## Submitting Incomplete Solutions
It's possible to submit an incomplete solution so you can see how others have completed the exercise.


text:
package reactor.core.publisher;

import java.util.Arrays;

import org.junit.Assert;
import org.junit.Test;

import reactor.test.subscriber.AssertSubscriber;

public class FluxFirstEmittingWithTest {

	@Test
	public void noStackOverflow() {
		int n = 5000;

		Flux<Integer> source = Flux.just(1);

		Flux<Integer> result = source;

		for (int i = 0; i < n; i++) {
			result = result.or(source);
		}

		AssertSubscriber<Integer> ts = AssertSubscriber.create();

		result.subscribe(ts);

		ts.assertValues(1)
		.assertNoError()
		.assertComplete();
	}

	@Test
	public void dontBreakAmb() {
		AssertSubscriber<Integer> ts = AssertSubscriber.create();

		Flux.first(Flux.just(1), Flux.just(2)).or(Flux.just(3))
		    .subscribe(ts);

		ts.assertValues(1)
		.assertNoError()
		.assertComplete();
	}

	@Test
	public void pairWise() {
		Flux<Integer> f = Flux.first(Mono.just(1), Mono.just(2))
		                      .or(Mono.just(3));

		Assert.assertTrue(f instanceof FluxFirstEmitting);
		FluxFirstEmitting<Integer> s = (FluxFirstEmitting<Integer>) f;
		Assert.assertTrue(s.array != null);
		Assert.assertTrue(s.array.length == 3);

		f.subscribeWith(AssertSubscriber.create())
		 .assertValues(1)
		 .assertComplete();
	}

	@Test
	public void pairWiseIterable() {
		Flux<Integer> f = Flux.first(Arrays.asList(Mono.just(1), Mono.just(2)))
		                      .or(Mono.just(3));

		Assert.assertTrue(f instanceof FluxFirstEmitting);
		FluxFirstEmitting<Integer> s = (FluxFirstEmitting<Integer>) f;
		Assert.assertTrue(s.array != null);
		Assert.assertTrue(s.array.length == 2);

		f.subscribeWith(AssertSubscriber.create())
		 .assertValues(1)
		 .assertComplete();
	}
}