async () => {
    const countBefore = await mockDatabase.table('item').count();
    const diaryFile: NativeFile = {
      id: 4,
      path: '::directory/subdirectory/subsubdirectory/',
      format: FileFormatType.JPG,
      file_name: 'dry_skin.jpg',
      size: 808
    };
    const creation_date = moment().format('YYYY-MM-DD');
    const document_name = 'Dry Skin on Arm';
    const specificValues = {
      page: PageType.Diary
    };
    const created_item = await item.createItemAsFile(
      diaryFile,
      creation_date,
      1,
      document_name,
      specificValues
    );

    expect(created_item.directory_id).toBe(1);
    expect(created_item.page).toBe(specificValues.page);
    expect(created_item.title).toBe(document_name);
    expect(created_item.file).toBe(diaryFile);
    expect(created_item.file_id).toBe(diaryFile.id);
    expect(created_item.chosen_date).toBe(creation_date);
    const countAfter = await mockDatabase.table('item').count();
    expect(countAfter).toBe(countBefore + 1);
  }


async () => {
    const countBefore = await mockDatabase.table('item').count();
    const medicalDoc: NativeFile = {
      id: 5,
      path: '::directory/subdirectory/subsubdirectory2/',
      format: FileFormatType.PDF,
      file_name: 'lab_test.jpg',
      size: 8869
    };
    const creation_date = moment().format('YYYY-MM-DD');
    const document_name = 'Blood Test';
    const specificValues = {
      page: PageType.Portfolio
    };
    const created_item = await item.createItemAsFile(
      medicalDoc,
      creation_date,
      1,
      document_name,
      specificValues
    );

    expect(created_item.directory_id).toBe(1);
    expect(created_item.page).toBe(specificValues.page);
    expect(created_item.title).toBe(document_name);
    expect(created_item.file).toBe(medicalDoc);
    expect(created_item.file_id).toBe(medicalDoc.id);
    expect(created_item.chosen_date).toBe(creation_date);
    const countAfter = await mockDatabase.table('item').count();
    expect(countAfter).toBe(countBefore + 1);
  }


async () => {
    const countBefore = await mockDatabase.table('item').count();
    const new_item: Item = {
      title: 'Blood Pressure Measurement',
      description: 'Morning measurement',
      chosen_date: moment().format('YYYY-MM-DD'),
      page: PageType.Diary,
      directory_id: 1
    };
    const created_item = await item.addItemToDB(new_item);

    expect(created_item.directory_id).toBe(1);
    expect(created_item.page).toBe(new_item.page);
    expect(created_item.title).toBe(new_item.title);
    expect(created_item.file).toBe(undefined);
    expect(created_item.file_id).toBe(undefined);
    expect(created_item.chosen_date).toBe(new_item.chosen_date);
    const countAfter = await mockDatabase.table('item').count();
    expect(countAfter).toBe(countBefore + 1);
  }


class DATABASE extends Dexie {
  constructor() {
    super('item_service_test');

    this.version(1).stores(SCHEMA);
    const date = new Date();
    const items = [
      {
        title: 'Health Problems1',
        directory_id: 1,
        description: 'lab test1',
        file_id: 1,
        page: PageType.Portfolio,
        chosen_date: '2018-01-01',
        document_type: PortfolioType.DIAGNOSIS,
        user_defined_file_name: 'User defined name',
        created: date
      },
      {
        title: 'Health Problems2',
        directory_id: 1,
        description: 'lab test1',
        file_id: 2,
        page: PageType.Portfolio,
        chosen_date: '2018-01-01',
        document_type: PortfolioType.DIAGNOSIS,
        user_defined_file_name: 'User defined name',
        created: date
      },
      {
        title: 'Health Problems3',
        description: 'lab test1',
        directory_id: 1,
        file_id: 3,
        page: PageType.Portfolio,
        chosen_date: '2018-01-01',
        document_type: PortfolioType.DIAGNOSIS,
        user_defined_file_name: 'User defined name',
        created: date
      }
    ];
    this.on('populate', () => {
      this.table('profile').add({
        directory: 1
      });
      this.table('directory').bulkAdd([{ id: 1 }, { id: 2 }]);
      this.table('item').bulkAdd(items);
      this.table('file').bulkAdd([
        {
          id: 1,
          path: '::directory/subdirectory/subsubdirectory/',
          file_name: 'filename1.jpg',
          size: 4576543,
          format: FileFormatType.JPG,
          type: 'jpg'
        },
        {
          id: 2,
          path: '::directory/subdirectory/subsubdirectory/',
          file_name: 'filename2.jpg',
          size: 4576543,
          format: FileFormatType.JPG,
          type: 'jpg'
        },
        {
          id: 3,
          path: '::directory/subdirectory/subsubdirectory/',
          file_name: 'filename3.pdf',
          size: 4576543,
          format: FileFormatType.PDF,
          type: 'jpg'
        }
      ]);
    });
  }
}


(a: Vec2Like, b: Vec2Like, attribs?: any): any[] =>
    ["line", {
        x1: ff(a[0]),
        y1: ff(a[1]),
        x2: ff(b[0]),
        y2: ff(b[1]),
        ...attribs
    }]


(y: number, attribs?: any) =>
    line([-1e6, y], [1e6, y], attribs)


(x: number, attribs?: any) =>
    line([x, -1e6], [x, 1e6], attribs)


(path: string) => {
      return store[path]
    }


() => {
  const app = new Hono()

  app.use('/foo', mustache())
  app.get('/foo', (c) => {
    return c.render(
      'index',
      { title: 'Hono!' },
      {
        header: 'header',
        footer: 'footer',
      }
    )
  })

  app.use('/bar', mustache({ root: 'view' }))
  app.get('/bar', (c) => {
    return c.render('index')
  })

  it('Mustache template rendering', async () => {
    const res = await app.request('http://localhost/foo')
    expect(res.status).toBe(200)
    expect(await res.text()).toBe('Title: Hono!')
  })

  it('Mustache template rendering with root', async () => {
    const res = await app.request('http://localhost/bar')
    expect(res.status).toBe(200)
    expect(await res.text()).toBe('
With Root
')
  })
}


(c) => {
    return c.render(
      'index',
      { title: 'Hono!' },
      {
        header: 'header',
        footer: 'footer',
      }
    )
  }


(c) => {
    return c.render('index')
  }


async () => {
    const res = await app.request('http://localhost/foo')
    expect(res.status).toBe(200)
    expect(await res.text()).toBe('Title: Hono!')
  }


async () => {
    const res = await app.request('http://localhost/bar')
    expect(res.status).toBe(200)
    expect(await res.text()).toBe('
With Root
')
  }


/**
 *

 */
export class KinesisVideoMediaClient extends __Client<
  __HttpHandlerOptions,
  ServiceInputTypes,
  ServiceOutputTypes,
  KinesisVideoMediaClientResolvedConfig
> {
  /**
   * The resolved configuration of KinesisVideoMediaClient class. This is resolved and normalized from the {@link KinesisVideoMediaClientConfig | constructor configuration interface}.
   */
  readonly config: KinesisVideoMediaClientResolvedConfig;

  constructor(configuration: KinesisVideoMediaClientConfig) {
    const _config_0 = __getRuntimeConfig(configuration);
    const _config_1 = resolveRegionConfig(_config_0);
    const _config_2 = resolveEndpointsConfig(_config_1);
    const _config_3 = resolveRetryConfig(_config_2);
    const _config_4 = resolveHostHeaderConfig(_config_3);
    const _config_5 = resolveAwsAuthConfig(_config_4);
    const _config_6 = resolveUserAgentConfig(_config_5);
    super(_config_6);
    this.config = _config_6;
    this.middlewareStack.use(getRetryPlugin(this.config));
    this.middlewareStack.use(getContentLengthPlugin(this.config));
    this.middlewareStack.use(getHostHeaderPlugin(this.config));
    this.middlewareStack.use(getLoggerPlugin(this.config));
    this.middlewareStack.use(getRecursionDetectionPlugin(this.config));
    this.middlewareStack.use(getAwsAuthPlugin(this.config));
    this.middlewareStack.use(getUserAgentPlugin(this.config));
  }

  /**
   * Destroy underlying resources, like sockets. It's usually not necessary to do this.
   * However in Node.js, it's best to explicitly shut down the client's agent when it is no longer needed.
   * Otherwise, sockets might stay open for quite a long time before the server terminates them.
   */
  destroy(): void {
    super.destroy();
  }
}


export interface ClientDefaults extends Partial<__SmithyResolvedConfiguration<__HttpHandlerOptions>> {
  /**
   * The HTTP handler to use. Fetch in browser and Https in Nodejs.
   */
  requestHandler?: __HttpHandler;

  /**
   * A constructor for a class implementing the {@link __Hash} interface
   * that computes the SHA-256 HMAC or checksum of a string or binary buffer.
   * @internal
   */
  sha256?: __HashConstructor;

  /**
   * The function that will be used to convert strings into HTTP endpoints.
   * @internal
   */
  urlParser?: __UrlParser;

  /**
   * A function that can calculate the length of a request body.
   * @internal
   */
  bodyLengthChecker?: __BodyLengthCalculator;

  /**
   * A function that converts a stream into an array of bytes.
   * @internal
   */
  streamCollector?: __StreamCollector;

  /**
   * The function that will be used to convert a base64-encoded string to a byte array.
   * @internal
   */
  base64Decoder?: __Decoder;

  /**
   * The function that will be used to convert binary data to a base64-encoded string.
   * @internal
   */
  base64Encoder?: __Encoder;

  /**
   * The function that will be used to convert a UTF8-encoded string to a byte array.
   * @internal
   */
  utf8Decoder?: __Decoder;

  /**
   * The function that will be used to convert binary data to a UTF-8 encoded string.
   * @internal
   */
  utf8Encoder?: __Encoder;

  /**
   * The runtime environment.
   * @internal
   */
  runtime?: string;

  /**
   * Disable dyanamically changing the endpoint of the client based on the hostPrefix
   * trait of an operation.
   */
  disableHostPrefix?: boolean;

  /**
   * Value for how many times a request will be made at most in case of retry.
   */
  maxAttempts?: number | __Provider<number>;

  /**
   * Specifies which retry algorithm to use.
   */
  retryMode?: string | __Provider<string>;

  /**
   * Optional logger for logging debug/info/warn/error.
   */
  logger?: __Logger;

  /**
   * Enables IPv6/IPv4 dualstack endpoint.
   */
  useDualstackEndpoint?: boolean | __Provider<boolean>;

  /**
   * Enables FIPS compatible endpoints.
   */
  useFipsEndpoint?: boolean | __Provider<boolean>;

  /**
   * Unique service identifier.
   * @internal
   */
  serviceId?: string;

  /**
   * The AWS region to which this client will send requests
   */
  region?: string | __Provider<string>;

  /**
   * Default credentials provider; Not available in browser runtime.
   * @internal
   */
  credentialDefaultProvider?: (input: any) => __Provider<__Credentials>;

  /**
   * Fetch related hostname, signing name or signing region with given region.
   * @internal
   */
  regionInfoProvider?: RegionInfoProvider;

  /**
   * The provider populating default tracking information to be sent with `user-agent`, `x-amz-user-agent` header
   * @internal
   */
  defaultUserAgentProvider?: Provider<__UserAgent>;

  /**
   * The {@link DefaultsMode} that will be used to determine how certain default configuration options are resolved in the SDK.
   */
  defaultsMode?: DefaultsMode | Provider<DefaultsMode>;
}


/**
 * The configuration interface of KinesisVideoMediaClient class constructor that set the region, credentials and other options.
 */
export interface KinesisVideoMediaClientConfig extends KinesisVideoMediaClientConfigType {}


/**
 * The resolved configuration interface of KinesisVideoMediaClient class. This is resolved and normalized from the {@link KinesisVideoMediaClientConfig | constructor configuration interface}.
 */
export interface KinesisVideoMediaClientResolvedConfig extends KinesisVideoMediaClientResolvedConfigType {}


export type ServiceInputTypes = GetMediaCommandInput;


export type ServiceOutputTypes = GetMediaCommandOutput;


type KinesisVideoMediaClientConfigType = Partial<__SmithyConfiguration<__HttpHandlerOptions>> &
  ClientDefaults &
  RegionInputConfig &
  EndpointsInputConfig &
  RetryInputConfig &
  HostHeaderInputConfig &
  AwsAuthInputConfig &
  UserAgentInputConfig;


type KinesisVideoMediaClientResolvedConfigType = __SmithyResolvedConfiguration<__HttpHandlerOptions> &
  Required<ClientDefaults> &
  RegionResolvedConfig &
  EndpointsResolvedConfig &
  RetryResolvedConfig &
  HostHeaderResolvedConfig &
  AwsAuthResolvedConfig &
  UserAgentResolvedConfig;


export class ProjectSyncWindowsResponse {
    'windows'?: Array<V1alpha1SyncWindow>;

    static discriminator: string | undefined = undefined;

    static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [
        {
            "name": "windows",
            "baseName": "windows",
            "type": "Array<V1alpha1SyncWindow>"
        }    ];

    static getAttributeTypeMap() {
        return ProjectSyncWindowsResponse.attributeTypeMap;
    }
}


static getAttributeTypeMap() {
        return ProjectSyncWindowsResponse.attributeTypeMap;
    }


documents => {
        const previousResults = this.applyQuery(query, documents);

        if (
          (hasLimitToFirst(query) || hasLimitToLast(query)) &&
          this.needsRefill(
            query.limitType,
            previousResults,
            remoteKeys,
            lastLimboFreeSnapshotVersion
          )
        ) {
          return this.executeFullCollectionScan(transaction, query);
        }

        if (getLogLevel() <= LogLevel.DEBUG) {
          logDebug(
            'QueryEngine',
            'Re-using previous result from %s to execute query: %s',
            lastLimboFreeSnapshotVersion.toString(),
            stringifyQuery(query)
          );
        }

        // Retrieve all results for documents that were updated since the last
        // limbo-document free remote snapshot.
        return this.localDocumentsView!.getDocumentsMatchingQuery(
          transaction,
          query,
          lastLimboFreeSnapshotVersion
        ).next(updatedResults => {
          // We merge `previousResults` into `updateResults`, since
          // `updateResults` is already a DocumentMap. If a document is
          // contained in both lists, then its contents are the same.
          previousResults.forEach(doc => {
            updatedResults = updatedResults.insert(doc.key, doc);
          });
          return updatedResults;
        });
      }


updatedResults => {
          // We merge `previousResults` into `updateResults`, since
          // `updateResults` is already a DocumentMap. If a document is
          // contained in both lists, then its contents are the same.
          previousResults.forEach(doc => {
            updatedResults = updatedResults.insert(doc.key, doc);
          });
          return updatedResults;
        }


doc => {
            updatedResults = updatedResults.insert(doc.key, doc);
          }


(_, maybeDoc) => {
      if (maybeDoc instanceof Document && queryMatches(query, maybeDoc)) {
        queryResults = queryResults.add(maybeDoc);
      }
    }


/**
 * A query engine that takes advantage of the target document mapping in the
 * QueryCache. Query execution is optimized by only reading the documents that
 * previously matched a query plus any documents that were edited after the
 * query was last listened to.
 *
 * There are some cases when this optimization is not guaranteed to produce
 * the same results as full collection scans. In these cases, query
 * processing falls back to full scans. These cases are:
 *
 * - Limit queries where a document that matched the query previously no longer
 *   matches the query.
 *
 * - Limit queries where a document edit may cause the document to sort below
 *   another document that is in the local cache.
 *
 * - Queries that have never been CURRENT or free of limbo documents.
 */
export class QueryEngine {
  private localDocumentsView: LocalDocumentsView | undefined;

  /** Sets the document view to query against. */
  setLocalDocumentsView(localDocuments: LocalDocumentsView): void {
    this.localDocumentsView = localDocuments;
  }

  /** Returns all local documents matching the specified query. */
  getDocumentsMatchingQuery(
    transaction: PersistenceTransaction,
    query: Query,
    lastLimboFreeSnapshotVersion: SnapshotVersion,
    remoteKeys: DocumentKeySet
  ): PersistencePromise<DocumentMap> {
    debugAssert(
      this.localDocumentsView !== undefined,
      'setLocalDocumentsView() not called'
    );

    // Queries that match all documents don't benefit from using
    // key-based lookups. It is more efficient to scan all documents in a
    // collection, rather than to perform individual lookups.
    if (matchesAllDocuments(query)) {
      return this.executeFullCollectionScan(transaction, query);
    }

    // Queries that have never seen a snapshot without limbo free documents
    // should also be run as a full collection scan.
    if (lastLimboFreeSnapshotVersion.isEqual(SnapshotVersion.min())) {
      return this.executeFullCollectionScan(transaction, query);
    }

    return this.localDocumentsView!.getDocuments(transaction, remoteKeys).next(
      documents => {
        const previousResults = this.applyQuery(query, documents);

        if (
          (hasLimitToFirst(query) || hasLimitToLast(query)) &&
          this.needsRefill(
            query.limitType,
            previousResults,
            remoteKeys,
            lastLimboFreeSnapshotVersion
          )
        ) {
          return this.executeFullCollectionScan(transaction, query);
        }

        if (getLogLevel() <= LogLevel.DEBUG) {
          logDebug(
            'QueryEngine',
            'Re-using previous result from %s to execute query: %s',
            lastLimboFreeSnapshotVersion.toString(),
            stringifyQuery(query)
          );
        }

        // Retrieve all results for documents that were updated since the last
        // limbo-document free remote snapshot.
        return this.localDocumentsView!.getDocumentsMatchingQuery(
          transaction,
          query,
          lastLimboFreeSnapshotVersion
        ).next(updatedResults => {
          // We merge `previousResults` into `updateResults`, since
          // `updateResults` is already a DocumentMap. If a document is
          // contained in both lists, then its contents are the same.
          previousResults.forEach(doc => {
            updatedResults = updatedResults.insert(doc.key, doc);
          });
          return updatedResults;
        });
      }
    );
  }

  /** Applies the query filter and sorting to the provided documents.  */
  private applyQuery(
    query: Query,
    documents: MaybeDocumentMap
  ): SortedSet<Document> {
    // Sort the documents and re-apply the query filter since previously
    // matching documents do not necessarily still match the query.
    let queryResults = new SortedSet<Document>(newQueryComparator(query));
    documents.forEach((_, maybeDoc) => {
      if (maybeDoc instanceof Document && queryMatches(query, maybeDoc)) {
        queryResults = queryResults.add(maybeDoc);
      }
    });
    return queryResults;
  }

  /**
   * Determines if a limit query needs to be refilled from cache, making it
   * ineligible for index-free execution.
   *
   * @param sortedPreviousResults - The documents that matched the query when it
   * was last synchronized, sorted by the query's comparator.
   * @param remoteKeys - The document keys that matched the query at the last
   * snapshot.
   * @param limboFreeSnapshotVersion - The version of the snapshot when the
   * query was last synchronized.
   */
  private needsRefill(
    limitType: LimitType,
    sortedPreviousResults: SortedSet<Document>,
    remoteKeys: DocumentKeySet,
    limboFreeSnapshotVersion: SnapshotVersion
  ): boolean {
    // The query needs to be refilled if a previously matching document no
    // longer matches.
    if (remoteKeys.size !== sortedPreviousResults.size) {
      return true;
    }

    // Limit queries are not eligible for index-free query execution if there is
    // a potential that an older document from cache now sorts before a document
    // that was previously part of the limit. This, however, can only happen if
    // the document at the edge of the limit goes out of limit.
    // If a document that is not the limit boundary sorts differently,
    // the boundary of the limit itself did not change and documents from cache
    // will continue to be "rejected" by this boundary. Therefore, we can ignore
    // any modifications that don't affect the last document.
    const docAtLimitEdge =
      limitType === LimitType.First
        ? sortedPreviousResults.last()
        : sortedPreviousResults.first();
    if (!docAtLimitEdge) {
      // We don't need to refill the query if there were already no documents.
      return false;
    }
    return (
      docAtLimitEdge.hasPendingWrites ||
      docAtLimitEdge.version.compareTo(limboFreeSnapshotVersion) > 0
    );
  }

  private executeFullCollectionScan(
    transaction: PersistenceTransaction,
    query: Query
  ): PersistencePromise<DocumentMap> {
    if (getLogLevel() <= LogLevel.DEBUG) {
      logDebug(
        'QueryEngine',
        'Using full collection scan to execute query:',
        stringifyQuery(query)
      );
    }

    return this.localDocumentsView!.getDocumentsMatchingQuery(
      transaction,
      query,
      SnapshotVersion.min()
    );
  }
}


/** Sets the document view to query against. */
setLocalDocumentsView(localDocuments: LocalDocumentsView): void {
    this.localDocumentsView = localDocuments;
  }


/** Returns all local documents matching the specified query. */
getDocumentsMatchingQuery(
    transaction: PersistenceTransaction,
    query: Query,
    lastLimboFreeSnapshotVersion: SnapshotVersion,
    remoteKeys: DocumentKeySet
  ): PersistencePromise<DocumentMap> {
    debugAssert(
      this.localDocumentsView !== undefined,
      'setLocalDocumentsView() not called'
    );

    // Queries that match all documents don't benefit from using
    // key-based lookups. It is more efficient to scan all documents in a
    // collection, rather than to perform individual lookups.
    if (matchesAllDocuments(query)) {
      return this.executeFullCollectionScan(transaction, query);
    }

    // Queries that have never seen a snapshot without limbo free documents
    // should also be run as a full collection scan.
    if (lastLimboFreeSnapshotVersion.isEqual(SnapshotVersion.min())) {
      return this.executeFullCollectionScan(transaction, query);
    }

    return this.localDocumentsView!.getDocuments(transaction, remoteKeys).next(
      documents => {
        const previousResults = this.applyQuery(query, documents);

        if (
          (hasLimitToFirst(query) || hasLimitToLast(query)) &&
          this.needsRefill(
            query.limitType,
            previousResults,
            remoteKeys,
            lastLimboFreeSnapshotVersion
          )
        ) {
          return this.executeFullCollectionScan(transaction, query);
        }

        if (getLogLevel() <= LogLevel.DEBUG) {
          logDebug(
            'QueryEngine',
            'Re-using previous result from %s to execute query: %s',
            lastLimboFreeSnapshotVersion.toString(),
            stringifyQuery(query)
          );
        }

        // Retrieve all results for documents that were updated since the last
        // limbo-document free remote snapshot.
        return this.localDocumentsView!.getDocumentsMatchingQuery(
          transaction,
          query,
          lastLimboFreeSnapshotVersion
        ).next(updatedResults => {
          // We merge `previousResults` into `updateResults`, since
          // `updateResults` is already a DocumentMap. If a document is
          // contained in both lists, then its contents are the same.
          previousResults.forEach(doc => {
            updatedResults = updatedResults.insert(doc.key, doc);
          });
          return updatedResults;
        });
      }
    );
  }


/** Applies the query filter and sorting to the provided documents.  */
private applyQuery(
    query: Query,
    documents: MaybeDocumentMap
  ): SortedSet<Document> {
    // Sort the documents and re-apply the query filter since previously
    // matching documents do not necessarily still match the query.
    let queryResults = new SortedSet<Document>(newQueryComparator(query));
    documents.forEach((_, maybeDoc) => {
      if (maybeDoc instanceof Document && queryMatches(query, maybeDoc)) {
        queryResults = queryResults.add(maybeDoc);
      }
    });
    return queryResults;
  }


/**
   * Determines if a limit query needs to be refilled from cache, making it
   * ineligible for index-free execution.
   *
   * @param sortedPreviousResults - The documents that matched the query when it
   * was last synchronized, sorted by the query's comparator.
   * @param remoteKeys - The document keys that matched the query at the last
   * snapshot.
   * @param limboFreeSnapshotVersion - The version of the snapshot when the
   * query was last synchronized.
   */
private needsRefill(
    limitType: LimitType,
    sortedPreviousResults: SortedSet<Document>,
    remoteKeys: DocumentKeySet,
    limboFreeSnapshotVersion: SnapshotVersion
  ): boolean {
    // The query needs to be refilled if a previously matching document no
    // longer matches.
    if (remoteKeys.size !== sortedPreviousResults.size) {
      return true;
    }

    // Limit queries are not eligible for index-free query execution if there is
    // a potential that an older document from cache now sorts before a document
    // that was previously part of the limit. This, however, can only happen if
    // the document at the edge of the limit goes out of limit.
    // If a document that is not the limit boundary sorts differently,
    // the boundary of the limit itself did not change and documents from cache
    // will continue to be "rejected" by this boundary. Therefore, we can ignore
    // any modifications that don't affect the last document.
    const docAtLimitEdge =
      limitType === LimitType.First
        ? sortedPreviousResults.last()
        : sortedPreviousResults.first();
    if (!docAtLimitEdge) {
      // We don't need to refill the query if there were already no documents.
      return false;
    }
    return (
      docAtLimitEdge.hasPendingWrites ||
      docAtLimitEdge.version.compareTo(limboFreeSnapshotVersion) > 0
    );
  }


private executeFullCollectionScan(
    transaction: PersistenceTransaction,
    query: Query
  ): PersistencePromise<DocumentMap> {
    if (getLogLevel() <= LogLevel.DEBUG) {
      logDebug(
        'QueryEngine',
        'Using full collection scan to execute query:',
        stringifyQuery(query)
      );
    }

    return this.localDocumentsView!.getDocumentsMatchingQuery(
      transaction,
      query,
      SnapshotVersion.min()
    );
  }


@Component({
  selector: 'ngx-one-column-layout',
  styleUrls: ['./one-column.layout.scss'],
  template: `
    <nb-layout windowMode>
      <nb-layout-header fixed>
        <ngx-header></ngx-header>
      </nb-layout-header>

      <nb-sidebar class="menu-sidebar" tag="menu-sidebar" responsive>
        <ng-content select="nb-menu"></ng-content>
      </nb-sidebar>

      <nb-layout-column>
        <ng-content select="router-outlet"></ng-content>
      </nb-layout-column>

    </nb-layout>
  `,
})
export class OneColumnLayoutComponent {}


bidData => {
      return <ActiveBid key={bidData.active_bid.__id} bid={bidData} />
    }


class ActiveBids extends React.Component<RelayProps, null> {
  hasContent() {
    return this.props.me.lot_standings.length > 0
  }

  renderRows() {
    const bids = this.props.me.lot_standings.map(bidData => {
      return <ActiveBid key={bidData.active_bid.__id} bid={bidData} />
    })
    return bids
  }

  render() {
    return this.hasContent()
      ? <Container>
          <LargeHeadline>Active Bids</LargeHeadline>
          {this.renderRows()}
        </Container>
      : null
  }
}


interface RelayProps {
  me: {
    lot_standings: Array<{
      active_bid: {
        __id: string
      } | null
    } | null> | null
  }
}


hasContent() {
    return this.props.me.lot_standings.length > 0
  }


renderRows() {
    const bids = this.props.me.lot_standings.map(bidData => {
      return <ActiveBid key={bidData.active_bid.__id} bid={bidData} />
    })
    return bids
  }


render() {
    return this.hasContent()
      ? <Container>
          <LargeHeadline>Active Bids</LargeHeadline>
          {this.renderRows()}
        </Container>
      : null
  }


@Component({
  selector: 'chat-bubble',
  templateUrl: './chat-bubble.component.html',
  styleUrls: ['./chat-bubble.component.scss'],
})
export class ChatBubbleComponent implements OnInit {
  @Input() msg:MessageChat;
  constructor() {
  }

  ngOnInit() {}

}


async () => {

    const modules: ModuleUUIDPair[] = [
        { Module: CoreModules.Avatar,      UUID: "390cec87-b1db-52d9-8e55-de82530e380d"},
        { Module: CoreModules.Config,      UUID: "ee285ab6-018a-5df2-8060-2504e14112b2"},
        { Module: CoreModules.Profile,     UUID: "37e0a335-4c46-541b-9afc-e6dd6dde1c95"},
        { Module: CoreModules.RHelp,       UUID: "8209817a-753c-54e9-833b-bdff74fd9fa3"}
    ]

    const bot = new Synergy({
        sequelizeURI: process.env.DATABASE_URI as string,
        masterGuildId: process.env.MASTER_GUILD_ID as string,
        moduleGlobalLoading: false,
        clientOptions: {
            intents: [
                Discord.Intents.FLAGS.DIRECT_MESSAGES,
                Discord.Intents.FLAGS.GUILDS,
                Discord.Intents.FLAGS.GUILD_MESSAGES,
                Discord.Intents.FLAGS.GUILD_MEMBERS
            ],
            presence: {
                status: "online",
                activities: [
                    {
                        type: "PLAYING",
                        name: "Synergy Core Unit Testing",
                    }
                ]
            }
        }
    }, modules);
    bot.login(process.env.DISCORD_TOKEN as string);
    let isready = await new Promise<boolean>(resolve => bot.events.once("Initialized", () => resolve(bot.isReady)));
    await bot.stop();
    expect(isready).toBeTruthy();
}


resolve => bot.events.once("Initialized", () => resolve(bot.isReady))


() => resolve(bot.isReady)


@Component({
  template: `

{{question.question}}

  `
})
export class PageOne {
  private question;

  constructor(public params:NavParams) {
    this.question = params.get("question");
  }
}


async function claim() {
			if (isAppReady) {
				try {
					setError(null);
					setTxModalOpen(true);
					const {
						contracts: { FeePool },
					} = synthetixjs!;

					let gasLimit = delegateWallet
						? (await FeePool.estimateGas.claimOnBehalf(delegateWallet.address)).toNumber()
						: (await FeePool.estimateGas.claimFees()).toNumber();

					if (!isL2) {
						gasLimit = normalizeGasLimit(gasLimit);
					}

					const transaction: ethers.ContractTransaction = delegateWallet
						? await FeePool.claimOnBehalf(delegateWallet.address, {
								gasPrice: normalizedGasPrice(gasPrice.toNumber()),
								gasLimit,
						  })
						: await FeePool.claimFees({
								gasPrice: normalizedGasPrice(gasPrice.toNumber()),
								gasLimit,
						  });

					if (transaction) {
						setTxHash(transaction.hash);
						setTransactionState(Transaction.WAITING);
						monitorTransaction({
							txHash: transaction.hash,
							onTxConfirmed: () => {
								setClaimedTradingRewards(tradingRewards.toNumber());
								setClaimedStakingRewards(stakingRewards.toNumber());
								setTransactionState(Transaction.SUCCESS);
								userStakingData.refetch();
							},
						});
						setTxModalOpen(false);
					}
				} catch (e) {
					setTransactionState(Transaction.PRESUBMIT);
					if (isL2) {
						setError(e?.data?.message ?? e.message);
					} else {
						setError(e.message);
					}
				}
			}
		}


() =>
			blockExplorerInstance != null && txHash != null
				? blockExplorerInstance.txLink(txHash)
				: undefined


() => !userStakingData.hasClaimed && totalRewards.gt(0)


async () => {
		if (!isL2) return;
		try {
			const {
				contracts: { FeePool },
			} = synthetixjs!;
			const [feePeriodDuration, recentFeePeriods] = await Promise.all([
				FeePool.feePeriodDuration(),
				FeePool.recentFeePeriods(0),
			]);

			const now = Math.ceil(getCurrentTimestampSeconds());
			const startTime = Number(recentFeePeriods.startTime);
			const duration = Number(feePeriodDuration);

			setIsCloseFeePeriodEnabled(now > duration + startTime);
		} catch (e) {
			console.log(e);
			setIsCloseFeePeriodEnabled(false);
		}
	}


() => {
		fetchFeePeriodData();
	}


() => {
		const getGasLimitEstimate = async () => {
			if (isAppReady && isWalletConnected && canClaim) {
				if (isBelowCRatio) {
					setLowCRatio(true);
					return;
				}
				try {
					setError(null);
					if (delegateWallet && !delegateWallet.canClaim) {
						throw new Error(t('staking.actions.mint.action.error.delegate-cannot-claim'));
					}
					const {
						contracts: { FeePool },
					} = synthetixjs!;

					let gasEstimate = wei(
						delegateWallet
							? await FeePool.estimateGas.claimOnBehalf(delegateWallet.address)
							: await FeePool.estimateGas.claimFees(),
						0
					);

					setGasLimitEstimate(gasEstimate);
				} catch (error) {
					if (isL2 && error.data) {
						if (error.data.message.includes('below penalty threshold')) {
							setLowCRatio(true);
						} else if (!error.data.message.includes('already claimed')) {
							setError(error.data.message);
						}
					} else {
						if (error.message.includes('below penalty threshold')) {
							setLowCRatio(true);
						} else if (!error.message.includes('already claimed')) {
							setError(error.message);
						}
					}
					setGasLimitEstimate(null);
				}
			}
		};
		getGasLimitEstimate();
	}


async () => {
			if (isAppReady && isWalletConnected && canClaim) {
				if (isBelowCRatio) {
					setLowCRatio(true);
					return;
				}
				try {
					setError(null);
					if (delegateWallet && !delegateWallet.canClaim) {
						throw new Error(t('staking.actions.mint.action.error.delegate-cannot-claim'));
					}
					const {
						contracts: { FeePool },
					} = synthetixjs!;

					let gasEstimate = wei(
						delegateWallet
							? await FeePool.estimateGas.claimOnBehalf(delegateWallet.address)
							: await FeePool.estimateGas.claimFees(),
						0
					);

					setGasLimitEstimate(gasEstimate);
				} catch (error) {
					if (isL2 && error.data) {
						if (error.data.message.includes('below penalty threshold')) {
							setLowCRatio(true);
						} else if (!error.data.message.includes('already claimed')) {
							setError(error.data.message);
						}
					} else {
						if (error.message.includes('below penalty threshold')) {
							setLowCRatio(true);
						} else if (!error.message.includes('already claimed')) {
							setError(error.message);
						}
					}
					setGasLimitEstimate(null);
				}
			}
		}


() => {
		async function claim() {
			if (isAppReady) {
				try {
					setError(null);
					setTxModalOpen(true);
					const {
						contracts: { FeePool },
					} = synthetixjs!;

					let gasLimit = delegateWallet
						? (await FeePool.estimateGas.claimOnBehalf(delegateWallet.address)).toNumber()
						: (await FeePool.estimateGas.claimFees()).toNumber();

					if (!isL2) {
						gasLimit = normalizeGasLimit(gasLimit);
					}

					const transaction: ethers.ContractTransaction = delegateWallet
						? await FeePool.claimOnBehalf(delegateWallet.address, {
								gasPrice: normalizedGasPrice(gasPrice.toNumber()),
								gasLimit,
						  })
						: await FeePool.claimFees({
								gasPrice: normalizedGasPrice(gasPrice.toNumber()),
								gasLimit,
						  });

					if (transaction) {
						setTxHash(transaction.hash);
						setTransactionState(Transaction.WAITING);
						monitorTransaction({
							txHash: transaction.hash,
							onTxConfirmed: () => {
								setClaimedTradingRewards(tradingRewards.toNumber());
								setClaimedStakingRewards(stakingRewards.toNumber());
								setTransactionState(Transaction.SUCCESS);
								userStakingData.refetch();
							},
						});
						setTxModalOpen(false);
					}
				} catch (e) {
					setTransactionState(Transaction.PRESUBMIT);
					if (isL2) {
						setError(e?.data?.message ?? e.message);
					} else {
						setError(e.message);
					}
				}
			}
		}
		claim();
	}


() => {
								setClaimedTradingRewards(tradingRewards.toNumber());
								setClaimedStakingRewards(stakingRewards.toNumber());
								setTransactionState(Transaction.SUCCESS);
								userStakingData.refetch();
							}


() => router.push(ROUTES.Staking.Burn)


() => router.push(ROUTES.Earn.Home)


async () => {
		const {
			contracts: { FeePool },
		} = synthetixjs!;
		try {
			const gasLimit = FeePool.estimateGas.closeCurrentFeePeriod();

			const transaction: ethers.ContractTransaction = await FeePool.closeCurrentFeePeriod({
				gasPrice: normalizedGasPrice(gasPrice.toNumber()),
				gasLimit,
			});
			if (transaction) {
				setTxHash(transaction.hash);
				monitorTransaction({
					txHash: transaction.hash,
					onTxConfirmed: () => {
						fetchFeePeriodData();
					},
				});
				setTxModalOpen(false);
			}
		} catch (e) {
			console.log(e);
		}
	}


() => {
						fetchFeePeriodData();
					}


() => setTxModalOpen(false)


(props) => props.theme.colors.pink


(props) => props.theme.colors.grayBlue


(props) => props.theme.colors.gray


(props) => props.theme.colors.white


type ClaimTabProps = {
	tradingRewards: Wei;
	stakingRewards: Wei;
	totalRewards: Wei;
};


t('earn.actions.claim.in-progress')


t('earn.actions.claim.claiming')


t('earn.actions.tx.notice')


t('earn.actions.tx.link')


t('earn.actions.claim.success')


t('earn.actions.claim.claimed')


link ? (
								<ExternalLink href={link}>
									<VerifyButton>{t('earn.actions.tx.verify')}</VerifyButton>
								</ExternalLink>
							) : null


t('earn.actions.tx.verify')


t('earn.actions.tx.dismiss')


t('earn.incentives.options.snx.trading-rewards')


t('earn.incentives.options.snx.staking-rewards')


t('earn.incentives.options.snx.total-value')


t('earn.actions.claim.ratio-notice')


t('earn.actions.claim.not-voted')


t('earn.actions.claim.low-ratio')


t('earn.actions.claim.close-fee-period')


(account) => apiRx.query.marginProtocol.positionsByTrader.entries(account)


([, value]) => !value.isEmpty


([storageKey]) => {
        const positionId = storageKey.args[1][1];
        return apiRx.query.marginProtocol.positions(positionId).pipe(
          filter((x) => x.isSome),
          map((x) => x.unwrap()),
          mergeMap((position) => combineLatest([of(position), getSwap(position), getUnrealizedPL(position)])),
          map(([position, swap, profit]) => {
            const { owner, poolId, pair, leverage, marginHeld } = position;
            return {
              account: owner.toString(),
              liquidityPoolId: poolId.toString(),
              positionId: positionId.toString(),
              pair: {
                base: pair.base.toString(),
                quote: pair.quote.toString()
              },
              leverage: leverage.toString(),
              marginHeld: marginHeld.toString(),
              accumulatedSwap: swap ? swap.toFixed(0) : '',
              profit: profit ? profit.toFixed(0) : ''
            };
          })
        );
      }


(x) => x.isSome


(x) => x.unwrap()


(position) => combineLatest([of(position), getSwap(position), getUnrealizedPL(position)])


([position, swap, profit]) => {
            const { owner, poolId, pair, leverage, marginHeld } = position;
            return {
              account: owner.toString(),
              liquidityPoolId: poolId.toString(),
              positionId: positionId.toString(),
              pair: {
                base: pair.base.toString(),
                quote: pair.quote.toString()
              },
              leverage: leverage.toString(),
              marginHeld: marginHeld.toString(),
              accumulatedSwap: swap ? swap.toFixed(0) : '',
              profit: profit ? profit.toFixed(0) : ''
            };
          }


export default class PositionsByTraderTask extends Task<{ account: string | string[] }, Position> {
  validationSchema() {
    return Joi.object({
      account: Joi.alt(Joi.string(), Joi.array().min(1).items(Joi.string())).required()
    }).required();
  }

  async start(guardian: LaminarGuardian) {
    const { apiRx } = await guardian.isReady();

    const accounts = castArray(this.arguments.account);

    const getSwap = accumulatedSwap(apiRx);
    const getUnrealizedPL = unrealizedPL(apiRx);

    return from(accounts).pipe(
      switchMap((account) => apiRx.query.marginProtocol.positionsByTrader.entries(account)),
      mergeAll(),
      filter(([, value]) => !value.isEmpty),
      mergeMap(([storageKey]) => {
        const positionId = storageKey.args[1][1];
        return apiRx.query.marginProtocol.positions(positionId).pipe(
          filter((x) => x.isSome),
          map((x) => x.unwrap()),
          mergeMap((position) => combineLatest([of(position), getSwap(position), getUnrealizedPL(position)])),
          map(([position, swap, profit]) => {
            const { owner, poolId, pair, leverage, marginHeld } = position;
            return {
              account: owner.toString(),
              liquidityPoolId: poolId.toString(),
              positionId: positionId.toString(),
              pair: {
                base: pair.base.toString(),
                quote: pair.quote.toString()
              },
              leverage: leverage.toString(),
              marginHeld: marginHeld.toString(),
              accumulatedSwap: swap ? swap.toFixed(0) : '',
              profit: profit ? profit.toFixed(0) : ''
            };
          })
        );
      })
    );
  }
}


validationSchema() {
    return Joi.object({
      account: Joi.alt(Joi.string(), Joi.array().min(1).items(Joi.string())).required()
    }).required();
  }


async start(guardian: LaminarGuardian) {
    const { apiRx } = await guardian.isReady();

    const accounts = castArray(this.arguments.account);

    const getSwap = accumulatedSwap(apiRx);
    const getUnrealizedPL = unrealizedPL(apiRx);

    return from(accounts).pipe(
      switchMap((account) => apiRx.query.marginProtocol.positionsByTrader.entries(account)),
      mergeAll(),
      filter(([, value]) => !value.isEmpty),
      mergeMap(([storageKey]) => {
        const positionId = storageKey.args[1][1];
        return apiRx.query.marginProtocol.positions(positionId).pipe(
          filter((x) => x.isSome),
          map((x) => x.unwrap()),
          mergeMap((position) => combineLatest([of(position), getSwap(position), getUnrealizedPL(position)])),
          map(([position, swap, profit]) => {
            const { owner, poolId, pair, leverage, marginHeld } = position;
            return {
              account: owner.toString(),
              liquidityPoolId: poolId.toString(),
              positionId: positionId.toString(),
              pair: {
                base: pair.base.toString(),
                quote: pair.quote.toString()
              },
              leverage: leverage.toString(),
              marginHeld: marginHeld.toString(),
              accumulatedSwap: swap ? swap.toFixed(0) : '',
              profit: profit ? profit.toFixed(0) : ''
            };
          })
        );
      })
    );
  }


@Component({
    selector: 'app-about',
    templateUrl: './about.component.html',
    styleUrls: ['./about.component.scss']
})
export class AboutComponent implements OnInit {

    public animation = 'bounce';

    constructor() { }

    public ngOnInit() { }

}


public ngOnInit() { }


export default function MyCollectionsPage() {
  const { user } = useAuth()
  const router = useRouter()
  const { t } = useTranslation()

  // Fetch collections and asset data
  const { data: { collections: allCollections } = {} } = useApi<{
    total: number
    collections: CollectionWithSets[]
  }>(urls.api.v1.getAllCollections)
  const { data: { collectibles } = {} } = useApi<CollectibleListWithTotal>(
    user?.username
      ? `${urls.api.v1.getAssetsByOwner}?ownerUsername=${user.username}&pageSize=-1`
      : null
  )

  return (
    <DefaultLayout
      pageTitle={t('common:pageTitles.My Collections')}
      panelPadding
      width="large"
    >
      {!allCollections || !collectibles ? (
        <Loading />
      ) : (
        <MyCollectionsTemplate
          assets={collectibles}
          collections={getCollectionsFromOwnedAssets(
            collectibles,
            allCollections
          )}
          onRedirectBrands={() => router.push(urls.releases)}


async (context) => {
  const user = await getAuthenticatedUser(context)
  if (!user) {
    return handleUnauthenticatedRedirect(context.resolvedUrl)
  }
  return { props: {} }
}


t('common:pageTitles.My Collections')


getCollectionsFromOwnedAssets(
            collectibles,
            allCollections
          )


export function EncryptionSymmetricAlgorithmDisplay<TFieldMeta>({ meta, fieldConfig, encryptionSymmetricAlgorithm, renderContext }: Props<TFieldMeta>) {
  return renderTemplatedTypeElement(
    EncryptionSymmetricAlgorithmTypeName,
    meta,
    fieldConfig,
    encryptionSymmetricAlgorithm,
    renderContext,
    EncryptionSymmetricAlgorithmSubElementsMap,
  )
}


({value, renderContext, fieldConfig}) => <UBLExtensionsDisplay
          key


({value, renderContext, fieldConfig}) => <IdentifierDisplay
          key


type Props<TFieldMeta> = {
  meta: FieldMeta<TFieldMeta>
  fieldConfig?: FieldConfig<EncryptionSymmetricAlgorithm, void>
  encryptionSymmetricAlgorithm: EncryptionSymmetricAlgorithm[] | undefined
  renderContext: RenderContext
}


() => {
  beforeEach(() => TestBed.configureTestingModule({}));

  it('should be created', () => {
    const service: SideNavService = TestBed.get(SideNavService);
    expect(service).toBeTruthy();
  });
}


() => {
    const service: SideNavService = TestBed.get(SideNavService);
    expect(service).toBeTruthy();
  }


() => {
  let spectator: Spectator<MatcherEnhancementsComponent>;
  const createComponent = createComponentFactory({
    component: MatcherEnhancementsComponent
  });

  beforeEach(() => spectator = createComponent());

  describe('Text', () => {
    it('should match mulitple elements with different text', () => {
      const el = spectator.query('.text-check');
      expect(el).toHaveText(['It should', 'different text']);
      expect(el).toContainText(['It should', 'different text']);
      expect(el).toHaveExactText(['It should have', 'Some different text']);
    });
  });

  describe('Value', () => {
    it('should match multiple inputs with different values', () => {
      const inputs = spectator.queryAll('input.sample');
      expect(inputs).toHaveValue(['test1', 'test2']);
      expect(inputs).toContainValue(['test1', 'test2']);
    });
  });

  describe('Class', () => {
    describe('strict', () => {
      it('should succeed if the element has classes in strict order', () => {
        expect('#multi-class').toHaveClass(['one-class', 'two-class']);
        expect('#multi-class').toHaveClass(['one-class', 'two-class'], { strict: true });
      });

      it('should succeed if the element has no classes in strict order', () => {
        expect('#multi-class').not.toHaveClass(['two-class', 'one-class']);
        expect('#multi-class').not.toHaveClass(['two-class', 'one-class'], { strict: true });
      });
    });

    describe('not strict', () => {
      it('should succeed if the element has classes in original order', () => {
        expect('#multi-class').toHaveClass(['one-class', 'two-class'], { strict: false });
      });

      it('should succeed if the element has classes in shuffled order', () => {
        expect('#multi-class').toHaveClass(['two-class', 'one-class'], { strict: false });
      });
    });
  });

  describe('Attribute', () => {
    it('should match attributes with object syntax', () => {
      expect('#attr-check').toHaveAttribute({ label: 'test label' });
    });
  });

  describe('Property', () => {
    it('should match properties with object syntax', () => {
      expect(spectator.query('.checkbox')).toHaveProperty({ checked: true });
    });

    it('should match partial properties with object syntax', () => {
      expect('img').toContainProperty({ src: 'assets/myimg.jpg' });
    });
  });

  describe('Partial', () => {
    it('should return true when expected is partial of actual', () => {
      expect(spectator.component.dummyValue).toBePartial({ label: 'this is a dummy value' });
      expect(spectator.component.dummyValue).toBePartial({ active: true });
    });

    it('should return true when expected is same as actual', () => {
      expect(spectator.component.dummyValue).toBePartial({...spectator.component.dummyValue});
    });

    it('should return false when expected is not partial of actual', () => {
      expect(spectator.component.dummyValue).not.toBePartial({ unknown: 'property' });
      expect(spectator.component.dummyValue).not.toBePartial({ label: 'this is another dummy value' });
      expect(spectator.component.dummyValue).not.toBePartial({ active: false });
    });
  });
}


() => spectator = createComponent()


() => {
    it('should match mulitple elements with different text', () => {
      const el = spectator.query('.text-check');
      expect(el).toHaveText(['It should', 'different text']);
      expect(el).toContainText(['It should', 'different text']);
      expect(el).toHaveExactText(['It should have', 'Some different text']);
    });
  }


() => {
      const el = spectator.query('.text-check');
      expect(el).toHaveText(['It should', 'different text']);
      expect(el).toContainText(['It should', 'different text']);
      expect(el).toHaveExactText(['It should have', 'Some different text']);
    }


() => {
    it('should match multiple inputs with different values', () => {
      const inputs = spectator.queryAll('input.sample');
      expect(inputs).toHaveValue(['test1', 'test2']);
      expect(inputs).toContainValue(['test1', 'test2']);
    });
  }


() => {
      const inputs = spectator.queryAll('input.sample');
      expect(inputs).toHaveValue(['test1', 'test2']);
      expect(inputs).toContainValue(['test1', 'test2']);
    }


() => {
    describe('strict', () => {
      it('should succeed if the element has classes in strict order', () => {
        expect('#multi-class').toHaveClass(['one-class', 'two-class']);
        expect('#multi-class').toHaveClass(['one-class', 'two-class'], { strict: true });
      });

      it('should succeed if the element has no classes in strict order', () => {
        expect('#multi-class').not.toHaveClass(['two-class', 'one-class']);
        expect('#multi-class').not.toHaveClass(['two-class', 'one-class'], { strict: true });
      });
    });

    describe('not strict', () => {
      it('should succeed if the element has classes in original order', () => {
        expect('#multi-class').toHaveClass(['one-class', 'two-class'], { strict: false });
      });

      it('should succeed if the element has classes in shuffled order', () => {
        expect('#multi-class').toHaveClass(['two-class', 'one-class'], { strict: false });
      });
    });
  }


() => {
      it('should succeed if the element has classes in strict order', () => {
        expect('#multi-class').toHaveClass(['one-class', 'two-class']);
        expect('#multi-class').toHaveClass(['one-class', 'two-class'], { strict: true });
      });

      it('should succeed if the element has no classes in strict order', () => {
        expect('#multi-class').not.toHaveClass(['two-class', 'one-class']);
        expect('#multi-class').not.toHaveClass(['two-class', 'one-class'], { strict: true });
      });
    }


() => {
        expect('#multi-class').toHaveClass(['one-class', 'two-class']);
        expect('#multi-class').toHaveClass(['one-class', 'two-class'], { strict: true });
      }


() => {
        expect('#multi-class').not.toHaveClass(['two-class', 'one-class']);
        expect('#multi-class').not.toHaveClass(['two-class', 'one-class'], { strict: true });
      }


() => {
      it('should succeed if the element has classes in original order', () => {
        expect('#multi-class').toHaveClass(['one-class', 'two-class'], { strict: false });
      });

      it('should succeed if the element has classes in shuffled order', () => {
        expect('#multi-class').toHaveClass(['two-class', 'one-class'], { strict: false });
      });
    }


() => {
        expect('#multi-class').toHaveClass(['one-class', 'two-class'], { strict: false });
      }


() => {
        expect('#multi-class').toHaveClass(['two-class', 'one-class'], { strict: false });
      }


() => {
    it('should match attributes with object syntax', () => {
      expect('#attr-check').toHaveAttribute({ label: 'test label' });
    });
  }


() => {
      expect('#attr-check').toHaveAttribute({ label: 'test label' });
    }


() => {
    it('should match properties with object syntax', () => {
      expect(spectator.query('.checkbox')).toHaveProperty({ checked: true });
    });

    it('should match partial properties with object syntax', () => {
      expect('img').toContainProperty({ src: 'assets/myimg.jpg' });
    });
  }


() => {
      expect(spectator.query('.checkbox')).toHaveProperty({ checked: true });
    }


() => {
      expect('img').toContainProperty({ src: 'assets/myimg.jpg' });
    }


() => {
    it('should return true when expected is partial of actual', () => {
      expect(spectator.component.dummyValue).toBePartial({ label: 'this is a dummy value' });
      expect(spectator.component.dummyValue).toBePartial({ active: true });
    });

    it('should return true when expected is same as actual', () => {
      expect(spectator.component.dummyValue).toBePartial({...spectator.component.dummyValue});
    });

    it('should return false when expected is not partial of actual', () => {
      expect(spectator.component.dummyValue).not.toBePartial({ unknown: 'property' });
      expect(spectator.component.dummyValue).not.toBePartial({ label: 'this is another dummy value' });
      expect(spectator.component.dummyValue).not.toBePartial({ active: false });
    });
  }


() => {
      expect(spectator.component.dummyValue).toBePartial({ label: 'this is a dummy value' });
      expect(spectator.component.dummyValue).toBePartial({ active: true });
    }


() => {
      expect(spectator.component.dummyValue).toBePartial({...spectator.component.dummyValue});
    }


() => {
      expect(spectator.component.dummyValue).not.toBePartial({ unknown: 'property' });
      expect(spectator.component.dummyValue).not.toBePartial({ label: 'this is another dummy value' });
      expect(spectator.component.dummyValue).not.toBePartial({ active: false });
    }


@Component({
  selector: "mrobot-setting-row",
  templateUrl: "./setting-row.component.html",
  styleUrls: ["./setting-row.component.sass"],
})
export class SettingRowComponent {
  @Input()
  public title: string

  @Input()
  public description: string
}


(error) => error


/**
 * Translator API Wrapper
 */
export class Translator {
  /**
   * Request timeout
   */
  timeout: number

  /**
   * gRPC web API URL
   */
  apiUrl: string

  /**
   * @param {number} timeout request timeout in second.
   * @param {string} apiUrl gRPC web URL.
   */
  constructor(timeout: number, apiUrl: string) {
    this.timeout = timeout
    this.apiUrl = apiUrl
  }

  /**
   * Returns the deadline time of gRPC web request.
   * @param {Date} cur base datetime.
   * @returns {string} deadline value of gRPC request.
   */
  grpcDeadline(cur: Date): string {
    cur.setSeconds(cur.getSeconds() + this.timeout)
    return cur.getTime().toString()
  }

  /**
   * Translate text with calling API.
   *
   * @param {LangType} srcLang source language type.
   * @param {LangType} targetLang target language type.
   * @param {string} text text to be translated.
   * @returns {Promise<TranslatorOutput>}
   */
  async translateText(
    srcLang: LangType,
    targetLang: LangType,
    text: string
  ): Promise<TranslatorOutput> {
    const req = new TranslateRequest()
      .setSrclang(srcLang)
      .setTargetlang(targetLang)
      .setText(text)

    // Call
    const translatorService = new TranslatorClient(this.apiUrl)
    const resp = await translatorService
      .translate(req, {
        deadline: this.grpcDeadline(new Date()),
      })
      .catch((error) => error)
    if (resp.code && resp.code !== 0) {
      throw new Error(resp.message)
    }

    const translatedList = resp.getTranslatedtextlistMap()

    const output: TranslatorOutput = {
      aws: '',
      google: '',
    }

    let v
    v = translatedList.get('aws')
    if (typeof v === 'undefined') {
      throw new Error(`error: undefined aws`)
    }
    output.aws = v.getText()

    v = translatedList.get('google')
    if (typeof v === 'undefined') {
      throw new Error(`error: undefined google`)
    }
    output.google = v.getText()

    return output
  }
}


/**
 * The value returned by translateText.
 */
export interface TranslatorOutput {
  /**
   * translated text by AWS
   */
  aws: string

  /**
   * translated text by Google
   */
  google: string
}


/**
   * Returns the deadline time of gRPC web request.
   * @param {Date} cur base datetime.
   * @returns {string} deadline value of gRPC request.
   */
grpcDeadline(cur: Date): string {
    cur.setSeconds(cur.getSeconds() + this.timeout)
    return cur.getTime().toString()
  }


/**
   * Translate text with calling API.
   *
   * @param {LangType} srcLang source language type.
   * @param {LangType} targetLang target language type.
   * @param {string} text text to be translated.
   * @returns {Promise<TranslatorOutput>}
   */
async translateText(
    srcLang: LangType,
    targetLang: LangType,
    text: string
  ): Promise<TranslatorOutput> {
    const req = new TranslateRequest()
      .setSrclang(srcLang)
      .setTargetlang(targetLang)
      .setText(text)

    // Call
    const translatorService = new TranslatorClient(this.apiUrl)
    const resp = await translatorService
      .translate(req, {
        deadline: this.grpcDeadline(new Date()),
      })
      .catch((error) => error)
    if (resp.code && resp.code !== 0) {
      throw new Error(resp.message)
    }

    const translatedList = resp.getTranslatedtextlistMap()

    const output: TranslatorOutput = {
      aws: '',
      google: '',
    }

    let v
    v = translatedList.get('aws')
    if (typeof v === 'undefined') {
      throw new Error(`error: undefined aws`)
    }
    output.aws = v.getText()

    v = translatedList.get('google')
    if (typeof v === 'undefined') {
      throw new Error(`error: undefined google`)
    }
    output.google = v.getText()

    return output
  }


@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: process.env.SECRET_JWT_KEY,
    });
  }

  async validate(payload: any) {
    return {
      firstName: payload.firstName,
      id: payload.id,
    };
  }
}


async validate(payload: any) {
    return {
      firstName: payload.firstName,
      id: payload.id,
    };
  }


export async function getServerSideProps() {
  // Call an external API endpoint to get posts.
  // You can use any data fetching library
  const data = await fetch('https://opentdb.com/api_category.php').then((r) =>
    r.json()
  )
  const categories = data.trivia_categories

  // By returning { props: categories }, the component
  // will receive `categories` as a prop at build time
  return {
    props: {
      categories,
    },
  }
}


({ categories }) => {
  // const [user] = useCurrentUser();
  const [quiz, setQuiz] = useState(null) // null to prevent the render down below
  const [allAnswered, setAllAnswered] = useState(false)
  const [finalScore, setFinalScore] = useState(null)

  return (
    <>
      <style jsx>
        {`
          p {
            text-align: center;
            color: #888;
          }
          h3 {
            color: #555;
          }
          h1.title {
            color: #fff;
            text-align: center;
          }
        `}


(r) =>
    r.json()


/**
 * The global configuration object for RxJS, used to configure things
 * like how to react on unhandled errors. Accessible via {@link config}
 * object.
 */
export interface GlobalConfig {
  /**
   * A registration point for unhandled errors from RxJS. These are errors that
   * cannot were not handled by consuming code in the usual subscription path. For
   * example, if you have this configured, and you subscribe to an observable without
   * providing an error handler, errors from that subscription will end up here. This
   * will _always_ be called asynchronously on another job in the runtime. This is because
   * we do not want errors thrown in this user-configured handler to interfere with the
   * behavior of the library.
   */
  onUnhandledError: ((err: any) => void) | null;

  /**
   * A registration point for notifications that cannot be sent to subscribers because they
   * have completed, errored or have been explicitly unsubscribed. By default, next, complete
   * and error notifications sent to stopped subscribers are noops. However, sometimes callers
   * might want a different behavior. For example, with sources that attempt to report errors
   * to stopped subscribers, a caller can configure RxJS to throw an unhandled error instead.
   * This will _always_ be called asynchronously on another job in the runtime. This is because
   * we do not want errors thrown in this user-configured handler to interfere with the
   * behavior of the library.
   */
  onStoppedNotification: ((notification: ObservableNotification<any>, subscriber: Subscriber<any>) => void) | null;

  /**
   * The promise constructor used by default for {@link Observable#toPromise toPromise} and {@link Observable#forEach forEach}
   * methods.
   *
   * @deprecated As of version 8, RxJS will no longer support this sort of injection of a
   * Promise constructor. If you need a Promise implementation other than native promises,
   * please polyfill/patch Promise as you see appropriate. Will be removed in v8.
   */
  Promise?: PromiseConstructorLike;
=======
let _enable_super_gross_mode_that_will_cause_bad_things = false;

/**
 * The global configuration object for RxJS, used to configure things
 * like what Promise contructor should used to create Promises
 */
export const config = {
  /**
   * The promise constructor used by default for methods such as
   * {@link toPromise} and {@link forEach}
   */
  Promise: undefined as PromiseConstructorLike,
>>>>>>> ba354fa661b4c6906c0342221d686a312a23a3ab

  /**
   * If true, turns on synchronous error rethrowing, which is a deprecated behavior
   * in v6 and higher. This behavior enables bad patterns like wrapping a subscribe
   * call in a try/catch block. It also enables producer interference, a nasty bug
   * where a multicast can be broken for all observers by a downstream consumer with
<<<<<<< HEAD
   * an unhandled error. DO NOT USE THIS FLAG UNLESS IT'S NEEDED TO BUY TIME
   * FOR MIGRATION REASONS.
   *
   * @deprecated As of version 8, RxJS will no longer support synchronous throwing
   * of unhandled errors. All errors will be thrown on a separate call stack to prevent bad
   * behaviors described above. Will be removed in v8.
   */
  useDeprecatedSynchronousErrorHandling: boolean;

  /**
   * If true, enables an as-of-yet undocumented feature from v5: The ability to access
   * `unsubscribe()` via `this` context in `next` functions created in observers passed
   * to `subscribe`.
   *
   * This is being removed because the performance was severely problematic, and it could also cause
   * issues when types other than POJOs are passed to subscribe as subscribers, as they will likely have
   * their `this` context overwritten.
   *
   * @deprecated As of version 8, RxJS will no longer support altering the
   * context of next functions provided as part of an observer to Subscribe. Instead,
   * you will have access to a subscription or a signal or token that will allow you to do things like
   * unsubscribe and test closed status. Will be removed in v8.
   */
  useDeprecatedNextContext: boolean;
}


export interface WtISSResponse {
    name: string;
    id: number;
    latitude: number;
    longitude: number;
    altitude: number;
    velocity: number;
    visibility: string;
    footprint: number;
    timestamp: number;
    daynum: number;
    solar_lat: number;
    solar_lon: number;
    units: string;
}


async (
  context: Context,
  searchParams?: GetProductSearchParams,
  customQuery?: CustomQuery,
): Promise<ApolloQueryResult<GroupedProductDetailQuery>> => {
  const defaultParams = {
    pageSize: 20,
    currentPage: 1,
    ...searchParams,
  };

  const variables: Variables = {
    pageSize: defaultParams.pageSize,
    currentPage: defaultParams.currentPage,
  };

  if (defaultParams.search) variables.search = defaultParams.search;

  if (defaultParams.filter) variables.filter = defaultParams.filter;

  if (defaultParams.sort) variables.sort = defaultParams.sort;

  const { products } = context.extendQuery(
    customQuery, {
      products: {
        query: groupedProductDetailQuery,
        variables: defaultParams,
      },
    },
  );
  try {
    return await context.client.query<GroupedProductDetailQuery, GroupedProductDetailQueryVariables>({
      query: gql`${products.query}`,
      variables: products.variables,
      fetchPolicy: 'no-cache',
    });
  } catch (error) {
    throw error.graphQLErrors?.[0].message || error.networkError?.result || error;
  }
}


type Variables = {
  pageSize: number;
  currentPage: number;
  search?: string;
  filter?: ProductAttributeFilterInput;
  sort?: ProductAttributeSortInput;
};


(props) => {
  const isStopped = props.masterState === "stopped"

  return (
    <Flex
      className={style.controls}
      column
      alignItemsCenter
      justifySpaceBetween
    >
      <Flex.Item style={{ margin: "2em" }}>
        <img class={style.logo} src="assets/logo.png" />
      </Flex.Item>
      <Flex.Item alignSelfCenter>
        {props.isInitializing && <Spinner colors={["red", "green", "purple"]} size={40} thick />}


interface ControlProps {
  masterState: "stopped" | "running",
  isInitializing: boolean,
  reportTimeout: number,
  toggleMasterState: () => void,
  cameraSelected: (camera: MediaDeviceInfo) => void
  timeoutSelected: (timeout: number | "none") => void
}


(): React.CSSProperties => {
        if (this.props.gridColumns)
            return {display: "grid",
                gridAutoFlow: this.props.horizontal ? "unset" : "column",
                gridGap: "1px",
                gridTemplateColumns: `repeat(${this.props.gridColumns}, 1fr)`,
                gridTemplateRows: `repeat(${Math.ceil(this.props.options.length/this.props.gridColumns)}, auto)`
            }
        return {}
    }


(option, i: number) =>
                <TS_Checkbox
                    key


export class TS_CheckboxField<T>
    extends Component<CheckboxFieldProps<T>, {}> {

    gridCss = (): React.CSSProperties => {
        if (this.props.gridColumns)
            return {display: "grid",
                gridAutoFlow: this.props.horizontal ? "unset" : "column",
                gridGap: "1px",
                gridTemplateColumns: `repeat(${this.props.gridColumns}, 1fr)`,
                gridTemplateRows: `repeat(${Math.ceil(this.props.options.length/this.props.gridColumns)}, auto)`
            }
        return {}
    }

    render() {
        return <div className={`${this.props.fieldContainerClass} ${this.props.horizontal && !this.props.gridColumns ? 'll_h_c' : ''}`} style={this.gridCss()}>
            {this.props.options.map((option, i: number) =>
                <TS_Checkbox
                    key={i}
                    value={option.value}
                    checked={Array.isArray(this.props.value) ? this.props.value.includes(option.value) : this.props.value === option.value}
                    onCheck={this.props.onCheck}
                    label={this.props.label(option)}
                    circle={this.props.circle}
                    rtl={this.props.rtl}
                    disabled={option.disabled}
                    buttonClass={this.props.buttonClass}
                    containerClass={this.props.checkboxContainerClass}
                    innerNode={this.props.innerNode}
                />
            )}
        </div>;
    }

}


export type CheckboxOption<T> = {
    value: T
    disabled?: boolean
}


type LabelType = ReactNode | ((checked: boolean, disabled: boolean) => ReactNode)


export type CheckboxFieldProps<T> = {
    id?: string
    options: CheckboxOption<T>[]
    value: T | T[]
    label: (option: CheckboxOption<T>) => LabelType
    circle?: boolean
    rtl?: boolean
    onCheck: (value: T, checked: boolean) => void
    fieldContainerClass?: string
    gridColumns?: number
    horizontal?: boolean
    buttonClass?: (checked: boolean, disabled: boolean) => string
    checkboxContainerClass?: (checked: boolean, disabled: boolean) => string
    innerNode?: (checked: boolean, disabled: boolean) => ReactNode
}


render() {
        return <div className={`${this.props.fieldContainerClass} ${this.props.horizontal && !this.props.gridColumns ? 'll_h_c' : ''}`} style={this.gridCss()}>
            {this.props.options.map((option, i: number) =>
                <TS_Checkbox
                    key={i}
                    value={option.value}
                    checked={Array.isArray(this.props.value) ? this.props.value.includes(option.value) : this.props.value === option.value}
                    onCheck={this.props.onCheck}
                    label={this.props.label(option)}
                    circle={this.props.circle}
                    rtl={this.props.rtl}
                    disabled={option.disabled}
                    buttonClass={this.props.buttonClass}
                    containerClass={this.props.checkboxContainerClass}
                    innerNode={this.props.innerNode}
                />
            )}
        </div>;
    }


(): void => {
    let ccApi: CreditcoinApi;
    let borrower: KeyringPair;
    let lender: KeyringPair;
    let dealOrder: DealOrderRegistered;
    let testTokenAddress: string;
    let txHash: string;
    let lenderWallet: Wallet;
    let borrowerWallet: Wallet;

    const { blockchain, expirationBlock, loanTerms, createWallet, keyring } = testData;

    beforeAll(async () => {
        ccApi = await creditcoinApi((global as any).CREDITCOIN_API_URL);
        lender = keyring.addFromUri('//Alice');
        borrower = keyring.addFromUri('//Bob');
    });

    afterAll(async () => {
        await ccApi.api.disconnect();
    });

    beforeEach(async () => {
        const {
            api,
            extrinsics: { registerAddress, registerDealOrder },
            utils: { signAccountId },
        } = ccApi;
        lenderWallet = createWallet();
        borrowerWallet = createWallet();
        const [lenderRegAddr, borrowerRegAddr] = await Promise.all([
            registerAddress(lenderWallet.address, blockchain, signAccountId(lenderWallet, lender.address), lender),
            registerAddress(
                borrowerWallet.address,
                blockchain,
                signAccountId(borrowerWallet, borrower.address),
                borrower,
            ),
        ]);
        const askGuid = Guid.newGuid();
        const bidGuid = Guid.newGuid();
        const signedParams = signLoanParams(api, borrower, expirationBlock, askGuid, bidGuid, loanTerms);

        dealOrder = await registerDealOrder(
            lenderRegAddr.itemId,
            borrowerRegAddr.itemId,
            loanTerms,
            expirationBlock,
            askGuid,
            bidGuid,
            borrower.publicKey,
            signedParams,
            lender,
        );

        [testTokenAddress, txHash] = await lendOnEth(
            lenderWallet,
            borrowerWallet,
            dealOrder.dealOrder.itemId,
            loanTerms,
        );
    }, 90000);

    it('fee is min 0.01 CTC', async (): Promise<void> => {
        const { api } = ccApi;
        const ccTransferKind = createCreditcoinTransferKind(api, {
            kind: 'Ethless',
            contractAddress: testTokenAddress,
        });

        return new Promise((resolve, reject): void => {
            const unsubscribe = api.tx.creditcoin
                .registerFundingTransfer(ccTransferKind, dealOrder.dealOrder.itemId, txHash)
                .signAndSend(lender, { nonce: -1 }, async ({ dispatchError, events, status }) => {
                    await extractFee(resolve, reject, unsubscribe, api, dispatchError, events, status);
                })
                .catch((error) => reject(error));
        }).then((fee) => {
            expect(fee).toBeGreaterThanOrEqual(POINT_01_CTC);
        });
    }, 30000);

    it('failure event is emitted if transfer is invalid', async (): Promise<void> => {
        // wrong amount
        const badLoanTerms = { ...loanTerms, amount: new BN(1) };
        const dealOrderId = dealOrder.dealOrder.itemId;
        const { api } = ccApi;

        const [failureTokenAddress, failureTxHash] = await lendOnEth(
            lenderWallet,
            borrowerWallet,
            dealOrder.dealOrder.itemId,
            badLoanTerms,
        );

        const transferId = createFundingTransferId(blockchain, failureTxHash);
        await ccApi.extrinsics.registerFundingTransfer(
            { kind: 'Ethless', contractAddress: failureTokenAddress },
            dealOrderId,
            failureTxHash,
            lender,
        );

        return new Promise((resolve, reject): void => {
            api.query.system
                .events((events: any) => {
                    // Loop through the Vec<EventRecord>
                    events.forEach((record: any) => {
                        // Extract the phase, event and the event types
                        const { event } = record;
                        if (api.events.creditcoin.TransferFailedVerification.is(event)) {
                            const failedTransferId = event.data[0].toString();
                            if (failedTransferId === transferId) {
                                const failureCause = event.data[1] as any;
                                expect(failureCause.isIncorrectAmount).toBeTruthy();
                                resolve();
                            }
                        }
                    });
                })
                .catch(reject);
        });
    }, 60000);
}


async () => {
        ccApi = await creditcoinApi((global as any).CREDITCOIN_API_URL);
        lender = keyring.addFromUri('//Alice');
        borrower = keyring.addFromUri('//Bob');
    }


async () => {
        await ccApi.api.disconnect();
    }


async () => {
        const {
            api,
            extrinsics: { registerAddress, registerDealOrder },
            utils: { signAccountId },
        } = ccApi;
        lenderWallet = createWallet();
        borrowerWallet = createWallet();
        const [lenderRegAddr, borrowerRegAddr] = await Promise.all([
            registerAddress(lenderWallet.address, blockchain, signAccountId(lenderWallet, lender.address), lender),
            registerAddress(
                borrowerWallet.address,
                blockchain,
                signAccountId(borrowerWallet, borrower.address),
                borrower,
            ),
        ]);
        const askGuid = Guid.newGuid();
        const bidGuid = Guid.newGuid();
        const signedParams = signLoanParams(api, borrower, expirationBlock, askGuid, bidGuid, loanTerms);

        dealOrder = await registerDealOrder(
            lenderRegAddr.itemId,
            borrowerRegAddr.itemId,
            loanTerms,
            expirationBlock,
            askGuid,
            bidGuid,
            borrower.publicKey,
            signedParams,
            lender,
        );

        [testTokenAddress, txHash] = await lendOnEth(
            lenderWallet,
            borrowerWallet,
            dealOrder.dealOrder.itemId,
            loanTerms,
        );
    }


async (): Promise<void> => {
        const { api } = ccApi;
        const ccTransferKind = createCreditcoinTransferKind(api, {
            kind: 'Ethless',
            contractAddress: testTokenAddress,
        });

        return new Promise((resolve, reject): void => {
            const unsubscribe = api.tx.creditcoin
                .registerFundingTransfer(ccTransferKind, dealOrder.dealOrder.itemId, txHash)
                .signAndSend(lender, { nonce: -1 }, async ({ dispatchError, events, status }) => {
                    await extractFee(resolve, reject, unsubscribe, api, dispatchError, events, status);
                })
                .catch((error) => reject(error));
        }).then((fee) => {
            expect(fee).toBeGreaterThanOrEqual(POINT_01_CTC);
        });
    }


(resolve, reject): void => {
            const unsubscribe = api.tx.creditcoin
                .registerFundingTransfer(ccTransferKind, dealOrder.dealOrder.itemId, txHash)
                .signAndSend(lender, { nonce: -1 }, async ({ dispatchError, events, status }) => {
                    await extractFee(resolve, reject, unsubscribe, api, dispatchError, events, status);
                })
                .catch((error) => reject(error));
        }


async ({ dispatchError, events, status }) => {
                    await extractFee(resolve, reject, unsubscribe, api, dispatchError, events, status);
                }


(error) => reject(error)


(fee) => {
            expect(fee).toBeGreaterThanOrEqual(POINT_01_CTC);
        }


async (): Promise<void> => {
        // wrong amount
        const badLoanTerms = { ...loanTerms, amount: new BN(1) };
        const dealOrderId = dealOrder.dealOrder.itemId;
        const { api } = ccApi;

        const [failureTokenAddress, failureTxHash] = await lendOnEth(
            lenderWallet,
            borrowerWallet,
            dealOrder.dealOrder.itemId,
            badLoanTerms,
        );

        const transferId = createFundingTransferId(blockchain, failureTxHash);
        await ccApi.extrinsics.registerFundingTransfer(
            { kind: 'Ethless', contractAddress: failureTokenAddress },
            dealOrderId,
            failureTxHash,
            lender,
        );

        return new Promise((resolve, reject): void => {
            api.query.system
                .events((events: any) => {
                    // Loop through the Vec<EventRecord>
                    events.forEach((record: any) => {
                        // Extract the phase, event and the event types
                        const { event } = record;
                        if (api.events.creditcoin.TransferFailedVerification.is(event)) {
                            const failedTransferId = event.data[0].toString();
                            if (failedTransferId === transferId) {
                                const failureCause = event.data[1] as any;
                                expect(failureCause.isIncorrectAmount).toBeTruthy();
                                resolve();
                            }
                        }
                    });
                })
                .catch(reject);
        });
    }


(resolve, reject): void => {
            api.query.system
                .events((events: any) => {
                    // Loop through the Vec<EventRecord>
                    events.forEach((record: any) => {
                        // Extract the phase, event and the event types
                        const { event } = record;
                        if (api.events.creditcoin.TransferFailedVerification.is(event)) {
                            const failedTransferId = event.data[0].toString();
                            if (failedTransferId === transferId) {
                                const failureCause = event.data[1] as any;
                                expect(failureCause.isIncorrectAmount).toBeTruthy();
                                resolve();
                            }
                        }
                    });
                })
                .catch(reject);
        }


(events: any) => {
                    // Loop through the Vec<EventRecord>
                    events.forEach((record: any) => {
                        // Extract the phase, event and the event types
                        const { event } = record;
                        if (api.events.creditcoin.TransferFailedVerification.is(event)) {
                            const failedTransferId = event.data[0].toString();
                            if (failedTransferId === transferId) {
                                const failureCause = event.data[1] as any;
                                expect(failureCause.isIncorrectAmount).toBeTruthy();
                                resolve();
                            }
                        }
                    });
                }


(record: any) => {
                        // Extract the phase, event and the event types
                        const { event } = record;
                        if (api.events.creditcoin.TransferFailedVerification.is(event)) {
                            const failedTransferId = event.data[0].toString();
                            if (failedTransferId === transferId) {
                                const failureCause = event.data[1] as any;
                                expect(failureCause.isIncorrectAmount).toBeTruthy();
                                resolve();
                            }
                        }
                    }


(cmp) => cmp.location.nativeElement


/**
 * `AppModule` is the main entry point into Angular2's bootstraping process
 */
@NgModule({
	bootstrap: [ AppComponent ],
	declarations: [
		AppComponent
	],
	imports: [ // import Angular's modules
		BrowserModule,
		FormsModule,
		HttpModule,
		RouterModule.forRoot(ROUTES, { useHash: true, preloadingStrategy: PreloadAllModules }),
		HomeModule
	],
	providers: [ // expose our Services and Providers into Angular's dependency injection
		ENV_PROVIDERS,
		APP_PROVIDERS
	]
})
export class AppModule {

	constructor(
		public appRef: ApplicationRef,
		public appState: AppState
	) {}

	public hmrOnInit(store: StoreType) {
		if (!store || !store.state) {
			return;
		}
		console.log('HMR store', JSON.stringify(store, null, 2));
		// set state
		this.appState._state = store.state;
		// set input values
		if ('restoreInputValues' in store) {
			let restoreInputValues = store.restoreInputValues;
			setTimeout(restoreInputValues);
		}

		this.appRef.tick();
		delete store.state;
		delete store.restoreInputValues;
	}

	public hmrOnDestroy(store: StoreType) {
		const cmpLocation = this.appRef.components.map((cmp) => cmp.location.nativeElement);
		// save state
		const state = this.appState._state;
		store.state = state;
		// recreate root elements
		store.disposeOldHosts = createNewHosts(cmpLocation);
		// save input values
		store.restoreInputValues  = createInputTransfer();
		// remove styles
		removeNgStyles();
	}

	public hmrAfterDestroy(store: StoreType) {
		// display new elements
		store.disposeOldHosts();
		delete store.disposeOldHosts;
	}

}


type StoreType = {
	state: InternalStateType,
	restoreInputValues: () => void,
	disposeOldHosts: () => void
};


public hmrOnInit(store: StoreType) {
		if (!store || !store.state) {
			return;
		}
		console.log('HMR store', JSON.stringify(store, null, 2));
		// set state
		this.appState._state = store.state;
		// set input values
		if ('restoreInputValues' in store) {
			let restoreInputValues = store.restoreInputValues;
			setTimeout(restoreInputValues);
		}

		this.appRef.tick();
		delete store.state;
		delete store.restoreInputValues;
	}


public hmrOnDestroy(store: StoreType) {
		const cmpLocation = this.appRef.components.map((cmp) => cmp.location.nativeElement);
		// save state
		const state = this.appState._state;
		store.state = state;
		// recreate root elements
		store.disposeOldHosts = createNewHosts(cmpLocation);
		// save input values
		store.restoreInputValues  = createInputTransfer();
		// remove styles
		removeNgStyles();
	}


public hmrAfterDestroy(store: StoreType) {
		// display new elements
		store.disposeOldHosts();
		delete store.disposeOldHosts;
	}


class SqsEventSourceTest extends cdk.Stack {
  constructor(parent: cdk.App, id: string) {
    super(parent, id);

    const fn = new TestFunction(this, 'F');
    const topic = new sns.Topic(this, 'T');

    fn.addEventSource(new SnsEventSource(topic));
  }
}


export async function generateTransaction({
  connection,
  feePayer,
}: {
  connection: Connection;
  feePayer: PublicKey;
}): Promise<Transaction> {
  const recentBlockhash = await connection.getRecentBlockhash();
  const options: TransactionCtorFields = {
    feePayer,
    recentBlockhash: recentBlockhash.blockhash,
  };
  const transaction = new Transaction(options);
  return transaction;
}


export async function signAndSendTransaction(
  connection: Connection,
  signTransaction: SignerWalletAdapterProps["signTransaction"],
  transaction: Transaction
): Promise<string> {
  const signedTrans = await signTransaction(transaction);
  const signature = await connection.sendRawTransaction(
    signedTrans.serialize()
  );
  return signature;
}


() => {
        return this.listPagingPage(location, options);
      }


/// <reference lib="esnext.asynciterable" />
/** Class containing NetAppResourceQuotaLimits operations. */
export class NetAppResourceQuotaLimitsImpl
  implements NetAppResourceQuotaLimits {
  private readonly client: NetAppManagementClient;

  /**
   * Initialize a new instance of the class NetAppResourceQuotaLimits class.
   * @param client Reference to the service client
   */
  constructor(client: NetAppManagementClient) {
    this.client = client;
  }

  /**
   * Get the default and current limits for quotas
   * @param location The location
   * @param options The options parameters.
   */
  public list(
    location: string,
    options?: NetAppResourceQuotaLimitsListOptionalParams
  ): PagedAsyncIterableIterator<SubscriptionQuotaItem> {
    const iter = this.listPagingAll(location, options);
    return {
      next() {
        return iter.next();
      },
      [Symbol.asyncIterator]() {
        return this;
      },
      byPage: () => {
        return this.listPagingPage(location, options);
      }
    };
  }

  private async *listPagingPage(
    location: string,
    options?: NetAppResourceQuotaLimitsListOptionalParams
  ): AsyncIterableIterator<SubscriptionQuotaItem[]> {
    let result = await this._list(location, options);
    yield result.value || [];
  }

  private async *listPagingAll(
    location: string,
    options?: NetAppResourceQuotaLimitsListOptionalParams
  ): AsyncIterableIterator<SubscriptionQuotaItem> {
    for await (const page of this.listPagingPage(location, options)) {
      yield* page;
    }
  }

  /**
   * Get the default and current limits for quotas
   * @param location The location
   * @param options The options parameters.
   */
  private _list(
    location: string,
    options?: NetAppResourceQuotaLimitsListOptionalParams
  ): Promise<NetAppResourceQuotaLimitsListResponse> {
    return this.client.sendOperationRequest(
      { location, options },
      listOperationSpec
    );
  }

  /**
   * Get the default and current subscription quota limit
   * @param location The location
   * @param quotaLimitName The name of the Quota Limit
   * @param options The options parameters.
   */
  get(
    location: string,
    quotaLimitName: string,
    options?: NetAppResourceQuotaLimitsGetOptionalParams
  ): Promise<NetAppResourceQuotaLimitsGetResponse> {
    return this.client.sendOperationRequest(
      { location, quotaLimitName, options },
      getOperationSpec
    );
  }
}


/**
   * Get the default and current limits for quotas
   * @param location The location
   * @param options The options parameters.
   */
public list(
    location: string,
    options?: NetAppResourceQuotaLimitsListOptionalParams
  ): PagedAsyncIterableIterator<SubscriptionQuotaItem> {
    const iter = this.listPagingAll(location, options);
    return {
      next() {
        return iter.next();
      },
      [Symbol.asyncIterator]() {
        return this;
      },
      byPage: () => {
        return this.listPagingPage(location, options);
      }
    };
  }


private async *listPagingPage(
    location: string,
    options?: NetAppResourceQuotaLimitsListOptionalParams
  ): AsyncIterableIterator<SubscriptionQuotaItem[]> {
    let result = await this._list(location, options);
    yield result.value || [];
  }


private async *listPagingAll(
    location: string,
    options?: NetAppResourceQuotaLimitsListOptionalParams
  ): AsyncIterableIterator<SubscriptionQuotaItem> {
    for await (const page of this.listPagingPage(location, options)) {
      yield* page;
    }
  }


/**
   * Get the default and current limits for quotas
   * @param location The location
   * @param options The options parameters.
   */
private _list(
    location: string,
    options?: NetAppResourceQuotaLimitsListOptionalParams
  ): Promise<NetAppResourceQuotaLimitsListResponse> {
    return this.client.sendOperationRequest(
      { location, options },
      listOperationSpec
    );
  }


/**
   * Get the default and current subscription quota limit
   * @param location The location
   * @param quotaLimitName The name of the Quota Limit
   * @param options The options parameters.
   */
get(
    location: string,
    quotaLimitName: string,
    options?: NetAppResourceQuotaLimitsGetOptionalParams
  ): Promise<NetAppResourceQuotaLimitsGetResponse> {
    return this.client.sendOperationRequest(
      { location, quotaLimitName, options },
      getOperationSpec
    );
  }


(data) => data.dso


(col) => col.payload


(col) => this.initializeEmailAndTransform(col)


(col) => col.uuid


(uuid) => this.collectionService.getContentSource(uuid)


(rd: RemoteData<ContentSource>) => {
      this.initializeOriginalContentSource(rd.payload);
    }


() => {
        this.updateFieldTranslations();
      }


(updates: FieldUpdates) => updates[initialContentSource.uuid]


(update: FieldUpdate) => {
      if (update) {
        const field = update.field as ContentSource;
        let configId;
        if (hasValue(this.contentSource) && isNotEmpty(this.contentSource.metadataConfigs)) {
          configId = this.contentSource.metadataConfigs[0].id;
        }
        if (hasValue(field) && hasValue(field.metadataConfigId)) {
          configId = field.metadataConfigId;
        }
        if (hasValue(field)) {
          this.formGroup.patchValue({
            oaiSourceContainer: {
              oaiSource: field.oaiSource
            },
            oaiSetContainer: {
              oaiSetId: field.oaiSetId,
              metadataConfigId: configId
            },
            harvestTypeContainer: {
              harvestType: field.harvestType
            }
          });
          this.contentSource = cloneDeep(field);
        }
        this.contentSource.metadataConfigId = configId;
      }
    }


(metadataConfig: MetadataConfig) => Object.assign({ value: metadataConfig.id, label: metadataConfig.label })


(fieldModel: DynamicFormControlModel) => {
        this.updateFieldTranslation(fieldModel);
      }


(key) => {
        fieldModel.errorMessages[key] = this.translate.instant(this.ERROR_KEY_PREFIX + fieldModel.id + '.' + key);
      }


(option) => {
          if (hasNoValue(option.label)) {
            option.label = this.translate.instant(this.OPTIONS_KEY_PREFIX + fieldModel.id + '.' + option.value);
          }
        }


(col) => col.payload.uuid


(uuid) => this.collectionService.getHarvesterEndpoint(uuid)


(endpoint) => this.requestService.removeByHrefSubstring(endpoint)


(coll) => this.updateCollection(coll.payload) as Observable<string>


(uuid) => this.collectionService.updateContentSource(uuid, this.contentSource)


(result: ContentSource | INotification) => {
      if (hasValue((result as any).harvestType)) {
        this.clearNotifications();
        this.initializeOriginalContentSource(result as ContentSource);
        this.displayedNotifications.push(this.notificationsService.success(this.getNotificationTitle('saved'), this.getNotificationContent('saved')));
      } else {
        this.displayedNotifications.push(result as INotification);
      }
    }


(address) => address.trim()


(address) =>  operations.push({
          op: 'add',
          value: address,
          path: '/metadata/cris.harvesting.ccAddress'
        })


(response) => {
        if (!response.isSuccess) {
          return throwError('The collection update fails');
        }
        return collection.uuid;
      }


(fieldModel: DynamicInputModel) => {
        this.updateContentSourceField(fieldModel, updateHarvestType);
      }


(notification: INotification) => {
      this.notificationsService.remove(notification);
    }


/**
   * Initialize properties to setup the Field Update and Form
   */
ngOnInit(): void {
    this.notificationsPrefix = 'collection.edit.tabs.source.notifications.';
    this.discardTimeOut = environment.collection.edit.undoTimeout;
    this.url = this.router.url;
    if (this.url.indexOf('?') > 0) {
      this.url = this.url.substr(0, this.url.indexOf('?'));
    }
    this.formGroup = this.formService.createFormGroup(this.formModel);
    this.collectionRD$ = this.route.parent.data.pipe(first(), map((data) => data.dso));

    this.collectionRD$.pipe(
      getFirstSucceededRemoteData(),
      map((col) => col.payload),
      tap((col) => this.initializeEmailAndTransform(col)),
      map((col) => col.uuid),
      switchMap((uuid) => this.collectionService.getContentSource(uuid)),
      getFirstCompletedRemoteData()
    ).subscribe((rd: RemoteData<ContentSource>) => {
      this.initializeOriginalContentSource(rd.payload);
    });

    this.updateFieldTranslations();
    this.translate.onLangChange
      .subscribe(() => {
        this.updateFieldTranslations();
      });
  }


initializeEmailAndTransform(collection: Collection) {

    const adminAddress = collection ? collection.firstMetadataValue('cris.harvesting.email') : '';
    const preTransform = collection ? collection.firstMetadataValue('cris.harvesting.preTransform') : '';
    const postTransform = collection ? collection.firstMetadataValue('cris.harvesting.postTransform') : '';
    const forceSynchronization = collection ? collection.firstMetadataValue('cris.harvesting.forceSynchronization') === 'true' : false;
    const itemValidationEnabled = collection ? collection.firstMetadataValue('cris.harvesting.itemValidationEnabled') === 'true' : false;
    const recordValidationEnabled = collection ? collection.firstMetadataValue('cris.harvesting.recordValidationEnabled') === 'true' : false;
    const ccAddresses = collection ? collection.allMetadataValues('cris.harvesting.ccAddress').join(', ') : '';

    this.adminEmailModel.value = adminAddress;
    this.preTransformModel.value = preTransform;
    this.postTransformModel.value = postTransform;
    this.forceSynchronizationModel.value = forceSynchronization;
    this.itemValidationEnabledModel.value = itemValidationEnabled;
    this.recordValidationEnabledModel.value = recordValidationEnabled;
    this.ccAddressesModel.value = ccAddresses;

    this.formGroup.patchValue({
      adminEmailContainer: {
        adminEmail: adminAddress,
      },
      forceSynchronizationContainer: {
        forceSynchronization : forceSynchronization
      },
      ccAddressesContainer: {
        ccAddresses : ccAddresses
      },
      validationContainer: {
        itemValidationEnabled: itemValidationEnabled,
        recordValidationEnabled: recordValidationEnabled
      },
      transformContainer: {
        preTransform: preTransform,
        postTransform: postTransform
      }
    });
  }


/**
   * Initialize the Field Update and subscribe on it to fire updates to the form whenever it changes
   */
initializeOriginalContentSource(contentSource: ContentSource) {
    this.contentSource = contentSource;
    this.initialHarvestType = contentSource.harvestType;
    this.initializeMetadataConfigs();
    const initialContentSource = cloneDeep(this.contentSource);
    this.objectUpdatesService.initialize(this.url, [initialContentSource], new Date());
    this.update$ = this.objectUpdatesService.getFieldUpdates(this.url, [initialContentSource]).pipe(
      map((updates: FieldUpdates) => updates[initialContentSource.uuid])
    );
    this.updateSub = this.update$.subscribe((update: FieldUpdate) => {
      if (update) {
        const field = update.field as ContentSource;
        let configId;
        if (hasValue(this.contentSource) && isNotEmpty(this.contentSource.metadataConfigs)) {
          configId = this.contentSource.metadataConfigs[0].id;
        }
        if (hasValue(field) && hasValue(field.metadataConfigId)) {
          configId = field.metadataConfigId;
        }
        if (hasValue(field)) {
          this.formGroup.patchValue({
            oaiSourceContainer: {
              oaiSource: field.oaiSource
            },
            oaiSetContainer: {
              oaiSetId: field.oaiSetId,
              metadataConfigId: configId
            },
            harvestTypeContainer: {
              harvestType: field.harvestType
            }
          });
          this.contentSource = cloneDeep(field);
        }
        this.contentSource.metadataConfigId = configId;
      }
    });
  }


/**
   * Fill the metadataConfigIdModel's options using the contentSource's metadataConfigs property
   */
initializeMetadataConfigs() {
    this.metadataConfigIdModel.options = this.contentSource.metadataConfigs
      .map((metadataConfig: MetadataConfig) => Object.assign({ value: metadataConfig.id, label: metadataConfig.label }));
    if (this.metadataConfigIdModel.options.length > 0) {
      this.formGroup.patchValue({
        oaiSetContainer: {
          metadataConfigId: this.metadataConfigIdModel.options[0].value
        }
      });
    }
  }


/**
   * Used the update translations of errors and labels on init and on language change
   */
private updateFieldTranslations() {
    this.inputModels.forEach(
      (fieldModel: DynamicFormControlModel) => {
        this.updateFieldTranslation(fieldModel);
      }
    );
  }