text:
package manifold.internal.javac;

import com.sun.source.util.TaskEvent;
import com.sun.tools.javac.parser.*;
import com.sun.tools.javac.util.Context;
import java.nio.CharBuffer;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.tools.JavaFileObject;

import manifold.util.JreUtil;
import manifold.util.ReflectUtil;

import static com.sun.tools.javac.parser.Tokens.TokenKind.STRINGLITERAL;

/**
 * Override ParserFactory to:

 * - facilitate a pluggable Java preprocessor

 * - handle embedded file fragments in comment tokens

 */
public class ManParserFactory_8 extends ParserFactory implements ParserFactoryFiles
{
  private TaskEvent _taskEvent;
  private final Preprocessor _preprocessor;

  public static ManParserFactory_8 instance( Context ctx )
  {
    ParserFactory parserFactory = ctx.get( parserFactoryKey );
    if( !(parserFactory instanceof ManParserFactory_8) )
    {
      ctx.put( parserFactoryKey, (ParserFactory)null );
      parserFactory = new ManParserFactory_8( ctx );
    }

    return (ManParserFactory_8)parserFactory;
  }

  private ManParserFactory_8( Context ctx )
  {
    super( ctx );
    _preprocessor = Preprocessor.instance( ctx );
    ReflectUtil.field( this, "scannerFactory" ).set( ManScannerFactory.instance( ctx, this ) );
  }

  @Override
  public JavacParser newParser( CharSequence input, boolean keepDocComments, boolean keepEndPos, boolean keepLineMap )
  {
    return newParser( input, keepDocComments, keepEndPos, keepLineMap, false );
  }

  //override Java 9+
  @SuppressWarnings("unused")
  public JavacParser newParser( CharSequence input, boolean keepDocComments, boolean keepEndPos, boolean keepLineMap, boolean parseModuleInfo )
  {
    input = _preprocessor.process( _taskEvent.getSourceFile(), input );
    mapInput( _taskEvent.getSourceFile(), input );
    Lexer lexer = ((ScannerFactory)ReflectUtil.field( this, "scannerFactory" ).get()).newScanner(input, keepDocComments);
    return (JavacParser)ReflectUtil.constructor( "com.sun.tools.javac.parser.ManJavacParser",
      ParserFactory.class, Lexer.class, boolean.class, boolean.class, boolean.class, boolean.class )
      .newInstance( this, lexer, keepDocComments, keepLineMap, keepEndPos, parseModuleInfo );
  }

  private void mapInput( JavaFileObject sourceFile, CharSequence input )
  {
    fileToProcessedInput.put( sourceFile.getName(), input );
  }

  @Override
  public void setTaskEvent( TaskEvent e )
  {
    _taskEvent = e;
  }

  /**
   * Override ScannerFactory so we can examine tokens as they are read.  This is purely a performance measure to avoid
   * having to tokenize each source file twice.
   */
  public static class ManScannerFactory extends ScannerFactory
  {
    private final ManParserFactory_8 _parserFactory;

    public static ScannerFactory instance( Context ctx, ManParserFactory_8 parserFactory )
    {
      ScannerFactory scannerFactory = ctx.get( scannerFactoryKey );
      if( !(scannerFactory instanceof ManScannerFactory) )
      {
        ctx.put( scannerFactoryKey, (ScannerFactory)null );
        scannerFactory = new ManScannerFactory( ctx, parserFactory );
      }

      return scannerFactory;
    }

    private ManScannerFactory( Context ctx, ManParserFactory_8 parserFactory )
    {
      super( ctx );
      _parserFactory = parserFactory;
    }

    public Scanner newScanner( CharSequence input, boolean keepDocComments )
    {
      if( input instanceof CharBuffer )
      {
        CharBuffer buf = (CharBuffer)input;
        if( keepDocComments )
        {
          return new ManScanner( this, new ManJavadocTokenizer( this, buf ) );
        }
        else
        {
          return new ManScanner( this, buf );
        }
      }
      else
      {
        char[] array = input.toString().toCharArray();
        return newScanner( array, array.length, keepDocComments );
      }
    }

    public Scanner newScanner( char[] input, int inputLength, boolean keepDocComments )
    {
      if( keepDocComments )
      {
        return new ManScanner( this, new ManJavadocTokenizer( this, input, inputLength ) );
      }
      else
      {
        return new ManScanner( this, input, inputLength );
      }
    }

    private class ManJavadocTokenizer extends JavadocTokenizer
    {
      private final ManScannerFactory _scannerFactory;
      private final UnicodeReader _reader;

      ManJavadocTokenizer( ManScannerFactory manScannerFactory, CharBuffer buf )
      {
        super( manScannerFactory, buf );
        _scannerFactory = manScannerFactory;
        //noinspection ConstantConditions
        _reader = JreUtil.isJava16orLater() ? (UnicodeReader)(Object)this : reader();
      }

      private UnicodeReader reader()
      {
        return (UnicodeReader)ReflectUtil.field( this, "reader" ).get();
      }

      ManJavadocTokenizer( ManScannerFactory manScannerFactory, char[] input, int inputLength )
      {
        super( manScannerFactory, input, inputLength );
        _scannerFactory = manScannerFactory;
        //noinspection ConstantConditions
        _reader = JreUtil.isJava16orLater() ? (UnicodeReader)(Object)this : reader();
      }

      protected Tokens.Comment processComment( int pos, int endPos, Tokens.Comment.CommentStyle style )
      {
        Tokens.Comment comment = super.processComment( pos, endPos, style );
        char[] buf = _reader.getRawCharacters( pos, endPos );
        FragmentProcessor.instance().processComment(
          _scannerFactory._parserFactory._taskEvent.getSourceFile(), pos, new String( buf ), style );
        return comment;
      }

      public Tokens.Token readToken()
      {
        Tokens.Token token = super.readToken();
        if( token.kind == STRINGLITERAL )
        {
          // todo: passing raw characters means we must parse string literal escaped chars esp. '"', '\n', unicode
          char[] buf = _reader.getRawCharacters( token.pos, token.endPos );
          FragmentProcessor.instance().processString(
            ((ManScannerFactory)ReflectUtil.field( this, "fac" ).get())._parserFactory._taskEvent.getSourceFile(), token.pos, new String( buf ) );
        }
        return token;
      }
    }

    private static class ManScanner extends Scanner
    {
      ManScanner( ManScannerFactory manScannerFactory, JavaTokenizer manJavadocTokenizer )
      {
        super( manScannerFactory, manJavadocTokenizer );
      }

      ManScanner( ManScannerFactory fac, char[] buf, int len )
      {
        this( fac, new ManJavaTokenizer( fac, buf, len ) );
      }

      ManScanner( ManScannerFactory fac, CharBuffer buf )
      {
        this( fac, new ManJavaTokenizer( fac, buf ) );
      }

      private static class ManJavaTokenizer extends JavaTokenizer
      {
        private final UnicodeReader _reader;

        ManJavaTokenizer( ManScannerFactory fac, char[] buf, int len )
        {
          super( fac, buf, len );
          //noinspection ConstantConditions
          _reader = JreUtil.isJava16orLater() ? (UnicodeReader)(Object)this : reader();
        }

        ManJavaTokenizer( ManScannerFactory fac, CharBuffer buf )
        {
          super( fac, buf );
          //noinspection ConstantConditions
          _reader = JreUtil.isJava16orLater() ? (UnicodeReader)(Object)this : reader();
        }

        private UnicodeReader reader()
        {
          return (UnicodeReader)ReflectUtil.field( this, "reader" ).get();
        }

        protected Tokens.Comment processComment( int pos, int endPos, Tokens.Comment.CommentStyle style )
        {
          Tokens.Comment comment = super.processComment( pos, endPos, style );
          char[] buf = _reader.getRawCharacters( pos, endPos );
          FragmentProcessor.instance().processComment(
            ((ManScannerFactory)fac)._parserFactory._taskEvent.getSourceFile(), pos, new String( buf ), style );
          return comment;
        }

        public Tokens.Token readToken()
        {
          Tokens.Token token = super.readToken();
          if( token.kind == STRINGLITERAL )
          {
            char[] buf = _reader.getRawCharacters( token.pos, token.endPos );
            FragmentProcessor.instance().processString(
              ((ManScannerFactory)fac)._parserFactory._taskEvent.getSourceFile(), token.pos, new String( buf ) );
          }
          return token;
        }
      }
    }
  }
}


text:
ALTER TABLE `results_v0`
	ADD COLUMN `username` VARCHAR(255) NULL AFTER `time_inserted`;

redpajama_set_name: RedPajamaGithub


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Face Recognition</title>
        <link href="vendor/css/bootstrap.min.css" rel="stylesheet">
        <link href="vendor/css/bootstrap-toggle.min.css" rel="stylesheet">
        <link href="vendor/css/bootstrap-dialog.min.css" rel="stylesheet">
        <link href="css/main.css" rel="stylesheet">

                <video id="videoel" width="400" height="300"
                       preload="auto" loop></video>

People in Video

Servers:

                    <button type="button" class="btn btn-default active">CMU</button>
                    <button type="button" class="btn btn-default">AWS East</button>
                    <button type="button" class="btn btn-default">AWS West</button>

Null Server RTTs

                        CMU: Not yet used.

                        AWS East: Not yet used.

                        AWS West: Not yet used.

Training
                    <input type="checkbox" checked data-toggle="toggle"
                           id="trainingChk">

                    <input type="text" class="form-control" id="addPersonTxt">

                        <button class="btn btn-default" type="button"
                                id="addPersonBtn">
                            Add Person
                        </button>

                    <button class="btn btn-default" type="button"
                            id="viewTSNEBtn">
                        Visualize with TSNE
                    </button>


text:
using System.Linq;
using Elders.Cronus;
using Elders.Cronus.Projections;
using Machine.Specifications;
using PushNotifications.Contracts;
using PushNotifications.Contracts.Subscriptions;
using PushNotifications.Contracts.Subscriptions.Events;
using PushNotifications.Projections.Subscriptions;

namespace PushNotifications.Tests.PushNotifications
{
    [Subject(nameof(SubscriberTokensProjection))]
    public class When_subscriber_has_subscribed
    {
        Establish context = () =>
        {
            var id = new SubscriptionId("id", "elders");
            projection = new SubscriberTokensProjection();
            subscriptionToken = new SubscriptionToken("token", SubscriptionType.FireBase);
            subscriberId = new SubscriberId("kv", "elders");
            @event = new Subscribed(id, subscriberId, subscriptionToken);
        };

        Because of = () => projection.Handle(@event);

        It should_subscribe_for_the_event = () => ((IProjectionDefinition)projection).GetProjectionIds(@event).ShouldContain(subscriberId);
        It should_handle_the_event = () => typeof(IEventHandler<Subscribed>).IsAssignableFrom(projection.GetType()).ShouldBeTrue();

        It should_have_correct_id = () => projection.State.SubscriberId.ShouldEqual(subscriberId);
        It should_have_valid_subscription_tokens = () => projection.State.Tokens.ShouldNotBeNull();
        It should_have_correct_subscription_token = () => projection.State.Tokens.Single().ShouldEqual(subscriptionToken);

        static SubscriberTokensProjection projection;
        static SubscriberId subscriberId;
        static SubscriptionToken subscriptionToken;
        static Subscribed @event;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/backdrop"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop"
        tools:src="@tools:sample/backgrounds/scenic" />

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        app:cardElevation="4dp"
        app:contentPadding="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                style="@style/TextAppearance.AppCompat.Large"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="8dp"
                android:text="Welcome" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:padding="8dp"
                android:text="How would you like to view the weather?" />

            <Button
                android:id="@+id/location_button"
                style="@style/Widget.AppCompat.Button.Colored"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Use my current location" />

            <Button
                android:id="@+id/search_button"
                style="@style/Widget.AppCompat.Button.Borderless.Colored"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Search for a location" />

        </LinearLayout>

    </android.support.v7.widget.CardView>

</android.support.constraint.ConstraintLayout>


text:
import {Utils as _} from "../../utils";
import {Constants as constants, Constants} from "../../constants";
import {GridOptionsWrapper} from "../../gridOptionsWrapper";
import {ColumnController} from "../../columnController/columnController";
import {FilterManager} from "../../filter/filterManager";
import {RowNode} from "../../entities/rowNode";
import {EventService} from "../../eventService";
import {Events, ModelUpdatedEvent} from "../../events";
import {Bean, Context, Autowired, PostConstruct, Optional} from "../../context/context";
import {SelectionController} from "../../selectionController";
import {IRowNodeStage} from "../../interfaces/iRowNodeStage";
import {IInMemoryRowModel} from "../../interfaces/iInMemoryRowModel";
import {InMemoryNodeManager} from "./inMemoryNodeManager";

enum RecursionType {Normal, AfterFilter, AfterFilterAndSort, PivotNodes};

@Bean('rowModel')
export class InMemoryRowModel implements IInMemoryRowModel {

    @Autowired('gridOptionsWrapper') private gridOptionsWrapper: GridOptionsWrapper;
    @Autowired('columnController') private columnController: ColumnController;
    @Autowired('filterManager') private filterManager: FilterManager;
    @Autowired('$scope') private $scope: any;
    @Autowired('selectionController') private selectionController: SelectionController;
    @Autowired('eventService') private eventService: EventService;
    @Autowired('context') private context: Context;

    // standard stages
    @Autowired('filterStage') private filterStage: IRowNodeStage;
    @Autowired('sortStage') private sortStage: IRowNodeStage;
    @Autowired('flattenStage') private flattenStage: IRowNodeStage;

    // enterprise stages
    @Optional('groupStage') private groupStage: IRowNodeStage;
    @Optional('aggregationStage') private aggregationStage: IRowNodeStage;
    @Optional('pivotStage') private pivotStage: IRowNodeStage;

    // top most node of the tree. the children are the user provided data.
    private rootNode: RowNode;

    private rowsToDisplay: RowNode[]; // the rows mapped to rows to display

    private nodeManager: InMemoryNodeManager;

    @PostConstruct
    public init(): void {

        this.eventService.addModalPriorityEventListener(Events.EVENT_COLUMN_EVERYTHING_CHANGED, this.refreshModel.bind(this, {step: Constants.STEP_EVERYTHING} ));
        this.eventService.addModalPriorityEventListener(Events.EVENT_COLUMN_ROW_GROUP_CHANGED, this.refreshModel.bind(this, {step: Constants.STEP_EVERYTHING} ));
        this.eventService.addModalPriorityEventListener(Events.EVENT_COLUMN_VALUE_CHANGED, this.onValueChanged.bind(this));
        this.eventService.addModalPriorityEventListener(Events.EVENT_COLUMN_PIVOT_CHANGED, this.refreshModel.bind(this, {step: Constants.STEP_PIVOT} ));

        this.eventService.addModalPriorityEventListener(Events.EVENT_ROW_GROUP_OPENED, this.onRowGroupOpened.bind(this));
        this.eventService.addModalPriorityEventListener(Events.EVENT_FILTER_CHANGED, this.onFilterChanged.bind(this));
        this.eventService.addModalPriorityEventListener(Events.EVENT_SORT_CHANGED, this.onSortChanged.bind(this));
        this.eventService.addModalPriorityEventListener(Events.EVENT_COLUMN_PIVOT_MODE_CHANGED, this.refreshModel.bind(this, {step: Constants.STEP_PIVOT} ));

        this.rootNode = new RowNode();
        this.nodeManager = new InMemoryNodeManager(this.rootNode, this.gridOptionsWrapper, this.context, this.eventService);

        this.context.wireBean(this.rootNode);

        if (this.gridOptionsWrapper.isRowModelDefault()) {
            this.setRowData(this.gridOptionsWrapper.getRowData(), this.columnController.isReady());
        }
    }

    private onRowGroupOpened(): void {
        let animate = this.gridOptionsWrapper.isAnimateRows();
        this.refreshModel({step: Constants.STEP_MAP, keepRenderedRows: true, animate: animate});
    }

    private onFilterChanged(): void {
        var animate = this.gridOptionsWrapper.isAnimateRows();
        this.refreshModel({step: Constants.STEP_FILTER, keepRenderedRows: true, animate: animate});
    }

    private onSortChanged(): void {
        // we only act on the sort event here if the user is doing in grid sorting.
        // we ignore it if the sorting is happening on the server side.
        if (this.gridOptionsWrapper.isEnableServerSideSorting()) { return; }

        var animate = this.gridOptionsWrapper.isAnimateRows();
        this.refreshModel({step: Constants.STEP_SORT, keepRenderedRows: true, animate: animate});
    }

    public getType(): string {
        return Constants.ROW_MODEL_TYPE_NORMAL;
    }

    private onValueChanged(): void {
        if (this.columnController.isPivotActive()) {
            this.refreshModel({step: Constants.STEP_PIVOT});
        } else {
            this.refreshModel({step: Constants.STEP_AGGREGATE});
        }
    }

    public refreshModel(params: {step: number, groupState?: any, keepRenderedRows?: boolean, animate?: boolean}): void {

        // this goes through the pipeline of stages. what's in my head is similar
        // to the diagram on this page:
        // http://commons.apache.org/sandbox/commons-pipeline/pipeline_basics.html
        // however we want to keep the results of each stage, hence we manually call
        // each step rather than have them chain each other.

        // fallthrough in below switch is on purpose,
        // eg if STEP_FILTER, then all steps below this
        // step get done
        // var start: number;
        // console.log('======= start =======');

        switch (params.step) {
            case constants.STEP_EVERYTHING:
                // start = new Date().getTime();
                this.doRowGrouping(params.groupState);
                // console.log('rowGrouping = ' + (new Date().getTime() - start));
            case constants.STEP_FILTER:
                // start = new Date().getTime();
                this.doFilter();
                // console.log('filter = ' + (new Date().getTime() - start));
            case constants.STEP_PIVOT:
                this.doPivot();
            case constants.STEP_AGGREGATE: // depends on agg fields
                // start = new Date().getTime();
                this.doAggregate();
                // console.log('aggregation = ' + (new Date().getTime() - start));
            case constants.STEP_SORT:
                // start = new Date().getTime();
                this.doSort();
                // console.log('sort = ' + (new Date().getTime() - start));
            case constants.STEP_MAP:
                // start = new Date().getTime();
                this.doRowsToDisplay();
                // console.log('rowsToDisplay = ' + (new Date().getTime() - start));
        }

        let event: ModelUpdatedEvent = {animate: params.animate, keepRenderedRows: params.keepRenderedRows};
        this.eventService.dispatchEvent(Events.EVENT_MODEL_UPDATED, event);

        if (this.$scope) {
            setTimeout( () => {
                this.$scope.$apply();
            }, 0);
        }
    }

    public isEmpty(): boolean {
        var rowsMissing: boolean;

        var rowsAlreadyGrouped = _.exists(this.gridOptionsWrapper.getNodeChildDetailsFunc());
        if (rowsAlreadyGrouped) {
            rowsMissing = _.missing(this.rootNode.childrenAfterGroup) || this.rootNode.childrenAfterGroup.length === 0
        } else {
            rowsMissing = _.missing(this.rootNode.allLeafChildren) || this.rootNode.allLeafChildren.length === 0;
        }

        var empty = _.missing(this.rootNode) || rowsMissing  || !this.columnController.isReady();

        return empty;
    }

    public isRowsToRender(): boolean {
        return _.exists(this.rowsToDisplay) && this.rowsToDisplay.length > 0;
    }

    public setDatasource(datasource: any): void {
        console.error('ag-Grid: should never call setDatasource on inMemoryRowController');
    }

    public getTopLevelNodes() {
        return this.rootNode ? this.rootNode.childrenAfterGroup : null;
    }

    public getRow(index: number): RowNode {
        return this.rowsToDisplay[index];
    }

    public getVirtualRowCount(): number {
        console.warn('ag-Grid: rowModel.getVirtualRowCount() is not longer a function, use rowModel.getRowCount() instead');
        return this.getRowCount();
    }

    public getRowCount(): number {
        if (this.rowsToDisplay) {
            return this.rowsToDisplay.length;
        } else {
            return 0;
        }
    }

    public getRowIndexAtPixel(pixelToMatch: number): number {
        if (this.isEmpty()) {
            return -1;
        }

        // do binary search of tree
        // http://oli.me.uk/2013/06/08/searching-javascript-arrays-with-a-binary-search/
        var bottomPointer = 0;
        var topPointer = this.rowsToDisplay.length - 1;

        // quick check, if the pixel is out of bounds, then return last row
        if (pixelToMatch<=0) {
            // if pixel is less than or equal zero, it's always the first row
            return 0;
        }
        var lastNode = this.rowsToDisplay[this.rowsToDisplay.length-1];
        if (lastNode.rowTop<=pixelToMatch) {
            return this.rowsToDisplay.length - 1;
        }

        while (true) {

            var midPointer = Math.floor((bottomPointer + topPointer) / 2);
            var currentRowNode = this.rowsToDisplay[midPointer];

            if (this.isRowInPixel(currentRowNode, pixelToMatch)) {
                return midPointer;
            } else if (currentRowNode.rowTop < pixelToMatch) {
                bottomPointer = midPointer + 1;
            } else if (currentRowNode.rowTop > pixelToMatch) {
                topPointer = midPointer - 1;
            }

        }
    }

    private isRowInPixel(rowNode: RowNode, pixelToMatch: number): boolean {
        var topPixel = rowNode.rowTop;
        var bottomPixel = rowNode.rowTop + rowNode.rowHeight;
        var pixelInRow = topPixel <= pixelToMatch && bottomPixel > pixelToMatch;
        return pixelInRow;
    }

    public getRowCombinedHeight(): number {
        if (this.rowsToDisplay && this.rowsToDisplay.length > 0) {
            var lastRow = this.rowsToDisplay[this.rowsToDisplay.length - 1];
            var lastPixel = lastRow.rowTop + lastRow.rowHeight;
            return lastPixel;
        } else {
            return 0;
        }
    }

    public forEachLeafNode(callback: Function): void {
        if (this.rootNode.allLeafChildren) {
            this.rootNode.allLeafChildren.forEach( (rowNode, index) => callback(rowNode, index) );
        }
    }

    public forEachNode(callback: Function): void {
        this.recursivelyWalkNodesAndCallback(this.rootNode.childrenAfterGroup, callback, RecursionType.Normal, 0);
    }

    public forEachNodeAfterFilter(callback: Function): void {
        this.recursivelyWalkNodesAndCallback(this.rootNode.childrenAfterFilter, callback, RecursionType.AfterFilter, 0);
    }

    public forEachNodeAfterFilterAndSort(callback: Function): void {
        this.recursivelyWalkNodesAndCallback(this.rootNode.childrenAfterSort, callback, RecursionType.AfterFilterAndSort, 0);
    }

    public forEachPivotNode(callback: Function): void {
        this.recursivelyWalkNodesAndCallback([this.rootNode], callback, RecursionType.PivotNodes, 0);
    }

    // iterates through each item in memory, and calls the callback function
    // nodes - the rowNodes to traverse
    // callback - the user provided callback
    // recursion type - need this to know what child nodes to recurse, eg if looking at all nodes, or filtered notes etc
    // index - works similar to the index in forEach in javascripts array function
    private recursivelyWalkNodesAndCallback(nodes: RowNode[], callback: Function, recursionType: RecursionType, index: number) {
        if (nodes) {
            for (var i = 0; i < nodes.length; i++) {
                var node = nodes[i];
                callback(node, index++);
                // go to the next level if it is a group
                if (node.group) {
                    // depending on the recursion type, we pick a difference set of children
                    var nodeChildren: RowNode[];
                    switch (recursionType) {
                        case RecursionType.Normal : nodeChildren = node.childrenAfterGroup; break;
                        case RecursionType.AfterFilter : nodeChildren = node.childrenAfterFilter; break;
                        case RecursionType.AfterFilterAndSort : nodeChildren = node.childrenAfterSort; break;
                        case RecursionType.PivotNodes :
                            // for pivot, we don't go below leafGroup levels
                            nodeChildren = !node.leafGroup ? node.childrenAfterSort : null; break;
                    }
                    if (nodeChildren) {
                        index = this.recursivelyWalkNodesAndCallback(nodeChildren, callback, recursionType, index);
                    }
                }
            }
        }
        return index;
    }

    // it's possible to recompute the aggregate without doing the other parts
    // + gridApi.recomputeAggregates()
    public doAggregate() {
        if (this.aggregationStage) {
            this.aggregationStage.execute(this.rootNode);
        }
    }

    // + gridApi.expandAll()
    // + gridApi.collapseAll()
    public expandOrCollapseAll(expand: boolean): void {

        if (this.rootNode){
            recursiveExpandOrCollapse(this.rootNode.childrenAfterGroup);
        }

        function recursiveExpandOrCollapse(rowNodes: RowNode[]): void {
            if (!rowNodes) { return; }
            rowNodes.forEach( (rowNode: RowNode) => {
                if (rowNode.group) {
                    rowNode.expanded = expand;
                    recursiveExpandOrCollapse(rowNode.childrenAfterGroup);
                }
            });
        }
        this.refreshModel({step: Constants.STEP_MAP});
    }

    private doSort() {
        this.sortStage.execute(this.rootNode);
    }

    private doRowGrouping(groupState: any) {

        // grouping is enterprise only, so if service missing, skip the step
        var rowsAlreadyGrouped = _.exists(this.gridOptionsWrapper.getNodeChildDetailsFunc());
        if (rowsAlreadyGrouped) { return; }

        if (this.groupStage) {

            // remove old groups from the selection model, as we are about to replace them
            // with new groups
            this.selectionController.removeGroupsFromSelection();

            this.groupStage.execute(this.rootNode);

            this.restoreGroupState(groupState);

            if (this.gridOptionsWrapper.isGroupSelectsChildren()) {
                this.selectionController.updateGroupsFromChildrenSelections();
            }

        } else {
            this.rootNode.childrenAfterGroup = this.rootNode.allLeafChildren;
        }
    }

    private restoreGroupState(groupState: any): void {
        if (!groupState) { return; }

        _.traverseNodesWithKey(this.rootNode.childrenAfterGroup, (node: RowNode, key: string)=> {
            // if the group was open last time, then open it this time. however
            // if was not open last time, then don't touch the group, so the 'groupDefaultExpanded'
            // setting will take effect.
            if (typeof groupState[key] === 'boolean') {
                node.expanded = groupState[key];
            }
        });
    }

    private doFilter() {
        this.filterStage.execute(this.rootNode);
    }

    private doPivot() {
        if (this.pivotStage) {
            this.pivotStage.execute(this.rootNode);
        }
    }

    private getGroupState(): any {
        if (!this.rootNode.childrenAfterGroup || !this.gridOptionsWrapper.isRememberGroupStateWhenNewData()) {
            return null;
        }
        var result: any = {};
        _.traverseNodesWithKey(this.rootNode.childrenAfterGroup, (node: RowNode, key: string)=> result[key] = node.expanded );
        return result;
    }

    // rows: the rows to put into the model
    // firstId: the first id to use, used for paging, where we are not on the first page
    public setRowData(rowData: any[], refresh: boolean, firstId?: number) {

        // remember group state, so we can expand groups that should be expanded
        var groupState = this.getGroupState();

        this.nodeManager.setRowData(rowData, firstId);

        // this event kicks off:
        // - clears selection
        // - updates filters
        // - shows 'no rows' overlay if needed
        this.eventService.dispatchEvent(Events.EVENT_ROW_DATA_CHANGED);

        if (refresh) {
            this.refreshModel({step: Constants.STEP_EVERYTHING, groupState: groupState});
        }
    }

    private doRowsToDisplay() {
        this.rowsToDisplay = <RowNode[]> this.flattenStage.execute(this.rootNode);
    }

    public insertItemsAtIndex(index: number, items: any[]): void {
        // remember group state, so we can expand groups that should be expanded
        var groupState = this.getGroupState();
        var newNodes = this.nodeManager.insertItemsAtIndex(index, items);
        this.refreshAndFireEvent(Events.EVENT_ITEMS_ADDED, newNodes, groupState);
    }

    public onRowHeightChanged(): void {
        this.refreshModel({step: Constants.STEP_MAP, keepRenderedRows: true});
    }

    public resetRowHeights(): void {
        this.forEachNode( (rowNode: RowNode) => rowNode.setRowHeight(null) );
        this.onRowHeightChanged();
    }

    public removeItems(rowNodes: RowNode[]): void {
        var groupState = this.getGroupState();
        var removedNodes = this.nodeManager.removeItems(rowNodes);
        this.refreshAndFireEvent(Events.EVENT_ITEMS_REMOVED, removedNodes, groupState);
    }

    public addItems(items: any[]): void {
        var groupState = this.getGroupState();
        var newNodes = this.nodeManager.addItems(items);
        this.refreshAndFireEvent(Events.EVENT_ITEMS_ADDED, newNodes, groupState);
    }

    private refreshAndFireEvent(eventName: string, rowNodes: RowNode[], groupState: any): void {
        if (rowNodes) {
            this.refreshModel({step: Constants.STEP_EVERYTHING, groupState: groupState});
            this.eventService.dispatchEvent(eventName, {rowNodes: rowNodes})
        }
    }

}


text:
'use strict';

var UserHandle = milo.createComponentClass({
    className: 'UserHandle',
    facets: {
        events: {
            messages: {
                'input': { subscriber: onInput, context: 'owner' }
            }
        }
    },
    methods: {
        start: start,
        setHandle: setHandle,
        getHandle: getHandle
    },
    staticMethods: {
        getHandle: getHandle
    }
});

var HANDLE_KEY = '/slack_clone/userHandle';

function start() {
    UserHandle.super.start.apply(this, arguments);
    this.el.value = this.getHandle() || '';
}

function onInput() {
    var handleText = this.el.value;
    this.setHandle(handleText);
}

function getHandle() {
    return window.localStorage.getItem(HANDLE_KEY);
}

function setHandle(text) {
    window.localStorage.setItem(HANDLE_KEY, text);
}


text:
def is_valid_coordinate(img, i, j, k):
    '''
    '''
    imgX, imgY, imgZ = img.shape
    return ((i >= 0 and i < imgX) and
            (j >= 0 and j < imgY) and
            (k >= 0 and k < imgZ))

def are_compatible_imgs(one_img, another_img):
    '''
    Returns true if one_img and another_img have the same shape, false
    otherwise.
    '''
    return (one_img.shape == another_img.shape)


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

<!--
  ~ Copyright (C) 2015 Twitter, 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.
  ~
  -->

<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="dgts__call_me">Llamarme</string>
    <string name="dgts__calling">Llamando…</string>
    <string name="dgts__confirmation_code">Código de confirmación</string>
    <string name="dgts__confirmation_edit_hint">Ingresa el código de 6 dígitos que te enviamos</string>
    <string name="dgts__confirmation_error">No se puede confirmar tu número de teléfono</string>
    <string name="dgts__confirmation_error_alternative">Lo sentimos, estamos teniendo problemas para enviarte un código de confirmación.</string>
    <string name="dgts__confirmation_expired">Este código ha caducado. Solicitar el reenvío del código de confirmación.</string>
    <string name="dgts__continue">Continuar</string>
    <string name="dgts__create_account">Crear cuenta</string>
    <string name="dgts__digits_logo_desc">ícono del logo de digits</string>
    <string name="dgts__digits_logo_name_desc">nombre del logo de digits</string>
    <string name="dgts__dismiss">Descartar</string>
    <string name="dgts__done">Listo</string>
    <string name="dgts__email_request_edit_hint">Dirección de correo electrónico</string>
    <string name="dgts__email_request_title">Introducir dirección de correo electrónico</string>
    <string name="dgts__find_your_friends">Encuentra a tus amigos</string>
    <string name="dgts__image_header_description">Encabezado de imagen para inicio de sesión</string>
    <string name="dgts__invalid_email">Correo electrónico no válido. Inténtalo de nuevo</string>
    <string name="dgts__login_digits_text">Usar mi número de teléfono</string>
    <string name="dgts__network_error">Revisa tu red e inténtalo de nuevo.</string>
    <string name="dgts__not_now">Ahora no</string>
    <string name="dgts__okay">Aceptar</string>
    <string name="dgts__phone_number_edit_hint">Tu número</string>
    <string name="dgts__phone_number_text">Introduce tu número de teléfono</string>
    <string name="dgts__pin_code_verification_title">Ingresa el código de doble verificación</string>
    <string name="dgts__resend_confirmation_button_code">Reenviar</string>
    <string name="dgts__resend_confirmation_text">Reenviar código de confirmación</string>
    <string name="dgts__send_confirmation_code">Enviar código de confirmación</string>
    <string name="dgts__sending">Enviando…</string>
    <string name="dgts__success_desc">Icono Éxito</string>
    <string name="dgts__terms_email_request">Al pulsar %1$sContinuar%1$s arriba, agregas este correo electrónico a tu cuenta de Digits. Aceptas que esta aplicación y %7$stodas las aplicaciones que aparecen en tu cuenta de Digits%5$s pueden acceder a esta dirección de correo electrónico y que sus usuarios puedan descubrirte por el correo electrónico.</string>
    <string name="dgts__terms_text">Al pulsar %1$sEnviar código de confirmación%1$s arriba, %6$sDigits by Twitter%5$s te enviará un SMS para confirmar tu número de teléfono. En la siguiente pantalla, puedes escoger "Reenviar código" para recibir un nuevo SMS o "Llámame" \
para iniciar una llamada telefónica que confirme tu número de teléfono. \
Se pueden aplicar cargos por mensajes, llamadas y datos.</string>
    <string name="dgts__terms_text_call_me">Al pulsar %1$s\"Llámame\"%1$s arriba, %6$sDigits by Twitter%5$s te llamará para confirmar tu número de teléfono. Se pueden aplicar cargos por llamadas y datos.</string>
    <string name="dgts__terms_text_create">Al pulsar %1$sCrear cuenta%1$s arriba, aceptas los %8$sTérminos de servicio%5$s, la %9$sPolítica de privacidad%5$s y la %10$sPolítica de cookies%5$s de %6$sDigits by Twitter%5$s, para compartir tu número de teléfono con %4$s, y que otros usuarios de %4$s puedan descubrirte por el número de teléfono.</string>
    <string name="dgts__terms_text_sign_in">Al pulsar %1$sContinuar%1$s arriba, tu %7$snúmero de teléfono o dirección de correo electrónico de Digits%5$s se compartirá con %4$s y otros usuarios de %4$s pueden descubrirte por el número de teléfono o correo electrónico.</string>
    <string name="dgts__terms_text_updated">Al pulsar %1$sContinuar%1$s arriba, aceptas los %8$sTérminos de servicio%5$s, la %9$sPolítica de privacidad%5$s y el %10$sUso de cookies%5$s de %6$sDigits by Twitter%5$s, para compartir tu %7$snúmero de teléfono o correo electrónico de Digits%5$s con %4$s, y que otros usuarios de %4$s puedan descubrirte por el número de teléfono o correo electrónico.</string>
    <string name="dgts__try_again">Reintentar</string>
    <string name="dgts__try_again_confirmation">Revisa tu código e inténtalo de nuevo.</string>
    <string name="dgts__try_again_email">Revisa tu correo electrónico e inténtalo de nuevo</string>
    <string name="dgts__try_again_phone_number">Revisa tu número e inténtalo de nuevo.</string>
    <string name="dgts__try_another_phone">Intenta con otro número de teléfono </string>
    <string name="dgts__unsupported_operator_error">No se pudo enviar un mensaje SMS a este número.</string>
    <string name="dgts__upload_contacts">Usamos Digits by Twitter para encontrar a amigos tuyos que usen esta aplicación. Cuando pulses \"Aceptar\", subiremos tu libreta de direcciones a Digits by Twitter para ayudarte a encontrar usuarios de %1$s que conozcas o ayudar a otros usuarios de %1$s a encontrarte.</string>
    <string name="dgts__verification_code">Código de verificación</string>
    <string name="dgts_pin_code_terms">Ya has establecido un código de doble verificación en digits.com</string>
</resources>


text:
'use strict';

var extend = require('extend');
var helper = require('../lib/helper');
var cookie = require('cookie');
var pick = require('object.pick');
var url = require('url');
var https = require('https');
var http = require('http');
var isStream = require('isstream');
var requestFactory = require('../lib/requestwrapper');
var RecognizeStream = require('./recognize_stream');
var pkg = require('../package.json'); // todo: consider using env properties here instead (to enable webpack support without requiring a plugin)
var util = require('util');
var BaseService = require('../lib/base_service');
var async = require('async');

var PARAMS_ALLOWED = ['continuous', 'max_alternatives', 'timestamps', 'word_confidence', 'inactivity_timeout',
  'model', 'content-type', 'interim_results', 'keywords', 'keywords_threshold', 'word_alternatives_threshold',
  'profanity_filter', 'smart_formatting', 'customization_id', 'speaker_labels'
];

function formatChunk(chunk) {
  // Convert the string into an array
  var result = chunk;

  // Check if in the stream doesn't have
  // two results together and parse them
  if (!result || result.indexOf('}{') === -1)
    return JSON.parse(result);

  // Check if we can parse the response
  try {
    result = '[' + result.replace(/}{/g, '},{') + ']';
    result = JSON.parse(result);
    return result[result.length - 1];
  } catch (e) {} // eslint-disable-line no-empty

  return result;
}

/**
 * Speech Recognition API Wrapper
 * @constructor
 * @param options
 */
function SpeechToTextV1(options) {
  BaseService.call(this, options);
}
util.inherits(SpeechToTextV1, BaseService);
SpeechToTextV1.prototype.name = 'speech_to_text';
SpeechToTextV1.prototype.version = 'v1';
SpeechToTextV1.URL = 'https://stream.watsonplatform.net/speech-to-text/api';

/**
 * Speech recognition for given audio using default model.
 *
 * @param {Audio} [audio] Audio to be recognized.
 * @param {String} [content_type] Content-type
 */
SpeechToTextV1.prototype.recognize = function(params, callback) {

  var missingParams = helper.getMissingParams(params, ['audio', 'content_type']);
  if (missingParams) {
    callback(missingParams);
    return;
  }
  if (!isStream(params.audio)) {
    callback(new Error('audio is not a standard Node.js Stream'));
    return;
  }

  var queryParams = pick(params, PARAMS_ALLOWED);
  if (Array.isArray(queryParams.keywords)) {
    queryParams.keywords = queryParams.keywords.join(',');
  }

  var _url = '/v1';
  _url += (params.session_id) ? ('/sessions/' + params.session_id) : '';
  _url += '/recognize';

  var parameters = {
    options: {
      method: 'POST',
      url: _url,
      headers: {
        'Content-Type': params.content_type
      },
      json: true,
      qs: queryParams,
    },
    defaultOptions: this._options
  };
  return params.audio.on('response', function(response) {
    // Replace content-type
    response.headers['content-type'] = params.content_type;
  }).pipe(requestFactory(parameters, callback));
};

/**
 * Creates a HTTP/HTTPS request to /recognize and keep the connection open.
 * Sets 'Transfer-Encoding': 'chunked' and prepare the connection to send
 * chunk data
 *
 * @param {String} [content_type] The Content-type e.g. audio/l16; rate=48000
 * @param {String} [session_id] The session id
 * @deprecated use createRecognizeStream instead
 */
SpeechToTextV1.prototype.recognizeLive = function(params, callback) {
  var missingParams = helper.getMissingParams(params, ['session_id', 'content_type', 'cookie_session']);

  if (missingParams) {
    callback(missingParams);
    return;
  }

  var serviceUrl = [this._options.url, '/v1/sessions/', params.session_id, '/recognize'].join('');
  var parts = url.parse(serviceUrl);
  var options = {
    agent: false,
    host: parts.hostname,
    port: parts.port,
    path: parts.pathname + (params.continuous ? '?continuous=true' : ''),
    method: 'POST',
    headers: extend({
      'Transfer-Encoding': 'chunked',
      'cookie': 'SESSIONID=' + params.cookie_session,
      'Content-type': params.content_type
    }, this._options.headers)
  };
  var protocol = (parts.protocol.match('http:')) ? http : https;
  var recognize_req = protocol.request(options, function(result) {
    result.setEncoding('utf-8');
    var transcript = '';

    result.on('data', function(chunk) {
      transcript += chunk;
    });

    result.on('end', function() {
      try {
        transcript = formatChunk(transcript);
      } catch (e) {
        callback(transcript);
        return;
      }
      callback(null, transcript);
    });
  });

  recognize_req.on('error', function(error) {
    callback(error);
  });
  return recognize_req;
};

/**
 * Result observer for upcoming or ongoing recognition task in the session.
 * This request has to be started before POST on recognize finishes,
 * otherwise it waits for the next recognition.
 *
 * @param {String} [params.session_id] Session used in the recognition.
 * @param {boolean} [params.interim_results] If true, interim results will be returned. Default: false.
 * @deprecated use createRecognizeStream instead
 */
SpeechToTextV1.prototype.observeResult = function(params, callback) {
  var missingParams = helper.getMissingParams(params, ['session_id', 'cookie_session']);
  if (missingParams) {
    callback(missingParams);
    return;
  }
  var serviceUrl = [this._options.url, '/v1/sessions/',
    params.session_id, '/observe_result'
  ].join('');
  var parts = url.parse(serviceUrl);
  var options = {
    agent: false,
    host: parts.hostname,
    port: parts.port,
    path: parts.pathname + (params.interim_results ? '?interim_results=true' : ''),
    method: 'GET',
    headers: extend({
      'cookie': 'SESSIONID=' + params.cookie_session,
      'Accept': 'application/json'
    }, this._options.headers)
  };
  var protocol = (parts.protocol.match('http:')) ? http : https;
  var req = protocol.request(options, function(result) {
    result.setEncoding('utf-8');
    result.on('data', function(chunk) {
      try {
        chunk = formatChunk(chunk);
      } catch (e) {
        callback(chunk);
        return;
      }
      callback(null, chunk);
    });
  });

  req.on('error', function(error) {
    callback(error);
  });

  req.end();

  return req;
};

/**
 * Get the state of the engine to check if recognize is available.
 * This is the way to check if the session is ready to accept a new recognition task.
 * The returned state has to be 'initialized' to be able to do recognize POST.
 *
 * @param {String} [params.session_id] Session used in the recognition.
 * @deprecated use createRecognizeStream instead
 */
SpeechToTextV1.prototype.getRecognizeStatus = function(params, callback) {
  var missingParams = helper.getMissingParams(params, ['session_id']);
  if (missingParams) {
    callback(missingParams);
    return;
  }

  var path = params || {};
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/sessions/' + path.session_id + '/recognize',
      path: path,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * List of models available.
 *
 * @param {Object} params
 * @param {Function} callback
 * @returns {ReadableStream|undefined}
 */
SpeechToTextV1.prototype.getModels = function(params, callback) {
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/models',
      path: params,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Get information about a model based on the given model_id
 *
 * @param {Object} params
 * @param {String} params.model_id The desired model
 * @param {Function} callback
 * @returns {ReadableStream|undefined}
 */
SpeechToTextV1.prototype.getModel = function(params, callback) {
  var path = params || {};

  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/models/' + path.model_id,
      path: path,
      json: true
    },
    requiredParams: ['model_id'],
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Create a session
 * Set-cookie header is returned with a cookie that must be used for
 * each request using this session.
 * The session expires after 15 minutes of inactivity.
 * @param string model The model to use during the session
 */
SpeechToTextV1.prototype.createSession = function(params, callback) {
  var parameters = {
    options: {
      method: 'POST',
      url: '/v1/sessions',
      json: true,
      qs: params
    },
    defaultOptions: this._options
  };

  // Add the cookie_session to the response
  function addSessionId(cb) {
    return function(error, body, response) {
      if (error) {
        cb(error, body, response);
        return;
      }
      var cookies = cookie.parse(response.headers['set-cookie'][0]);
      body.cookie_session = cookies.SESSIONID;
      cb(error, body, response);
    };
  }

  return requestFactory(parameters, addSessionId(callback));
};

/**
 * Deletes the specified session.
 *
 * @param {String} [params.session_id] Session id.
 */
SpeechToTextV1.prototype.deleteSession = function(params, callback) {
  var missingParams = helper.getMissingParams(params, ['session_id']);
  if (missingParams) {
    callback(missingParams);
    return;
  }

  var parameters = {
    options: {
      method: 'DELETE',
      url: '/v1/sessions/' + params.session_id,
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Replaces recognizeLive & friends with a single 2-way stream over websockets
 * @param params
 * @returns {RecognizeStream}
 */
SpeechToTextV1.prototype.createRecognizeStream = function(params) {
  params = params || {};
  params.url = this._options.url;

  params.headers = extend({
    'user-agent': pkg.name + '-nodejs-' + pkg.version,
    authorization: this._options.headers.Authorization
  }, params.headers);

  return new RecognizeStream(params);
};

// set up a warning message for the deprecated methods
['recognizeLive', 'observeResult'].forEach(function(name) {
  var original = SpeechToTextV1.prototype[name];
  SpeechToTextV1.prototype[name] = function deprecated(params) {
    if (!(params || {}).silent && !this._options.silent) {
      // eslint-disable-next-line no-console
      console.log(new Error('The ' + name + '() method is deprecated and will be removed from a future version of the watson-developer-cloud SDK. ' +
        'Please use createRecognizeStream() instead.\n(Set {silent: true} to hide this message.)'));
    }
    return original.apply(this, arguments);
  };
});

/**
 * Creates a new empty custom voice model
 *
 * Response looks like:
 *
 * ```json
 * {
 *   "customization_id": "abc996ea-86ca-482e-b7ec-0f31c34e5ee9"
 * }
 * ```
 *
 *
 * @param {Object} params
 * @param {String} params.name
 * @param {String} params.base_model_name - for example, en-US_BroadbandModel
 * @param {String} [params.description]
 * @param {Function} callback
 */
SpeechToTextV1.prototype.createCustomization = function(params, callback) {
  var parameters = {
    options: {
      method: 'POST',
      url: '/v1/customizations',
      body: pick(params, ['name', 'base_model_name', 'description']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * @typedef Word
 * @type {Object}
 * @property {String} word - the word as written
 * @property {String} translation - The phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA or IBM SPR translation. A sounds-like translation consists of one or more words that, when combined, sound like the word.
 */

/**
 * Update voice model
 *
 * An example of params.words could be:
 *
 * ```json
 *  [
 *    {"word":"NCAA", "translation":"N C double A"},
 *    {"word":"iPhone", "translation":"I phone"}
 *  ]
 * ```
 *
 * @param {Object} params
 * @param {String} params.customization_id
 * @param {String} [params.name]
 * @param {String} [params.description]
 * @param {Array<Word>} params.words - Array of {word, translation} objects where translation is the phonetic or sounds-like translation for the word. A phonetic translation is based on the SSML format for representing the phonetic string of a word either as an IPA or IBM SPR translation. A sounds-like translation consists of one or more words that, when combined, sound like the word.
 * @param {Function} callback
 */
SpeechToTextV1.prototype.updateCustomization = function(params, callback) {
  var parameters = {
    requiredParams: ['customization_id', 'words'],
    options: {
      method: 'POST',
      url: '/v1/customizations/' + params.customization_id,
      body: pick(params, ['name', 'description', 'words']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * List all customizations
 *
* Example response:
```json
{ customizations:
    [ { owner: '8a6f5bb1-5b2d-4a20-85a9-eaa421d25c88',
        base_model_name: 'en-US_BroadbandModel',
        customization_id: '6a7785a0-9665-11e6-a73a-0da9193a4475',
        created: '2016-10-20T01:35:00.346Z',
        name: 'IEEE-test',
        description: '',
        progress: 0,
        language: 'en-US',
        status: 'pending' },
      { owner: '8a6f5bb1-5b2d-4a20-85a9-eaa421d25c88',
        base_model_name: 'en-US_BroadbandModel',
        customization_id: '9e2f6bb0-9665-11e6-a73a-0da9193a4475',
        created: '2016-10-20T01:36:27.115Z',
        name: 'IEEE-test',
        description: '',
        progress: 0,
        language: 'en-US',
        status: 'ready' },
      { owner: '8a6f5bb1-5b2d-4a20-85a9-eaa421d25c88',
        base_model_name: 'en-US_BroadbandModel',
        customization_id: '6b194e70-9666-11e6-a73a-0da9193a4475',
        created: '2016-10-20T01:42:10.903Z',
        name: 'IEEE-test',
        description: '',
        progress: 100,
        language: 'en-US',
        status: 'available' } ] }

```
 *
 * @param {Object} [params]
 * @param {String} [params.language] optional filter. Currently only en-US is supported.
 * @param {Function} callback
 */
SpeechToTextV1.prototype.getCustomizations = function(params, callback) {
  if (typeof params === 'function' && !callback) {
    callback = params;
    params = {};
  }
  var parameters = {
    options: {
      method: 'GET',
      url: '/v1/customizations/',
      qs: pick(params, ['language']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

function isPending(customization) {
  return (customization.status === 'pending' || customization.status === 'training')
}

/**
 * Get customization details
 *
 * Example response:
 *
```json
 { owner: '8a6f5bb1-5b2d-4a20-85a9-eaa421d25c88',
   base_model_name: 'en-US_BroadbandModel',
   customization_id: 'e695ad30-97c1-11e6-be92-bb627d4684b9',
   created: '2016-10-21T19:09:33.443Z',
   name: 'js-sdk-test-temporary',
   description: 'Temporary customization to test the JS SDK. Should be automatically deleted within a few minutes.',
   progress: 0,
   language: 'en-US',
   status: 'pending' }
```
 *
 *
 * @param {Object} params
 * @param {String} params.customization_id
 * @param {Function} callback
 */
SpeechToTextV1.prototype.getCustomization = function(params, callback) {
  var parameters = {
    requiredParams: ['customization_id'],
    options: {
      method: 'GET',
      url: '/v1/customizations/{customization_id}',
      path: pick(params, ['customization_id']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Train a custom model
 *
 * @param {Object} params
 * @param {String} params.customization_id
 * @param {String} [params.word_type_to_add=all] - set to 'user' to train the model only on new words that were added or modified by the user; the model is not trained on new words extracted from corpora.
 * @param {Function} callback
 */
SpeechToTextV1.prototype.trainCustomization = function(params, callback) {
  var parameters = {
    requiredParams: ['customization_id'],
    options: {
      method: 'POST',
      url: '/v1/customizations/{customization_id}/train',
      path: pick(params, ['customization_id']),
      qs: pick(params, ['word_type_to_add']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Reset a custom model
 *
 * @param {Object} params
 * @param {String} params.customization_id
 * @param {Function} callback
 */
SpeechToTextV1.prototype.resetCustomization = function(params, callback) {
  var parameters = {
    requiredParams: ['customization_id'],
    options: {
      method: 'POST',
      url: '/v1/customizations/{customization_id}/reset',
      path: pick(params, ['customization_id']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Upgrade a custom model
 *
 * Note: This method is not currently implemented. It will be added for a future release of the API.
 *
 * @param {Object} params
 * @param {String} params.customization_id
 * @param {Function} callback
 */
SpeechToTextV1.prototype.upgradeCustomization = function(params, callback) {
  var parameters = {
    requiredParams: ['customization_id'],
    options: {
      method: 'POST',
      url: '/v1/customizations/{customization_id}/upgrade_model',
      path: pick(params, ['customization_id']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Delete a custom model
 *
 * @param {Object} params
 * @param {String} params.customization_id
 * @param {Function} callback
 */
SpeechToTextV1.prototype.deleteCustomization = function(params, callback) {
  var parameters = {
    requiredParams: ['customization_id'],
    options: {
      method: 'DELETE',
      url: '/v1/customizations/{customization_id}',
      path: pick(params, ['customization_id']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Add a corpus to a custom model
 *
 * @param {Object} params
 * @param {String} params.customization_id - The GUID of the custom language model to which a corpus is to be added. You must make the request with the service credentials of the model's owner.
 * @params {String} params.name - The name of the corpus that is to be added. The name cannot contain spaces and cannot be the string user, which is reserved by the service to denote custom words added or modified by the user.
 * @params {Boolean [parms.allow_overwrite=false] - Indicates whether the specified corpus is to overwrite an existing corpus with the same name. If a corpus with the same name already exists, the request fails unless allow_overwrite is set to true; by default, the parameter is false. The parameter has no effect if a corpus with the same name does not already exist.
 * @param {String|Buffer|ReadStream} [params.corpus] - the text of the corpus - may be provided as a String, a Buffer, or a ReadableStream. A ReadableStream is recommended when reading a file from disk.
 * @param {Function} callback
 */
SpeechToTextV1.prototype.addCorpus = function(params, callback) {

  var parameters = {
    requiredParams: ['customization_id', 'name', 'corpus'],
    originalParams: params,
    options: {
      method: 'POST', // shouldn't this be a PUT?
      url: '/v1/customizations/{customization_id}/corpora/{name}',
      path: pick(params, ['customization_id', 'name']),
      qs: pick(params, ['allow_overwrite']),
      body: params.corpus
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * List corpora
 *
 * Lists information about all corpora that have been added to the specified custom language model.
 * The information includes the total number of words and out-of-vocabulary (OOV) words, name, and status of each corpus.
 *
 * Example Result:
 * ```json
 * { corpora:
   [ { out_of_vocabulary_words: 0,
       total_words: 233,
       name: 'test_corpus_1',
       status: 'analyzed' },
     { out_of_vocabulary_words: 0,
       total_words: 0,
       name: 'test_corpus_2',
       status: 'being_processed' } ] }
 ```
 *
 * @param {Object} params
 * @param {String} params.customization_id
 * @param {Function} callback
 */
SpeechToTextV1.prototype.getCorpora = function(params, callback) {
  var parameters = {
    requiredParams: ['customization_id'],
    options: {
      method: 'GET',
      url: '/v1/customizations/{customization_id}/corpora',
      path: pick(params, ['customization_id']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Delete a corpus
 *
 * @param {Object} params
 * @param {String} params.customization_id
 * @params {String} params.name - The name of the corpus that is to be deleted
 * @param {Function} callback
 */
SpeechToTextV1.prototype.deleteCorpus = function(params, callback) {
  var parameters = {
    requiredParams: ['customization_id', 'name'],
    options: {
      method: 'DELETE',
      url: '/v1/customizations/{customization_id}/corpora/{name}',
      path: pick(params, ['customization_id', 'name']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

SpeechToTextV1.ERR_NO_CORPORA = 'ERR_NO_CORPORA';
SpeechToTextV1.ERR_TIMEOUT = 'ERR_TIMEOUT';
/**
 * Waits while a customization status is 'pending' or 'training', fires callback once the status is 'ready' or 'available'
 *
 * Note: the customization will remain in 'pending' status until at least one corpus is added. Calling this on a customization with no corpa will result in an error.
 *
 * See http://www.ibm.com/watson/developercloud/speech-to-text/api/v1/#list_models for status details
 *
 * @param {Object} params
 * @param {String} params.customization_id
 * @param {Number} [params.interval=5000] - (milliseconds) - how log to wait between status checks
 * @param {Number} [params.times=30] - maximum number of attempts
 * @param {Function} callback
 */
SpeechToTextV1.prototype.whenCustomizationReady = function(params, callback) {
  var self = this;

  async.parallel([

    // validate that it has at least one corpus
    function(next) {
      self.getCorpora(params, function(err, res) {
        if (err) {
          return next(err);
        }
        if (!res.corpora.length) {
          err = new Error('Customization has no corpa and therefore will never be ready.');
          err.code = SpeechToTextV1.ERR_NO_CORPORA;
          return next(err)
        }
        next();
      })
    },

    // check the customization status repeatedly until it's ready or avaliable
    function(next) {
      var options = extend({
        interval: 5000,
        times: 30
      }, params);
      options.errorFilter = function(err) {
        // if it's a timeout error, then getCustomization is called again after params.interval
        // otherwise the error is passed back to the user
        // if the params.times limit is reached, the error will be passed to the user regardless
        return err.code === SpeechToTextV1.ERR_TIMEOUT;
      };
      async.retry(options, function(done) {
        self.getCustomization(params, function(err, customization) {
          if (err) {
            done(err);
          } else if (isPending(customization)) {
            // if the loop times out, async returns the last error, which will be this one.
            err = new Error('Customization is still pending, try increasing interval or times params');
            err.code = SpeechToTextV1.ERR_TIMEOUT;
            done(err);
          } else if (customization.status === 'ready' || customization.status === 'available') {
            done(null, customization);
          } else if (customization.status === 'failed') {
            done(new Error('Customization training failed'));
          } else {
            done(new Error('Unexpected customization status: ' + customization.status));
          }
        })
      }, next)
    }

  ], function(err, res) {
    if (err) {
      return callback(err);
    }
    callback(null, res[1]); // callback with the final customization object
  });
};

//Check if there is a corpus that is still being processed
function isProcessing(corporaList) {
  var recordsBeingProcessed = corporaList.corpora.filter(function(record) {
    return record['status'] === 'being_processed';
  });
  if (recordsBeingProcessed.length === 0) {
    return false;
  } else {
    return true;
  }
}

//Check if corpora has been analyzed
function isAnalyzed(corporaList) {
  var recordsAnalyzed = corporaList.corpora.filter(function(record) {
    return record['status'] === 'analyzed';
  });
  if (recordsAnalyzed.length === corporaList.corpora.length) {
    return true;
  } else {
    return false;
  }
}
/**
 * Waits while corpora analysis status is 'being_processes', fires callback once the status is 'analyzed'
 *
 * Note: the code will throw an error in case there in no corpus in the customization
 *
 *
 * @param {Object} params
 * @param {String} params.customization_id
 * @param {Number} [params.interval=5000] - (milliseconds) - how long to wait between status checks
 * @param {Number} [params.times=30] - maximum number of attempts
 * @param {Function} callback
 */
SpeechToTextV1.prototype.whenCorporaAnalyzed = function(params, callback) {
  var self = this;

  async.parallel([

    // validate that it has at least one corpus
    function(next) {
      self.getCorpora(params, function(err, res) {
        if (err) {
          return next(err);
        }
        if (!res.corpora.length) {
          err = new Error('Customization has no corpa and therefore corpus cannot be analyzed');
          err.code = SpeechToTextV1.ERR_NO_CORPORA;
          return next(err)
        }
        next();
      })
    },

    // check the customization status repeatedly until it's available
    function(next) {
      var options = extend({
        interval: 5000,
        times: 30
      }, params);
      options.errorFilter = function(err) {
        // if it's a timeout error, then getCorpora is called again after params.interval
        // otherwise the error is passed back to the user
        // if the params.times limit is reached, the error will be passed to the user regardless
        return err.code === SpeechToTextV1.ERR_TIMEOUT;
      };
      async.retry(options, function(done) {
        self.getCorpora(params, function(err, corpora) {
          if (err) {
            done(err);
          } else if (isProcessing(corpora)) {
            // if the loop times out, async returns the last error, which will be this one.
            err = new Error('Corpora is still being processed, try increasing interval or times params');
            err.code = SpeechToTextV1.ERR_TIMEOUT;
            done(err);
          } else if (isAnalyzed(corpora)) {
            done(null, corpora);
          } else {
            done(new Error('Unexpected corpus analysis status'));
          }
        })
      }, next)
    }

  ], function(err, res) {
    if (err) {
      return callback(err);
    }
    callback(null, res[1]); // callback with the final customization object
  });
};

/**
 * Add multiple custom words
 *
 * @param {Object} params
 * @param {String} params.customization_id
 * @param {Array<Word>} params.words - Array of objects: [{word: String, sounds_like: [String, ...], display_as: String}, ...]
 * @param {Function} callback
 */
SpeechToTextV1.prototype.addWords = function(params, callback) {
  var parameters = {
    requiredParams: ['customization_id', 'words'],
    options: {
      method: 'POST',
      url: '/v1/customizations/{customization_id}/words',
      path: pick(params, ['customization_id']),
      body: pick(params, ['words']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Add a single custom word
 *
 * @param {Object} params
 * @param {String} params.customization_id
 * @param {String} params.word
 * @param {Array<String>} params.sounds_like
 * @param {String} [params.display_as]
 * @param {Function} callback
 */
SpeechToTextV1.prototype.addWord = function(params, callback) {
  var parameters = {
    requiredParams: ['customization_id', 'word', 'sounds_like'],
    options: {
      method: 'PUT',
      url: '/v1/customizations/{customization_id}/words/{word}',
      path: pick(params, ['customization_id', 'word']),
      body: pick(params, ['sounds_like', 'display_as']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * List all custom words
 *
 * Lists information about all custom words from a custom language model.
 * You can list all words from the custom model's words resource, only custom words that were added or modified by the user, or only OOV words that were extracted from corpora.
 *
 * Example response:
```json
{
    "words": [
       {
          "word": "hhonors",
          "sounds_like": ["hilton honors","h honors"],
          "display_as": "HHonors",
          "source": ["corpus1"]
       },
       {
          "word": "ieee",
          "sounds_like": ["i triple e"],
          "display_as": "IEEE",
          "source": ["corpus1","corpus2"]
       },
       {
          "word": "tomato",
          "sounds_like": ["tomatoh","tomayto"],
          "display_as": "",
          "source": ["user"]
       },
       {
          "word": "$75.00",
          "sounds_like": ["75 dollars"],
          "display_as": "",
          "source": ["user"],
          "error":" Numbers are not allowed in sounds-like"
       }
    ]
 }
 ```
 *
 * @param {Object} params
 * @param {String} params.customization_id
 * @param {String} [params.word_type=all] - all|user|corpora - user shows only custom words that were added or modified by the user; corpora shows only OOV that were extracted from corpora.
 * @param {Function} callback
 */
SpeechToTextV1.prototype.getWords = function(params, callback) {
  if (typeof params === 'function' && !callback) {
    callback = params;
    params = {};
  }
  var parameters = {
    requiredParams: ['customization_id'],
    options: {
      method: 'GET',
      url: '/v1/customizations/{customization_id}/words',
      path: pick(params, ['customization_id']),
      qs: pick(params, ['language']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Get a custom word
 *
 * Lists information about a custom word from a custom language model.
 *
 * Example output:
 *
 * ```json
 {
    "sounds_like": ["N. C. A. A.","N. C. double A."],
    "display_as": "NCAA",
    "source": ["corpus3","user"]
 }
 ```
 *
 * @param {Object} params
 * @param {String} params.customization_id
 * @param {String} params.word
 * @param {Function} callback
 */
SpeechToTextV1.prototype.getWord = function(params, callback) {
  var parameters = {
    requiredParams: ['customization_id', 'word'],
    options: {
      method: 'GET',
      url: '/v1/customizations/{customization_id}/words/{word}',
      path: pick(params, ['customization_id', 'word']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

/**
 * Delete a custom word
 *
 * Removing a custom word does not affect the custom model until you train the model with the Train a custom model method.
 *
 * @param {Object} params
 * @param {String} params.customization_id
 * @param {String} params.word
 * @param {Function} callback
 */
SpeechToTextV1.prototype.deleteWord = function(params, callback) {
  var parameters = {
    requiredParams: ['customization_id', 'word'],
    options: {
      method: 'DELETE',
      url: '/v1/customizations/{customization_id}/words/{word}',
      path: pick(params, ['customization_id', 'word']),
      json: true
    },
    defaultOptions: this._options
  };
  return requestFactory(parameters, callback);
};

module.exports = SpeechToTextV1;


text:
<?php

namespace Brouzie\Specificator\Bridge\Elastica;

use Elastica\Query\BoolQuery;

/**
 * @author Konstantin Myakshin <molodchick@gmail.com>
 */
interface ElasticaFilterMapper
{
    /**
     * Maps filter to query.
     */
    public function mapFilter(object $filter, BoolQuery $query): void;
}


text:
define([], () => {
    'use strict';

    /**
     * Abstract Cache Strategy class
     * @type {AbstractStrategy}
     */
    class AbstractStrategy {
        constructor(){
            if(new.target === AbstractStrategy){
                throw new TypeError('Cannot construct AbstractStrategy instances directly');
            }
        }

        /**
         * factory for Strategy* instances
         * @returns {AbstractStrategy}
         */
        static create(){
            return new this();
        }
    }

    /**
     * LIFO Cache Strategy - First In First Out
     * -> The cache evicts the entries in the order they were added,
     *    without any regard to how often or how many times they were accessed before.
     * @type {StrategyFIFO}
     */
    class StrategyFIFO extends AbstractStrategy {
        valueToCompare(metaData){
            return metaData.age();
        }

        compare(a, b){
            return b - a;
        }
    }

    /**
     * LFU Cache Strategy - Least Frequently Used
     * -> The cache evicts the entries in order how often have been accessed.
     *   Those that are used least often are discarded first
     * @type {StrategyLFU}
     */
    class StrategyLFU extends AbstractStrategy {
        valueToCompare(metaData){
            return metaData.hitCount;
        }

        compare(a, b){
            return  a - b;
        }
    }

    /**
     * LRU Cache Strategy - Least Recently Used
     * -> The cache evicts entries that have not been used for the longest amount of time.
     *    No matter how often they have been accessed.
     * @type {StrategyLRU}
     */
    class StrategyLRU extends AbstractStrategy {
        valueToCompare(metaData){
            return metaData.hits[metaData.hits.length - 1] || metaData.set;
        }

        compare(a, b){
            return  a - b;
        }
    }

    /**
     * Each entry in cache also has its own instance of CacheEntryMeta
     * -> The configured Cache Strategy use this meta data for eviction policy
     * @type {CacheEntryMeta}
     */
    class CacheEntryMeta {
        constructor(ttl, tSet){
            this._ttl = ttl;                                // ttl < 0 => no expire
            this._tSet = tSet || this.constructor.now();
            this._tHits = [];
        }

        get set(){
            return this._tSet;
        }

        get hits(){
            return this._tHits;
        }

        get hitCount(){
            return this.hits.length;
        }

        newHit(current){
            this._tHits.push(current || this.constructor.now());
        }

        age(current){
            return (current || this.constructor.now()) - this._tSet;
        }

        expired(current){
            return this._ttl < 0 ? false : this._ttl < this.age(current);
        }

        static now(){
            return new Date().getTime() / 1000;
        }

        static create(ttl, tSet){
            return new this(ttl, tSet);
        }
    }

    /**
     * Each instance of Cache represents a key value in memory data store
     * -> Name should be set to identify current Cache instance
     * -> Default ttl can be overwritten by individual entries
     * -> Cache Strategy handles eviction policy
     * -> Buffer Size (in percent) can be used to remove e.g. 10% of all entries
     *    if cache reaches maxSize limit, to increase performance.
     * @type {Cache}
     */
    class Cache {

        constructor(config = {}){
            this._config    = Object.assign({}, Cache.defaultConfig, config);
            this._store     = new Map();
            this._metaStore = new WeakMap();
            this._strategy  = this.constructor.setStrategy(this._config.strategy);

            this.debug = (msg,...data) => {
                if(this._config.debug){
                    data = (data || []);
                    data.unshift(this._config.name);
                    console.debug('debug: CACHE %o | ' + msg, ...data);
                }
            };

            this.debug('New Cache instance');
        }

        get size(){
            return this._store.size;
        }

        isFull(){
            return this.size>= this._config.maxSize;
        }

        set(key, value, ttl){
            if(this._store.has(key)){
                this.debug('SET key %o, UPDATE value %o', key, value);
                this._store.set(key, value);
            }else{
                this.debug('SET key %o, NEW value %o', key, value);
                if(this.isFull()){
                    this.debug(' ↪ FULL trim cache…');
                    this.trim(this.trimCount(1));
                }
                this._store.set(key, value);
            }

            this._metaStore.set(value, CacheEntryMeta.create(ttl || this._config.ttl));
        }

        get(key){
            if(this._store.has(key)){
                let value = this._store.get(key);
                if(value){
                    let metaData = this._metaStore.get(value);
                    if(metaData.expired()){
                        this.debug('EXPIRED key %o delete', key);
                        this.delete(key);
                    }else{
                        this.debug('HIT key %o', key);
                        metaData.newHit();
                        return value;
                    }
                }
            }
            this.debug('MISS key %o', key);
        }

        getOrDefault(key, def){
            return this.get(key) || def;
        }

        keysForTrim(count){
            let trimKeys = [];
            let compare = [];
            for(let [key, value] of this._store){
                let metaData = this._metaStore.get(value);
                if(metaData.expired()){
                    trimKeys.push(key);
                    if(count === trimKeys.length){
                        break;
                    }
                }else{
                    compare.push({
                        key: key,
                        value: this._strategy.valueToCompare(metaData)
                    });
                }
            }

            let countLeft = count - trimKeys.length;
            if(countLeft > 0){
                compare = compare.sort((a, b) => this._strategy.compare(a.value, b.value));
                trimKeys = trimKeys.concat(compare.splice(0, countLeft).map(a => a.key));
            }

            return trimKeys;
        }

        keys(){
            return this._store.keys();
        }

        delete(key){
            return this._store.delete(key);
        }

        clear(){
            this._store.clear();
        }

        trimCount(spaceLeft){
            let bufferSize = Math.max(Math.round(this._config.maxSize / 100 * this._config.bufferSize), spaceLeft);
            return Math.min(Math.max(this.size - this._config.maxSize + bufferSize, 0), this.size);
        }

        trim(count){
            if(count > 0){
                let trimKeys = this.keysForTrim(count);
                if(count > trimKeys.length){
                    console.warn(' ↪ Failed to trim(%i) entries. Only %i in store', count, this.size);
                }
                this.debug(' ↪ DELETE min %i keys: %o', count, trimKeys);
                trimKeys.forEach(key => this.delete(key));
            }
        }

        status(){
            return {
                config: this._config,
                store: this._store,
                metaStore: this._metaStore
            };
        }

        static setStrategy(name){
            switch(name){
                case 'FIFO': return StrategyFIFO.create();
                case 'LFU': return StrategyLFU.create();
                case 'LRU': return StrategyLRU.create();
                default:
                    throw new ReferenceError('Unknown cache strategy name: ' + name);

            }
        }
    }

    Cache.defaultConfig = {
        name:       'Default',          // custom unique name for identification
        ttl:        3600,               // default ttl for cache entries
        maxSize:    600,                // max cache entries
        bufferSize: 10,                 // cache entry count in percent to be removed if maxSize reached
        strategy:   'FIFO',             // cache strategy policy
        debug:      false               // debug output in console
    };

    return Cache;
});


text:
/*
 * eXist Open Source Native XML Database
 * Copyright (C) 2001-2007 The eXist Project
 * http://exist-db.org
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *  $Id: ElementImpl.java 6453 2007-08-30 20:24:52Z brihaye $
 */
package org.exist.memtree;

import java.util.HashMap;
import java.util.Map;
import java.util.HashSet;
import java.util.Set;

import org.exist.Namespaces;
import org.exist.dom.NamedNodeMapImpl;
import org.exist.dom.NodeListImpl;
import org.exist.dom.QName;
import org.exist.dom.QNameable;
import org.exist.xquery.value.Type;
import org.w3c.dom.Attr;
import org.w3c.dom.DOMException;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.TypeInfo;

public class ElementImpl extends NodeImpl implements Element, QNameable {

	public ElementImpl(DocumentImpl doc, int nodeNumber) {
		super(doc, nodeNumber);
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#getTagName()
	 */
	public String getTagName() {
		return getNodeName();
	}

	public QName getQName() {
		return (QName)
			document.namePool.get(document.nodeName[nodeNumber]);
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Node#hasChildNodes()
	 */
	public boolean hasChildNodes() {
		return nodeNumber + 1 < document.size
			&& document.treeLevel[nodeNumber + 1] > document.treeLevel[nodeNumber];
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Node#getFirstChild()
	 */
	public Node getFirstChild() {
		short level = document.treeLevel[nodeNumber];
		int nextNode = nodeNumber + 1;
		if (nextNode < document.size && document.treeLevel[nextNode] > level) {
			return document.getNode(nextNode);
		} else
			return null;
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Node#getChildNodes()
	 */
	public NodeList getChildNodes() {
		NodeListImpl nl = new NodeListImpl();
		int nextNode = document.getFirstChildFor(nodeNumber);
		while (nextNode > nodeNumber) {
			Node n = document.getNode(nextNode);
			nl.add(n);
            nextNode = document.next[nextNode];
        }
		return nl;
	}

    public int getChildCount() {
        return document.getChildCountFor(nodeNumber);
    }

	/* (non-Javadoc)
	 * @see org.w3c.dom.Node#getNamespaceURI()
	 */
	public String getNamespaceURI() {
		return getQName().getNamespaceURI();
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Node#getPrefix()
	 */
	public String getPrefix() {
		return getQName().getPrefix();
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Node#getLocalName()
	 */
	public String getLocalName() {
		return getQName().getLocalName();
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Node#hasAttributes()
	 */
	public boolean hasAttributes() {
		return document.alpha[nodeNumber] > -1 || document.alphaLen[nodeNumber] > -1;
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#getAttribute(java.lang.String)
	 */
	public String getAttribute(String name) {
		int attr = document.alpha[nodeNumber];
		if (-1 < attr) {
			while (attr < document.nextAttr
				&& document.attrParent[attr] == nodeNumber) {
				QName attrQName = (QName)document.namePool.get(document.attrName[attr]);
				if (attrQName.getStringValue().equals(name))
					return document.attrValue[attr];
				++attr;
			}
		}

		if(name.startsWith("xmlns:")) {
			int ns = document.alphaLen[nodeNumber];
			if (-1 < ns) {
				while (ns < document.nextNamespace
						&& document.namespaceParent[ns] == nodeNumber) {
					QName nsQName=(QName)document.namePool.get(document.namespaceCode[ns]);
					if (nsQName.getStringValue().equals(name))
						return nsQName.getNamespaceURI();
					++ns;
				}
			}
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#setAttribute(java.lang.String, java.lang.String)
	 */
	public void setAttribute(String arg0, String arg1) throws DOMException {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#removeAttribute(java.lang.String)
	 */
	public void removeAttribute(String arg0) throws DOMException {
		// TODO Auto-generated method stub

	}

    public int getAttributesCount() {
       return document.getAttributesCountFor(nodeNumber)+document.getNamespacesCountFor(nodeNumber);
    }

	/* (non-Javadoc)
	 * @see org.w3c.dom.Node#getAttributes()
	 */
	public NamedNodeMap getAttributes() {
		NamedNodeMapImpl map = new NamedNodeMapImpl();
        int attr = document.alpha[nodeNumber];
		if(-1 < attr) {
			while (attr < document.nextAttr
				&& document.attrParent[attr] == nodeNumber) {
				map.add(new AttributeImpl(document, attr));
				++attr;
			}
		}
		// add namespace declarations attached to this element
		int ns = document.alphaLen[nodeNumber];
		if (ns < 0)
			return map;
		while (ns < document.nextNamespace
				&& document.namespaceParent[ns] == nodeNumber) {
			NamespaceNode node = new NamespaceNode(document, ns);
			map.add(node);
			++ns;
		}
		return map;
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#getAttributeNode(java.lang.String)
	 */
	public Attr getAttributeNode(String name) {
		int attr = document.alpha[nodeNumber];
		if (-1 < attr) {
			while (attr < document.nextAttr
				&& document.attrParent[attr] == nodeNumber) {
				QName attrQName = (QName)document.namePool.get(document.attrName[attr]);
				if (attrQName.getStringValue().equals(name))
					return new AttributeImpl(document, attr);
				++attr;
			}
		}

		if(name.startsWith("xmlns:")) {
			int ns = document.alphaLen[nodeNumber];
			if (-1 < ns) {
				while (ns < document.nextNamespace
						&& document.namespaceParent[ns] == nodeNumber) {
					QName nsQName=(QName)document.namePool.get(document.namespaceCode[ns]);
					if (nsQName.getStringValue().equals(name))
						return new NamespaceNode(document, ns);
					++ns;
				}
			}
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#setAttributeNode(org.w3c.dom.Attr)
	 */
	public Attr setAttributeNode(Attr arg0) throws DOMException {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#removeAttributeNode(org.w3c.dom.Attr)
	 */
	public Attr removeAttributeNode(Attr arg0) throws DOMException {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#getElementsByTagName(java.lang.String)
	 */
	public NodeList getElementsByTagName(String name) {
		NodeListImpl nl = new NodeListImpl();
		int nextNode = nodeNumber;
		while (++nextNode < document.size) {
			if (document.nodeKind[nextNode] == Node.ELEMENT_NODE) {
    			QName qn = (QName) document.namePool.get(document.nodeName[nextNode]);
    			if(qn.getStringValue().equals(name))
    				nl.add(document.getNode(nextNode));
    		}
			if (document.next[nextNode] <= nodeNumber) break;
		}
		return nl;
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#getAttributeNS(java.lang.String, java.lang.String)
	 */
	public String getAttributeNS(String namespaceURI, String localName) {
		int attr = document.alpha[nodeNumber];
		if (-1 < attr) {
			QName name;
			while (attr < document.nextAttr
				&& document.attrParent[attr] == nodeNumber) {
				name = (QName)document.namePool.get(document.attrName[attr]);
				if (name.getLocalName().equals(localName)
					&& name.getNamespaceURI().equals(namespaceURI))
					return document.attrValue[attr];
				++attr;
			}
		}

		if(Namespaces.XMLNS_NS.equals(namespaceURI)) {
			int ns = document.alphaLen[nodeNumber];
			if (-1 < ns) {
				while (ns < document.nextNamespace
						&& document.namespaceParent[ns] == nodeNumber) {
					QName nsQName=(QName)document.namePool.get(document.namespaceCode[ns]);
					if (nsQName.getLocalName().equals(localName))
						return nsQName.getNamespaceURI();
					++ns;
				}
			}
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#setAttributeNS(java.lang.String, java.lang.String, java.lang.String)
	 */
	public void setAttributeNS(String arg0, String arg1, String arg2)
		throws DOMException {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#removeAttributeNS(java.lang.String, java.lang.String)
	 */
	public void removeAttributeNS(String arg0, String arg1)
		throws DOMException {
		// TODO Auto-generated method stub

	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#getAttributeNodeNS(java.lang.String, java.lang.String)
	 */
	public Attr getAttributeNodeNS(String namespaceURI, String localName) {
		int attr = document.alpha[nodeNumber];
		if (-1 < attr) {
			QName name;
			while (attr < document.nextAttr
				&& document.attrParent[attr] == nodeNumber) {
				name = (QName)document.namePool.get(document.attrName[attr]);
				if (name.getLocalName().equals(localName)
					&& name.getNamespaceURI().equals(namespaceURI))
					return new AttributeImpl(document, attr);
				++attr;
			}
		}

		if(Namespaces.XMLNS_NS.equals(namespaceURI)) {
			int ns = document.alphaLen[nodeNumber];
			if (-1 < ns) {
				while (ns < document.nextNamespace
						&& document.namespaceParent[ns] == nodeNumber) {
					QName nsQName=(QName)document.namePool.get(document.namespaceCode[ns]);
					if (nsQName.getLocalName().equals(localName))
						return new NamespaceNode(document, ns);
					++ns;
				}
			}
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#setAttributeNodeNS(org.w3c.dom.Attr)
	 */
	public Attr setAttributeNodeNS(Attr arg0) throws DOMException {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#getElementsByTagNameNS(java.lang.String, java.lang.String)
	 */
	public NodeList getElementsByTagNameNS(String namespaceURI, String name) {
		QName qname = new QName(name, namespaceURI);
		NodeListImpl nl = new NodeListImpl();
		int nextNode = nodeNumber;
		while (++nextNode < document.size) {
			if (document.nodeKind[nextNode] == Node.ELEMENT_NODE) {
    			QName qn = (QName) document.namePool.get(document.nodeName[nextNode]);
    			if(qname.compareTo(qn) == 0)
    				nl.add(document.getNode(nextNode));
    		}
			if (document.next[nextNode] <= nodeNumber) break;
		}
		return nl;
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#hasAttribute(java.lang.String)
	 */
	public boolean hasAttribute(String name) {
		return getAttribute(name) != null;
	}

	/* (non-Javadoc)
	 * @see org.w3c.dom.Element#hasAttributeNS(java.lang.String, java.lang.String)
	 */
	public boolean hasAttributeNS(String namespaceURI, String localName) {
		return getAttributeNS(namespaceURI, localName) != null;
	}

	/**
     * The method getNamespaceForPrefix
     *
     * @param name a String value
     * @return a String value
     */
    public String getNamespaceForPrefix(String name) {
        int ns = document.alphaLen[nodeNumber];
        if (-1 < ns) {
            while (ns < document.nextNamespace
                   && document.namespaceParent[ns] == nodeNumber) {
                QName nsQName=(QName)document.namePool.get(document.namespaceCode[ns]);
                if (nsQName.getStringValue().equals("xmlns:" + name))
                    return nsQName.getNamespaceURI();
                ++ns;
            }
        }
		return null;
	}

	/**
     * The method getPrefixes
     *
     * @return a Set value
     */
    public Set getPrefixes() {
        HashSet set = new HashSet();
        int ns = document.alphaLen[nodeNumber];
        if (-1 < ns) {
            while (ns < document.nextNamespace
                   && document.namespaceParent[ns] == nodeNumber) {
                QName nsQName=(QName)document.namePool.get(document.namespaceCode[ns]);
                set.add(nsQName.getStringValue());
                ++ns;
            }
        }
		return set;
	}

    /**
     * The method declaresNamespacePrefixes
     *
     * @return a boolean value
     */
    public boolean declaresNamespacePrefixes() {
        return  (document.getNamespacesCountFor(nodeNumber) > 0);
    }

    /**
     * The method getNamespaceMap
     *
     * @return a Map value
     */
    public Map getNamespaceMap() {
        Map map = new HashMap();
        int ns = document.alphaLen[nodeNumber];
        if (-1 < ns) {
            while (ns < document.nextNamespace
                   && document.namespaceParent[ns] == nodeNumber) {
                QName nsQName = (QName) document.namePool.get(document.namespaceCode[ns]);
                map.put(nsQName.getLocalName(), nsQName.getNamespaceURI());
                ++ns;
            }
        }
        return map;
    }

	public int getItemType() {
		return Type.ELEMENT;
	}

    /** ? @see org.w3c.dom.Node#getBaseURI()
	 */
    public String getBaseURI() {
        String baseURI = getAttributeNS(Namespaces.XML_NS, "base");
        if ( baseURI == null) {
            baseURI = "";
        }
        int parent = -1;
        int test = -1;
        test = document.getParentNodeFor(nodeNumber);

        if (document.nodeKind[test] != Node.DOCUMENT_NODE) {
            parent = test;
        }
        // fixme! UNDEFINED instead of all the -1s in this file./ljo
        while (parent != -1 && document.getNode(parent).getBaseURI() != null) {
            if ("".equals(baseURI)) {
                baseURI = document.getNode(parent).getBaseURI();
            } else {
                baseURI = document.getNode(parent).getBaseURI() + "/" + baseURI;
            }

            test = document.getParentNodeFor(parent);
            if (document.nodeKind[test] == Node.DOCUMENT_NODE) {
                return baseURI;
            } else {
                parent = test;
            }
        }
        if ("".equals(baseURI)) {
            baseURI = getDocument().getBaseURI();
        }
        return baseURI;
    }

	/** ? @see org.w3c.dom.Element#getSchemaTypeInfo()
	 */
	public TypeInfo getSchemaTypeInfo() {
		// maybe TODO - new DOM interfaces - Java 5.0
		return null;
	}

	/** ? @see org.w3c.dom.Element#setIdAttribute(java.lang.String, boolean)
	 */
	public void setIdAttribute(String name, boolean isId) throws DOMException {
		// maybe TODO - new DOM interfaces - Java 5.0

	}

	/** ? @see org.w3c.dom.Element#setIdAttributeNS(java.lang.String, java.lang.String, boolean)
	 */
	public void setIdAttributeNS(String namespaceURI, String localName, boolean isId) throws DOMException {
		// maybe TODO - new DOM interfaces - Java 5.0

	}

	/** ? @see org.w3c.dom.Element#setIdAttributeNode(org.w3c.dom.Attr, boolean)
	 */
	public void setIdAttributeNode(Attr idAttr, boolean isId) throws DOMException {
		// maybe TODO - new DOM interfaces - Java 5.0

	}

	public String toString() {
    		StringBuffer result = new StringBuffer();
    		result.append("in-memory#");
    		result.append("element {");
    		result.append(getQName().getStringValue());
    		result.append("} {");
		NamedNodeMap theAttrs;
        	if((theAttrs=getAttributes()) != null) {
			for(int i = 0; i < theAttrs.getLength(); i++) {
				if(i > 0)
					result.append(" ");
				Node natt=theAttrs.item(i);
				if("org.exist.memtree.AttributeImpl".equals(natt.getClass().getName())) {
					result.append(((AttributeImpl)natt).toString());
				} else {
					result.append(((NamespaceNode)natt).toString());
				}
			}
		}
        	for(int i = 0; i < this.getChildCount(); i++ ) {
        		if(i > 0)
            		result.append(" ");
    			Node child = getChildNodes().item(i);
        	    result.append(child.toString());
        	}
        	result.append("} ");
        	return result.toString();
	}
}


text:
{% extends "base/base.html" %}
{% load staticfiles %}

{% block title %}
  Contact
{% endblock title %}

{% block heading %}
  Contact
{% endblock heading %}

{% block sub_heading %}
  Example App
{% endblock sub_heading %}

{% block menu %}

    Admin

  {{ block.super }}
{% endblock menu %}

{% block footer %}
{% endblock footer %}


text:
'use strict';

if (require('./RegularModule').getModuleStateValue()) {
  console.log('Hello, world!');
} else {
  console.log('Automocking is not properly disabled in jest-runtime.');
}


text:
import './editable_node_selector.html';
import { Blaze } from 'meteor/blaze';
import { Template } from 'meteor/templating';
import './x_editable_node_selector.js';
import './x_editable_node_selector.css';

/**
 * Template Helpers
 */
Template.EditableNodeSelector.helpers({});

/**
 * Template Event Handlers
 */
Template.EditableNodeSelector.events({});

/**
 * Template Created
 */
Template.EditableNodeSelector.created = function () {

};

/**
 * Template Rendered
 */
Template.EditableNodeSelector.rendered = function () {
  var instance = Template.instance();

  //console.log("EditableNodeSelector context:", instance.data);

  // Make sure there's a project version id
  if(!instance.data.projectVersionId){
    throw new Meteor.Error('Null project version id:', instance.data);
  }

  instance.$(".editable").editable({
    type            : "nodeSelector",
    mode            : instance.data.mode || "popup",
    placement       : instance.data.placement || "auto",
    value           : instance.data.value,
    projectVersionId: instance.data.projectVersionId,
    parentInstance  : instance,
    highlight       : false,
    display() {
    },
    success(response, newValue) {
      console.log("EditableNodeSelector edited: ", newValue);
      var editedElement = this;
      $(editedElement).trigger("edited", [ newValue ]);
      setTimeout(function () {
        $(editedElement).removeClass('editable-unsaved');
      }, 10);
    }
  });

  // this event listener needs to be registered directly
  instance.$(".editable").on("hidden", function () {
    console.log("EditableNodeSelector .editable hidden: ", instance.searchView);
    if (instance.searchView) {
      setTimeout(function () {
        Blaze.remove(instance.searchView);
      }, 100);
    }
  });

  instance.autorun(function () {
    var data = Template.currentData();
    console.log("EditableNodeSelector autorun setting value: ", data.value);
    instance.$(".editable").editable("setValue", data.value);
  });
};

/**
 * Template Destroyed
 */
Template.EditableNodeSelector.destroyed = function () {

};