() => (this._collectionsPouch as any).put({
                            _id: internalPrimary,
                            schemaHash,
                            schema: collection.schema.normalized,
                            version: collection.schema.version
                        })


() => {
                const cEvent = createChangeEvent(
                    'RxDatabase.collection',
                    this as any,
                    col
                );
                cEvent.data.v = col.name;
                cEvent.data.col = '_collections';

                (this.collections as any)[args.name] = col;

                if (!(this as any)[args.name]) {
                    Object.defineProperty(this, args.name, {
                        get: () => (this.collections as any)[args.name]
                    });
                }

                this.$emit(cEvent);

                return col;
            }


() => (this.collections as any)[args.name]


knownVersions => knownVersions
                .map(v => this._spawnPouchDB(collectionName, v))


v => this._spawnPouchDB(collectionName, v)


pouches => {
                return Promise.all(
                    pouches.map(
                        pouch => this.lockedRun(
                            () => pouch.destroy()
                        )
                    )
                );
            }


pouch => this.lockedRun(
                            () => pouch.destroy()
                        )


() => pouch.destroy()


() => (this.broadcastChannel as any).close()


sub => sub.unsubscribe()


key => (this.collections as any)[key]


col => col.destroy()


() => _removeUsedCombination(this.name, this.adapter)


() => removeDatabase(this.name, this.adapter)


ad => {
        if (ad === adapter)
            used = true;
    }


(pwHashDoc: any) => {

            /**
             * if pwHash was not saved, we save it,
             * this operation might throw because another instance runs save at the same time,
             * also we do not await the output because it does not mather
             */
            if (!pwHashDoc) {
                (rxDatabase._adminPouch as any).put({
                    _id: '_local/pwHash',
                    value: pwHash
                }).catch(() => null);
            }

            // different hash was already set by other instance
            if (pwHashDoc && rxDatabase.password && pwHash !== pwHashDoc.value) {
                return rxDatabase.destroy().then(() => {
                    throw newRxError('DB1', {
                        passwordHash: hash(rxDatabase.password),
                        existingPasswordHash: pwHashDoc.value
                    });
                });
            }
            return true;
        }


() => {
                    throw newRxError('DB1', {
                        passwordHash: hash(rxDatabase.password),
                        existingPasswordHash: pwHashDoc.value
                    });
                }


() => {
            // no doc exists -> insert
            return (rxDatabase._adminPouch as any).put({
                _id: '_local/storageToken',
                value: randomToken(10)
            })
                .catch(() => { })
                .then(() => promiseWait(0));
        }


() => promiseWait(0)


() => (rxDatabase._adminPouch as any).get('_local/storageToken')


(storageTokenDoc2: any) => storageTokenDoc2.value


() => (rxDatabase._collectionsPouch as any).allDocs({
            include_docs: true
        })


(data: any) => {
        const relevantDocs = data.rows
            .map((row: any) => row.doc)
            .filter((doc: any) => {
                const name = doc._id.split('-')[0];
                return name === collectionName;
            });
        return Promise.all(
            relevantDocs
                .map((doc: any) => rxDatabase.lockedRun(
                    () => (rxDatabase._collectionsPouch as any).remove(doc)
                ))
        ).then(() => relevantDocs.map((doc: any) => doc.version));
    }


(row: any) => row.doc


(doc: any) => {
                const name = doc._id.split('-')[0];
                return name === collectionName;
            }


(doc: any) => rxDatabase.lockedRun(
                    () => (rxDatabase._collectionsPouch as any).remove(doc)
                )


() => (rxDatabase._collectionsPouch as any).remove(doc)


() => relevantDocs.map((doc: any) => doc.version)


(doc: any) => doc.version


msg => {
        if (msg.st !== rxDatabase.storageToken) return; // not same storage-state
        if (msg.db === rxDatabase.token) return; // same db
        const changeEvent = changeEventfromJSON(msg.d);
        (rxDatabase.broadcastChannel$ as any).next(changeEvent);
    }


cE => {
            rxDatabase.$emit(cE);
        }


() => {
        // validate/insert password-hash
        return Promise.all([
            _ensureStorageTokenExists(rxDatabase),
            _preparePasswordHash(rxDatabase)
        ]);
    }


([storageToken]) => {
        rxDatabase.storageToken = storageToken;
        if (rxDatabase.multiInstance) {
            _prepareBroadcastChannel(rxDatabase);
        }
    }


() => {
            runPluginHooks('createRxDatabase', db);
            return db;
        }


collectionsData => Promise.all(
            collectionsData.rows
                .map((colDoc: any) => colDoc.id)
                .map((id: string) => {
                    const split = id.split('-');
                    const name = split[0];
                    const version = parseInt(split[1], 10);
                    const pouch = _spawnPouchDB(databaseName, adapter, name, version);
                    return pouch.destroy();
                })
        )


(colDoc: any) => colDoc.id


(id: string) => {
                    const split = id.split('-');
                    const name = split[0];
                    const version = parseInt(split[1], 10);
                    const pouch = _spawnPouchDB(databaseName, adapter, name, version);
                    return pouch.destroy();
                }


() => Promise.all([
            collectionsPouch.destroy(),
            adminPouch.destroy()
        ])


/**
     * removes all internal collection-info
     * only use this if you have to upgrade from a major rxdb-version
     * do NEVER use this to change the schema of a collection
     */
dangerousRemoveCollectionInfo(): Promise<void> {
        const colPouch: any = this._collectionsPouch;
        return colPouch.allDocs()
            .then((docsRes: any) => {
                return Promise.all(
                    docsRes.rows
                        .map((row: any) => ({
                            _id: row.key,
                            _rev: row.value.rev
                        }))
                        .map((doc: any) => colPouch.remove(doc._id, doc._rev))
                );
            }) as any;
    }


/**
     * spawns a new pouch-instance
     */
_spawnPouchDB(
        collectionName: string,
        schemaVersion: number,
        pouchSettings: PouchSettings = {}
    ): PouchDBInstance {
        return _spawnPouchDB(
            this.name, this.adapter,
            collectionName, schemaVersion,
            pouchSettings, this.pouchSettings
        );
    }


/**
     * returns a promise which resolves when the instance becomes leader
     */
waitForLeadership(): Promise<boolean> {
        if (!this.multiInstance) return Promise.resolve(true);
        return this.leaderElector.waitForLeadership();
    }


/**
     * This is the main handle-point for all change events
     * ChangeEvents created by this instance go:
     * RxDocument -> RxCollection -> RxDatabase.$emit -> MultiInstance
     * ChangeEvents created by other instances go:
     * MultiInstance -> RxDatabase.$emit -> RxCollection -> RxDatabase
     */
$emit(changeEvent: RxChangeEvent) {
        if (!changeEvent) return;

        // emit into own stream
        this.subject.next(changeEvent);

        // write to socket if event was created by this instance
        if (changeEvent.data.it === this.token) {
            writeToSocket(this as any, changeEvent);
        }
    }


/**
     * removes the collection-doc from this._collectionsPouch
     */
removeCollectionDoc(name: string, schema: any): Promise<void> {
        const docId = _collectionNamePrimary(name, schema);
        return (this._collectionsPouch as any)
            .get(docId)
            .then((doc: any) => this.lockedRun(
                () => (this._collectionsPouch as any).remove(doc)
            ));
    }


/**
     * create or fetch a collection
     */
collection<
        RxDocumentType = any,
        OrmMethods = {},
        StaticMethods = { [key: string]: any }
    >(args: RxCollectionCreator): Promise<
        RxCollection<
            RxDocumentType,
            OrmMethods,
            StaticMethods
        >
    > {
        if (typeof args === 'string')
            return Promise.resolve(this.collections[args]);

        args = Object.assign({}, args);

        (args as any).database = this;

        runPluginHooks('preCreateRxCollection', args);

        if (args.name.charAt(0) === '_') {
            throw newRxError('DB2', {
                name: args.name
            });
        }
        if ((this.collections as any)[args.name]) {
            throw newRxError('DB3', {
                name: args.name
            });
        }
        if (!args.schema) {
            throw newRxError('DB4', {
                name: args.name,
                args
            });
        }

        const internalPrimary = _collectionNamePrimary(args.name, args.schema);

        // check unallowed collection-names
        if (properties().includes(args.name)) {
            throw newRxError('DB5', {
                name: args.name
            });
        }

        const schema = createRxSchema(args.schema);
        args.schema = schema as any;

        // check schemaHash
        const schemaHash = schema.hash;

        let colDoc: any;
        let col: any;
        return this.lockedRun(
            () => (this._collectionsPouch as any).get(internalPrimary)
        )
            .catch(() => null)
            .then((collectionDoc: any) => {
                colDoc = collectionDoc;

                if (collectionDoc && collectionDoc.schemaHash !== schemaHash) {
                    // collection already exists with different schema, check if it has documents
                    const pouch = this._spawnPouchDB(args.name, args.schema.version, args.pouchSettings);
                    return pouch.find({
                        selector: {
                            _id: {}
                        },
                        limit: 1
                    }).then(oneDoc => {
                        if (oneDoc.docs.length !== 0) {
                            // we have one document
                            throw newRxError('DB6', {
                                name: args.name,
                                previousSchemaHash: collectionDoc.schemaHash,
                                schemaHash
                            });
                        }
                        return collectionDoc;
                    });
                } else return collectionDoc;
            })
            .then(() => createRxCollection(args as any))
            .then((collection: any) => {
                col = collection;
                if (
                    Object.keys(collection.schema.encryptedPaths).length > 0 &&
                    !this.password
                ) {
                    throw newRxError('DB7', {
                        name: args.name
                    });
                }

                if (!colDoc) {
                    return this.lockedRun(
                        () => (this._collectionsPouch as any).put({
                            _id: internalPrimary,
                            schemaHash,
                            schema: collection.schema.normalized,
                            version: collection.schema.version
                        })
                    ).catch(() => { });
                }
            })
            .then(() => {
                const cEvent = createChangeEvent(
                    'RxDatabase.collection',
                    this as any,
                    col
                );
                cEvent.data.v = col.name;
                cEvent.data.col = '_collections';

                (this.collections as any)[args.name] = col;

                if (!(this as any)[args.name]) {
                    Object.defineProperty(this, args.name, {
                        get: () => (this.collections as any)[args.name]
                    });
                }

                this.$emit(cEvent);

                return col;
            });
    }


/**
     * delete all data of the collection and its previous versions
     */
removeCollection(collectionName: string): Promise<void> {
        if ((this.collections as any)[collectionName])
            (this.collections as any)[collectionName].destroy();

        // remove schemas from internal db
        return _removeAllOfCollection(this as any, collectionName)
            // get all relevant pouchdb-instances
            .then(knownVersions => knownVersions
                .map(v => this._spawnPouchDB(collectionName, v)))
            // remove documents
            .then(pouches => {
                return Promise.all(
                    pouches.map(
                        pouch => this.lockedRun(
                            () => pouch.destroy()
                        )
                    )
                );
            })
            .then(() => { });
    }


/**
     * runs the given function between idleQueue-locking
     */
lockedRun<T>(fn: (...args: any[]) => T): T extends Promise<any> ? T : Promise<T> {
        return this.idleQueue.wrapCall(fn) as any;
    }


requestIdlePromise() {
        return this.idleQueue.requestIdlePromise();
    }


/**
     * Export database to a JSON friendly format.
     * @param _decrypted
     * When true, all encrypted values will be decrypted.
     */
dump(_decrypted: boolean, _collections?: string[]): Promise<RxDumpDatabase<Collections>>;


dump(_decrypted?: false, _collections?: string[]): Promise<RxDumpDatabaseAny<Collections>>;


dump(_decrypted: boolean = false, _collections?: string[]): Promise<any> {
        throw pluginMissing('json-dump');
    }


/**
     * Import the parsed JSON export into the collection.
     * @param _exportedJSON The previously exported data from the `<db>.dump()` method.
     * @note When an interface is loaded in this collection all base properties of the type are typed as `any`
     * since data could be encrypted.
     */
importDump(_exportedJSON: RxDumpDatabaseAny<Collections>): Promise<void> {
        throw pluginMissing('json-dump');
    }


/**
     * spawn server
     */
server(_options?: ServerOptions): {
        app: any;
        pouchApp: any;
        server: any;
    } {
        throw pluginMissing('server');
    }


/**
     * destroys the database-instance and all collections
     */
public destroy(): Promise<boolean> {
        if (this.destroyed) return Promise.resolve(false);
        runPluginHooks('preDestroyRxDatabase', this);
        DB_COUNT--;
        this.destroyed = true;

        if (this.broadcastChannel) {
            /**
             * The broadcast-channel gets closed lazy
             * to ensure that all pending change-events
             * get emitted
             */
            setTimeout(() => (this.broadcastChannel as any).close(), 1000);
        }

        if (this._leaderElector)
            this._leaderElector.destroy();

        this._subs.map(sub => sub.unsubscribe());

        // destroy all collections
        return Promise.all(Object.keys(this.collections)
            .map(key => (this.collections as any)[key])
            .map(col => col.destroy())
        )
            // remove combination from USED_COMBINATIONS-map
            .then(() => _removeUsedCombination(this.name, this.adapter))
            .then(() => true);
    }


/**
     * deletes the database and its stored data
     */
remove(): Promise<void> {
        return this
            .destroy()
            .then(() => removeDatabase(this.name, this.adapter));
    }


/* -------------------------------------------- */
/* Definindo um conjunto de types com optional operator
/* -------------------------------------------- */
type AccountInfo = {
  id: number;
  name: string;
  email?: string; // ? optional operator
}


/* -------------------------------------------- */
/* Definindo um outro conjunto de types
/* -------------------------------------------- */
type CharInfo = {
  nickname: string;
  level?: number;
}


/* -------------------------------------------- */
/* Fazendo a intersecção de dois types
/* -------------------------------------------- */
type PlayerInfo = AccountInfo & CharInfo


export class LearnplaceNavParams {
    static learnplaceObjectId: number;
    static learnplaceName: string;
}


export class UserListaFilmesController {
  constructor(
    @repository(UserRepository) protected userRepository: UserRepository,
  ) { }

  @get('/users/{id}/lista-filmes', {
    responses: {
      '200': {
        description: 'User has one ListaFilmes',
        content: {
          'application/json': {
            schema: getModelSchemaRef(ListaFilmes),
          },
        },
      },
    },
  })
  async get(
    @param.path.number('id') id: number,
    @param.query.object('filter') filter?: Filter<ListaFilmes>,
  ): Promise<ListaFilmes> {
    return this.userRepository.user_lista(id).get(filter);
  }

  @post('/users/{id}/lista-filmes', {
    responses: {
      '200': {
        description: 'User model instance',
        content: {'application/json': {schema: getModelSchemaRef(ListaFilmes)}},
      },
    },
  })
  async create(
    @param.path.number('id') id: typeof User.prototype.id,
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(ListaFilmes, {
            title: 'NewListaFilmesInUser',
            exclude: ['id_lista'],
            optional: ['userId']
          }),
        },
      },
    }) listaFilmes: Omit<ListaFilmes, 'id_lista'>,
  ): Promise<ListaFilmes> {
    return this.userRepository.user_lista(id).create(listaFilmes);
  }

  @patch('/users/{id}/lista-filmes', {
    responses: {
      '200': {
        description: 'User.ListaFilmes PATCH success count',
        content: {'application/json': {schema: CountSchema}},
      },
    },
  })
  async patch(
    @param.path.number('id') id: number,
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(ListaFilmes, {partial: true}),
        },
      },
    })
    listaFilmes: Partial<ListaFilmes>,
    @param.query.object('where', getWhereSchemaFor(ListaFilmes)) where?: Where<ListaFilmes>,
  ): Promise<Count> {
    return this.userRepository.user_lista(id).patch(listaFilmes, where);
  }

  @del('/users/{id}/lista-filmes', {
    responses: {
      '200': {
        description: 'User.ListaFilmes DELETE success count',
        content: {'application/json': {schema: CountSchema}},
      },
    },
  })
  async delete(
    @param.path.number('id') id: number,
    @param.query.object('where', getWhereSchemaFor(ListaFilmes)) where?: Where<ListaFilmes>,
  ): Promise<Count> {
    return this.userRepository.user_lista(id).delete(where);
  }
}


@get('/users/{id}/lista-filmes', {
    responses: {
      '200': {
        description: 'User has one ListaFilmes',
        content: {
          'application/json': {
            schema: getModelSchemaRef(ListaFilmes),
          },
        },
      },
    },
  })
  async get(
    @param.path.number('id') id: number,
    @param.query.object('filter') filter?: Filter<ListaFilmes>,
  ): Promise<ListaFilmes> {
    return this.userRepository.user_lista(id).get(filter);
  }


@post('/users/{id}/lista-filmes', {
    responses: {
      '200': {
        description: 'User model instance',
        content: {'application/json': {schema: getModelSchemaRef(ListaFilmes)}},
      },
    },
  })
  async create(
    @param.path.number('id') id: typeof User.prototype.id,
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(ListaFilmes, {
            title: 'NewListaFilmesInUser',
            exclude: ['id_lista'],
            optional: ['userId']
          }),
        },
      },
    }) listaFilmes: Omit<ListaFilmes, 'id_lista'>,
  ): Promise<ListaFilmes> {
    return this.userRepository.user_lista(id).create(listaFilmes);
  }


@patch('/users/{id}/lista-filmes', {
    responses: {
      '200': {
        description: 'User.ListaFilmes PATCH success count',
        content: {'application/json': {schema: CountSchema}},
      },
    },
  })
  async patch(
    @param.path.number('id') id: number,
    @requestBody({
      content: {
        'application/json': {
          schema: getModelSchemaRef(ListaFilmes, {partial: true}),
        },
      },
    })
    listaFilmes: Partial<ListaFilmes>,
    @param.query.object('where', getWhereSchemaFor(ListaFilmes)) where?: Where<ListaFilmes>,
  ): Promise<Count> {
    return this.userRepository.user_lista(id).patch(listaFilmes, where);
  }


@del('/users/{id}/lista-filmes', {
    responses: {
      '200': {
        description: 'User.ListaFilmes DELETE success count',
        content: {'application/json': {schema: CountSchema}},
      },
    },
  })
  async delete(
    @param.path.number('id') id: number,
    @param.query.object('where', getWhereSchemaFor(ListaFilmes)) where?: Where<ListaFilmes>,
  ): Promise<Count> {
    return this.userRepository.user_lista(id).delete(where);
  }


@NgModule({
  imports: [
    CommonModule,
    ConfigModule.withConfig(<ViewConfig>defaultScrollConfig),
    ConfigModule.withConfig(<CmsConfig>{
      cmsComponents: {
        CMSProductListComponent: {
          component: ProductListComponent,
        },
        ProductGridComponent: {
          component: ProductListComponent,
        },
        SearchResultsListComponent: {
          component: ProductListComponent,
        },
        ProductRefinementComponent: {
          component: ProductFacetNavigationComponent,
        },
      },
    }),
    RouterModule,
    MediaModule,
    AddToCartModule,
    ItemCounterModule,
    ListNavigationModule,
    UrlModule,
    I18nModule,
    StarRatingModule,
    IconModule,
    SpinnerModule,
    InfiniteScrollModule,
    ViewConfigModule,
    ProductVariantSelectorModule,
    FeaturesConfigModule,
  ],
  declarations: [
    ProductListComponent,
    ProductFacetNavigationComponent,
    ProductListItemComponent,
    ProductGridItemComponent,
    ProductViewComponent,
    ProductScrollComponent,
  ],
  exports: [
    ProductListComponent,
    ProductFacetNavigationComponent,
    ProductListItemComponent,
    ProductGridItemComponent,
    ProductViewComponent,
    ProductScrollComponent,
  ],
  entryComponents: [ProductListComponent, ProductFacetNavigationComponent],
})
export class ProductListModule {}


(config: d.Config, stencilSys: d.CompilerSystem, inMemoryFs: d.InMemoryFileSystem, tsSys: ts.System) => {
  const realpath = (path: string) => {
    const rp = stencilSys.realpathSync(path);
    if (isString(rp)) {
      return rp;
    }
    return path;
  };

  const getAccessibleFileSystemEntries = (path: string) => {
    try {
      const entries = stencilSys.readDirSync(path || '.').sort();
      const files: string[] = [];
      const directories: string[] = [];

      for (const absPath of entries) {
        // This is necessary because on some file system node fails to exclude
        // "." and "..". See https://github.com/nodejs/node/issues/4002
        const stat = inMemoryFs.statSync(absPath);
        if (!stat) {
          continue;
        }

        const entry = basename(absPath);
        if (stat.isFile) {
          files.push(entry);
        } else if (stat.isDirectory) {
          directories.push(entry);
        }
      }
      return { files, directories };
    } catch (e) {
      return { files: [], directories: [] };
    }
  };

  tsSys.createDirectory = p => {
    stencilSys.createDirSync(p, { recursive: true });
  };

  tsSys.directoryExists = p => {
    const s = inMemoryFs.statSync(p);
    return s.isDirectory;
  };

  tsSys.exit = stencilSys.exit;

  tsSys.fileExists = p => {
    let filePath = p;

    if (isRemoteUrl(p)) {
      filePath = getTypescriptPathFromUrl(config, tsSys.getExecutingFilePath(), p);
    }

    const s = inMemoryFs.statSync(filePath);
    return !!(s && s.isFile);
  };

  tsSys.getCurrentDirectory = stencilSys.getCurrentDirectory;

  tsSys.getExecutingFilePath = stencilSys.getCompilerExecutingPath;

  tsSys.getDirectories = p => {
    const items = stencilSys.readDirSync(p);
    return items.filter(itemPath => {
      const s = inMemoryFs.statSync(itemPath);
      return !!(s && s.exists && s.isDirectory);
    });
  };

  tsSys.readDirectory = (path, extensions, exclude, include, depth) => {
    const cwd = stencilSys.getCurrentDirectory();
    return (ts as any).matchFiles(path, extensions, exclude, include, IS_CASE_SENSITIVE_FILE_NAMES, cwd, depth, getAccessibleFileSystemEntries, realpath);
  };

  tsSys.readFile = p => {
    let filePath = p;
    const isUrl = isRemoteUrl(p);

    if (isUrl) {
      filePath = getTypescriptPathFromUrl(config, tsSys.getExecutingFilePath(), p);
    }

    let content = inMemoryFs.readFileSync(filePath, { useCache: isUrl });

    if (typeof content !== 'string' && isUrl) {
      if (IS_WEB_WORKER_ENV) {
        content = fetchUrlSync(p);
        if (typeof content === 'string') {
          inMemoryFs.writeFile(filePath, content);
        }
      } else {
        config.logger.error(`ts.sys can only request http resources from within a web worker: ${p}`);
      }
    }

    return content;
  };

  tsSys.writeFile = (p, data) => inMemoryFs.writeFile(p, data);

  return tsSys;
}


(path: string) => {
    const rp = stencilSys.realpathSync(path);
    if (isString(rp)) {
      return rp;
    }
    return path;
  }


(path: string) => {
    try {
      const entries = stencilSys.readDirSync(path || '.').sort();
      const files: string[] = [];
      const directories: string[] = [];

      for (const absPath of entries) {
        // This is necessary because on some file system node fails to exclude
        // "." and "..". See https://github.com/nodejs/node/issues/4002
        const stat = inMemoryFs.statSync(absPath);
        if (!stat) {
          continue;
        }

        const entry = basename(absPath);
        if (stat.isFile) {
          files.push(entry);
        } else if (stat.isDirectory) {
          directories.push(entry);
        }
      }
      return { files, directories };
    } catch (e) {
      return { files: [], directories: [] };
    }
  }


p => {
    stencilSys.createDirSync(p, { recursive: true });
  }


p => {
    const s = inMemoryFs.statSync(p);
    return s.isDirectory;
  }


p => {
    let filePath = p;

    if (isRemoteUrl(p)) {
      filePath = getTypescriptPathFromUrl(config, tsSys.getExecutingFilePath(), p);
    }

    const s = inMemoryFs.statSync(filePath);
    return !!(s && s.isFile);
  }


p => {
    const items = stencilSys.readDirSync(p);
    return items.filter(itemPath => {
      const s = inMemoryFs.statSync(itemPath);
      return !!(s && s.exists && s.isDirectory);
    });
  }


itemPath => {
      const s = inMemoryFs.statSync(itemPath);
      return !!(s && s.exists && s.isDirectory);
    }


(path, extensions, exclude, include, depth) => {
    const cwd = stencilSys.getCurrentDirectory();
    return (ts as any).matchFiles(path, extensions, exclude, include, IS_CASE_SENSITIVE_FILE_NAMES, cwd, depth, getAccessibleFileSystemEntries, realpath);
  }


p => {
    let filePath = p;
    const isUrl = isRemoteUrl(p);

    if (isUrl) {
      filePath = getTypescriptPathFromUrl(config, tsSys.getExecutingFilePath(), p);
    }

    let content = inMemoryFs.readFileSync(filePath, { useCache: isUrl });

    if (typeof content !== 'string' && isUrl) {
      if (IS_WEB_WORKER_ENV) {
        content = fetchUrlSync(p);
        if (typeof content === 'string') {
          inMemoryFs.writeFile(filePath, content);
        }
      } else {
        config.logger.error(`ts.sys can only request http resources from within a web worker: ${p}`);
      }
    }

    return content;
  }


(p, data) => inMemoryFs.writeFile(p, data)


(stencilSys: d.CompilerSystem, tsSys: ts.System) => {
  tsSys.watchDirectory = (p, cb, recursive) => {
    const watcher = stencilSys.watchDirectory(
      p,
      filePath => {
        cb(filePath);
      },
      recursive,
    );
    return {
      close() {
        watcher.close();
      },
    };
  };

  tsSys.watchFile = (p, cb) => {
    const watcher = stencilSys.watchFile(p, (filePath, eventKind) => {
      if (eventKind === 'fileAdd') {
        cb(filePath, ts.FileWatcherEventKind.Created);
      } else if (eventKind === 'fileUpdate') {
        cb(filePath, ts.FileWatcherEventKind.Changed);
      } else if (eventKind === 'fileDelete') {
        cb(filePath, ts.FileWatcherEventKind.Deleted);
      }
    });
    return {
      close() {
        watcher.close();
      },
    };
  };
}


(p, cb, recursive) => {
    const watcher = stencilSys.watchDirectory(
      p,
      filePath => {
        cb(filePath);
      },
      recursive,
    );
    return {
      close() {
        watcher.close();
      },
    };
  }


filePath => {
        cb(filePath);
      }


(p, cb) => {
    const watcher = stencilSys.watchFile(p, (filePath, eventKind) => {
      if (eventKind === 'fileAdd') {
        cb(filePath, ts.FileWatcherEventKind.Created);
      } else if (eventKind === 'fileUpdate') {
        cb(filePath, ts.FileWatcherEventKind.Changed);
      } else if (eventKind === 'fileDelete') {
        cb(filePath, ts.FileWatcherEventKind.Deleted);
      }
    });
    return {
      close() {
        watcher.close();
      },
    };
  }


(filePath, eventKind) => {
      if (eventKind === 'fileAdd') {
        cb(filePath, ts.FileWatcherEventKind.Created);
      } else if (eventKind === 'fileUpdate') {
        cb(filePath, ts.FileWatcherEventKind.Changed);
      } else if (eventKind === 'fileDelete') {
        cb(filePath, ts.FileWatcherEventKind.Deleted);
      }
    }


(config: d.Config, inMemoryFs: d.InMemoryFileSystem) => {
  if (!(ts as any).__patched) {
    if (config.sys) {
      patchTsSystemFileSystem(config, config.sys, inMemoryFs, ts.sys);
      patchTsSystemWatch(config.sys, ts.sys);
    }
    patchTypeScriptResolveModule(config, inMemoryFs);
    patchTypeScriptGetParsedCommandLineOfConfigFile();
    (ts as any).__patched = true;
  }
}


() => {
  if (!ts.sys) {
    // patches just the bare minimum
    // if ts.sys already exists then it must be node ts.sys
    // otherwise we're either browser or deno
    // will be updated later on with the stencil sys
    ts.sys = {
      args: [],
      createDirectory: noop,
      directoryExists: () => false,
      exit: noop,
      fileExists: () => false,
      getCurrentDirectory,
      getDirectories: () => [],
      getExecutingFilePath: () => './',
      readDirectory: () => [],
      readFile: noop,
      newLine: '\n',
      resolvePath: resolve,
      useCaseSensitiveFileNames: false,
      write: noop,
      writeFile: noop,
    };
  }
}


(config: d.Config, tsExecutingUrl: string, url: string) => {
  const tsBaseUrl = new URL('..', tsExecutingUrl).href;
  if (url.startsWith(tsBaseUrl)) {
    const tsFilePath = url.replace(tsBaseUrl, '/');
    const tsNodePath = config.sys.getLocalModulePath({ rootDir: config.rootDir, moduleId: 'typescript', path: tsFilePath });
    return normalizePath(tsNodePath);
  }
  return url;
}


() => {
  const orgGetParsedCommandLineOfConfigFile = ts.getParsedCommandLineOfConfigFile;

  ts.getParsedCommandLineOfConfigFile = (configFileName, optionsToExtend, host, extendedConfigCache) => {
    const results = orgGetParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache);

    // manually filter out any .spec or .e2e files
    results.fileNames = results.fileNames.filter(f => {
      // filter e2e tests
      if (f.includes('.e2e.') || f.includes('/e2e.')) {
        return false;
      }
      // filter spec tests
      if (f.includes('.spec.') || f.includes('/spec.')) {
        return false;
      }
      return true;
    });

    return results;
  };
}


(configFileName, optionsToExtend, host, extendedConfigCache) => {
    const results = orgGetParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache);

    // manually filter out any .spec or .e2e files
    results.fileNames = results.fileNames.filter(f => {
      // filter e2e tests
      if (f.includes('.e2e.') || f.includes('/e2e.')) {
        return false;
      }
      // filter spec tests
      if (f.includes('.spec.') || f.includes('/spec.')) {
        return false;
      }
      return true;
    });

    return results;
  }


f => {
      // filter e2e tests
      if (f.includes('.e2e.') || f.includes('/e2e.')) {
        return false;
      }
      // filter spec tests
      if (f.includes('.spec.') || f.includes('/spec.')) {
        return false;
      }
      return true;
    }


close() {
        watcher.close();
      }


export function rootContainer(container: any, opts: any) {
  return React.createElement(GlobalStyles, opts, container);
}


export function innerProvider(container: any) {
  return React.createElement(Foo, { title: 'innerProvider' }, container);
}


export function i18nProvider(container: any) {
  return React.createElement(Foo, { title: 'i18nProvider' }, container);
}


export function dataflowProvider(container: any) {
  return React.createElement(Foo, { title: 'dataflowProvider' }, container);
}


export function outerProvider(container: any) {
  return React.createElement(Foo, { title: 'outerProvider' }, container);
}


function Foo(props: any) {
  return <div>{props.children}</div>;
}


type cases = [
  Expect<Equal<LastIndexOf<[1, 2, 3, 2, 1], 2>, 3>>,
  Expect<Equal<LastIndexOf<[2, 6, 3, 8, 4, 1, 7, 3, 9], 3>, 7>>,
  Expect<Equal<LastIndexOf<[0, 0, 0], 2>, -1>>,
  Expect<Equal<LastIndexOf<[string, 2, number, 'a', number, 1], number>, 4>>,
  Expect<Equal<LastIndexOf<[string, any, 1, number, 'a', any, 1], any>, 5>>,
]


// Persistent storage for user settings that supports a limited set of keys.
export class Settings {
  static readonly STORAGE_KEY = 'settings';

  private readonly settings = new Map<string, string>();

  constructor(
      private storage: Storage = window.localStorage,
      private validKeys: string[] = Object.values(SettingsKey)) {
    this.loadSettings();
  }

  get(key: string) {
    return this.settings.get(key);
  }

  set(key: string, value: string) {
    if (!this.isValidSetting(key)) {
      throw new Error(`Cannot set invalid key ${key}`);
    }
    this.settings.set(key, value);
    this.storeSettings();
  }

  remove(key: string) {
    this.settings.delete(key);
    this.storeSettings();
  }

  isValidSetting(key: string) {
    return this.validKeys.includes(key);
  }

  private loadSettings() {
    const settingsJson = this.storage.getItem(Settings.STORAGE_KEY);
    if (!settingsJson) {
      console.debug(`No settings found in storage`);
      return;
    }
    const storageSettings = JSON.parse(settingsJson);
    for (const key in storageSettings) {
      if (storageSettings.hasOwnProperty(key)) {
        this.settings.set(key, storageSettings[key]);
      }
    }
  }

  private storeSettings() {
    const storageSettings: StorageSettings = {};
    for (const [key, value] of this.settings) {
      storageSettings[key] = value;
    }
    const storageSettingsJson = JSON.stringify(storageSettings);
    this.storage.setItem(Settings.STORAGE_KEY, storageSettingsJson);
  }
}


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


// Setting keys supported by the `Settings` class.
export enum SettingsKey {
  VPN_WARNING_DISMISSED = 'vpn-warning-dismissed',
  AUTO_CONNECT_DIALOG_DISMISSED = 'auto-connect-dialog-dismissed',
  PRIVACY_ACK = 'privacy-ack'
}


get(key: string) {
    return this.settings.get(key);
  }


set(key: string, value: string) {
    if (!this.isValidSetting(key)) {
      throw new Error(`Cannot set invalid key ${key}`);
    }
    this.settings.set(key, value);
    this.storeSettings();
  }


remove(key: string) {
    this.settings.delete(key);
    this.storeSettings();
  }


isValidSetting(key: string) {
    return this.validKeys.includes(key);
  }


private loadSettings() {
    const settingsJson = this.storage.getItem(Settings.STORAGE_KEY);
    if (!settingsJson) {
      console.debug(`No settings found in storage`);
      return;
    }
    const storageSettings = JSON.parse(settingsJson);
    for (const key in storageSettings) {
      if (storageSettings.hasOwnProperty(key)) {
        this.settings.set(key, storageSettings[key]);
      }
    }
  }


private storeSettings() {
    const storageSettings: StorageSettings = {};
    for (const [key, value] of this.settings) {
      storageSettings[key] = value;
    }
    const storageSettingsJson = JSON.stringify(storageSettings);
    this.storage.setItem(Settings.STORAGE_KEY, storageSettingsJson);
  }


export class PINRequest {
    'AdditionalInput'?: string;
    'CardholderPIN'?: CardholderPIN;
    'KeyReference'?: string;
    'MaxWaitingTime'?: number;
    'PINEncAlgorithm'?: string;
    'PINFormat'?: PINRequest.PINFormatEnum;
    'PINRequestType': PINRequestType;
    'PINVerifMethod'?: string;

    static discriminator: string | undefined = undefined;

    static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [
        {
            "name": "AdditionalInput",
            "baseName": "AdditionalInput",
            "type": "string"
        },
        {
            "name": "CardholderPIN",
            "baseName": "CardholderPIN",
            "type": "CardholderPIN"
        },
        {
            "name": "KeyReference",
            "baseName": "KeyReference",
            "type": "string"
        },
        {
            "name": "MaxWaitingTime",
            "baseName": "MaxWaitingTime",
            "type": "number"
        },
        {
            "name": "PINEncAlgorithm",
            "baseName": "PINEncAlgorithm",
            "type": "string"
        },
        {
            "name": "PINFormat",
            "baseName": "PINFormat",
            "type": "PINRequest.PINFormatEnum"
        },
        {
            "name": "PINRequestType",
            "baseName": "PINRequestType",
            "type": "PINRequestType"
        },
        {
            "name": "PINVerifMethod",
            "baseName": "PINVerifMethod",
            "type": "string"
        }    ];

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


export enum PINFormatEnum {
        Iso0 = <any> 'ISO0',
        Iso1 = <any> 'ISO1',
        Iso2 = <any> 'ISO2',
        Iso3 = <any> 'ISO3'
    }


static getAttributeTypeMap() {
        return PINRequest.attributeTypeMap;
    }


function setup() {
  const actions = {
    increment: spy(),
    incrementIfOdd: spy(),
    incrementAsync: spy(),
    decrement: spy()
  };
  const component = shallow(<Counter counter={1} {...actions} />);
  return {
    component,
    actions,
    buttons: component.find('button'),
    p: component.find('.counter')
  };
}


() => {
  it('should should display count', () => {
    const { p } = setup();
    expect(p.text()).toMatch(/^1$/);
  });

  it('should first button should call increment', () => {
    const { buttons, actions } = setup();
    buttons.at(0).simulate('click');
    expect(actions.increment.called).toBe(true);
  });

  it('should match exact snapshot', () => {
    const { actions } = setup();
    const counter = (
      <div>
        <Router>
          <Counter counter={1} {...actions} />
        </Router>
      </div>
    );
    const tree = renderer.create(counter).toJSON();

    expect(tree).toMatchSnapshot();
  }


() => {
    const { p } = setup();
    expect(p.text()).toMatch(/^1$/);
  }


() => {
    const { buttons, actions } = setup();
    buttons.at(0).simulate('click');
    expect(actions.increment.called).toBe(true);
  }


() => {
    const { actions } = setup();
    const counter = (
      <div>
        <Router>
          <Counter counter={1} {...actions} />
        </Router>
      </div>


() => {
    const { buttons, actions } = setup();
    buttons.at(1).simulate('click');
    expect(actions.decrement.called).toBe(true);
  }


() => {
    const { buttons, actions } = setup();
    buttons.at(2).simulate('click');
    expect(actions.incrementIfOdd.called).toBe(true);
  }


() => {
    const { buttons, actions } = setup();
    buttons.at(3).simulate('click');
    expect(actions.incrementAsync.called).toBe(true);
  }


export function initializeLocalization() {
  // messages.js are generated by ``yarn lingui-compile``
  languages.forEach(
    (code) => (catalogs[code] = require(`../../locale/${code}/messages.js`))
  );

  currentUILanguage = userSettings.UILanguage;
  // if the language in the settings isn't one this version supports,
  // or if there was no setting for this and we have the default (empty string)
  if (languages.indexOf(currentUILanguage) < 0) {
    // See if their OS's language is one we support
    currentUILanguage = remote.app.getLocale();
    // Do we have a localization for that language? If not, the default is English.
    if (languages.indexOf(currentUILanguage) < 0) {
      currentUILanguage = "en";
    }
  }

  i18n = setupI18n({
    language: currentUILanguage,
    catalogs,
  }).use(currentUILanguage);

  moment.locale(currentUILanguage); // this is a global change

  olacRoles = loadOLACRoles();
}


export function setUILanguage(code: string): void {
  currentUILanguage = code;
  i18n.use(code);
  userSettings.UILanguage = code;
  remote.getCurrentWindow().reload();
}


// call to this must have the comment /*18n*/ in order for the lingui scanner to find it
// e.g. translationMessage(/*18n*/{id: "foobar"})
export function translateMessage(arg: { id: string }): string {
  if (i18n) {
    return i18n._(arg.id);
  } // unit testing
  else return arg.id;
}


export function translateFileType(englishTypeName: string): string {
  switch (englishTypeName) {
    case "Project":
      return i18n._(t`Project`);
    case "Session":
      return i18n._(t`Session`);
    case "Person":
      return i18n._(t`Person`);
    case "Video":
      return i18n._(t`Video`);
    case "Image":
      return i18n._(t`Image`);
    case "Audio":
      return i18n._(t`Audio`);
    default:
      return englishTypeName; // e.g. "mp3"
  }
}


export function translateFieldLabel(fieldDef: FieldDefinition): string {
  if (fieldDef === undefined) {
    return "LABEL ERROR";
  }
  return getMatch(fields, fieldDef.englishLabel, "fields.csv");
}


export function translateTooltip(fieldDef: FieldDefinition): string {
  if (!fieldDef.tooltip) {
    return "";
  }
  return fieldDef.tooltip ? getMatch(tips, fieldDef.tooltip, "tips.csv") : "";
}


export function translateTooltipNotice(notice: string): string {
  return getMatch(tips, notice, "tips.csv");
}


export function translateSpecialInfo(fieldDef: FieldDefinition): string {
  if (!fieldDef.specialInfo) {
    return "";
  }
  return fieldDef.specialInfo
    ? getMatch(tips, fieldDef.specialInfo, "tips.csv")
    : "";
}


export function translateAccessProtocol(choice: string): string {
  return getMatch(accessProtocols, choice, "accessProtocols.csv");
}


export function translateChoice(choice: string, fieldName?: string): string {
  return getMatch(choices, choice, "choices.csv", fieldName);
}


export function translateRole(role: string) {
  const roleChoice: IChoice | undefined = olacRoles.find((c) => c.id === role);

  return getMatch(roles, roleChoice?.label || role, "roles.csv");
}


export function translateGenre(genre: string) {
  return getMatch(genres, genre, "genres.csv");
}


function getMatch(
  lines: any[],
  s: string,
  fileThatShouldHaveThis: string,
  fieldName?: string
): string {
  const match = lines.find((f) => f.en === s);

  if (currentUILanguage === "ps") {
    // do we have a column for english for this?
    if (match && match["en"]) return s + "✓";
    else {
      if (s && s.length > 0) {
        // at the moment we're not asking translators to take on translating country names, so we don't expect to find them in the locale/choices.csv file
        if (!fieldName || fieldName.toLowerCase().indexOf("country") < 0) {
          const forField = fieldName ? `for field ${fieldName}` : "";

          console.warn(
            `TODO: Add \t"${s}"\t to locale/${fileThatShouldHaveThis} ${forField}`
          );
        }
        return "MISSING-" + s;
      }
    }
  }

  if (match && match[currentUILanguage]) {
    return match[currentUILanguage];
  }
  //console.log(`No ${currentUILanguage} translation for ${s}, "${s}"`);
  return s;
}


(code) => (catalogs[code] = require(`../../locale/${code}/messages.js`))


(c) => c.id === role


(f) => f.en === s


() => {
    let props: NodeExecutionsTableProps;
    let apiContext: APIContextValue;
    let executionContext: ExecutionContextData;
    let dataCache: ExecutionDataCache;
    let requestConfig: RequestConfig;
    let mockNodeExecutions: NodeExecution[];
    let mockGetExecution: jest.Mock<ReturnType<typeof getExecution>>;
    let mockGetTask: jest.Mock<ReturnType<typeof getTask>>;
    let mockListTaskExecutions: jest.Mock<ReturnType<
        typeof listTaskExecutions
    >>;
    let mockListTaskExecutionChildren: jest.Mock<ReturnType<
        typeof listTaskExecutionChildren
    >>;

    beforeEach(() => {
        const {
            nodeExecutions,
            workflow,
            workflowExecution
        } = createMockExecutionEntities({
            workflowName: 'SampleWorkflow',
            nodeExecutionCount: 2
        });

        mockNodeExecutions = nodeExecutions;

        mockListTaskExecutions = jest.fn().mockResolvedValue({ entities: [] });
        mockListTaskExecutionChildren = jest
            .fn()
            .mockResolvedValue({ entities: [] });
        mockGetExecution = jest
            .fn()
            .mockImplementation(async (id: WorkflowExecutionIdentifier) => {
                return { ...createMockExecution(id.name), id };
            });
        mockGetTask = jest.fn().mockImplementation(async (id: Identifier) => {
            return { template: { ...mockTasks[0].template, id } };
        });

        apiContext = mockAPIContextValue({
            getExecution: mockGetExecution,
            getTask: mockGetTask,
            listTaskExecutions: mockListTaskExecutions,
            listTaskExecutionChildren: mockListTaskExecutionChildren
        });

        dataCache = createExecutionDataCache(apiContext);
        dataCache.insertWorkflow(workflow);
        dataCache.insertWorkflowExecutionReference(
            workflowExecution.id,
            workflow.id
        );

        requestConfig = {};
        executionContext = {
            execution: workflowExecution,
            terminateExecution: jest.fn().mockRejectedValue('Not Implemented')
        };

        props = {
            value: nodeExecutions,
            lastError: null,
            state: State.from(fetchStates.LOADED),
            moreItemsAvailable: false,
            fetch: jest.fn()
        };
    });

    const renderTable = () =>
        render(
            <APIContext.Provider value={apiContext}>
                <NodeExecutionsRequestConfigContext.Provider
                    value={requestConfig}
                >
                    <ExecutionContext.Provider value={executionContext}>
                        <ExecutionDataCacheContext.Provider value={dataCache}>
                            <NodeExecutionsTable {...props} />
                        </ExecutionDataCacheContext.Provider>
                    </ExecutionContext.Provider>
                </NodeExecutionsRequestConfigContext.Provider>
            </APIContext.Provider>
        );

    it('renders task name for task nodes', async () => {
        const { queryAllByText } = renderTable();
        await waitFor(() => {});

        const node = dataCache.getNodeForNodeExecution(
            mockNodeExecutions[0].id
        );
        const taskId = node?.node.taskNode?.referenceId;
        expect(taskId).toBeDefined();
        const task = dataCache.getTaskTemplate(taskId!);
        expect(task).toBeDefined();
        expect(queryAllByText(task!.id.name)[0]).toBeInTheDocument();
    });

    it('requests child node executions using configuration from context', async () => {
        const { taskExecutions } = createMockTaskExecutionsListResponse(1);
        taskExecutions[0].isParent = true;
        mockListTaskExecutions.mockResolvedValue({ entities: taskExecutions });
        requestConfig.filter = [
            { key: 'test', operation: FilterOperationName.EQ, value: 'test' }
        ];

        renderTable();
        await waitFor(() =>
            expect(mockListTaskExecutionChildren).toHaveBeenCalled()
        );

        expect(mockListTaskExecutionChildren).toHaveBeenCalledWith(
            taskExecutions[0].id,
            expect.objectContaining(requestConfig)
        );
    });

    describe('for task nodes with cache status', () => {
        let taskNodeMetadata: TaskNodeMetadata;
        let cachedNodeExecution: NodeExecution;
        beforeEach(() => {
            cachedNodeExecution = mockNodeExecutions[0];
            taskNodeMetadata = {
                cacheStatus: Core.CatalogCacheStatus.CACHE_MISS,
                catalogKey: {
                    datasetId: makeIdentifier({
                        resourceType: Core.ResourceType.DATASET
                    }),
                    sourceTaskExecution: { ...mockTaskExecution.id }
                }
            };
            cachedNodeExecution.closure.taskNodeMetadata = taskNodeMetadata;
        });

        [
            Core.CatalogCacheStatus.CACHE_HIT,
            Core.CatalogCacheStatus.CACHE_LOOKUP_FAILURE,
            Core.CatalogCacheStatus.CACHE_POPULATED,
            Core.CatalogCacheStatus.CACHE_PUT_FAILURE
        ].forEach(cacheStatusValue =>
            it(`renders correct icon for ${Core.CatalogCacheStatus[cacheStatusValue]}`, async () => {
                taskNodeMetadata.cacheStatus = cacheStatusValue;
                const { getByTitle } = renderTable();
                await waitFor(() =>
                    getByTitle(cacheStatusMessages[cacheStatusValue])
                );
            })
        );

        [
            Core.CatalogCacheStatus.CACHE_DISABLED,
            Core.CatalogCacheStatus.CACHE_MISS
        ].forEach(cacheStatusValue =>
            it(`renders no icon for ${Core.CatalogCacheStatus[cacheStatusValue]}`, async () => {
                taskNodeMetadata.cacheStatus = cacheStatusValue;
                const { getByText, queryByTitle } = renderTable();
                await waitFor(() => getByText(cachedNodeExecution.id.nodeId));
                expect(
                    queryByTitle(cacheStatusMessages[cacheStatusValue])
                ).toBeNull();
            })
        );
    });
}


() => {
        const {
            nodeExecutions,
            workflow,
            workflowExecution
        } = createMockExecutionEntities({
            workflowName: 'SampleWorkflow',
            nodeExecutionCount: 2
        });

        mockNodeExecutions = nodeExecutions;

        mockListTaskExecutions = jest.fn().mockResolvedValue({ entities: [] });
        mockListTaskExecutionChildren = jest
            .fn()
            .mockResolvedValue({ entities: [] });
        mockGetExecution = jest
            .fn()
            .mockImplementation(async (id: WorkflowExecutionIdentifier) => {
                return { ...createMockExecution(id.name), id };
            });
        mockGetTask = jest.fn().mockImplementation(async (id: Identifier) => {
            return { template: { ...mockTasks[0].template, id } };
        });

        apiContext = mockAPIContextValue({
            getExecution: mockGetExecution,
            getTask: mockGetTask,
            listTaskExecutions: mockListTaskExecutions,
            listTaskExecutionChildren: mockListTaskExecutionChildren
        });

        dataCache = createExecutionDataCache(apiContext);
        dataCache.insertWorkflow(workflow);
        dataCache.insertWorkflowExecutionReference(
            workflowExecution.id,
            workflow.id
        );

        requestConfig = {};
        executionContext = {
            execution: workflowExecution,
            terminateExecution: jest.fn().mockRejectedValue('Not Implemented')
        };

        props = {
            value: nodeExecutions,
            lastError: null,
            state: State.from(fetchStates.LOADED),
            moreItemsAvailable: false,
            fetch: jest.fn()
        };
    }


async (id: WorkflowExecutionIdentifier) => {
                return { ...createMockExecution(id.name), id };
            }


async (id: Identifier) => {
            return { template: { ...mockTasks[0].template, id } };
        }


() =>
        render(
            <APIContext.Provider value={apiContext}>
                <NodeExecutionsRequestConfigContext.Provider
                    value={requestConfig}
                >
                    <ExecutionContext.Provider value={executionContext}>
                        <ExecutionDataCacheContext.Provider value={dataCache}>
                            <NodeExecutionsTable {...props} />
                        </ExecutionDataCacheContext.Provider>
                    </ExecutionContext.Provider>
                </NodeExecutionsRequestConfigContext.Provider>
            </APIContext.Provider>
        )


async () => {
        const { queryAllByText } = renderTable();
        await waitFor(() => {});

        const node = dataCache.getNodeForNodeExecution(
            mockNodeExecutions[0].id
        );
        const taskId = node?.node.taskNode?.referenceId;
        expect(taskId).toBeDefined();
        const task = dataCache.getTaskTemplate(taskId!);
        expect(task).toBeDefined();
        expect(queryAllByText(task!.id.name)[0]).toBeInTheDocument();
    }


async () => {
        const { taskExecutions } = createMockTaskExecutionsListResponse(1);
        taskExecutions[0].isParent = true;
        mockListTaskExecutions.mockResolvedValue({ entities: taskExecutions });
        requestConfig.filter = [
            { key: 'test', operation: FilterOperationName.EQ, value: 'test' }
        ];

        renderTable();
        await waitFor(() =>
            expect(mockListTaskExecutionChildren).toHaveBeenCalled()
        );

        expect(mockListTaskExecutionChildren).toHaveBeenCalledWith(
            taskExecutions[0].id,
            expect.objectContaining(requestConfig)
        );
    }


() =>
            expect(mockListTaskExecutionChildren).toHaveBeenCalled()


() => {
        let taskNodeMetadata: TaskNodeMetadata;
        let cachedNodeExecution: NodeExecution;
        beforeEach(() => {
            cachedNodeExecution = mockNodeExecutions[0];
            taskNodeMetadata = {
                cacheStatus: Core.CatalogCacheStatus.CACHE_MISS,
                catalogKey: {
                    datasetId: makeIdentifier({
                        resourceType: Core.ResourceType.DATASET
                    }),
                    sourceTaskExecution: { ...mockTaskExecution.id }
                }
            };
            cachedNodeExecution.closure.taskNodeMetadata = taskNodeMetadata;
        });

        [
            Core.CatalogCacheStatus.CACHE_HIT,
            Core.CatalogCacheStatus.CACHE_LOOKUP_FAILURE,
            Core.CatalogCacheStatus.CACHE_POPULATED,
            Core.CatalogCacheStatus.CACHE_PUT_FAILURE
        ].forEach(cacheStatusValue =>
            it(`renders correct icon for ${Core.CatalogCacheStatus[cacheStatusValue]}`, async () => {
                taskNodeMetadata.cacheStatus = cacheStatusValue;
                const { getByTitle } = renderTable();
                await waitFor(() =>
                    getByTitle(cacheStatusMessages[cacheStatusValue])
                );
            })
        );

        [
            Core.CatalogCacheStatus.CACHE_DISABLED,
            Core.CatalogCacheStatus.CACHE_MISS
        ].forEach(cacheStatusValue =>
            it(`renders no icon for ${Core.CatalogCacheStatus[cacheStatusValue]}`, async () => {
                taskNodeMetadata.cacheStatus = cacheStatusValue;
                const { getByText, queryByTitle } = renderTable();
                await waitFor(() => getByText(cachedNodeExecution.id.nodeId));
                expect(
                    queryByTitle(cacheStatusMessages[cacheStatusValue])
                ).toBeNull();
            })
        );
    }


() => {
            cachedNodeExecution = mockNodeExecutions[0];
            taskNodeMetadata = {
                cacheStatus: Core.CatalogCacheStatus.CACHE_MISS,
                catalogKey: {
                    datasetId: makeIdentifier({
                        resourceType: Core.ResourceType.DATASET
                    }),
                    sourceTaskExecution: { ...mockTaskExecution.id }
                }
            };
            cachedNodeExecution.closure.taskNodeMetadata = taskNodeMetadata;
        }


cacheStatusValue =>
            it(`renders correct icon for ${Core.CatalogCacheStatus[cacheStatusValue]}`, async () => {
                taskNodeMetadata.cacheStatus = cacheStatusValue;
                const { getByTitle } = renderTable();
                await waitFor(() =>
                    getByTitle(cacheStatusMessages[cacheStatusValue])
                );
            })


async () => {
                taskNodeMetadata.cacheStatus = cacheStatusValue;
                const { getByTitle } = renderTable();
                await waitFor(() =>
                    getByTitle(cacheStatusMessages[cacheStatusValue])
                );
            }


() =>
                    getByTitle(cacheStatusMessages[cacheStatusValue])


cacheStatusValue =>
            it(`renders no icon for ${Core.CatalogCacheStatus[cacheStatusValue]}`, async () => {
                taskNodeMetadata.cacheStatus = cacheStatusValue;
                const { getByText, queryByTitle } = renderTable();
                await waitFor(() => getByText(cachedNodeExecution.id.nodeId));
                expect(
                    queryByTitle(cacheStatusMessages[cacheStatusValue])
                ).toBeNull();
            })


async () => {
                taskNodeMetadata.cacheStatus = cacheStatusValue;
                const { getByText, queryByTitle } = renderTable();
                await waitFor(() => getByText(cachedNodeExecution.id.nodeId));
                expect(
                    queryByTitle(cacheStatusMessages[cacheStatusValue])
                ).toBeNull();
            }


() => getByText(cachedNodeExecution.id.nodeId)


async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
  const clearMessage = logConsoleProgress(
    `Creating a new container ${params.collectionId} for database ${params.databaseId}`
  );
  try {
    let collection: DataModels.Collection;
    if (userContext.authType === AuthType.AAD && !userContext.useSDKOperations) {
      if (params.createNewDatabase) {
        const createDatabaseParams: DataModels.CreateDatabaseParams = {
          autoPilotMaxThroughput: params.autoPilotMaxThroughput,
          databaseId: params.databaseId,
          databaseLevelThroughput: params.databaseLevelThroughput,
          offerThroughput: params.offerThroughput,
        };
        await createDatabase(createDatabaseParams);
      }
      collection = await createCollectionWithARM(params);
    } else if (userContext.apiType === "Mongo") {
      collection = await createMongoCollectionWithProxy(params);
    } else {
      collection = await createCollectionWithSDK(params);
    }

    logConsoleInfo(`Successfully created container ${params.collectionId}`);
    return collection;
  } catch (error) {
    handleError(error, "CreateCollection", `Error while creating container ${params.collectionId}`);
    throw error;
  } finally {
    clearMessage();
  }
}


async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
  if (!params.createNewDatabase) {
    const isValid = await useDatabases.getState().validateCollectionId(params.databaseId, params.collectionId);
    if (!isValid) {
      const collectionName = getCollectionName().toLocaleLowerCase();
      throw new Error(
        `Create ${collectionName} failed: ${collectionName} with id ${params.collectionId} already exists`
      );
    }
  }

  const { apiType } = userContext;
  switch (apiType) {
    case "SQL":
      return createSqlContainer(params);
    case "Mongo":
      return createMongoCollection(params);
    case "Cassandra":
      return createCassandraTable(params);
    case "Gremlin":
      return createGraph(params);
    case "Tables":
      return createTable(params);
    default:
      throw new Error(`Unsupported default experience type: ${apiType}`);
  }
}


async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
  const options: ARMTypes.CreateUpdateOptions = constructRpOptions(params);
  const resource: ARMTypes.SqlContainerResource = {
    id: params.collectionId,
  };
  if (params.analyticalStorageTtl) {
    resource.analyticalStorageTtl = params.analyticalStorageTtl;
  }
  if (params.indexingPolicy) {
    resource.indexingPolicy = params.indexingPolicy;
  }
  if (params.partitionKey) {
    resource.partitionKey = params.partitionKey;
  }
  if (params.uniqueKeyPolicy) {
    resource.uniqueKeyPolicy = params.uniqueKeyPolicy;
  }

  const rpPayload: ARMTypes.SqlDatabaseCreateUpdateParameters = {
    properties: {
      resource,
      options,
    },
  };

  const createResponse = await createUpdateSqlContainer(
    userContext.subscriptionId,
    userContext.resourceGroup,
    userContext.databaseAccount.name,
    params.databaseId,
    params.collectionId,
    rpPayload
  );
  return createResponse && (createResponse.properties.resource as DataModels.Collection);
}


async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
  const mongoWildcardIndexOnAllFields: ARMTypes.MongoIndex[] = [{ key: { keys: ["$**"] } }, { key: { keys: ["_id"] } }];
  const options: ARMTypes.CreateUpdateOptions = constructRpOptions(params);
  const resource: ARMTypes.MongoDBCollectionResource = {
    id: params.collectionId,
  };
  if (params.analyticalStorageTtl) {
    resource.analyticalStorageTtl = params.analyticalStorageTtl;
  }
  if (params.partitionKey) {
    const partitionKeyPath: string = params.partitionKey.paths[0];
    resource.shardKey = { [partitionKeyPath]: "Hash" };
  }
  if (params.createMongoWildcardIndex) {
    resource.indexes = mongoWildcardIndexOnAllFields;
  }

  const rpPayload: ARMTypes.MongoDBCollectionCreateUpdateParameters = {
    properties: {
      resource,
      options,
    },
  };

  const createResponse = await createUpdateMongoDBCollection(
    userContext.subscriptionId,
    userContext.resourceGroup,
    userContext.databaseAccount.name,
    params.databaseId,
    params.collectionId,
    rpPayload
  );

  if (params.createMongoWildcardIndex) {
    TelemetryProcessor.trace(Action.CreateMongoCollectionWithWildcardIndex, ActionModifiers.Mark, {
      message: "Mongo Collection created with wildcard index on all fields.",
    });
  }

  return createResponse && (createResponse.properties.resource as DataModels.Collection);
}


async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
  const options: ARMTypes.CreateUpdateOptions = constructRpOptions(params);
  const resource: ARMTypes.CassandraTableResource = {
    id: params.collectionId,
  };
  if (params.analyticalStorageTtl) {
    resource.analyticalStorageTtl = params.analyticalStorageTtl;
  }

  const rpPayload: ARMTypes.CassandraTableCreateUpdateParameters = {
    properties: {
      resource,
      options,
    },
  };

  const createResponse = await createUpdateCassandraTable(
    userContext.subscriptionId,
    userContext.resourceGroup,
    userContext.databaseAccount.name,
    params.databaseId,
    params.collectionId,
    rpPayload
  );
  return createResponse && (createResponse.properties.resource as DataModels.Collection);
}


async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
  const options: ARMTypes.CreateUpdateOptions = constructRpOptions(params);
  const resource: ARMTypes.GremlinGraphResource = {
    id: params.collectionId,
  };

  if (params.indexingPolicy) {
    resource.indexingPolicy = params.indexingPolicy;
  }
  if (params.partitionKey) {
    resource.partitionKey = params.partitionKey;
  }
  if (params.uniqueKeyPolicy) {
    resource.uniqueKeyPolicy = params.uniqueKeyPolicy;
  }

  const rpPayload: ARMTypes.GremlinGraphCreateUpdateParameters = {
    properties: {
      resource,
      options,
    },
  };

  const createResponse = await createUpdateGremlinGraph(
    userContext.subscriptionId,
    userContext.resourceGroup,
    userContext.databaseAccount.name,
    params.databaseId,
    params.collectionId,
    rpPayload
  );
  return createResponse && (createResponse.properties.resource as DataModels.Collection);
}


async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
  const options: ARMTypes.CreateUpdateOptions = constructRpOptions(params);
  const resource: ARMTypes.TableResource = {
    id: params.collectionId,
  };

  const rpPayload: ARMTypes.TableCreateUpdateParameters = {
    properties: {
      resource,
      options,
    },
  };

  const createResponse = await createUpdateTable(
    userContext.subscriptionId,
    userContext.resourceGroup,
    userContext.databaseAccount.name,
    params.collectionId,
    rpPayload
  );
  return createResponse && (createResponse.properties.resource as DataModels.Collection);
}


(params: DataModels.CreateDatabaseParams): ARMTypes.CreateUpdateOptions => {
  if (params.databaseLevelThroughput) {
    return {};
  }

  if (params.autoPilotMaxThroughput) {
    return {
      autoscaleSettings: {
        maxThroughput: params.autoPilotMaxThroughput,
      },
    };
  }

  return {
    throughput: params.offerThroughput,
  };
}


async (params: DataModels.CreateCollectionParams): Promise<DataModels.Collection> => {
  const createCollectionBody: ContainerRequest = {
    id: params.collectionId,
    partitionKey: params.partitionKey || undefined,
    indexingPolicy: params.indexingPolicy || undefined,
    uniqueKeyPolicy: params.uniqueKeyPolicy || undefined,
    analyticalStorageTtl: params.analyticalStorageTtl,
  } as ContainerRequest; // TODO: remove cast when https://github.com/Azure/azure-cosmos-js/issues/423 is fixed
  const collectionOptions: RequestOptions = {};
  const createDatabaseBody: DatabaseRequest = { id: params.databaseId };

  if (params.databaseLevelThroughput) {
    if (params.autoPilotMaxThroughput) {
      createDatabaseBody.maxThroughput = params.autoPilotMaxThroughput;
    } else {
      createDatabaseBody.throughput = params.offerThroughput;
    }
  } else {
    if (params.autoPilotMaxThroughput) {
      createCollectionBody.maxThroughput = params.autoPilotMaxThroughput;
    } else {
      createCollectionBody.throughput = params.offerThroughput;
    }
  }

  const databaseResponse: DatabaseResponse = await client().databases.createIfNotExists(createDatabaseBody);
  const collectionResponse: ContainerResponse = await databaseResponse?.database.containers.create(
    createCollectionBody,
    collectionOptions
  );
  return collectionResponse?.resource as DataModels.Collection;
}


type Menu = {
  Monday: ["Steak and lettuce", "Codd and tomatoes"],
  Tuesday: ["Chicken and carrots", "Peas and carrots"],
  Wednesday: ["Fish and chips", "Turkey and stuffing"],
  Thursday: ["Sushi and rice", "Wok and noodles"],
  Friday: ["Lamb and tomatoes", "Salmon and cheese"],
  Saturday: ["Spaghetti and pesto", "Penne and arrabiata"],
  Sunday: ["Fries and ketchup", "Fries and mayonnaise"],
}


type MealsWithSteak = MealsWithIngredient<"Steak">


type MealsWithFries = MealsWithIngredient<"Fries">


type MealsWithTomatoes = MealsWithIngredient<"tomatoes">


type MealsWithHummus = MealsWithIngredient<"hummus">


type DaysWithSteak = DaysWith<"Steak">


type DaysWithFries = DaysWith<"Fries">


type DaysWithTomatoes = DaysWith<"tomatoes">


type DaysWithHummus = DaysWith<"hummus">


(props: any) => {
    const { inputLabel, children, width, loading, ...rest } = props;
    const setWidth = width ? width : 210;
    const StyledInputFlex = styled.div`
    display: flex;
    align-items: center;
    overflow-x: hidden;
    height: 40px;
    `;
    const StyledInput = styled.div`
    color: ${p => lighten(0.1, p.theme.primaryColor)} !important;
    font-size: 14px;
    max-width: 100%;
    text-overflow: ellipsis;
    padding: 0 20px;
    overflow:hidden;
    white-space:nowrap;
    margin-top: 2px;
    `;

    const DepositLabel = styled.label`
    position: absolute;
    top: 0;
    width: ${setWidth}px;
    text-align: center;
    margin-left: calc(calc(100% - ${setWidth}px) / 2);
    font-size: 1.4rem;
    color: ${p => p.theme.lightGrey};
    background-color: white;
    margin-top: -10px;
    `;

    return (
        <OuterDiv>
            <StyledInputFlex>
                <StyledInput {...rest}>{props.children}</StyledInput>
                {loading ? <ScanningDot /> : <></>}
            </StyledInputFlex>
            <DepositLabel>{inputLabel}</DepositLabel>
        </OuterDiv>


p => lighten(0.1, p.theme.primaryColor)


p => p.theme.lightGrey


(props: any) => {
    const { inputLabel, children, width, ...rest } = props;
    const setWidth = width ? width : 210;
    const StyledInput = styled.input`
    color: ${p => lighten(0.1, p.theme.primaryColor)} !important;
    font-size: 14px !important;
    font-weight: 400 !important;
    `;

    const DepositLabel = styled.label`
    position: absolute;
    top: 0;
    width: ${setWidth}px;
    text-align: center;
    margin-left: calc(calc(100% - ${setWidth}px) / 2);
    font-size: 1.4rem;
    color: ${p => p.theme.lightGrey};
    background-color: white;
    margin-top: -10px;
    `;

    return (
        <OuterDiv>
            <StyledInput type="text" {...rest} />
            <DepositLabel>{inputLabel}</DepositLabel>
            {props.children}
        </OuterDiv>


(props) => {
  const {repoAddress} = props;
  const {canLaunchPipelineExecution} = usePermissions();

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        minWidth: 0,
        width: '100%',
        height: '100%',
      }}


interface Props {
  repoAddress: RepoAddress;
}


@Injectable()
export class ClassroomService {
  constructor(private prisma: PrismaService) {}

  create(createClassroomInput: CreateClassroomInput): Promise<Classroom> {
    return this.prisma.classroom.create({
      data: createClassroomInput,
    });
  }

  findAll(): Promise<Classroom[]> {
    return this.prisma.classroom.findMany();
  }

  findOne(id: string): Promise<Classroom> {
    return this.prisma.classroom.findUnique({
      where: {
        id,
      },
    });
  }

  update(
    id: string,
    updateClassroomInput: UpdateClassroomInput,
  ): Promise<Classroom> {
    const { name } = updateClassroomInput;

    return this.prisma.classroom.update({
      where: {
        id,
      },
      data: {
        ...(name && { name }),
      },
    });
  }

  remove(id: string): Promise<Classroom> {
    return this.prisma.classroom.delete({
      where: {
        id,
      },
    });
  }
}


create(createClassroomInput: CreateClassroomInput): Promise<Classroom> {
    return this.prisma.classroom.create({
      data: createClassroomInput,
    });
  }


findAll(): Promise<Classroom[]> {
    return this.prisma.classroom.findMany();
  }


findOne(id: string): Promise<Classroom> {
    return this.prisma.classroom.findUnique({
      where: {
        id,
      },
    });
  }


update(
    id: string,
    updateClassroomInput: UpdateClassroomInput,
  ): Promise<Classroom> {
    const { name } = updateClassroomInput;

    return this.prisma.classroom.update({
      where: {
        id,
      },
      data: {
        ...(name && { name }),
      },
    });
  }


remove(id: string): Promise<Classroom> {
    return this.prisma.classroom.delete({
      where: {
        id,
      },
    });
  }


@Injectable({
  providedIn: 'root'
})

export class UserService {

  constructor(private http:HttpClient) {  }
  getDepartmentTeachers(sheetId:number){
    return this.http.get<User[]>("/api/users/teachers/ofdepartment/"+sheetId)
  }
  getStudentOfSheet(sheetId:number){
    return this.http.get<User>("/api/users/studentsBySheet/"+sheetId)
  }
  getUserById(id:number){
    return this.http.get<User>("/api/users/"+id)
  }
  getAllUsers(){
    return this.http.get<User[]>("/api/student/isnonautorised")
  }
  allowStudent(id:number){
    return this.http.get<User>("/api/student/authorize?id="+id)
  }
}


getDepartmentTeachers(sheetId:number){
    return this.http.get<User[]>("/api/users/teachers/ofdepartment/"+sheetId)
  }


getStudentOfSheet(sheetId:number){
    return this.http.get<User>("/api/users/studentsBySheet/"+sheetId)
  }


getUserById(id:number){
    return this.http.get<User>("/api/users/"+id)
  }


getAllUsers(){
    return this.http.get<User[]>("/api/student/isnonautorised")
  }


allowStudent(id:number){
    return this.http.get<User>("/api/student/authorize?id="+id)
  }


class ListUsersService {
  async execute() {
    const usersRepositories = getCustomRepository(UsersRepositories);

    const users = await usersRepositories.find();

    return classToPlain(users);
  }
}


async execute() {
    const usersRepositories = getCustomRepository(UsersRepositories);

    const users = await usersRepositories.find();

    return classToPlain(users);
  }


() => this.state = 'fulfilled'


() => this.state = 'rejected'


export class Deferred<T> {
  public promise: Promise<T>;

  private fate: 'resolved' | 'unresolved';
  private state: 'pending' | 'fulfilled' | 'rejected';

  private _resolve: Function;
  private _reject: Function;

  constructor() {
    this.state = 'pending';
    this.fate = 'unresolved';
    this.promise = new Promise((resolve, reject) => {
      this._resolve = resolve;
      this._reject = reject;
    });
    this.promise.then(
      () => this.state = 'fulfilled',
      () => this.state = 'rejected'
    );
  }

  resolve(value?: any) {
    if (this.fate === 'resolved') {
      throw 'Deferred cannot be resolved twice';
    }
    this.fate = 'resolved';
    this._resolve(value);
  }

  reject(reason?: any) {
    if (this.fate === 'resolved') {
      throw 'Deferred cannot be resolved twice';
    }
    this.fate = 'resolved';
    this._reject(reason);
  }

  isResolved() {
    return this.fate === 'resolved';
  }

  isPending() {
    return this.state === 'pending';
  }

  isFulfilled() {
    return this.state === 'fulfilled';
  }

  isRejected() {
    return this.state === 'rejected';
  }
}


resolve(value?: any) {
    if (this.fate === 'resolved') {
      throw 'Deferred cannot be resolved twice';
    }
    this.fate = 'resolved';
    this._resolve(value);
  }


reject(reason?: any) {
    if (this.fate === 'resolved') {
      throw 'Deferred cannot be resolved twice';
    }
    this.fate = 'resolved';
    this._reject(reason);
  }


isResolved() {
    return this.fate === 'resolved';
  }


isPending() {
    return this.state === 'pending';
  }


isFulfilled() {
    return this.state === 'fulfilled';
  }


isRejected() {
    return this.state === 'rejected';
  }


(editor) => editor.document === vimState.document


//
//  Implements :quit
//  http://vimdoc.sourceforge.net/htmldoc/editing.html#:quit
//
export class QuitCommand extends node.CommandBase {
  protected _arguments: IQuitCommandArguments;

  constructor(args: IQuitCommandArguments) {
    super();
    this._arguments = args;
  }

  get arguments(): IQuitCommandArguments {
    return this._arguments;
  }

  async execute(vimState: VimState): Promise<void> {
    // NOTE: We can't currently get all open text editors, so this isn't perfect. See #3809
    const duplicatedInSplit =
      vscode.window.visibleTextEditors.filter((editor) => editor.document === vimState.document)
        .length > 1;
    if (
      vimState.document.isDirty &&
      !this.arguments.bang &&
      (!duplicatedInSplit || this._arguments.quitAll)
    ) {
      throw error.VimError.fromCode(error.ErrorCode.NoWriteSinceLastChange);
    }

    if (this._arguments.quitAll) {
      await vscode.commands.executeCommand('workbench.action.closeAllEditors');
    } else {
      if (!this.arguments.bang) {
        await vscode.commands.executeCommand('workbench.action.closeActiveEditor');
      } else {
        await vscode.commands.executeCommand('workbench.action.revertAndCloseActiveEditor');
      }
    }
  }
}


export interface IQuitCommandArguments extends node.ICommandArgs {
  bang?: boolean;
  range?: node.LineRange;
  quitAll?: boolean;
}


async execute(vimState: VimState): Promise<void> {
    // NOTE: We can't currently get all open text editors, so this isn't perfect. See #3809
    const duplicatedInSplit =
      vscode.window.visibleTextEditors.filter((editor) => editor.document === vimState.document)
        .length > 1;
    if (
      vimState.document.isDirty &&
      !this.arguments.bang &&
      (!duplicatedInSplit || this._arguments.quitAll)
    ) {
      throw error.VimError.fromCode(error.ErrorCode.NoWriteSinceLastChange);
    }

    if (this._arguments.quitAll) {
      await vscode.commands.executeCommand('workbench.action.closeAllEditors');
    } else {
      if (!this.arguments.bang) {
        await vscode.commands.executeCommand('workbench.action.closeActiveEditor');
      } else {
        await vscode.commands.executeCommand('workbench.action.revertAndCloseActiveEditor');
      }
    }
  }


export function Tab(props: Props) {
  return (
    <StyledTab active={props.active} onClick={() => props.onClick()}


_ => ({
  type: 'button',
  className: 'btn',
})


(props: StyledProps) =>
    props.active &&
    css`
      background-color: var(--white);
      &:hover {
        color: var(--primary);
      }
    `


interface Props {
  text: string;
  active: boolean;
  onClick: () => void;
}


interface StyledProps {
  active: boolean;
}


(x) => x.lang === this.langStoreValue


(element) => element.text


(element) => element.flag


(isRunning) => {
        this.isOpenSidebar = isRunning;
      }


(res) => {
      if (!res.success) {
        this.router.navigate(['/authentication/signin']);
      }
    }


@HostListener('window:scroll', [])
  onWindowScroll() {
    const offset =
      this.window.pageYOffset ||
      this.document.documentElement.scrollTop ||
      this.document.body.scrollTop ||
      0;
    if (offset > 50) {
      this.isNavbarShow = true;
    } else {
      this.isNavbarShow = false;
    }
  }


ngOnInit() {
    this.config = this.configService.configData;

    this.langStoreValue = localStorage.getItem('lang');
    const val = this.listLang.filter((x) => x.lang === this.langStoreValue);
    this.countryName = val.map((element) => element.text);
    if (val.length === 0) {
      if (this.flagvalue === undefined) {
        this.defaultFlag = 'assets/images/flags/us.jpg';
      }
    } else {
      this.flagvalue = val.map((element) => element.flag);
    }
  }


ngAfterViewInit() {
    // set theme on startup
    if (localStorage.getItem('theme')) {
      this.renderer.removeClass(this.document.body, this.config.layout.variant);
      this.renderer.addClass(this.document.body, localStorage.getItem('theme'));
    } else {
      this.renderer.addClass(this.document.body, this.config.layout.variant);
    }

    if (localStorage.getItem('menuOption')) {
      this.renderer.addClass(
        this.document.body,
        localStorage.getItem('menuOption')
      );
    } else {
      this.renderer.addClass(
        this.document.body,
        'menu_' + this.config.layout.sidebar.backgroundColor
      );
    }

    if (localStorage.getItem('choose_logoheader')) {
      this.renderer.addClass(
        this.document.body,
        localStorage.getItem('choose_logoheader')
      );
    } else {
      this.renderer.addClass(
        this.document.body,
        'logo-' + this.config.layout.logo_bg_color
      );
    }

    if (localStorage.getItem('sidebar_status')) {
      if (localStorage.getItem('sidebar_status') === 'close') {
        this.renderer.addClass(this.document.body, 'side-closed');
        this.renderer.addClass(this.document.body, 'submenu-closed');
      } else {
        this.renderer.removeClass(this.document.body, 'side-closed');
        this.renderer.removeClass(this.document.body, 'submenu-closed');
      }
    } else {
      if (this.config.layout.sidebar.collapsed === true) {
        this.renderer.addClass(this.document.body, 'side-closed');
        this.renderer.addClass(this.document.body, 'submenu-closed');
      }
    }
  }


callFullscreen() {
    if (
      !document.fullscreenElement &&
      !document.mozFullScreenElement &&
      !document.webkitFullscreenElement &&
      !document.msFullscreenElement
    ) {
      if (document.documentElement.requestFullscreen) {
        document.documentElement.requestFullscreen();
      } else if (document.documentElement.msRequestFullscreen) {
        document.documentElement.msRequestFullscreen();
      } else if (document.documentElement.mozRequestFullScreen) {
        document.documentElement.mozRequestFullScreen();
      } else if (document.documentElement.webkitRequestFullscreen) {
        document.documentElement.webkitRequestFullscreen();
      }
    } else {
      if (document.exitFullscreen) {
        document.exitFullscreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
      }
    }
  }


setLanguage(text: string, lang: string, flag: string) {
    this.countryName = text;
    this.flagvalue = flag;
    this.langStoreValue = lang;
    this.languageService.setLanguage(lang);
  }


mobileMenuSidebarOpen(event: any, className: string) {
    const hasClass = event.target.classList.contains(className);
    if (hasClass) {
      this.renderer.removeClass(this.document.body, className);
    } else {
      this.renderer.addClass(this.document.body, className);
    }
  }


callSidemenuCollapse() {
    const hasClass = this.document.body.classList.contains('side-closed');
    if (hasClass) {
      this.renderer.removeClass(this.document.body, 'side-closed');
      this.renderer.removeClass(this.document.body, 'submenu-closed');
    } else {
      this.renderer.addClass(this.document.body, 'side-closed');
      this.renderer.addClass(this.document.body, 'submenu-closed');
    }
  }


public toggleRightSidebar(): void {
    this.subs.sink = this.rightSidebarService.sidebarState.subscribe(
      (isRunning) => {
        this.isOpenSidebar = isRunning;
      }
    );

    this.rightSidebarService.setRightSidebar(
      (this.isOpenSidebar = !this.isOpenSidebar)
    );
  }


logout() {
    this.subs.sink = this.authService.logout().subscribe((res) => {
      if (!res.success) {
        this.router.navigate(['/authentication/signin']);
      }
    });
  }


ChangePassword(){
    this.router.navigate(['/profile/change-password']);
  }


ModifyProfile(){
    this.router.navigate(['/profile/modify-profile']);
  }


declare function FastifyCsrfPlugin<
    HttpServer = any,
    HttpRequest = any,
    HttpResponse = any>(opts?: FastifyCsrfPlugin.Options<HttpRequest>): FastifyCsrfPlugin.Plugin<
    HttpServer,
    HttpRequest,
    HttpResponse>;


interface FastifyRequest<HttpRequest,
        Query = fastify.DefaultQuery,
        Params = fastify.DefaultParams,
        Headers = fastify.DefaultHeaders,
        Body = any> {
        csrfToken(): string;
    }


interface Options<HttpRequest> extends TokenOptions {
        value?: (req: HttpRequest) => string;
        cookie?: fastify.CookieSerializeOptions | boolean;
        ignoreMethods?: string[];
        sessionKey?: string;
    }


interface Plugin<HttpServer, HttpRequest, HttpResponse>
        extends fastify.Plugin<HttpServer, HttpRequest, HttpResponse, FastifyCsrfPlugin.Options<HttpRequest>> {
    }


export declare class Querier {
    private static initCalled;
    private static hosts;
    private static apiKey;
    private static apiVersion;
    private static lastTriedIndex;
    private static hostsAliveForTesting;
    private __hosts;
    private rIdToCore;
    private constructor();
    getAPIVersion: () => Promise<string>;
    static reset(): void;
    getHostsAliveForTesting: () => Set<string>;
    static getNewInstanceOrThrowError(rIdToCore?: string): Querier;
    static init(
        hosts?: {
            domain: NormalisedURLDomain;
            basePath: NormalisedURLPath;
        }[],
        apiKey?: string
    ): void;
    sendPostRequest: (path: NormalisedURLPath, body: any) => Promise<any>;
    sendDeleteRequest: (path: NormalisedURLPath, body: any) => Promise<any>;
    sendGetRequest: (path: NormalisedURLPath, params: any) => Promise<any>;
    sendPutRequest: (path: NormalisedURLPath, body: any) => Promise<any>;
    private sendRequestHelper;
}


static reset(): void;


static getNewInstanceOrThrowError(rIdToCore?: string): Querier;


static init(
        hosts?: {
            domain: NormalisedURLDomain;
            basePath: NormalisedURLPath;
        }[],
        apiKey?: string
    ): void;


export function SideBar(props: SideBarProps) {
  // Complete aqui
  function handleClickButton(id: number) {
    props.setSelectedGenreId(id);
  }

  return (
    <>

        Watch
Me

        {props.genres.map((genre) => (
          <Button
            key={String(genre.id)}
            title={genre.title}
            iconName={genre.name}
            onClick={() => handleClickButton(genre.id)}


// Complete aqui
function handleClickButton(id: number) {
    props.setSelectedGenreId(id);
  }


(genre) => (
          <Button
            key={String(genre.id


interface SideBarProps {
  genres: IGenres[];
  setSelectedGenreId: (id: number) => void;
  selectedGenreId: number;
}


interface IGenres {
  id: number;
  title: string;
  name: "action" | "comedy" | "documentary" | "drama" | "horror" | "family";
}


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


() => {
  let mockTitleService: IMock<TitleService>;
  let fixture: ComponentFixture<ErrorComponent>;
  let pageObject: ErrorPageObject;

  beforeEach(() => {
    mockTitleService = Mock.ofType<TitleService>();
    mockTitleService.setup(x => x.setTitle(It.isAnyString()));
    mockTitleService.setup(x => x.resetTitle());

    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [ErrorComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
      providers: [
        { provide: TitleService, useFactory: () => mockTitleService.object }
      ]
    }).compileComponents();

    fixture = TestBed.createComponent(ErrorComponent);
    pageObject = new ErrorPageObject(fixture);
    fixture.detectChanges();
  });

  it('should show 404 text', () => {
    const heading = pageObject.title;
    expect(heading).toBeTruthy();
    expect(heading.textContent.length).toBeGreaterThan(0);
  });

  it('should show navigation links', () => {
    const links = pageObject.navigationLinks;
    expect(links).toBeTruthy();
    expect(links.length).toBeGreaterThan(0);
  });

  it('should reset title', () => {
    mockTitleService.verify(s => s.resetTitle(), Times.once());
    expect().nothing();
  });
}


() => {
    mockTitleService = Mock.ofType<TitleService>();
    mockTitleService.setup(x => x.setTitle(It.isAnyString()));
    mockTitleService.setup(x => x.resetTitle());

    TestBed.configureTestingModule({
      imports: [RouterTestingModule],
      declarations: [ErrorComponent],
      schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA],
      providers: [
        { provide: TitleService, useFactory: () => mockTitleService.object }
      ]
    }).compileComponents();

    fixture = TestBed.createComponent(ErrorComponent);
    pageObject = new ErrorPageObject(fixture);
    fixture.detectChanges();
  }


x => x.setTitle(It.isAnyString())


x => x.resetTitle()


() => mockTitleService.object


() => {
    const heading = pageObject.title;
    expect(heading).toBeTruthy();
    expect(heading.textContent.length).toBeGreaterThan(0);
  }


() => {
    const links = pageObject.navigationLinks;
    expect(links).toBeTruthy();
    expect(links.length).toBeGreaterThan(0);
  }


() => {
    mockTitleService.verify(s => s.resetTitle(), Times.once());
    expect().nothing();
  }


s => s.resetTitle()


class ErrorPageObject extends PageObjectBase<ErrorComponent> {
  public get title(): HTMLHeadingElement {
    return this.select('[data-title]');
  }

  public get navigationLinks(): HTMLAnchorElement[] {
    return this.selectAll('[data-navigation] a');
  }
}


function useEventListener<K extends keyof WindowEventMap>(
  eventName: K,
  handler: (event: WindowEventMap[K]) => void,
): void;


function useEventListener<
  K extends keyof HTMLElementEventMap,
  T extends HTMLElement = HTMLDivElement,
>(eventName: K, handler: (event: HTMLElementEventMap[K]) => void, element: RefObject<T>): void;


/**
 * Hook that creates an event listener.
 * @param eventName The name of the event to listen to.
 * @param handler The handler to call when the event is triggered.
 * @param element The element to attach the event listener to.
 */
function useEventListener<
  KW extends keyof WindowEventMap,
  KH extends keyof HTMLElementEventMap,
  T extends HTMLElement | void = void,
>(
  eventName: KW | KH,
  handler: (event: WindowEventMap[KW] | HTMLElementEventMap[KH] | Event) => void,
  element?: RefObject<T>,
): void {
  // Create a ref that stores handler
  const savedHandler = useRef<typeof handler>();

  useEffect(() => {
    // Define the listening target
    const targetElement: T | Window = element?.current || window;
    if (!(targetElement && targetElement.addEventListener)) {
      return;
    }

    // Update saved handler if necessary
    if (savedHandler.current !== handler) {
      savedHandler.current = handler;
    }

    // Create event listener that calls handler function stored in ref
    // eslint-disable-next-line require-jsdoc
    const eventListener: typeof handler = (event) => {
      if (savedHandler?.current) {
        savedHandler.current(event);
      }
    };

    targetElement.addEventListener(eventName, eventListener);

    // Remove event listener on cleanup
    return () => {
      targetElement.removeEventListener(eventName, eventListener);
    };
  }, [eventName, element, handler]);
}


() => {
    // Define the listening target
    const targetElement: T | Window = element?.current || window;
    if (!(targetElement && targetElement.addEventListener)) {
      return;
    }

    // Update saved handler if necessary
    if (savedHandler.current !== handler) {
      savedHandler.current = handler;
    }

    // Create event listener that calls handler function stored in ref
    // eslint-disable-next-line require-jsdoc
    const eventListener: typeof handler = (event) => {
      if (savedHandler?.current) {
        savedHandler.current(event);
      }
    };

    targetElement.addEventListener(eventName, eventListener);

    // Remove event listener on cleanup
    return () => {
      targetElement.removeEventListener(eventName, eventListener);
    };
  }


(event) => {
      if (savedHandler?.current) {
        savedHandler.current(event);
      }
    }


() => {
      targetElement.removeEventListener(eventName, eventListener);
    }


it => predicate(it.index, it.value)


it => it.value


export class FilterIndexed {
  /**
   * Returns a new sequence consisting of all elements that match the given `predicate`.
   *
   * @param {(index: number, value: T) => boolean} predicate
   * @returns {Sequence<T>}
   */
  filterIndexed<T>(
    this: Sequence<T>,
    predicate: (index: number, value: T) => boolean
  ): Sequence<T> {
    return this.withIndex()
      .filter(it => predicate(it.index, it.value))
      .map(it => it.value);
  }
}


/**
   * Returns a new sequence consisting of all elements that match the given `predicate`.
   *
   * @param {(index: number, value: T) => boolean} predicate
   * @returns {Sequence<T>}
   */
filterIndexed<T>(
    this: Sequence<T>,
    predicate: (index: number, value: T) => boolean
  ): Sequence<T> {
    return this.withIndex()
      .filter(it => predicate(it.index, it.value))
      .map(it => it.value);
  }


/* tslint:disable */
/* eslint-disable */
// This file was automatically generated and should not be edited.
// ====================================================
// GraphQL query operation: SearchAttribute
// ====================================================
export interface SearchAttribute_attributes_edges_node_values {
  __typename: "AttributeValue";
  id: string;
  name: string | null;
  slug: string | null;
}


export interface SearchAttribute_attributes_edges_node {
  __typename: "Attribute";
  id: string;
  name: string | null;
  slug: string | null;
  values: (SearchAttribute_attributes_edges_node_values | null)[] | null;
}


export interface SearchAttribute_attributes_edges {
  __typename: "AttributeCountableEdge";
  node: SearchAttribute_attributes_edges_node;
}


export interface SearchAttribute_attributes {
  __typename: "AttributeCountableConnection";
  edges: SearchAttribute_attributes_edges[];
}


export interface SearchAttribute {
  attributes: SearchAttribute_attributes | null;
}


export interface SearchAttributeVariables {
  search: string;
}


export function TaskList() {
  const [tasks, setTasks] = useState<Task[]>([]);
  const [newTaskTitle, setNewTaskTitle] = useState('');

  function handleCreateNewTask() {
    if(newTaskTitle !== '') {
      setTasks([...tasks, { id: new Date().getTime(), title: newTaskTitle, isComplete: false }]);
    }
  }

  function handleToggleTaskCompletion(id: number) {
    const updatedTask = tasks.map(task => ({...task}));
    const task = updatedTask.find(task => task.id === id);

    if(task) {
      task.isComplete = !task.isComplete;
      setTasks(updatedTask);
    }
  }

  function handleRemoveTask(id: number) {
    setTasks(oldState => oldState.filter(task => task.id !== id));
  }

  return (

Minhas tasks

          <input
            type="text"
            placeholder="Adicionar novo todo"
            onChange={(e) => setNewTaskTitle(e.target.value)}


function handleCreateNewTask() {
    if(newTaskTitle !== '') {
      setTasks([...tasks, { id: new Date().getTime(), title: newTaskTitle, isComplete: false }]);
    }
  }


function handleToggleTaskCompletion(id: number) {
    const updatedTask = tasks.map(task => ({...task}));
    const task = updatedTask.find(task => task.id === id);

    if(task) {
      task.isComplete = !task.isComplete;
      setTasks(updatedTask);
    }
  }


function handleRemoveTask(id: number) {
    setTasks(oldState => oldState.filter(task => task.id !== id));
  }


task => ({...task})


task => task.id === id


oldState => oldState.filter(task => task.id !== id)