text:
body {
  color: #000000;
  font-family: 'Play', sans-serif;
  font-size: 1.75em;
  overflow-x: hidden; }
  body textarea {
    resize: vertical; }
  body app-info {
    position: fixed;
    bottom: 0;
    height: 10vh;
    width: 100%;
    display: flex;
    justify-content: space-around;
    align-items: center; }
    body app-info .flex-item {
      flex: 1;
      text-align: center;
      text-decoration: none; }
      body app-info .flex-item:hover {
        background: #f0f0f0; }
      body app-info .flex-item img {
        min-height: 5vh;
        height: 10vh;
        max-height: 10vh;
        width: auto !important;
        max-width: 24vw; }
  body #modal-window {
    display: none; }
  body a:hover, body a:focus {
    outline: none; }
  body a:hover {
    cursor: pointer; }
  body #marked-preview {
    font-size: 0.8em; }
    body #marked-preview h1, body #marked-preview h2, body #marked-preview h3 {
      font-size: 1.2em; }
  body .btn:hover, body .btn:focus {
    outline: none; }
  body .nopadding {
    padding: 0; }
    body .nopadding nav {
      font-size: 1em; }
    body .nopadding #sliding-window {
      width: 100%;
      height: 5em;
      background-color: rgba(0, 0, 0, 0.5);
      position: fixed;
      border: 1px #101010 solid;
      transition-duration: 1.25s;
      z-index: 10;
      overflow-X: hidden; }
      body .nopadding #sliding-window button {
        margin: 0px 5px 0px 5px; }
      body .nopadding #sliding-window #slider-data {
        width: 96%;
        margin: 20px 2% 2% 2%;
        height: 91%;
        background-color: #ffffff; }
        body .nopadding #sliding-window #slider-data .recent-track {
          display: block;
          width: 100%;
          border: 0; }
    body .nopadding .home {
      background: transparent url("#") fixed center top/cover;
      min-height: 98vh;
      height: auto !important;
      margin-top: 2vh;
      padding-top: 4vh; }
      body .nopadding .home #dialog {
        display: block; }
      body .nopadding .home .overlay {
        height: 100%;
        width: 0;
        position: fixed;
        z-index: 1;
        top: 0;
        left: 0;
        background-color: rgba(0, 0, 0, 0.9);
        overflow-x: hidden;
        transition: 0.5s; }
        body .nopadding .home .overlay #usersMgmtPanel .table, body .nopadding .home .overlay #linksMgmtPanel .table {
          text-align: left; }
        body .nopadding .home .overlay .panel {
          background-color: rgba(255, 255, 255, 0); }
      body .nopadding .home .overlay-content {
        position: relative;
        top: 25%;
        width: 100%;
        text-align: center;
        margin-top: 30px;
        color: rgba(255, 255, 255, 0.9); }
        body .nopadding .home .overlay-content .table {
          font-size: 0.6em;
          /* Small (544px) */
          /* Medium (768px) */
          /* Large (992px) */
          /* Extra large (1200px) */ }
          @media screen and (min-width: 34em) {
            body .nopadding .home .overlay-content .table {
              font-size: 0.7em; } }
          @media screen and (min-width: 48em) {
            body .nopadding .home .overlay-content .table {
              font-size: 0.8em; } }
          @media screen and (min-width: 62em) {
            body .nopadding .home .overlay-content .table {
              font-size: 0.9em; } }
          @media screen and (min-width: 75em) {
            body .nopadding .home .overlay-content .table {
              font-size: 1em; } }
      body .nopadding .home .overlay a {
        text-decoration: none;
        font-size: 36px;
        color: #818181;
        display: block;
        transition: 0.3s; }
        @media screen and (max-height: 450px) {
          body .nopadding .home .overlay a {
            font-size: 20px; } }
      body .nopadding .home .overlay a:hover, body .nopadding .home .overlay a:focus {
        color: #f1f1f1;
        cursor: pointer;
        outline: none; }
      body .nopadding .home .closebtn {
        position: absolute;
        top: 0.5em;
        right: 0.3em;
        font-size: 60px !important; }
        @media screen and (max-height: 450px) {
          body .nopadding .home .closebtn {
            font-size: 40px !important;
            top: 0.5em;
            right: 0.3em; } }
      body .nopadding .home .output {
        margin-top: 50px;
        text-align: center; }
        body .nopadding .home .output a:hover {
          text-decoration: none; }
        body .nopadding .home .output .fullscreen-bg {
          position: fixed;
          top: 0;
          right: 0;
          bottom: 0;
          left: 0;
          overflow: hidden;
          z-index: -100; }
          @media screen and (max-width: 767px) {
            body .nopadding .home .output .fullscreen-bg {
              background: url("../vid/bgvid.jpg") center center/cover no-repeat; } }
        body .nopadding .home .output .fullscreen-bg__video {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%; }
          @media screen and (min-aspect-ratio: 16 / 9) {
            body .nopadding .home .output .fullscreen-bg__video {
              height: 300%;
              top: -100%; } }
          @media screen and (max-aspect-ratio: 16 / 9) {
            body .nopadding .home .output .fullscreen-bg__video {
              width: 300%;
              left: -100%; } }
          @media screen and (max-width: 767px) {
            body .nopadding .home .output .fullscreen-bg__video {
              display: none; } }
        body .nopadding .home .output .grid {
          padding-top: 1vh; }
          body .nopadding .home .output .grid .grid-item {
            background-color: #ffffff; }
            @media screen and (max-width: 430px) {
              body .nopadding .home .output .grid .grid-item {
                width: 90%;
                -moz-box-shadow: 3px 3px 4px 4px #ccc;
                -webkit-box-shadow: 3px 3px 4px 4px #ccc;
                box-shadow: 3px 3px 4px 4px #ccc;
                margin: 1em; } }
            @media screen and (min-width: 430px) and (max-width: 950px) {
              body .nopadding .home .output .grid .grid-item {
                width: 28%;
                -moz-box-shadow: 3px 3px 4px 4px #ccc;
                -webkit-box-shadow: 3px 3px 4px 4px #ccc;
                box-shadow: 3px 3px 4px 4px #ccc;
                margin: 0.5em; } }
            @media screen and (min-width: 950px) and (max-width: 1456px) {
              body .nopadding .home .output .grid .grid-item {
                width: 27%;
                -moz-box-shadow: 3px 3px 4px 4px #ccc;
                -webkit-box-shadow: 3px 3px 4px 4px #ccc;
                box-shadow: 3px 3px 4px 4px #ccc;
                margin: 1.5em; } }
            @media screen and (min-width: 1456px) {
              body .nopadding .home .output .grid .grid-item {
                width: 29%;
                -moz-box-shadow: 3px 3px 4px 4px #ccc;
                -webkit-box-shadow: 3px 3px 4px 4px #ccc;
                box-shadow: 3px 3px 4px 4px #ccc;
                margin: 1.5em; } }
            body .nopadding .home .output .grid .grid-item #url-img, body .nopadding .home .output .grid .grid-item #post-img {
              display: block;
              width: 100%;
              height: auto !important; }
            body .nopadding .home .output .grid .grid-item #url-user-details-api-link, body .nopadding .home .output .grid .grid-item #url-link, body .nopadding .home .output .grid .grid-item #owner-link, body .nopadding .home .output .grid .grid-item #remove-link, body .nopadding .home .output .grid .grid-item #add-to-user-collection {
              display: inline-block; }
            body .nopadding .home .output .grid .grid-item #details-api-link, body .nopadding .home .output .grid .grid-item #post-timestamp {
              display: inline-block; }
            body .nopadding .home .output .grid .grid-item #post-timestamp {
              font-size: 0.65em; }
            body .nopadding .home .output .grid .grid-item #post-text {
              display: none; }
          body .nopadding .home .output .grid .selected-grid-item {
            box-shadow: 3px 3px 4px 4px #ff0000; }
        body .nopadding .home .output #blog-grid {
          width: 60%; }
          body .nopadding .home .output #blog-grid .grid-item {
            background-color: #ffffff; }
            @media screen and (max-width: 430px) {
              body .nopadding .home .output #blog-grid .grid-item {
                width: 80%;
                -moz-box-shadow: 3px 3px 4px 4px #ccc;
                -webkit-box-shadow: 3px 3px 4px 4px #ccc;
                box-shadow: 3px 3px 4px 4px #ccc;
                margin: 1em; } }
            @media screen and (min-width: 430px) and (max-width: 950px) {
              body .nopadding .home .output #blog-grid .grid-item {
                width: 80%;
                -moz-box-shadow: 3px 3px 4px 4px #ccc;
                -webkit-box-shadow: 3px 3px 4px 4px #ccc;
                box-shadow: 3px 3px 4px 4px #ccc;
                margin: 0.5em; } }
            @media screen and (min-width: 950px) and (max-width: 1456px) {
              body .nopadding .home .output #blog-grid .grid-item {
                width: 23%;
                -moz-box-shadow: 3px 3px 4px 4px #ccc;
                -webkit-box-shadow: 3px 3px 4px 4px #ccc;
                box-shadow: 3px 3px 4px 4px #ccc;
                margin: 1.5em; } }
            @media screen and (min-width: 1456px) {
              body .nopadding .home .output #blog-grid .grid-item {
                width: 25%;
                -moz-box-shadow: 3px 3px 4px 4px #ccc;
                -webkit-box-shadow: 3px 3px 4px 4px #ccc;
                box-shadow: 3px 3px 4px 4px #ccc;
                margin: 1.5em; } }
          body .nopadding .home .output #blog-grid .selected-grid-item {
            box-shadow: 3px 3px 4px 4px #ff0000;
            /* this shows blog post text in container, it is considered a bad practice and should be removed later
                        #post-text {
                            display: block;
                            width: 100%;
                            height: auto !important;
                            background: $white;
                            text-align: left;
                            padding: 0 0.65em 0 0.65em;
                            font-size: 0.8em;
                            img {
                                max-width: 100%;
                            }
                        }
                        #post-img {
                            display: none;
                        }
                        */ }
          body .nopadding .home .output #blog-grid #post-heading {
            font-size: 0.8em;
            font-weight: bold; }
        body .nopadding .home .output #blog-sidebar-details {
          position: fixed;
          right: 0;
          top: 50px;
          display: inline-block;
          background: rgba(0, 0, 0, 0.5);
          color: #ffffff;
          text-align: left;
          width: 40%;
          height: calc(100vh - 50px);
          padding: 0 0.65em 0 0.65em;
          font-size: 0.8em;
          overflow-y: scroll; }
          body .nopadding .home .output #blog-sidebar-details img {
            max-width: 100%; }
        body .nopadding .home .output .profile {
          margin-top: 2vh; }
          body .nopadding .home .output .profile .user_extended {
            margin-top: 2vh; }
        body .nopadding .home .output .edit {
          width: 100%; }
        body .nopadding .home .output .done {
          width: 100%;
          display: none; }
        body .nopadding .home .output #user-stories {
          display: none;
          position: absolute;
          z-index: 15;
          top: 8vh;
          font-size: 0.85em;
          text-align: left; }
          body .nopadding .home .output #user-stories h4 {
            text-align: center; }
        body .nopadding .home .output .login #email-auth {
          margin-top: 2vh; }
  body #flex-nav {
    display: flex;
    align-items: center; }
    body #flex-nav .flex-nav-item {
      flex: 1;
      text-align: center;
      text-decoration: none; }
      body #flex-nav .flex-nav-item:hover {
        background: #f0f0f0; }
    body #flex-nav .selected {
      background-color: #f0f0f0; }
  body #dashboard .spinner, body dashboard-details .spinner {
    /* default is ok for now */ }
  body #dashboard .input-label:hover, body dashboard-details .input-label:hover {
    cursor: default; }
  body #dashboard #filters, body dashboard-details #filters {
    z-index: 2;
    width: 100%;
    border: 1px #101010 dotted;
    box-sizing: border-box;
    padding: 0.5em;
    display: flex;
    align-items: center; }
    body #dashboard #filters .flex-item, body dashboard-details #filters .flex-item {
      flex: 1;
      text-align: center; }
  body #dashboard #dashboard-data .users, body dashboard-details #dashboard-data .users {
    list-style: none;
    padding: 0; }
    body #dashboard #dashboard-data .users li, body dashboard-details #dashboard-data .users li {
      padding-left: 1.2em; }
      body #dashboard #dashboard-data .users li:before, body dashboard-details #dashboard-data .users li:before {
        content: "\f007";
        font-family: FontAwesome;
        display: inline-block;
        margin-left: -1.2em;
        width: 1.2em; }
      body #dashboard #dashboard-data .users li h3, body dashboard-details #dashboard-data .users li h3 {
        display: inline-block; }
        body #dashboard #dashboard-data .users li h3:hover, body dashboard-details #dashboard-data .users li h3:hover {
          cursor: default; }
      body #dashboard #dashboard-data .users li div:hover, body dashboard-details #dashboard-data .users li div:hover {
        cursor: default; }
  body #dashboard #dashboard-data .labels, body dashboard-details #dashboard-data .labels {
    list-style: none;
    padding: 0; }
    body #dashboard #dashboard-data .labels li, body dashboard-details #dashboard-data .labels li {
      padding-left: 1.5em; }
      body #dashboard #dashboard-data .labels li:before, body dashboard-details #dashboard-data .labels li:before {
        content: "\f02e";
        font-family: FontAwesome;
        display: inline-block;
        margin-left: -1.5em;
        width: 1.5em; }
      body #dashboard #dashboard-data .labels li h3, body #dashboard #dashboard-data .labels li span, body dashboard-details #dashboard-data .labels li h3, body dashboard-details #dashboard-data .labels li span {
        display: inline-block; }
        body #dashboard #dashboard-data .labels li h3:hover, body #dashboard #dashboard-data .labels li span:hover, body dashboard-details #dashboard-data .labels li h3:hover, body dashboard-details #dashboard-data .labels li span:hover {
          cursor: default; }
      body #dashboard #dashboard-data .labels li div:hover, body dashboard-details #dashboard-data .labels li div:hover {
        cursor: default; }
    body #dashboard #dashboard-data .labels .label-item, body dashboard-details #dashboard-data .labels .label-item {
      display: flex;
      justify-content: flex-start;
      align-items: stretch; }
      body #dashboard #dashboard-data .labels .label-item .label-details, body dashboard-details #dashboard-data .labels .label-item .label-details {
        padding-left: 0.5em;
        padding-right: 0.5em;
        flex-grow: 1;
        display: flex;
        justify-content: space-around;
        align-items: stretch; }


text:
// See what happens when Aria.load doesn't have any callback
Aria.classDefinition({
    $classpath : "test.aria.jsunit.load.IgnoreCallbacksTestCase",
    $extends : "aria.jsunit.TestCase",
    $prototype : {
        testAsyncLoadError: function () {
            // Simply expect 0 undisposed objects
            this._expectedErrorList = [aria.core.MultiLoader.LOAD_ERROR];

            Aria.load({
                classes : ["test.aria.jsunit.load.dependencies.AnotherFileNotFound"]
            });

            this.notifyTestEnd("testAsyncLoadError");
        }
    }
});

redpajama_set_name: RedPajamaGithub


text:
package com.google.javascript.rhino.testing;

import com.google.javascript.rhino.ErrorReporter;
import com.google.javascript.rhino.jstype.JSType;
import com.google.javascript.rhino.jstype.StaticScope;

import junit.framework.Assert;

/**
 * Helper methods for making assertions about the validity of types.
 * @author nicksantos@google.com (Nick Santos)
 */
public class Asserts {
  private Asserts() {} // all static

  public static JSType assertResolvesToSame(JSType type) {
    Assert.assertSame(type, assertValidResolve(type));
    return type;
  }

  /** @return The resolved type */
  public static JSType assertValidResolve(JSType type) {
    return assertValidResolve(type, new EmptyScope());
  }

  /** @return The resolved type */
  public static JSType assertValidResolve(
      JSType type, StaticScope<JSType> scope) {
    ErrorReporter t = TestErrorReporter.forNoExpectedReports();
    JSType resolvedType = type.resolve(t, scope);
    assertTypeEquals("JSType#resolve should not affect object equality",
        type, resolvedType);
    Assert.assertEquals("JSType#resolve should not affect hash codes",
        type.hashCode(), resolvedType.hashCode());
    return resolvedType;
  }

  public static void assertTypeEquals(JSType a, JSType b) {
    assertTypeEquals("", a, b);
  }

  public static void assertTypeEquals(String message, JSType a, JSType b) {
    Assert.assertTrue(
        message +
        (message.isEmpty() ? "" : "\n") +
        "Expected: " + b + "\n" +
        "Actual  : " + a,
        a.isEquivalentTo(b));
  }
}


text:
import {
  AfterViewInit,
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component,
  ElementRef,
  EventEmitter,
  Input,
  OnDestroy,
  OnInit,
  Optional,
  Output,
  Self,
  TemplateRef,
  ViewChild,
  ViewEncapsulation,
} from '@angular/core';
import { ControlValueAccessor, NgControl } from '@angular/forms';
import { SkyAppWindowRef } from '@skyux/core';
import { SkyInputBoxHostService } from '@skyux/forms';
import { SkyLibResourcesService } from '@skyux/i18n';
import {
  SkyToken,
  SkyTokensMessage,
  SkyTokensMessageType,
} from '@skyux/indicators';
import { SkyModalInstance, SkyModalService } from '@skyux/modals';
import { SkyThemeService } from '@skyux/theme';

import { Subject, fromEvent as observableFromEvent } from 'rxjs';
import { take, takeUntil } from 'rxjs/operators';

import { SkyAutocompleteInputDirective } from '../autocomplete/autocomplete-input.directive';
import { SkyAutocompleteMessage } from '../autocomplete/types/autocomplete-message';
import { SkyAutocompleteMessageType } from '../autocomplete/types/autocomplete-message-type';
import { SkyAutocompleteSearchAsyncArgs } from '../autocomplete/types/autocomplete-search-async-args';
import { SkyAutocompleteSelectionChange } from '../autocomplete/types/autocomplete-selection-change';
import { SkyAutocompleteShowMoreArgs } from '../autocomplete/types/autocomplete-show-more-args';

import { SkyLookupAdapterService } from './lookup-adapter.service';
import { SkyLookupAutocompleteAdapter } from './lookup-autocomplete-adapter';
import { SkyLookupShowMoreAsyncModalComponent } from './lookup-show-more-async-modal.component';
import { SkyLookupShowMoreModalComponent } from './lookup-show-more-modal.component';
import { SkyLookupAddCallbackArgs } from './types/lookup-add-click-callback-args';
import { SkyLookupAddClickEventArgs } from './types/lookup-add-click-event-args';
import { SkyLookupSelectModeType } from './types/lookup-select-mode-type';
import { SkyLookupShowMoreConfig } from './types/lookup-show-more-config';
import { SkyLookupShowMoreNativePickerAsyncContext } from './types/lookup-show-more-native-picker-async-context';
import { SkyLookupShowMoreNativePickerContext } from './types/lookup-show-more-native-picker-context';

@Component({
  selector: 'sky-lookup',
  templateUrl: './lookup.component.html',
  styleUrls: ['./lookup.component.scss'],
  providers: [SkyLookupAdapterService],
  encapsulation: ViewEncapsulation.None,
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class SkyLookupComponent
  extends SkyLookupAutocompleteAdapter
  implements OnInit, AfterViewInit, OnDestroy, ControlValueAccessor
{
  /**
   * Specifies an ARIA label for the typeahead search input
   * [to support accessibility](https://developer.blackbaud.com/skyux/learn/accessibility).
   * If the input includes a visible label, use `ariaLabelledBy` instead.
   */
  @Input()
  public ariaLabel: string | undefined;

  /**
   * Specifies the HTML element ID (without the leading `#`) of the element that labels
   * the typeahead search input. This sets the input's `aria-labelledby` attribute
   * [to support accessibility](https://developer.blackbaud.com/skyux/learn/accessibility).
   * If the input does not include a visible label, use `ariaLabel` instead.
   */
  @Input()
  public ariaLabelledBy: string | undefined;

  /**
   * Specifies the value for the `autocomplete` attribute on the form input.
   */
  @Input()
  public autocompleteAttribute: string | undefined;

  /**
   * Specifies a data source for the lookup component to search when users
   * enter text. You can specify static data such as an array of objects, or
   * you can pull data from a database.
   * @default []
   */
  @Input()
  public set data(value: any[] | undefined) {
    this.#_data = value;

    if (this.#openNativePicker && this.searchAsync.observers.length === 0) {
      this.#openNativePicker.componentInstance.updateItemData(value);
    }
  }

  public get data(): any[] {
    return this.#_data || [];
  }

  /**
   * Indicates whether to disable the lookup field.
   * @default false
   */
  @Input()
  public set disabled(value: boolean | undefined) {
    this.#_disabled = value ?? false;
  }

  public get disabled(): boolean {
    return this.#_disabled;
  }

  /**
   * Indicates whether to enable users to open a picker where they can view all options.
   * @default false
   */
  @Input()
  public set enableShowMore(value: boolean | undefined) {
    this.#_enableShowMore = value ?? false;
  }

  public get enableShowMore(): boolean {
    return this.#_enableShowMore;
  }

  /**
   * Specifies placeholder text to display in the lookup field.
   */
  @Input()
  public placeholderText: string | undefined;

  /**
   * Specifies an object property that represents the object's unique identifier.
   * Specifying this property enables token animations and more efficient rendering.
   * This property is required when using `enableShowMore` and `searchAsync` together.
   */
  @Input()
  public idProperty: string | undefined;

  /**
   * Indicates whether to display a button that lets users add options to the list.
   * @default false
   */
  @Input()
  public set showAddButton(value: boolean | undefined) {
    this.#_showAddButton = value ?? false;
  }

  public get showAddButton(): boolean {
    return this.#_showAddButton;
  }

  /**
   * Specifies configuration options for the picker that displays all options.
   */
  @Input()
  public showMoreConfig: SkyLookupShowMoreConfig | undefined;

  /**
   * Specifies whether users can select one option or multiple options.
   * @default "multiple"
   */
  @Input()
  public set selectMode(value: SkyLookupSelectModeType | undefined) {
    const multipleToSingle: boolean =
      value === 'single' && this.selectMode === 'multiple';

    this.#_selectMode = value;
    this.#updateForSelectMode();

    if (multipleToSingle) {
      if (this.value && this.value.length > 1) {
        // The `setTimeout` is needed to avoid a `ExpressionChangedAfterItHasBeenCheckedError` error in template forms.
        setTimeout(() => {
          this.writeValue([this.value[0]]);
          this.#changeDetector.detectChanges();
        });
      }
    }
  }

  public get selectMode(): SkyLookupSelectModeType {
    return this.#_selectMode || 'multiple';
  }

  /**
   * @internal
   */
  @Input()
  public wrapperClass: string | undefined;

  /**
   * Fires when users select the button to add options to the list.
   */
  @Output()
  public addClick: EventEmitter<SkyLookupAddClickEventArgs> = new EventEmitter();

  public get tokens(): SkyToken[] | undefined {
    return this.#_tokens;
  }

  public set tokens(value: SkyToken[] | undefined) {
    // Collapse the tokens into a single token if the user has selected many options.
    if (this.enableShowMore && this.value.length > 5) {
      this.#resourcesService
        .getString('skyux_lookup_tokens_summary', this.value.length.toString())
        .pipe(take(1))
        .subscribe((label) => {
          this.#_tokens = [
            {
              value: { [this.descriptorProperty]: label },
            },
          ];
          this.#changeDetector.markForCheck();
        });
    } else {
      this.#_tokens = value;
      this.#changeDetector.markForCheck();
    }
  }

  public get value(): any[] {
    return this.#_value ? this.#_value : [];
  }

  public set value(newValue: any[]) {
    this.#_value = newValue;

    if (!this.#openNativePicker) {
      this.tokens = this.#parseTokens(newValue);
    }

    this.onChange(this.#_value);
    this.onTouched();
  }

  public autocompleteController = new Subject<SkyAutocompleteMessage>();
  public isInputFocused = false;
  public showMorePickerId: string | undefined;
  public tokensController = new Subject<SkyTokensMessage>();

  @ViewChild(SkyAutocompleteInputDirective, {
    read: SkyAutocompleteInputDirective,
    static: false,
  })
  public set autocompleteInputDirective(
    value: SkyAutocompleteInputDirective | undefined
  ) {
    this.#_autocompleteInputDirective = value;
    this.#updateForSelectMode();
  }

  public get autocompleteInputDirective():
    | SkyAutocompleteInputDirective
    | undefined {
    return this.#_autocompleteInputDirective;
  }

  @ViewChild('showMoreButtonTemplateRef', {
    read: TemplateRef,
    static: true,
  })
  public showMoreButtonTemplateRef: TemplateRef<unknown> | undefined;

  @ViewChild('inputTemplateRef', {
    read: TemplateRef,
    static: true,
  })
  public inputTemplateRef: TemplateRef<unknown> | undefined;

  @ViewChild('lookupWrapper', {
    read: ElementRef,
  })
  public lookupWrapperRef: ElementRef | undefined;

  @ViewChild('searchIconTemplateRef', {
    read: TemplateRef,
    static: true,
  })
  public searchIconTemplateRef: TemplateRef<unknown> | undefined;

  #adapter: SkyLookupAdapterService;

  #elementRef: ElementRef;

  #changeDetector: ChangeDetectorRef;

  #idle = new Subject<void>();

  #markForTokenFocusOnKeyUp = false;

  #modalService: SkyModalService;

  #ngUnsubscribe = new Subject<void>();

  #openNativePicker: SkyModalInstance | undefined;

  #resourcesService: SkyLibResourcesService;

  #windowRef: SkyAppWindowRef;

  #_autocompleteInputDirective: SkyAutocompleteInputDirective | undefined;

  #_data: any[] | undefined;

  #_disabled = false;

  #_enableShowMore = false;

  #_selectMode: SkyLookupSelectModeType | undefined;

  #_showAddButton = false;

  #_tokens: SkyToken[] | undefined;

  #_value: any[] | undefined;

  constructor(
    changeDetector: ChangeDetectorRef,
    elementRef: ElementRef,
    windowRef: SkyAppWindowRef,
    adapter: SkyLookupAdapterService,
    modalService: SkyModalService,
    resourcesService: SkyLibResourcesService,
    @Self() @Optional() ngControl?: NgControl,
    @Optional() public inputBoxHostSvc?: SkyInputBoxHostService,
    @Optional() public themeSvc?: SkyThemeService
  ) {
    super();

    this.#changeDetector = changeDetector;
    this.#elementRef = elementRef;
    this.#windowRef = windowRef;
    this.#adapter = adapter;
    this.#modalService = modalService;
    this.#resourcesService = resourcesService;

    if (ngControl) {
      ngControl.valueAccessor = this;
    }
  }

  public ngOnInit(): void {
    if (this.inputBoxHostSvc && this.inputTemplateRef) {
      this.inputBoxHostSvc.populate({
        inputTemplate: this.inputTemplateRef,
        buttonsTemplate: this.enableShowMore
          ? this.showMoreButtonTemplateRef
          : undefined,
        iconsInsetTemplate: this.enableShowMore
          ? undefined
          : this.searchIconTemplateRef,
      });
    }

    /* istanbul ignore else */
    if (this.themeSvc) {
      // This is required for the autocomplete directive to be set after elements
      // are rearranged when switching themes.
      this.themeSvc.settingsChange
        .pipe(takeUntil(this.#ngUnsubscribe))
        .subscribe(() => {
          this.#changeDetector.markForCheck();
        });
    }
  }

  public ngAfterViewInit(): void {
    if (!this.disabled) {
      this.#addEventListeners();
    }
  }

  public ngOnDestroy(): void {
    this.#removeEventListeners();
    this.#ngUnsubscribe.next();
    this.#ngUnsubscribe.complete();
    this.tokensController.complete();
  }

  public addButtonClicked(): void {
    this.addClick.emit({
      itemAdded: (args: SkyLookupAddCallbackArgs) =>
        this.#onAddButtonComplete(args),
    });
  }

  public onAutocompleteSelectionChange(
    change: SkyAutocompleteSelectionChange
  ): void {
    /* istanbul ignore else */
    if (change.selectedItem) {
      this.#addToSelected(change.selectedItem);
    } else if (this.selectMode === 'single') {
      this.writeValue([]);
    }
  }

  public onAutocompleteBlur(): void {
    this.onTouched();
  }

  public onTokensChange(change: SkyToken[]): void {
    if (!change) {
      return;
    }

    if (this.tokens !== change) {
      if (change.length === 0) {
        this.#focusInput();
      }

      // NOTE: We do this here instead of just using the `value` setter because we need to use the
      // set of tokens returned here for the purposes of setting focus (see `onTokensKeyUp`).
      this.#_value = change.map((token) => {
        return token.value;
      });
      this.tokens = change;
      this.onChange(this.#_value);
      this.onTouched();
    }
  }

  public onTokensFocusIndexOverRange(): void {
    this.#windowRef.nativeWindow.setTimeout(() => {
      this.#focusInput();
    });
  }

  public onTokensKeyUp(event: KeyboardEvent): void {
    /* istanbul ignore else */
    if (this.selectMode !== 'single') {
      switch (event.key) {
        case 'Backspace':
          this.#sendTokensMessage(SkyTokensMessageType.RemoveActiveToken);
          this.#sendTokensMessage(SkyTokensMessageType.FocusPreviousToken);
          event.preventDefault();
          break;

        case 'Del':
        case 'Delete':
          this.#sendTokensMessage(SkyTokensMessageType.RemoveActiveToken);
          this.#windowRef.nativeWindow.setTimeout(() => {
            this.#sendTokensMessage(SkyTokensMessageType.FocusActiveToken);
          });
          event.preventDefault();
          break;
      }
    }
  }

  public onTokensRendered(): void {
    this.#sendAutocompleteMessage(
      SkyAutocompleteMessageType.RepositionDropdown
    );
  }

  public writeValue(value: any[]): void {
    // Since we are dealing with arrays - clone the array being sent in to ensure we aren't modifying a consumers outer array
    this.value = value ? value.slice() : [];
    this.#updateForSelectMode();
  }

  // Angular automatically constructs these methods.
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  public onChange = (value: any[]) => {};
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  public onTouched = () => {};

  public registerOnChange(fn: (value: any) => void) {
    this.onChange = fn;
  }

  public registerOnTouched(fn: () => void): void {
    this.onTouched = fn;
  }

  // Allows Angular to disable the input.
  public setDisabledState(disabled: boolean): void {
    this.#removeEventListeners();

    if (!disabled) {
      this.#addEventListeners();
    }

    this.disabled = disabled;
    this.#changeDetector.markForCheck();
  }

  public clearSearchText(): void {
    if (this.autocompleteInputDirective) {
      this.autocompleteInputDirective.value = undefined;
      this.autocompleteInputDirective.inputTextValue = '';
    }
  }

  // Handles when to focus on the tokens.
  // Check for empty search text on keydown, before the escape key is fully pressed.
  // (Otherwise, a single character being escaped would register as empty on keyup.)
  // If empty on keydown, set a flag so that the appropriate action can be taken on keyup.
  public inputKeydown(event: KeyboardEvent): void {
    const value = (event.target as HTMLTextAreaElement).value;

    /* Sanity check as this should only be called when in multiple select mode */
    /* istanbul ignore else */
    if (this.selectMode !== 'single') {
      switch (event.key) {
        case 'Enter':
          event.preventDefault();
          break;
        case 'ArrowLeft':
        case 'Backspace':
        case 'Left':
          if (value) {
            this.#markForTokenFocusOnKeyUp = false;
          } else {
            this.#markForTokenFocusOnKeyUp = true;
          }
          break;
        default:
      }
    }
  }

  public inputKeyup(event: KeyboardEvent): void {
    /* Sanity check as this should only be called when in multiple select mode */
    /* istanbul ignore else */
    if (this.selectMode !== 'single') {
      switch (event.key) {
        case 'Esc':
        case 'Escape':
          this.clearSearchText();
          event.preventDefault();
          break;
        case 'ArrowLeft':
        case 'Backspace':
        case 'Left':
          /* istanbul ignore else */
          if (this.#markForTokenFocusOnKeyUp) {
            this.#sendTokensMessage(SkyTokensMessageType.FocusLastToken);
            event.preventDefault();
          }
          break;
        default:
      }

      event.stopPropagation();
    }
  }

  public onSearchButtonClick(): void {
    /*istanbul ignore next*/
    if (this.disabled) {
      return;
    }
    this.#sendAutocompleteMessage(SkyAutocompleteMessageType.CloseDropdown);
    let isValueInTextBox = false;
    if (this.selectMode === 'single') {
      isValueInTextBox =
        this.autocompleteInputDirective?.value &&
        this.autocompleteInputDirective.inputTextValue ===
          this.autocompleteInputDirective.value[this.descriptorProperty];
    }

    let searchValue = '';

    if (!isValueInTextBox && this.autocompleteInputDirective) {
      searchValue = this.autocompleteInputDirective.inputTextValue;
    }

    this.openPicker(searchValue);
    this.autocompleteInputDirective?.restoreInputTextValueToPreviousState();
  }

  public onShowMoreClick(event: SkyAutocompleteShowMoreArgs): void {
    /* Sanity check */
    /* istanbul ignore else*/
    if (event) {
      this.openPicker(event.inputValue);
    }
  }

  #createNativePickerInstance(initialSearch: string): SkyModalInstance {
    const initialValue = this.value;
    const modalConfig = this.showMoreConfig?.nativePickerConfig || {};

    if (!modalConfig.itemTemplate) {
      modalConfig.itemTemplate = this.searchResultTemplate;
    }

    let contextProviderType:
      | typeof SkyLookupShowMoreNativePickerContext
      | typeof SkyLookupShowMoreNativePickerAsyncContext;

    let contextProviderValue:
      | SkyLookupShowMoreNativePickerContext
      | SkyLookupShowMoreNativePickerAsyncContext;

    let modalComponentType:
      | typeof SkyLookupShowMoreModalComponent
      | typeof SkyLookupShowMoreAsyncModalComponent;

    if (this.searchAsync.observers.length > 0) {
      contextProviderType = SkyLookupShowMoreNativePickerAsyncContext;
      modalComponentType = SkyLookupShowMoreAsyncModalComponent;

      contextProviderValue = new SkyLookupShowMoreNativePickerAsyncContext(
        this.descriptorProperty,
        this.idProperty!,
        initialSearch,
        initialValue,
        (args) => {
          this.searchAsync.emit(args);
          return args.result!;
        },
        this.selectMode,
        this.showAddButton,
        modalConfig
      );
    } else {
      contextProviderType = SkyLookupShowMoreNativePickerContext;
      modalComponentType = SkyLookupShowMoreModalComponent;

      contextProviderValue = new SkyLookupShowMoreNativePickerContext(
        this.descriptorProperty,
        initialSearch,
        initialValue,
        this.data,
        this.searchOrDefault,
        this.selectMode,
        this.showAddButton,
        modalConfig
      );
    }

    return this.#modalService.open(modalComponentType, {
      providers: [
        {
          provide: contextProviderType,
          useValue: contextProviderValue,
        },
      ],
      size: 'large',
      wrapperClass: this.wrapperClass,
    });
  }

  public openPicker(initialSearch: string): void {
    if (this.showMoreConfig?.customPicker) {
      this.showMorePickerId = undefined;

      this.showMoreConfig.customPicker.open({
        items: this.data,
        initialSearch,
        initialValue: this.value,
      });
    } else {
      const initialValue = this.value;

      this.#openNativePicker = this.#createNativePickerInstance(initialSearch);

      this.showMorePickerId = this.#openNativePicker.componentInstance.id;

      this.#openNativePicker.componentInstance.addClick.subscribe(() => {
        this.addButtonClicked();
      });

      this.#openNativePicker.closed.subscribe((closeArgs) => {
        this.#openNativePicker = undefined;
        this.showMorePickerId = undefined;

        if (closeArgs.reason === 'save') {
          let selectedItems: any[] = [];

          if (this.searchAsync.observers.length > 0) {
            selectedItems = closeArgs.data.map((item: any) => item.itemData);
          } else {
            this.data.forEach((item: any, dataIndex: number) => {
              if (
                closeArgs.data.some((savedItem: any) => {
                  return savedItem.index === dataIndex;
                })
              ) {
                selectedItems.push(item);
              }
            });
          }

          this.writeValue(selectedItems);
        } else {
          this.writeValue(initialValue);
        }

        this.#focusInput();
        this.#changeDetector.markForCheck();
      });

      this.#changeDetector.markForCheck();
    }
  }

  public onSearchAsync(args: SkyAutocompleteSearchAsyncArgs): void {
    this.searchAsync.emit(args);
  }

  #addToSelected(item: any): void {
    let selectedItems: any[];

    if (this.selectMode === 'single') {
      selectedItems = [item];
    } else {
      selectedItems = this.value;

      const idProperty = this.idProperty || '';

      // If items have a unique identifier, don't allow the same item to be added twice.
      if (
        !this.idProperty ||
        !this.value.some(
          (existingItem) => existingItem[idProperty] === item[idProperty]
        )
      ) {
        selectedItems.push(item);
      }

      this.clearSearchText();
    }

    this.writeValue(selectedItems);
  }

  #addEventListeners(): void {
    this.#idle = new Subject();
    this.#focusInputOnHostClick();
  }

  #removeEventListeners(): void {
    this.#idle.next();
    this.#idle.complete();
  }

  #focusInputOnHostClick(): void {
    let hostElement = !this.inputBoxHostSvc
      ? this.#elementRef.nativeElement
      : this.lookupWrapperRef?.nativeElement;
    const documentObj = this.#windowRef.nativeWindow.document;

    // Handles focusing the input when the host is clicked.
    // The input should NOT be focused if other elements (tokens, etc.)
    // are currently focused or being tabbed through.

    observableFromEvent<MouseEvent>(documentObj, 'mousedown')
      .pipe(takeUntil(this.#idle))
      .subscribe((event) => {
        hostElement = !this.inputBoxHostSvc
          ? this.#elementRef.nativeElement
          : this.lookupWrapperRef?.nativeElement;
        this.isInputFocused = hostElement.contains(event.target);

        this.#changeDetector.markForCheck();
      });

    observableFromEvent<KeyboardEvent>(documentObj, 'focusin')
      .pipe(takeUntil(this.#idle))
      .subscribe((event) => {
        hostElement = !this.inputBoxHostSvc
          ? this.#elementRef.nativeElement
          : this.lookupWrapperRef?.nativeElement;
        this.isInputFocused = hostElement.contains(event.target);

        this.#changeDetector.markForCheck();
      });

    observableFromEvent(hostElement, 'mouseup')
      .pipe(takeUntil(this.#idle))
      .subscribe(() => {
        const classList = documentObj.activeElement.classList;
        if (!classList || !classList.contains('sky-token')) {
          this.#focusInput();
        }
      });
  }

  #focusInput(): void {
    if (this.lookupWrapperRef) {
      this.#adapter.focusInput(this.lookupWrapperRef);
    }
  }

  #onAddButtonComplete(args: SkyLookupAddCallbackArgs) {
    if (args.data) {
      this.data = args.data;
    }

    if (this.data.indexOf(args.item) >= 0) {
      if (this.#openNativePicker) {
        (
          this.#openNativePicker
            .componentInstance as SkyLookupShowMoreModalComponent
        ).onItemSelect(true, { value: args.item, selected: false });
      } else {
        let newValue = this.value;
        if (this.selectMode === 'multiple') {
          newValue = this.value.concat(args.item);
        } else {
          newValue = [args.item];
        }
        this.writeValue(newValue);
      }
    }
  }

  #parseTokens(data: any[]): SkyToken[] {
    return data.map((item: any) => {
      return {
        value: item,
      };
    });
  }

  #sendAutocompleteMessage(type: SkyAutocompleteMessageType): void {
    this.autocompleteController.next({ type });
  }

  #sendTokensMessage(type: SkyTokensMessageType): void {
    this.tokensController.next({ type });
  }

  #updateForSelectMode(): void {
    if (this.autocompleteInputDirective) {
      if (this.selectMode === 'single') {
        this.autocompleteInputDirective.value = this.value && this.value[0];
      } else {
        this.clearSearchText();
      }
    }
  }
}


text:
<template name="CompetitionsSubscribe">

  {{#contentFor "headerButtonLeft"}}
    {{>ionNavBackButton class="button-positive"}}
  {{/contentFor}}

  {{#contentFor "headerButtonRight"}}
    <button class="button button-clear" data-ion-popover="_filterCompetitions"> Subscribe
      {{#if isAndroid}}
        {{> ionIcon icon='android-more-vertical'}}
      {{else}}
        {{> ionIcon icon='more'}}
      {{/if}}
    </button>
  {{/contentFor}}

  {{#contentFor "headerTitle"}}

Competition {{name}}

  {{/contentFor}}

  {{#ionView}}
    {{#ionContent}}

      {{#ionList}}
        {{#ionItem iconRight=false}}
{{name}}
{{/ionItem}}
        {{#ionItem iconRight=false}}
          Open inschrijvingsformulier
        {{/ionItem}}
      {{/ionList}}

    {{/ionContent}}
  {{/ionView}}
</template>


text:
package com.google.javascript.jscomp.regex;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;

import com.google.common.truth.ThrowableSubject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class RegExpTreeTest {

  private String parseRegExpAndPrintPattern(String regex, String flags) {
    RegExpTree tree = RegExpTree.parseRegExp(regex, flags);
    StringBuilder sb = new StringBuilder();
    tree.appendSourceCode(sb);
    return sb.toString();
  }

  private RuntimeException exceptionFrom(String regex, String flags) {
    try {
      String printed = parseRegExpAndPrintPattern(regex, flags);
      assertWithMessage("Expected exception, but none was thrown. Instead got back: " + printed)
          .fail();
      throw new AssertionError(); // unreachable
    } catch (RuntimeException thrownException) {
      return thrownException;
    }
  }

  private void assertRegexCompilesTo(String regex, String flags, String expected) {
    assertThat(parseRegExpAndPrintPattern(regex, flags)).isEqualTo(expected);
  }

  private ThrowableSubject assertRegexThrowsExceptionThat(String regex, String flags) {
    return assertThat(exceptionFrom(regex, flags));
  }

  private void assertRegexCompilesToSame(String regex, String flags) {
    assertRegexCompilesTo(regex, flags, regex);
  }

  @Test
  public void testValidEs2018LookbehindAssertions() {
    assertRegexCompilesToSame("(?<=asdf)", "");
    assertRegexCompilesToSame("(?<!asdf)", "");
    assertRegexCompilesToSame("(?<=(?<!asdf))", "");
    assertRegexCompilesToSame("(?<=(?<!asdf))", "");
  }

  @Test
  public void testInvalidEs2018LookbehindAssertions() {
    assertRegexThrowsExceptionThat("(?<asdf)", "")
        .hasMessageThat()
        .isEqualTo("Invalid capture group name: <asdf)");
  }

  @Test
  public void testValidEs2018UnicodePropertyEscapes() {
    assertRegexCompilesToSame("\\p{Script=Greek}", "u");
    assertRegexCompilesToSame("\\P{Script=Greek}", "u");
    assertRegexCompilesToSame("\\p{Letter}", "u");
    assertRegexCompilesToSame("\\P{Letter}", "u");
    assertRegexCompilesTo("\\p", "", "p"); // Without 'u' flag, '\p' is just 'p'
    assertRegexCompilesTo("\\P", "", "P");
  }

  @Test
  public void testInvalidEs2018UnicodePropertyEscapes() {
    assertRegexThrowsExceptionThat("\\p{", "u")
        .hasMessageThat()
        .isEqualTo("Malformed Unicode Property Escape: expected '=' or '}' after \\p{");

    assertRegexThrowsExceptionThat("\\P{", "u")
        .hasMessageThat()
        .isEqualTo("Malformed Unicode Property Escape: expected '=' or '}' after \\P{");

    assertRegexThrowsExceptionThat("\\p{=Greek}", "u")
        .hasMessageThat()
        .isEqualTo("if '=' is present in a unicode property escape, the name cannot be empty");

    assertRegexThrowsExceptionThat("\\P{=Greek}", "u")
        .hasMessageThat()
        .isEqualTo("if '=' is present in a unicode property escape, the name cannot be empty");

    assertRegexThrowsExceptionThat("\\p{}", "u")
        .hasMessageThat()
        .isEqualTo("unicode property escape value cannot be empty");

    assertRegexThrowsExceptionThat("\\P{}", "u")
        .hasMessageThat()
        .isEqualTo("unicode property escape value cannot be empty");
  }

  @Test
  public void testValidEs2018RegexNamedCaptureGroups() {
    assertRegexCompilesToSame("(?<name>)", "");
    assertRegexCompilesToSame("(?<h$h1h_>)", "u");
    assertRegexCompilesToSame("(?<$var_name>blah)", "");
    assertRegexCompilesToSame("(?<_var_name>>>>)", "");
  }

  @Test
  public void testInvalidEs2018RegexNamedCaptureGroups() {
    assertRegexThrowsExceptionThat("(?<name)", "")
        .hasMessageThat()
        .isEqualTo("Invalid capture group name: <name)");
    assertRegexThrowsExceptionThat("(?<1b>)", "")
        .hasMessageThat()
        .isEqualTo("Invalid capture group name: <1b>)");
    assertRegexThrowsExceptionThat("(?<>)", "")
        .hasMessageThat()
        .isEqualTo("Invalid capture group name: <>)");
    assertRegexThrowsExceptionThat("(?<.name>)", "")
        .hasMessageThat()
        .isEqualTo("Invalid capture group name: <.name>)");
  }

  @Test
  public void testNumCapturingGroups() {
    assertRegexCompilesToSame("(h(i))\\2", "");
    // TODO(b/116048051): reference to non-existent capture group should be an error.
    assertRegexCompilesTo("(h(i))\\3", "", "(h(i))\\x03");

    assertRegexCompilesToSame("(?<foo>.*(?<bar>))", "");
  }

  @Test
  public void testValidEs2018CaptureNameBackreferencing() {
    assertRegexCompilesToSame("(?<name>)\\k<name>", "");
    // Note that (?: ) only used for printing purposes to
    // indicate the nesting structure of Concatenation nodes.
    // It is not actually what the compiler prints out as source code.
    assertRegexCompilesTo(
        "(?<foo>(?<bar>))\\k<foo>\\k<bar>", "", "(?:(?<foo>(?<bar>))\\k<foo>)\\k<bar>");
    assertRegexCompilesTo(
        "(?<foo>(?<bar>)\\k<bar>)\\k<foo>", "", "(?<foo>(?<bar>)\\k<bar>)\\k<foo>");

    // The below examples where the backreference comes before the definition of named groups is
    // allowed syntactically, although it is not able to reference the original group semantically
    assertRegexCompilesToSame("\\k<foo>(?<foo>)", "");
    assertRegexCompilesToSame("\\k<foo>(?<foo>\\k<bar>(?<bar>))", "");

    // Backreferencing the name in the group it is defined is also allowed
    assertRegexCompilesToSame("(?<foo>\\k<foo>)", "");
  }

  @Test
  public void testInvalidEs2018CaptureNameBackreferencing() {
    assertRegexThrowsExceptionThat("(?<foo>)\\k<bar>", "")
        .hasMessageThat()
        .isEqualTo("Invalid named capture referenced: \\k<bar>");
    assertRegexThrowsExceptionThat("(?<foo>)\\k<foo", "")
        .hasMessageThat()
        .isEqualTo("Malformed named capture group: <foo");
    assertRegexThrowsExceptionThat("\\k<1b>(?<foo>)", "")
        .hasMessageThat()
        .isEqualTo("Invalid capture group name: <1b>(?<foo>)");

    // Even though enclosed in (?<>), 'foo' not a capture name definition
    assertRegexThrowsExceptionThat("[(?<foo>)](?<bar>)\\k<foo>", "")
        .hasMessageThat()
        .isEqualTo("Invalid named capture referenced: \\k<foo>");
  }

  @Test
  public void testBackreferencingTreatedAsStringIfNoGroup() {
    // Backreferencing without named group definitions is just treated as normal string
    assertRegexCompilesTo("\\k<foo>", "", "k<foo>");

    // Note that the (?: ) that is wrapped around "k<" at expected output is only used for printing
    // purposes to indicate the nesting structure of Concatenation nodes.
    // It is not actually what the compiler prints out as source code.
    assertRegexCompilesTo("\\k<.", "", "(?:k<).");

    // Even though enclosed in (?<>), 'foo' not a capture name definition
    // (?: ) in expected output serves same purpose as above test
    assertRegexCompilesTo("[(?<foo>)]\\k<foo>", "", "(?:[()<>?fo]k)<foo>");
  }
}


text:
package com.microsoft.azure.management.gallery;

import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.annotation.JsonSubTypes;

/**
 * The action that is performed when the alert rule becomes active, and when an
 * alert condition is resolved.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "odata.type")
@JsonTypeName("RuleAction")
@JsonSubTypes({
    @JsonSubTypes.Type(name = "Microsoft.Azure.Management.Insights.Models.RuleEmailAction", value = RuleEmailAction.class),
    @JsonSubTypes.Type(name = "Microsoft.Azure.Management.Insights.Models.RuleWebhookAction", value = RuleWebhookAction.class)
})
public class RuleAction {
}


text:
  Lapeyrère est
       un village
       localisé dans le département de Haute-Garonne en Midi-Pyrénées. On dénombrait 81 habitants en 2008.

À proximité de Lapeyrère sont localisées les communes de
Sainte-Suzanne localisée à 5 km, 231 habitants,
Sieuras à 3 km, 78 habitants,
Latrape localisée à 4 km, 337 habitants,
Massabrac située à 5 km, 74 habitants,
Castagnac localisée à 3 km, 272 habitants,
Canens à 1 km, 62 habitants,
 entre autres. De plus, Lapeyrère est située à seulement 26 km de Fort-de-France.

Si vous envisagez de demenager à Lapeyrère, vous pourrez aisément trouver une maison à vendre.

Le nombre d'habitations, à Lapeyrère, se décomposait en 2011 en zero appartements et 31 maisons soit
 un marché relativement équilibré.


text:
layout: example.11ty.cjs
title: <my-element> ⌲ Examples ⌲ Name Property
tags: example
name: Name Property
description: Setting the name property
---

<my-element name="Earth"></my-element>

HTML

```html
<my-element name="Earth"></my-element>
```


text:
package v2

import (
	"code.cloudfoundry.org/cli/command"
	"code.cloudfoundry.org/cli/command/flag"
	"code.cloudfoundry.org/cli/command/translatableerror"
)

type BindRunningSecurityGroupCommand struct {
	RequiredArgs    flag.SecurityGroup `positional-args:"yes"`
	usage           interface{}        `usage:"CF_NAME bind-running-security-group SECURITY_GROUP\n\nTIP: Changes will not apply to existing running applications until they are restarted."`
	relatedCommands interface{}        `related_commands:"apps, bind-security-group, bind-staging-security-group, restart, running-security-groups, security-groups"`
}

func (BindRunningSecurityGroupCommand) Setup(config command.Config, ui command.UI) error {
	return nil
}

func (BindRunningSecurityGroupCommand) Execute(args []string) error {
	return translatableerror.UnrefactoredCommandError{}
}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Br. mycol. Soc. 88(4): 465 (1987)

#### Original name
Collybia alpina Vilgalys & O.K. Mill., 1987

### Remarks
null


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace infrastructure.user.entities
{
    public class UserUsernameDb
    {
        public int id { get; set; }
        public int user_id { get; set; }
        public string token { get; set; }
        public DateTime date_created { get; set; }

        public UserDb User { get; set; }
    }
}


text:
package org.eclipse.php.internal.core.ast.nodes;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.eclipse.php.internal.core.PHPVersion;
import org.eclipse.php.internal.core.ast.match.ASTMatcher;
import org.eclipse.php.internal.core.ast.visitor.Visitor;

/**
 * Represents a 'use' statement
 *
e.g.
use MyNamespace;
 *use MyNamespace as MyAlias;
 *use MyProject\Sub\Level as MyAlias;
 *use \MyProject\Sub\Level as MyAlias;
 *use \MyProject\Sub\Level as MyAlias, MyNamespace as OtherAlias, MyOtherNamespace;
 */
public class UseStatement extends Statement {

	private final ASTNode.NodeList<UseStatementPart> parts = new ASTNode.NodeList<UseStatementPart>(PARTS_PROPERTY);

	/**
	 * The structural property of this node type.
	 */
	public static final ChildListPropertyDescriptor PARTS_PROPERTY =
		new ChildListPropertyDescriptor(UseStatement.class, "parts", UseStatementPart.class, NO_CYCLE_RISK); //$NON-NLS-1$

	/**
	 * A list of property descriptors (element type:
	 * {@link StructuralPropertyDescriptor}),
	 * or null if uninitialized.
	 */
	private static final List<StructuralPropertyDescriptor> PROPERTY_DESCRIPTORS;
	static {
		List<StructuralPropertyDescriptor> properyList = new ArrayList<StructuralPropertyDescriptor>(1);
		properyList.add(PARTS_PROPERTY);
		PROPERTY_DESCRIPTORS = Collections.unmodifiableList(properyList);
	}

	public UseStatement(AST ast) {
		super(ast);
	}

	public UseStatement(int start, int end, AST ast, List parts) {
		super(start, end, ast);

		if (parts == null || parts.size() == 0) {
			throw new IllegalArgumentException();
		}

		Iterator<UseStatementPart> it = parts.iterator();
		while (it.hasNext()) {
			this.parts.add(it.next());
		}
	}

	public UseStatement(int start, int end, AST ast, UseStatementPart[] parts) {
		super(start, end, ast);

		if (parts == null || parts.length == 0) {
			throw new IllegalArgumentException();
		}

		for (UseStatementPart part : parts) {
			this.parts.add(part);
		}
	}

	public void accept0(Visitor visitor) {
		final boolean visit = visitor.visit(this);
		if (visit) {
			childrenAccept(visitor);
		}
		visitor.endVisit(this);
	}

	public void childrenAccept(Visitor visitor) {
		for (ASTNode node : this.parts) {
			node.accept(visitor);
		}
	}

	public void traverseTopDown(Visitor visitor) {
		accept(visitor);
		for (ASTNode node : this.parts) {
			node.traverseTopDown(visitor);
		}
	}

	public void traverseBottomUp(Visitor visitor) {
		for (ASTNode node : this.parts) {
			node.traverseBottomUp(visitor);
		}
		accept(visitor);
	}

	public void toString(StringBuffer buffer, String tab) {
		buffer.append(tab).append("<UseStatement"); //$NON-NLS-1$
		appendInterval(buffer);
		buffer.append(">\n"); //$NON-NLS-1$
		for (UseStatementPart part : this.parts) {
			part.toString(buffer, TAB + tab);
			buffer.append("\n"); //$NON-NLS-1$
		}
		buffer.append(tab).append("</UseStatement>"); //$NON-NLS-1$
	}

	public int getType() {
		return ASTNode.USE_STATEMENT;
	}

	/**
	 * The list of single parts of this 'use' statement
	 *
	 * @return List of this statement parts
	 */
	public List<UseStatementPart> parts() {
		return this.parts;
	}

	final List internalGetChildListProperty(ChildListPropertyDescriptor property) {
		if (property == PARTS_PROPERTY) {
			return parts();
		}
		// allow default implementation to flag the error
		return super.internalGetChildListProperty(property);
	}

	/*
	 * Method declared on ASTNode.
	 */
	public boolean subtreeMatch(ASTMatcher matcher, Object other) {
		// dispatch to correct overloaded match method
		return matcher.match(this, other);
	}

	@Override
	ASTNode clone0(AST target) {
		final List parts = ASTNode.copySubtrees(target, parts());
		final UseStatement result = new UseStatement(getStart(), getEnd(), target, parts);
		return result;
	}

	@Override
	List<StructuralPropertyDescriptor> internalStructuralPropertiesForType(PHPVersion apiLevel) {
		return PROPERTY_DESCRIPTORS;
	}
}


text:
__title__ = 'pycicl'
__version__ = '0.1'
__author__ = 'Francis Ferrell'
__author_email__ = 'codepanda@gmail.com'
__copyright__ = 'Copyright 2016 {}'.format( __author__ )
__description__ = "runs your python unit tests so you don't have to."
__url__ = 'http://github.com/codepanda/pycicl'


text:
package com.sleepycat.je.rep.impl.node;

import static com.sleepycat.je.rep.impl.node.ReplicaStatDefinition.N_LAG_CONSISTENCY_WAITS;
import static com.sleepycat.je.rep.impl.node.ReplicaStatDefinition.N_LAG_CONSISTENCY_WAIT_MS;
import static com.sleepycat.je.rep.impl.node.ReplicaStatDefinition.N_VLSN_CONSISTENCY_WAITS;
import static com.sleepycat.je.rep.impl.node.ReplicaStatDefinition.N_VLSN_CONSISTENCY_WAIT_MS;

import java.io.IOException;
import java.net.ConnectException;
import java.net.Socket;
import java.nio.channels.ClosedByInterruptException;
import java.nio.channels.SocketChannel;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.sleepycat.je.CheckpointConfig;
import com.sleepycat.je.DatabaseException;
import com.sleepycat.je.EnvironmentFailureException;
import com.sleepycat.je.ReplicaConsistencyPolicy;
import com.sleepycat.je.StatsConfig;
import com.sleepycat.je.dbi.DatabaseId;
import com.sleepycat.je.dbi.DatabaseImpl;
import com.sleepycat.je.dbi.DbConfigManager;
import com.sleepycat.je.dbi.EnvironmentImpl;
import com.sleepycat.je.rep.CommitPointConsistencyPolicy;
import com.sleepycat.je.rep.GroupShutdownException;
import com.sleepycat.je.rep.InsufficientLogException;
import com.sleepycat.je.rep.MasterStateException;
import com.sleepycat.je.rep.ReplicaConsistencyException;
import com.sleepycat.je.rep.RestartRequiredException;
import com.sleepycat.je.rep.TimeConsistencyPolicy;
import com.sleepycat.je.rep.impl.RepImpl;
import com.sleepycat.je.rep.impl.RepParams;
import com.sleepycat.je.rep.stream.Protocol;
import com.sleepycat.je.rep.stream.ReplicaFeederHandshake;
import com.sleepycat.je.rep.stream.ReplicaFeederSyncup;
import com.sleepycat.je.rep.stream.MasterStatus.MasterSyncException;
import com.sleepycat.je.rep.stream.Protocol.Heartbeat;
import com.sleepycat.je.rep.stream.Protocol.ShutdownRequest;
import com.sleepycat.je.rep.stream.ReplicaFeederSyncup.TestHook;
import com.sleepycat.je.rep.utilint.BinaryProtocolStatDefinition;
import com.sleepycat.je.rep.utilint.NamedChannel;
import com.sleepycat.je.rep.utilint.RepUtils;
import com.sleepycat.je.rep.utilint.ServiceDispatcher;
import com.sleepycat.je.rep.utilint.BinaryProtocol.Message;
import com.sleepycat.je.rep.utilint.BinaryProtocol.MessageOp;
import com.sleepycat.je.rep.utilint.BinaryProtocol.ProtocolException;
import com.sleepycat.je.rep.utilint.RepUtils.ExceptionAwareCountDownLatch;
import com.sleepycat.je.rep.utilint.ServiceDispatcher.Response;
import com.sleepycat.je.rep.utilint.ServiceDispatcher.ServiceConnectFailedException;
import com.sleepycat.je.utilint.LoggerUtils;
import com.sleepycat.je.utilint.LongStat;
import com.sleepycat.je.utilint.StatGroup;
import com.sleepycat.je.utilint.VLSN;

/**
 * The Replica class is the locus of the replay operations and replica
 * transaction consistency tracking and management operations at a replica
 * node.
 *
 * A single instance of this class is created when the replication node is
 * created and exists for the lifetime of the replication node, although it is
 * only really used when the node is operating as a Replica.
 *
 * Note that the Replica (like the FeederManager) does not have its own
 * independent thread of control; it runs in the RepNode's thread.
 */
public class Replica {

    /* The Node to which the Replica belongs. */
    private final RepNode repNode;
    private final RepImpl repImpl;

    /* The replay component of the Replica */
    private final Replay replay;

    /* The exception that provoked the replica exit. */
    private Exception shutdownException = null;

    /* It's non null when the loop is active. */
    private NamedChannel replicaFeederChannel = null;

    /* The consistency component. */
    private final ConsistencyTracker consistencyTracker;

    /*
     * A test delay introduced in the replica loop to simulate a loaded
     * replica. The replica waits this amount of time before processing each
     * message.
     */
    private int testDelayMs = 0;

    /* For testing only - mimic a network partition. */
    private boolean dontProcessStream = false;

    /* Number of times to retry on a network connection failure. */
    private static final int NETWORK_RETRIES = 2 ;

    /*
     * Service unavailable retries. These are typically the result of service
     * request being made before the node is ready to provide them. For
     * example, the feeder service is only available after a node has
     * transitioned to becoming the master.
     */
    private static final int SERVICE_UNAVAILABLE_RETRIES = 10;

    /*
     * The number of ms to wait between above retries, allowing time for the
     * master to assume its role, and start listening on its port.
     */
    private static final int CONNECT_RETRY_SLEEP_MS = 1000;

    /* The protocol instance if one is currently in use by the Replica. */
    private Protocol protocol = null;

    /*
     * Protocol statistics aggregated across all past protocol instantiations.
     * It does not include the statistics for the current Protocol object in
     * use. A node can potentially go through the Replica state multiple time
     * during it's lifetime. This instance aggregates replica statistics
     * across all transitions into and out of the Replica state.
     */
    private final StatGroup aggProtoStats;

    private final Logger logger;

    /* For testing only. */
    private TestHook<Object> replicaFeederSyncupHook;

    /*
     * A cache of DatabaseImpls for the Replay to speed up DbTree.getId().
     * Cleared/invalidated by a heartbeat or if je.rep.dbIdCacheOpCount
     * operations have gone by, or if any replay operations on Name LNs are
     * executed.
     */
    private final Map<DatabaseId, DatabaseImpl> dbCache =
        new HashMap<DatabaseId, DatabaseImpl>();

    Replica(RepNode repNode, Replay replay) {
        this.repNode = repNode;
        this.repImpl = repNode.getRepImpl();
        consistencyTracker = new ConsistencyTracker();
        this.replay = replay;
        logger = LoggerUtils.getLogger(getClass());
        aggProtoStats =
            new StatGroup(BinaryProtocolStatDefinition.GROUP_NAME,
                          BinaryProtocolStatDefinition.GROUP_DESC);
        testDelayMs =
            repNode.getConfigManager().getInt(RepParams.TEST_REPLICA_DELAY);
    }

    /**
     * Shutdown the Replica, free any threads that may have been waiting for
     * the replica to reach some degree of consistency. This method is only
     * invoked as part of the repnode shutdown.
     *
     * If the shutdown is being executed from a different thread, it attempts
     * to interrupt the thread by first shutting down the channel it may be
     * waiting on for input from the feeder. The replica thread should notice
     * the channel shutdown and/or the shutdown state of the rep node itself.
     * The caller will use harsher methods, like an interrupt, if the rep node
     * thread (Replica or Feeder) is still active.
     */
    public void shutdown() {
        if (!repNode.isShutdown()) {
            throw EnvironmentFailureException.unexpectedState
                ("Rep node must have initiated the shutdown.");
        }
        consistencyTracker.shutdown();
        if (Thread.currentThread() == repNode) {
            return;
        }

        /*
         * Perform the actions to provoke a "soft" shutdown.
         *
         * Since the replica shares the RepNode thread, it will take care of
         * the actual thread shutdown itself.
         */

        /*
         * Shutdown the channel as an attempt to interrupt just the socket
         * read/write operation.
         */
        RepUtils.shutdownChannel(replicaFeederChannel);

        /*
         * Clear the latch in case the replica loop is waiting for the outcome
         * of an election.
         */
        repNode.getVLSNFreezeLatch().clearLatch();
    }

    /**
     * For unit testing only!
     */
    public void setTestDelayMs(int testDelayMs) {
        this.testDelayMs = testDelayMs;
    }

    /**
     * For unit testing only!
     */
    public void setDontProcessStream() {
        dontProcessStream = true;
    }

    public Replay replay() {
        return replay;
    }

    Map<DatabaseId, DatabaseImpl> getDbCache() {
        return dbCache;
    }

    public ConsistencyTracker getConsistencyTracker() {
        return consistencyTracker;
    }

    SocketChannel getReplicaFeederChannel() {
        return replicaFeederChannel.getChannel();
    }

    Protocol getProtocol() {
        return protocol;
    }

    /**
     * Returns the last commit VLSN at the master, as known at the replica.
     *
     * @return the commit VLSN
     */
    long getMasterCommitVLSN() {
        return consistencyTracker.getMasterCommitVLSN();
    }

    /**
     * The core control loop when the node is serving as a Replica. Note that
     * if a Replica is also serving the role of a feeder, it will run
     * additional feeder loops in separate threads. The loop exits when it
     * encounters one of the following possible conditions:
     *
     * 1) The connection to the master can no longer be maintained, due to
     * connectivity issues, or because the master has explicitly shutdown its
     * connections due to an election.
     *
     * 2) The node becomes aware of a change in master, that is, assertSync()
     * fails.
     *
     * 3) The loop is interrupted, which is interpreted as a request to
     * shutdown the replication node as a whole.
     *
     * 4) It fails to establish its node information in the master as it
     * attempts to join the replication group for the first time.
     *
     * Normal exit from this run loop results in the rep node retrying an
     * election and continuing in its new role as determined by the outcome of
     * the election. A thrown exception, on the other hand, results in the rep
     * node as a whole terminating its operation and no longer participating in
     * the replication group, that is, it enters the DETACHED state.
     *
     * Note that the in/out streams are handles synchronously on the replica,
     * while they are handled asynchronously by the Feeder.
     *
     * @throws InterruptedException
     * @throws RestoreFailedException
     * @throws DatabaseException if the environment cannot be closed/for a
     * re-init
     * @throws GroupShutdownException
     */
    void runReplicaLoop()
        throws InterruptedException,
               DatabaseException,
               GroupShutdownException {

        Class<? extends RetryException> retryExceptionClass = null;
        int retryCount = 0;
        try {

            while (true) {
                try {
                    runReplicaLoopInternal();
                    /* Normal exit */
                    break;
                } catch (RetryException e) {
                    if (!repNode.getMasterStatus().inSync()) {
                        LoggerUtils.fine(logger, repImpl,
                                         "Retry terminated, out of sync.");
                        break;
                    }
                    if ((e.getClass() == retryExceptionClass) ||
                        (e.retries == 0)) {
                        if (++retryCount >= e.retries) {
                            /* Exit replica retry elections */
                            LoggerUtils.info
                                (logger, repImpl,
                                 "Failed to recover from exception: " +
                                 e.getMessage() + ", despite " + e.retries +
                                 " retries.\n" +
                                 LoggerUtils.getStackTrace(e));
                            break;
                        }
                    } else {
                        retryCount = 0;
                        retryExceptionClass = e.getClass();
                    }
                    LoggerUtils.info(logger, repImpl, "Retry #: " +
                                     retryCount + "/" + e.retries +
                                     " Will retry replica loop after " +
                                     e.retrySleepMs + "ms. ");
                    Thread.sleep(e.retrySleepMs);
                    if (!repNode.getMasterStatus().inSync()) {
                        break;
                    }
                }
            }
        } finally {
            repNode.resetReadyLatch(shutdownException);
        }
        /* Exit use elections to try a different master. */
    }

    private void runReplicaLoopInternal()
        throws RestartRequiredException,
               InterruptedException,
               RetryException,
               InsufficientLogException {

        shutdownException = null;
        LoggerUtils.info(logger, repImpl,
                         "Replica loop started with master: " +
                         repNode.getMasterStatus().getNodeMasterNameId());
        if (testDelayMs > 0) {
            LoggerUtils.info(logger, repImpl,
                             "Test delay of: " + testDelayMs + "ms." +
                             " after each message sent");
        }
        try {
            initReplicaLoop();
            doRunReplicaLoopInternalWork();
        } catch (RestartRequiredException rre) {
            shutdownException = rre;
            throw rre;
        } catch (ClosedByInterruptException closedByInterruptException) {
            if (repNode.isShutdown()) {
                LoggerUtils.info(logger, repImpl,
                                 "Replica loop interrupted for shutdown.");
                return;
            }
            LoggerUtils.warning(logger, repImpl,
                                "Replica loop unexpected interrupt.");
            throw new InterruptedException
                (closedByInterruptException.getMessage());
        } catch (IOException e) {

            /*
             * Master may have changed with the master shutting down its
             * connection as a result. Normal course of events, log it and
             * return to the outer node level loop.
             */
            LoggerUtils.info(logger, repImpl,
                             "Replica IO exception: " + e.getMessage() +
                             "\n" + LoggerUtils.getStackTrace(e));
        } catch (RetryException e) {
            /* Propagate it outwards. Node does not need to shutdown. */
            throw e;
        } catch (GroupShutdownException e) {
            shutdownException = e;
            throw e;
        } catch (RuntimeException e) {
            shutdownException = e;
            LoggerUtils.severe(logger, repImpl,
                               "Replica unexpected exception " + e +
                                " " + LoggerUtils.getStackTrace(e));
            throw e;
        } catch (MasterSyncException e) {
            /* expected change in masters from an election. */
            LoggerUtils.info(logger, repImpl, e.getMessage());
        } catch (Exception e) {
            shutdownException = e;
            LoggerUtils.severe(logger, repImpl,
                               "Replica unexpected exception " + e +
                               " " + LoggerUtils.getStackTrace(e));
            throw EnvironmentFailureException.unexpectedException(e);
        } finally {
            loopExitCleanup();
        }
    }

    protected void doRunReplicaLoopInternalWork()
        throws Exception {

        final int dbTreeCacheClearingOpCount =
            repNode.getDbTreeCacheClearingOpCount();
        long opCount = 0;
        while (true) {
            Message message = protocol.read(replicaFeederChannel);

            if (repNode.isShutdown() || (message == null)) {
                return;
            }
            repNode.getMasterStatus().assertSync();
            MessageOp messageOps = message.getOp();
            if (messageOps == Protocol.SHUTDOWN_REQUEST) {
                throw processShutdown((ShutdownRequest) message);
            }
            if (messageOps == Protocol.HEARTBEAT) {
                processHeartbeat(replicaFeederChannel,
                                 (Protocol.Heartbeat) message);
                /* For HA, periodically flush the Replay's dbid cache. */
                clearDbTreeCache();
            } else {
                /* For testing only! */
                if (dontProcessStream) {
                    LoggerUtils.info(logger, repImpl, "Not processing " +
                                     message);
                    continue;
                }

                replay.replayEntry(replicaFeederChannel,
                                   protocol,
                                   (Protocol.Entry) message);

                /*
                 * Note: the consistency tracking is more obscure than it needs
                 * to be, because the commit VLSN is set in
                 * Replay.replayEntry() and is then used below. An alternative
                 * would be to promote the following conditional to a level
                 * above, so commit operations get their own replay method
                 * which does the commit tracking.
                 */

                if (messageOps == Protocol.COMMIT) {
                    consistencyTracker.trackCommit();
                }
                consistencyTracker.trackVLSN();
            }

            if (testDelayMs > 0) {
                Thread.sleep(testDelayMs);
            }

            if (opCount++ % dbTreeCacheClearingOpCount == 0) {
                clearDbTreeCache();
            }
        }
    }

    /**
     * Process the shutdown message from the master and return the
     * GroupShutdownException that must be thrown to exit the Replica loop.
     *
     * @return the GroupShutdownException
     */
    private GroupShutdownException processShutdown(ShutdownRequest shutdown)
        throws IOException {

        CheckpointConfig config = new CheckpointConfig();
        config.setForce(true);
        repNode.getRepImpl().invokeCheckpoint(config, false, "Group Shutdown");
        protocol.write(protocol.new ShutdownResponse(), replicaFeederChannel);

        return new GroupShutdownException(logger,
                                          repNode,
                                          shutdown.getShutdownTimeMs());
    }

    /**
     * Initialize for replica loop entry, which involves completing the
     * following steps successfully:
     *
     * 1) The replica feeder handshake.
     * 2) The replica feeder syncup.
     * 3) Processing the first heartbeat request from the feeder.
     */
    private void initReplicaLoop()
        throws IOException,
               ConnectRetryException,
               DatabaseException,
               ProtocolException,
               InterruptedException {

        createReplicaFeederChannel();
        ReplicaFeederHandshake handshake =
            new ReplicaFeederHandshake(repNode, replicaFeederChannel);
        protocol = handshake.execute();
        ReplicaFeederSyncup syncup =
            new ReplicaFeederSyncup(repNode, replay, replicaFeederChannel,
                                    protocol);
        syncup.execute(repNode.getCBVLSNTracker());
        VLSN matchedTxnVLSN = syncup.getMatchedVLSN();
        long matchedTxnCommitTime = syncup.getMatchedVLSNTime();
        consistencyTracker.reinit(matchedTxnVLSN.getSequence(),
                                  matchedTxnCommitTime);
        Protocol.Heartbeat heartbeat =
            protocol.read(replicaFeederChannel.getChannel(),
                          Protocol.Heartbeat.class);
        processHeartbeat(replicaFeederChannel, heartbeat);
        long replicaDelta = consistencyTracker.getMasterCommitVLSN() -
            consistencyTracker.lastReplayedVLSN.getSequence();
        LoggerUtils.info(logger, repImpl, String.format
                         ("Replica initialization completed. Replica VLSN: %s "
                          + " Heartbeat master commit VLSN: %,d " +
                          "VLSN delta: %,d",
                          consistencyTracker.lastReplayedVLSN,
                          consistencyTracker.getMasterCommitVLSN(),
                          replicaDelta));

        /*
         * The replica is ready for business, indicate that the node is
         * ready by counting down the latch and releasing any waiters.
         */
        repNode.getReadyLatch().countDown();
    }

    /**
     * Process a heartbeat message. It sends back a response and updates
     * the consistency tracker with the information in the heartbeat.
     *
     * @param channel
     * @param heartbeat
     * @throws IOException
     */
    private void processHeartbeat(NamedChannel namedChannel,
                                  Heartbeat heartbeat)
        throws IOException {

        protocol.write(protocol.new HeartbeatResponse
                       (repNode.getCBVLSNTracker().getBroadcastCBVLSN()),
                       namedChannel);
        consistencyTracker.trackHeartbeat(heartbeat);
    }

    /**
     * Performs the cleanup actions upon exit from the internal replica loop.
     *
     * @param replicaFeederChannel
     */
    private void loopExitCleanup() {

        if (shutdownException != null) {
            if (shutdownException instanceof RetryException) {
                LoggerUtils.info(logger, repImpl,
                                 "Retrying connection to feeder. Message: " +
                                 shutdownException.getMessage());
            } else if (shutdownException instanceof GroupShutdownException) {
                LoggerUtils.info(logger, repImpl,
                                 "Exiting inner Replica loop." +
                                 " Master requested shutdown.");
            } else {
                LoggerUtils.warning
                    (logger, repImpl,
                     "Exiting inner Replica loop with exception " +
                     shutdownException + "\n" +
                     LoggerUtils.getStackTrace(shutdownException));
            }
        } else {
            LoggerUtils.info(logger, repImpl, "Exiting inner Replica loop." );
        }

        clearDbTreeCache();
        RepUtils.shutdownChannel(replicaFeederChannel);

        if (consistencyTracker != null) {
            consistencyTracker.logStats();
        }

        /* Sum up statistics for the loop. */
        if (protocol != null) {
            aggProtoStats.addAll(protocol.getStats(StatsConfig.DEFAULT));
        }
        protocol = null;
    }

    /*
     * Clear the DatabaseId -> DatabaseImpl cache used to speed up DbTree
     * lookup operations.  Called during heartbeats and operations on the
     * DbTree (truncate, remove, rename).
     */
    void clearDbTreeCache() {
        repNode.getRepImpl().getDbTree().releaseDbs(dbCache);
        dbCache.clear();
    }

    /**
     * Invoked when this node transitions to the master state. Aborts all
     * inflight replay transactions outstanding from a previous state as a
     * Replica, because they were initiated by a different master and will
     * never complete. Also, release any Replica transactions that were waiting
     * on consistency policy requirements.
     */
    void masterTransitionCleanup()
        throws DatabaseException {

        replay.abortOldTxns();
        consistencyTracker.forceTripLatches
            (new MasterStateException(repNode.getRepImpl().
                                      getStateChangeEvent()));
    }

    /**
     * Returns a channel used by the Replica to connect to the Feeder. The
     * socket is configured with a read timeout that's multiple of the
     * heartbeat interval to help detect, or initiate a change in master.
     *
     * @throws IOException
     * @throws ConnectRetryException
     */
    private void createReplicaFeederChannel()
        throws IOException, ConnectRetryException {

        SocketChannel channel = SocketChannel.open();
        replicaFeederChannel = new NamedChannel(channel);
        Socket socket = channel.socket();
        channel.configureBlocking(true);

        /*
         * Push responses out rapidly, they are small (heart beat or commit
         * response) and need timely delivery to the master.
         */
        socket.setTcpNoDelay(true);

        final DbConfigManager configManager = repNode.getConfigManager();
        long readTimeout = ((long)configManager.
            getInt(RepParams.FEEDER_HEARTBEAT_TIMEOUT)) *
            repNode.getHeartbeatInterval();
        socket.setSoTimeout(readTimeout > Integer.MAX_VALUE ?
                            0 : ((int) readTimeout));

        try {
            final int openTimeout = configManager.
                getDuration(RepParams.REPSTREAM_OPEN_TIMEOUT);
            socket.connect(repNode.getMasterStatus().getNodeMaster(),
                           openTimeout);
            ServiceDispatcher.doServiceHandshake
                (channel, FeederManager.FEEDER_SERVICE);
        } catch (ConnectException e) {

            /*
             * A network problem, or the node went down between the time we
             * learned it was the master and we tried to connect.
             */
            throw new ConnectRetryException(e.getMessage(),
                                            NETWORK_RETRIES,
                                            CONNECT_RETRY_SLEEP_MS);
        } catch (ServiceConnectFailedException e) {

            /*
             * The feeder may not have established the Feeder Service
             * as yet. For example, the transition to the master may not have
             * been completed. Wait longer.
             */
           if (e.getResponse() == Response.UNKNOWN_SERVICE) {
               throw new ConnectRetryException(e.getMessage(),
                                               SERVICE_UNAVAILABLE_RETRIES,
                                               CONNECT_RETRY_SLEEP_MS);
           }
           throw EnvironmentFailureException.unexpectedException(e);
        }
   }

    /**
     * Returns the replay statistics associated with the Replica.
     *
     * @return the statistics.
     */
    public StatGroup getReplayStats(StatsConfig config) {
        return replay.getStats(config);
    }

    /* Get the protocl statistics for this replica. */
    public StatGroup getProtocolStats(StatsConfig config) {
        StatGroup protoStats = aggProtoStats.cloneGroup(config.getClear());

        /* Guard against concurrent modification. */
        Protocol prot = this.protocol;
        if (prot != null) {
            /* These statistics are not ye a part of the agg statistics. */
            protoStats.addAll(prot.getStats(config));
        }

        return protoStats;
    }

    /* Get the consistency tracker stats for this replica. */
    public StatGroup getTrackerStats(StatsConfig config) {
        return consistencyTracker.getStats(config);
    }

    /* Reset the stats associated with this Replica. */
    public void resetStats() {
        replay.resetStats();
        aggProtoStats.clear();
        if (protocol != null) {
            protocol.resetStats();
        }
        consistencyTracker.resetStats();
    }

    /**
     * Tracks the consistency of this replica wrt the Master. It provides the
     * mechanisms that will cause a beginTransaction() or a joinGroup() to wait
     * until the specified consistency policy is satisfied.
     */
    public class ConsistencyTracker {
        private final long NULL_VLSN_SEQUENCE = VLSN.NULL_VLSN.getSequence();

        /*
         * Initialized by the Feeder handshake and updated by commit replays.
         * All access to lastReplayedXXXX must be synchronized on the
         * ConsistencyTracker itself.
         */
        private long lastReplayedTxnVLSN = NULL_VLSN_SEQUENCE;
        private VLSN lastReplayedVLSN = VLSN.NULL_VLSN;
        private long txnMasterCommitTime = 0l;

        /* Updated by heartbeats */
        private long masterCommitVLSN;
        private long masterNow = 0l;

        private final StatGroup stats =
            new StatGroup(ReplicaStatDefinition.GROUP_NAME,
                          ReplicaStatDefinition.GROUP_DESC);

        private final LongStat nLagConsistencyWaits =
            new LongStat(stats, N_LAG_CONSISTENCY_WAITS);

        private final LongStat nLagConsistencyWaitMs =
            new LongStat(stats, N_LAG_CONSISTENCY_WAIT_MS);

        private final LongStat nVLSNConsistencyWaits =
            new LongStat(stats, N_VLSN_CONSISTENCY_WAITS);

        private final LongStat nVLSNConsistencyWaitMs =
            new LongStat(stats, N_VLSN_CONSISTENCY_WAIT_MS);

        private final OrderedLatches vlsnLatches =
            new OrderedLatches(repNode.getRepImpl()) {
                /*
                 * Note that this assumes that NULL_VLSN is -1, and that
                 * the vlsns ascend.
                 */
                @Override
                    boolean tripPredicate(long keyVLSN, long tripVLSN) {
                    return keyVLSN <= tripVLSN;
                }
            };

        private final OrderedLatches lagLatches =
            new OrderedLatches(repNode.getRepImpl()) {
                @Override
                boolean tripPredicate(long keyLag, long currentLag) {
                    return currentLag <= keyLag;
                }
            };

        /**
         * Invoked each time after a replica syncup so that the Replica
         * can re-establish it's consistency vis a vis the master and what
         * part of the replication stream it considers as having been replayed.
         *
         * @param matchedTxnVLSN the replica state corresponds to this txn
         * @param matchedCommitTime the time at which this txn was committed
         * on the master
         */
        void reinit(long matchedTxnVLSN, long matchedCommitTime) {
            this.lastReplayedVLSN = new VLSN(matchedTxnVLSN);
            this.lastReplayedTxnVLSN = matchedTxnVLSN;
            this.txnMasterCommitTime = matchedCommitTime;
        }

        public long getMasterCommitVLSN() {
            return masterCommitVLSN;
        }

        void close() {
            logStats();
        }

        void logStats() {
            if (logger.isLoggable(Level.INFO)) {
                LoggerUtils.info
                    (logger, repImpl,
                    "Replica stats - Lag waits: " + nLagConsistencyWaits.get() +
                     " Lag wait time: " + nLagConsistencyWaitMs.get()
                     + "ms. " +
                     " VLSN waits: " + nVLSNConsistencyWaits.get() +
                     " Lag wait time: " +  nVLSNConsistencyWaitMs.get() +
                     "ms.");
            }
        }

        /**
         * Calculates the time lag in ms at the Replica.
         */
        private long currentLag() {
            if (masterNow == 0l) {

                /*
                 * Have not seen a heartbeat, can't determine the time lag in
                 * its absence. It's the first message sent by the feeder after
                 * completion of the handshake.
                 */
                return Integer.MAX_VALUE;
            }

            long lag;
            if (lastReplayedTxnVLSN < masterCommitVLSN) {
                lag = System.currentTimeMillis() - txnMasterCommitTime;
            } else if (lastReplayedTxnVLSN == masterCommitVLSN) {

                /*
                 * The lag is determined by the transactions (if any) that are
                 * further downstream, assume the worst.
                 */
                lag = System.currentTimeMillis() - masterNow;
            } else {
               /* commit leapfrogged the heartbeat */
               lag = System.currentTimeMillis() - masterNow;
            }
            return lag;
        }

        /**
         * Frees all the threads that are waiting on latches.
         *
         * @param exception the exception to be thrown to explain the reason
         * behind the latches being forced.
         */
        synchronized void forceTripLatches(DatabaseException exception) {
            assert (exception != null);
            vlsnLatches.trip(Long.MAX_VALUE, exception);
            lagLatches.trip(0, exception);
        }

        synchronized void trackCommit() {
            Replay.TxnInfo lastReplayedTxn = replay.getLastReplayedTxn();
            lastReplayedTxnVLSN = lastReplayedTxn.getTxnVLSN().getSequence();
            txnMasterCommitTime = lastReplayedTxn.getMasterCommitTime();

            if ((lastReplayedTxnVLSN > masterCommitVLSN) &&
                (txnMasterCommitTime >= masterNow)) {
                masterCommitVLSN = lastReplayedTxnVLSN;
                masterNow = txnMasterCommitTime;
            }

            /*
             * Advances both replica VLSN and commit time, trip qualifying
             * latches in both sets.
             */
            vlsnLatches.trip(lastReplayedTxnVLSN, null);
            lagLatches.trip(currentLag(), null);
        }

        synchronized void trackVLSN() {
            lastReplayedVLSN = replay.getLastReplayedVLSN();
            vlsnLatches.trip(lastReplayedVLSN.getSequence(), null);
        }

        synchronized void trackHeartbeat(Protocol.Heartbeat heartbeat) {
            masterCommitVLSN = heartbeat.getCurrentCommitVLSN();
            masterNow = heartbeat.getMasterNow();
            /* Trip just the time lag latches. */
            lagLatches.trip(currentLag(), null);
        }

        public void lagAwait(TimeConsistencyPolicy consistencyPolicy)
            throws InterruptedException,
                   ReplicaConsistencyException,
                   DatabaseException {

            long currentLag = currentLag();
            long lag =
                consistencyPolicy.getPermissibleLag(TimeUnit.MILLISECONDS);
            if (currentLag <= lag) {
                return;
            }
            long waitStart = System.currentTimeMillis();
            ExceptionAwareCountDownLatch waitLagLatch =
                lagLatches.getOrCreate(lag);
            await(waitLagLatch, consistencyPolicy);
            nLagConsistencyWaits.increment();
            nLagConsistencyWaitMs.add(System.currentTimeMillis() - waitStart);
        }

        /**
         * Wait until the commit log record identified by VLSN has gone by.
         */
        public void commitVLSNAwait(long vlsn,
                                    ReplicaConsistencyPolicy consistencyPolicy)
            throws InterruptedException,
                   ReplicaConsistencyException,
                   DatabaseException {

            VLSNAwait(vlsn, consistencyPolicy);
        }

        /**
         * Wait until the log record identified by VLSN has gone by.
         */
        public void anyVLSNAwait(long vlsn,
                                 ReplicaConsistencyPolicy consistencyPolicy)
            throws InterruptedException,
                   ReplicaConsistencyException,
                   DatabaseException {

            VLSNAwait(vlsn, consistencyPolicy);
        }

        /**
         * The implementation of the VLSN wait.
         */
        private void VLSNAwait(long vlsn,
                               ReplicaConsistencyPolicy consistencyPolicy)
            throws InterruptedException,
                   ReplicaConsistencyException,
                   DatabaseException {

            long waitStart = System.currentTimeMillis();

            ExceptionAwareCountDownLatch waitVLSNLatch = null;

            synchronized(this) {
                final long compareVLSN =
                   (consistencyPolicy instanceof CommitPointConsistencyPolicy)?
                    lastReplayedTxnVLSN :
                    lastReplayedVLSN.getSequence();
                if (vlsn <= compareVLSN) {
                    return;
                }
                waitVLSNLatch = vlsnLatches.getOrCreate(vlsn);
            }
            await(waitVLSNLatch, consistencyPolicy);
            /* Stats after the await, so the counts and times are related. */
            nVLSNConsistencyWaits.increment();
            nVLSNConsistencyWaitMs.add(System.currentTimeMillis() - waitStart);
        }

        /**
         * Wait on the given countdown latch and generate the appropriate
         * exception upon timeout.
         *
         * @throws InterruptedException
         */
        private void await(ExceptionAwareCountDownLatch consistencyLatch,
                           ReplicaConsistencyPolicy consistencyPolicy)
            throws ReplicaConsistencyException,
                   DatabaseException,
                   InterruptedException {

            if (!consistencyLatch.awaitOrException
                 (consistencyPolicy.getTimeout(TimeUnit.MILLISECONDS),
                  TimeUnit.MILLISECONDS)) {
                /* Timed out. */
                final boolean detached =
                    repNode.getRepImpl().getState().isDetached();
                throw new ReplicaConsistencyException(consistencyPolicy,
                                                      detached);
            }
        }

        private StatGroup getStats(StatsConfig config) {
            if (config.getClear()) {
                stats.clear();
            }
            StatGroup ret = stats.cloneGroup(false);

            return ret;
        }

        private void resetStats() {
            stats.clear();
        }

        /**
         * Shutdown the consistency tracker. This is typically done as part
         * of the shutdown of a replication node. It counts down all open
         * latches, so the threads waiting on them can make progress. It's
         * the responsibility of the waiting threads to check whether the
         * latch countdown was due to a shutdown, and take appropriate action.
         */
        public void shutdown() {
            forceTripLatches(EnvironmentFailureException.unexpectedException
                             ("Node: " + repNode.getNameIdPair() +
                              " was shut down.",
                              repNode.getSavedShutdownException()));
        }
    }

    /**
     * Manages a set of ordered latches. They are ordered by the key value.
     */
    private abstract class OrderedLatches {

        final EnvironmentImpl envImpl;

        final SortedMap<Long, ExceptionAwareCountDownLatch> latchMap =
            new TreeMap<Long, ExceptionAwareCountDownLatch>();

        abstract boolean tripPredicate(long key, long tripValue);

        OrderedLatches(EnvironmentImpl envImpl) {
            this.envImpl = envImpl;
        }

        synchronized ExceptionAwareCountDownLatch getOrCreate(Long key) {
            ExceptionAwareCountDownLatch latch = latchMap.get(key);
            if (latch == null) {
                latch = new ExceptionAwareCountDownLatch(envImpl, 1);
                latchMap.put(key, latch);
            }
            return latch;
        }

        /**
         * Trip all latches until the first latch that will not trip.
         *
         * @param tripValue
         * @param exception the exception to be thrown by the waiter upon
         * exit from the await. It can be null if no exception need be thrown.
         */
        synchronized void trip(long tripValue,
                               DatabaseException exception) {
            while (latchMap.size() > 0) {
                Long key = latchMap.firstKey();
                if (!tripPredicate(key, tripValue)) {
                    /* It will fail on the rest as well. */
                    return;
                }
                /* Set the waiters free. */
                ExceptionAwareCountDownLatch latch = latchMap.remove(key);
                latch.releaseAwait(exception);
            }
        }
    }

    /**
     * Thrown to indicate that the Replica must retry connecting to the same
     * master, after some period of time.
     */
    @SuppressWarnings("serial")
    static class RetryException extends Exception {
        final int retries;
        final int retrySleepMs;

        RetryException(String message,
                       int retries,
                       int retrySleepMs) {
            super(message);
            this.retries = retries;
            this.retrySleepMs = retrySleepMs;
        }

        @Override
        public String getMessage() {
          return "Failed after retries: " + retries +
                 " with retry interval: " + retrySleepMs + "ms.";
        }
    }

    @SuppressWarnings("serial")
    static class ConnectRetryException extends RetryException {

        ConnectRetryException(String message,
                              int retries,
                              int retrySleepMs) {
            super(message, retries, retrySleepMs);
        }
    }

    /**
     * Set a test hook which is executed when the ReplicaFeederSyncup
     * finishes. This differs from the static method
     * ReplicaFeederSyncup.setGlobalSyncupHook in that it sets the hook for a
     * specific node, whereas the other method is static and sets it globally.
     *
     * This method is required when a test is trying to set the hook for only
     * one node, and the node already exists. The other method is useful when a
     * test is trying to set the hook before a node exists.
     */
    public void setReplicaFeederSyncupHook(TestHook<Object> syncupHook) {
        replicaFeederSyncupHook = syncupHook;
    }

    public TestHook<Object> getReplicaFeederSyncupHook() {
        return replicaFeederSyncupHook;
    }
}