column(): number {
        return this.native.column();
    }


background(): QBrush {
        return new QBrush(this.native.background());
    }


setCheckState(state: CheckState): void {
        this.native.setCheckState(state);
    }


checkState(): CheckState {
        return this.native.checkState();
    }


setData(role: number, value: QVariant): void {
        this.native.setData(role, value.native);
    }


data(role: number): QVariant {
        return new QVariant(this.native.data(role));
    }


setFlags(flags: ItemFlag): void {
        this.native.setFlags(flags);
    }


flags(): ItemFlag {
        return this.native.flags();
    }


setFont(font: QFont): void {
        this.native.setFont(font.native);
    }


font(): QFont {
        return new QFont(this.native.font());
    }


setForeground(brush: QBrush): void {
        this.native.setForeground(brush.native);
    }


foreground(): QBrush {
        return new QBrush(this.native.foreground());
    }


setIcon(icon: QIcon): void {
        this.native.setIcon(icon.native);
    }


icon(): QIcon {
        return new QIcon(this.native.icon());
    }


setSelected(select: boolean): void {
        this.native.setSelected(select);
    }


isSelected(): boolean {
        return this.native.isSelected();
    }


setSizeHint(size: QSize): void {
        this.native.setSizeHint(size.native);
    }


sizeHint(): QSize {
        return new QSize(this.native.sizeHint());
    }


setStatusTip(statusTip: string): void {
        this.native.setStatusTip(statusTip);
    }


statusTip(): string {
        return this.native.statusTip();
    }


setText(text: string): void {
        this.native.setText(text);
    }


text(): string {
        return this.native.text();
    }


setTextAlignment(alignment: AlignmentFlag): void {
        this.native.setTextAlignment(alignment);
    }


textAlignment(): AlignmentFlag {
        return this.native.textAlignment();
    }


setToolTip(toolTip: string): void {
        this.native.setToolTip(toolTip);
    }


toolTip(): string {
        return this.native.toolTip();
    }


setWhatsThis(whatsThis: string): void {
        this.native.setWhatsThis(whatsThis);
    }


whatsThis(): string {
        return this.native.whatsThis();
    }


type(): number {
        return this.native.type$();
    }


export default class CreateProjectDto {
    @ApiProperty({description:'Enter Project Title.', minLength: 3, default: 'Project', maxLength: 20})
    readonly title: string;
    @ApiPropertyOptional({description:'Enter Project Description.', minLength: 3, default: 'Description', maxLength: 200})
    readonly description: string;
    @ApiProperty({description:'Enter Project Price.', default: 0.0})
    readonly price: number;
    @ApiProperty({description:'Enter Project Type.'})
    readonly type: number;
    @ApiProperty({description:'Enter Project Deadline.'})
    readonly deadline: Date;
    @ApiPropertyOptional({description:'Upload Project Attachments (Optional).', default: null, type: Buffer})
    readonly attachment: Buffer;
    @ApiProperty({description:'Enter Project Status.'})
    readonly isPublished: boolean;
}


(props: SVGProps<SVGSVGElement>): ReactElement<SVGElement> => {
    return (
      <svg
        width="100%"
        height="100%"
        viewBox="0 0 24 24"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
        {


create<K extends Ord, V>(getKey: GetKey<K, V>): AVLTree<K, V> {
        return new AVLTree(getKey)
    }


scalar<T extends Ord = never>(): AVLTree<T, T> {
        return new AVLTree((x) => x)
    }


@Component({
    selector: `os-member-import-list`,
    templateUrl: `./member-import-list.component.html`,
    styleUrls: [`./member-import-list.component.scss`]
})
export class MemberImportListComponent extends BaseUserImportListComponent implements OnInit {
    public constructor(
        componentServiceCollector: ComponentServiceCollector,
        protected translate: TranslateService,
        formBuilder: FormBuilder,
        public importer: MemberImportService,
        private memberService: MemberService
    ) {
        super(
            componentServiceCollector,
            translate,
            importer,
            formBuilder,
            BaseUserHeadersAndVerboseNames,
            BaseUserHeaders
        );
    }

    public ngOnInit(): void {
        super.ngOnInit();
        this.loadUsers();
    }

    private async loadUsers(): Promise<void> {
        try {
            const request = await this.memberService.getAllOrgaUsersModelRequest();
            this.requestModels(request, `load_users`);
        } catch (e) {
            console.log(`Error`, e);
        }
    }

    /**
     * Guess the type of the property, since
     * `const type = typeof User[property];`
     * always returns undefined
     */
    protected guessType(userProperty: keyof User): 'string' | 'number' | 'boolean' {
        const numberProperties: (keyof User)[] = [`id`, `vote_weight`];
        const booleanProperties: (keyof User)[] = [`is_physical_person`, `is_active`];
        if (numberProperties.includes(userProperty)) {
            return `number`;
        } else if (booleanProperties.includes(userProperty)) {
            return `boolean`;
        } else {
            return `string`;
        }
    }
}


public ngOnInit(): void {
        super.ngOnInit();
        this.loadUsers();
    }


private async loadUsers(): Promise<void> {
        try {
            const request = await this.memberService.getAllOrgaUsersModelRequest();
            this.requestModels(request, `load_users`);
        } catch (e) {
            console.log(`Error`, e);
        }
    }


/**
     * Guess the type of the property, since
     * `const type = typeof User[property];`
     * always returns undefined
     */
protected guessType(userProperty: keyof User): 'string' | 'number' | 'boolean' {
        const numberProperties: (keyof User)[] = [`id`, `vote_weight`];
        const booleanProperties: (keyof User)[] = [`is_physical_person`, `is_active`];
        if (numberProperties.includes(userProperty)) {
            return `number`;
        } else if (booleanProperties.includes(userProperty)) {
            return `boolean`;
        } else {
            return `string`;
        }
    }


function applyDefaultServerOptions(options: ServerOptions) {
  const withDefaults: ServerOptions = Object.assign({}, options);
  Object.assign(withDefaults, {
    port: options.port || 0,
    hostname: options.hostname || 'localhost',
    root: path.resolve(options.root || '.'),
    compile: options.compile || 'auto',
    certPath: options.certPath || 'cert.pem',
    keyPath: options.keyPath || 'key.pem',
    componentDir: getComponentDir(options),
    componentUrl: options.componentUrl || 'components'
  });
  withDefaults.packageName = getPackageName(withDefaults);
  return withDefaults;
}


/**
 * @param {ServerOptions} options used to configure the generated polyserve app
 *     and server.
 * @param {ExpressAppMapper} appMapper optional mapper function which is called
 *     with the generated polyserve app and the options used to generate
 *     it and returns an optional substitution Express app.  This is usually one
 *     that mounts the original app, to add routes or middleware in advance of
 *     polyserve's catch-all routes.
 * @return {Promise} A Promise that completes when the server has started.
 * @deprecated Please use `startServers` instead. This function will be removed
 *     in a future release.
 */
export async function startServer(
    options: ServerOptions,
    appMapper?: ExpressAppMapper): Promise<http.Server> {
  return (await _startServer(options, appMapper)).server;
}


async function _startServer(
    options: ServerOptions, appMapper?: ExpressAppMapper) {
  options = options || {};
  assertNodeVersion(options);
  try {
    let app = getApp(options);
    if (appMapper) {
      // If the map function doesn't return an app, we should fallback to the
      // original app, hence the `appMapper(app) || app`.
      app = await appMapper(app, options) || app;
    }
    const server = await startWithApp(options, app);
    return {app, server};
  } catch (e) {
    console.error('ERROR: Server failed to start:', e);
    throw new Error(e);
  }
}


/**
 * Starts one or more web servers, based on the given options and
 * variant bower_components directories that are found in the root dir.
 */
export async function startServers(
    options: ServerOptions,
    appMapper?: ExpressAppMapper): Promise<StartServerResult> {
  options = applyDefaultServerOptions(options);
  const variants = await findVariants(options);
  // TODO(rictic): support manually configuring variants? tracking more
  //   metadata about them besides their names?
  if (variants.length > 0) {
    return await startVariants(options, variants, appMapper);
  }

  const serverAndApp = await _startServer(options, appMapper);
  return {
    options,
    kind: 'mainline',
    server: serverAndApp.server,
    app: serverAndApp.app,
  };
}


// TODO(usergenic): Variants should support the directory naming convention in
// the .bowerrc instead of hardcoded 'bower_components' form seen here.
async function findVariants(options: ServerOptions) {
  const root = options.root || process.cwd();
  const filesInRoot = await fs.readdir(root);
  const variants = filesInRoot
                       .map((f) => {
                         const match = f.match(`^${options.componentDir}-(.*)`);
                         return match && {name: match[1], directory: match[0]};
                       })
                       .filter((f) => f != null && f.name !== '');
  return variants;
}


async function startVariants(
    options: ServerOptions,
    variants: {name: string, directory: string}[],
    appMapper?: ExpressAppMapper) {
  const mainlineOptions = Object.assign({}, options);
  mainlineOptions.port = 0;
  const mainServer = await _startServer(mainlineOptions, appMapper);
  const mainServerInfo: MainlineServer = {
    kind: 'mainline',
    server: mainServer.server,
    app: mainServer.app,
    options: mainlineOptions,
  };

  const variantServerInfos: VariantServer[] = [];
  for (const variant of variants) {
    const variantOpts = Object.assign({}, options);
    variantOpts.port = 0;
    variantOpts.componentDir = variant.directory;
    const variantServer = await _startServer(variantOpts, appMapper);
    variantServerInfos.push({
      kind: 'variant',
      variantName: variant.name,
      dependencyDir: variant.directory,
      server: variantServer.server,
      app: variantServer.app,
      options: variantOpts
    });
  }

  const controlServerInfo =
      await startControlServer(options, mainServerInfo, variantServerInfos);
  const servers = ([controlServerInfo, mainServerInfo] as PolyserveServer[])
                      .concat(variantServerInfos);

  const result: MultipleServersInfo = {
    kind: 'MultipleServers',
    control: controlServerInfo,
    mainline: mainServerInfo,
    variants: variantServerInfos,
    servers,
  };
  return result;
}


export async function startControlServer(
    options: ServerOptions,
    mainlineInfo: MainlineServer,
    variantInfos: VariantServer[]) {
  options = applyDefaultServerOptions(options);
  const app = express();
  app.get('/api/serverInfo', (_req, res) => {
    res.contentType('json');
    res.send(JSON.stringify({
      packageName: options.packageName,
      mainlineServer: {
        port: assertNotString(mainlineInfo.server.address()).port,
      },
      variants: variantInfos.map((info) => {
        return {
          name: info.variantName,
          port: assertNotString(info.server.address()).port,
        };
      })
    }));
    res.end();
  });
  const indexPath = path.join(__dirname, '..', 'static', 'index.html');
  app.get('/', async (_req, res) => {
    res.contentType('html');
    const indexContents = await fs.readFile(indexPath, 'utf-8');
    res.send(indexContents);
    res.end();
  });
  const controlServer: ControlServer = {
    kind: 'control',
    options: options,
    server: await startWithApp(options, app),
    app
  };
  return controlServer;
}


export function getApp(options: ServerOptions): express.Express {
  options = applyDefaultServerOptions(options);

  // Preload the h2-push manifest to avoid the cost on first push
  if (options.pushManifestPath) {
    getPushManifest(options.root, options.pushManifestPath);
  }

  const root = options.root || '.';
  const app = express();

  app.use(compression());

  if (options.additionalRoutes) {
    options.additionalRoutes.forEach((handler, route) => {
      app.get(route, handler);
    });
  }

  const componentUrl = options.componentUrl;

  const polyserve = makeApp({
    componentDir: options.componentDir,
    packageName: options.packageName,
    root: root,
    headers: options.headers,
  });

  const filePathRegex: RegExp = /.*\/.+\..{1,}$/;

  if (options.proxy) {
    if (options.proxy.path.startsWith(componentUrl)) {
      console.error(`proxy path can not start with ${componentUrl}.`);
      return;
    }

    let escapedPath = options.proxy.path;

    for (const char of ['*', '?', '+']) {
      if (escapedPath.indexOf(char) > -1) {
        console.warn(
            `Proxy path includes character "${char}"` +
            `which can cause problems during route matching.`);
      }
    }

    if (escapedPath.startsWith('/')) {
      escapedPath = escapedPath.substring(1);
    }
    if (escapedPath.endsWith('/')) {
      escapedPath = escapedPath.slice(0, -1);
    }
    const pathRewrite = {};
    pathRewrite[`^/${escapedPath}`] = '';
    const apiProxy = httpProxy(`/${escapedPath}`, {
      target: options.proxy.target,
      changeOrigin: true,
      pathRewrite: pathRewrite,
      logLevel: 'warn',
    });
    app.use(`/${escapedPath}/`, apiProxy);
  }

  app.use('*', injectCustomElementsEs5Adapter(options.compile));
  app.use(
      '*',
      babelCompile(
          options.compile,
          options.moduleResolution,
          root,
          options.packageName,
          options.componentUrl,
          options.componentDir));

  app.use(`/${componentUrl}/`, polyserve);

  // `send` expects files to be specified relative to the given root and as a
  // URL rather than a file system path.
  const entrypoint = options.entrypoint ?
      urlFromPath(root as LocalFsPath, options.entrypoint as LocalFsPath) :
      'index.html';

  app.get('/*', (req, res) => {
    pushResources(options, req, res);
    const filePath = req.path;
    send(
        req,
        filePath,
        {root: root, index: entrypoint, etag: false, lastModified: false})
        .on('error',
            (error: send.SendError) => {
              if (error.status === 404 && !filePathRegex.test(filePath)) {
                // The static file handling middleware failed to find a file on
                // disk. Serve the entry point HTML file instead of a 404.
                send(req, entrypoint, {root: root}).pipe(res);
              } else {
                res.status(error.status || 500);
                res.type('html');
                res.end(escapeHtml(error.message));
              }
            })
        .pipe(res);
  });
  return app;
}


/**
 * Determines whether a protocol requires HTTPS
 * @param {string} protocol Protocol to evaluate.
 * @returns {boolean}
 */
function isHttps(protocol: string): boolean {
  return ['https/1.1', 'https', 'h2'].indexOf(protocol) > -1;
}


/**
 * Gets the URLs for the main and component pages
 * @param {ServerOptions} options
 * @returns {{serverUrl: {protocol: string, hostname: string, port: string},
 * componentUrl: url.Url}}
 */
export function getServerUrls(options: ServerOptions, server: http.Server) {
  options = applyDefaultServerOptions(options);
  const address = assertNotString(server.address());
  const serverUrl: url.Url = {
    protocol: isHttps(options.protocol) ? 'https' : 'http',
    hostname: address.address,
    port: String(address.port),
  };
  const componentUrl: url.Url = Object.assign({}, serverUrl);
  componentUrl.pathname = `${options.componentUrl}/${options.packageName}/`;
  return {serverUrl, componentUrl};
}


/**
 * Asserts that Node version is valid for h2 protocol
 * @param {ServerOptions} options
 */
function assertNodeVersion(options: ServerOptions) {
  if (options.protocol === 'h2') {
    const matches = /(\d+)\./.exec(process.version);
    if (matches) {
      const major = Number(matches[1]);
      assert(
          major >= 5,
          'h2 requires ALPN which is only supported in node.js >= 5.0');
    }
  }
}


/**
 * Creates an HTTP(S) server
 * @param app
 * @param {ServerOptions} options
 * @returns {Promise<http.Server>} Promise of server
 */
async function createServer(
    app: express.Application, options: ServerOptions): Promise<http.Server> {
  // tslint:disable-next-line: no-any bad typings
  const opt: any = {spdy: {protocols: [options.protocol]}};

  if (isHttps(options.protocol)) {
    const keys = await getTLSCertificate(options.keyPath, options.certPath);
    opt.key = keys.key;
    opt.cert = keys.cert;
  } else {
    opt.spdy.plain = true;
    opt.spdy.ssl = false;
  }

  return http.createServer(opt, app);
}


/**
 * Starts an HTTP(S) server serving the given app.
 */
export async function startWithApp(
    options: ServerOptions, app: express.Application): Promise<http.Server> {
  options = applyDefaultServerOptions(options);
  const ports = options.port ? [options.port] : SAUCE_PORTS;
  const server = await startWithFirstAvailablePort(options, app, ports);
  const urls = getServerUrls(options, server);
  openBrowser(options, urls.serverUrl, urls.componentUrl);

  return server;
}


async function startWithFirstAvailablePort(
    options: ServerOptions, app: express.Application, ports: number[]):
    Promise<http.Server> {
  for (const port of ports) {
    const server = await tryStartWithPort(options, app, port);
    if (server) {
      return server;
    }
  }
  throw new Error(`No available ports. Ports tried: ${JSON.stringify(ports)}`);
}


async function tryStartWithPort(
    options: ServerOptions, app: express.Application, port: number) {
  const server = await createServer(app, options);
  return new Promise<http.Server|null>((resolve, _reject) => {
    server.listen(port, options.hostname, () => {
      resolve(server);
    });

    server.on('error', (_err: {}) => {
      resolve(null);
    });
  });
}


// TODO(usergenic): Something changed in the typings of net.Server.address() in that
// it can now return AddressInfo OR string.  I don't know the circumstances where the
// the address() returns a string or how to handle it, so I made this assert function
// when calling on the address to fix compilation errors and have a runtime error as
// soon as the address is fetched.
export function assertNotString<T>(value: string|T): T {
  assert(typeof value !== 'string');
  return value as T;
}


(f) => {
                         const match = f.match(`^${options.componentDir}-(.*)`);
                         return match && {name: match[1], directory: match[0]};
                       }


(f) => f != null && f.name !== ''


(_req, res) => {
    res.contentType('json');
    res.send(JSON.stringify({
      packageName: options.packageName,
      mainlineServer: {
        port: assertNotString(mainlineInfo.server.address()).port,
      },
      variants: variantInfos.map((info) => {
        return {
          name: info.variantName,
          port: assertNotString(info.server.address()).port,
        };
      })
    }));
    res.end();
  }


(info) => {
        return {
          name: info.variantName,
          port: assertNotString(info.server.address()).port,
        };
      }


async (_req, res) => {
    res.contentType('html');
    const indexContents = await fs.readFile(indexPath, 'utf-8');
    res.send(indexContents);
    res.end();
  }


(handler, route) => {
      app.get(route, handler);
    }


(req, res) => {
    pushResources(options, req, res);
    const filePath = req.path;
    send(
        req,
        filePath,
        {root: root, index: entrypoint, etag: false, lastModified: false})
        .on('error',
            (error: send.SendError) => {
              if (error.status === 404 && !filePathRegex.test(filePath)) {
                // The static file handling middleware failed to find a file on
                // disk. Serve the entry point HTML file instead of a 404.
                send(req, entrypoint, {root: root}).pipe(res);
              } else {
                res.status(error.status || 500);
                res.type('html');
                res.end(escapeHtml(error.message));
              }
            })
        .pipe(res);
  }


(error: send.SendError) => {
              if (error.status === 404 && !filePathRegex.test(filePath)) {
                // The static file handling middleware failed to find a file on
                // disk. Serve the entry point HTML file instead of a 404.
                send(req, entrypoint, {root: root}).pipe(res);
              } else {
                res.status(error.status || 500);
                res.type('html');
                res.end(escapeHtml(error.message));
              }
            }


(resolve, _reject) => {
    server.listen(port, options.hostname, () => {
      resolve(server);
    });

    server.on('error', (_err: {}) => {
      resolve(null);
    });
  }


() => {
      resolve(server);
    }


(_err: {}) => {
      resolve(null);
    }


export interface ServerOptions {
  /** The root directory to serve **/
  root?: string;

  /**
   * The path on disk of the entry point HTML file that will be served for
   * app-shell style projects. Must be contained by `root`. Defaults to
   * `index.html`.
   */
  entrypoint?: string;

  /** Whether or not to compile JavaScript **/
  compile?: 'always'|'never'|'auto';

  /** Resolution algorithm to use for rewriting module specifiers */
  moduleResolution?: 'none'|'node';

  /** The port to serve from */
  port?: number;

  /** The hostname to serve from */
  hostname?: string;

  /** Headers to send with every response */
  headers?: {[name: string]: string};

  /** Whether to open the browser when run **/
  open?: boolean;

  /** The browser(s) to open when run with open argument **/
  browser?: string[];

  /** The URL path to open in each browser **/
  openPath?: string;

  /** The component directory to use **/
  componentDir?: string;

  /** The component url to serve **/
  componentUrl?: string;

  /** The package name to use for the root directory **/
  packageName?: string;

  /**
   * Sets npm mode: component directory is 'node_modules' and the package name
   * is read from package.json.
   */
  npm?: boolean;

  /** The HTTP protocol to use */
  protocol?: string;

  /** Path to TLS service key for HTTPS */
  keyPath?: string;

  /** Path to TLS certificate for HTTPS */
  certPath?: string;

  /** Path to H2 push-manifest file */
  pushManifestPath?: string;

  /** Proxy to redirect for all matching `path` to `target` */
  proxy?: {path: string, target: string};

  /**
   * An optional list of routes & route handlers to attach to the polyserve
   * app, to be handled before all others
   */
  additionalRoutes?: Map<string, express.RequestHandler>;
}


export interface PolyserveServer {
  kind: 'control'|'mainline'|'variant';
  server: http.Server;
  app: express.Application;
  options: ServerOptions;
}


/**
 * The `default` or `primary` server. If only one ServerInfo is returned from
 * startServers it must be a MainlineServer. This is the server that's running
 * with the default configuration and not running a variant configuration.
 */
export interface MainlineServer extends PolyserveServer {
  kind: 'mainline';
}


/**
 * These are servers which are running some named variant configuration. For
 * multiple variant dependency directories are detected/configured, there will
 * be one MainlineServer that serves out the default dependency directory, and
 * one VariantServer for each other dependency directory.
 */
export interface VariantServer extends PolyserveServer {
  kind: 'variant';
  variantName: string;
  dependencyDir: string;
}


/**
 * If more than one server is started by startServers, the main port will serve
 * out a control server. This server serves out an HTML interface that
 * describes the other servers which have been started, and provides convenience
 * links to them.
 */
export interface ControlServer extends PolyserveServer {
  kind: 'control';
}


export interface MultipleServersInfo {
  kind: 'MultipleServers';
  mainline: MainlineServer;
  variants: VariantServer[];
  control: ControlServer;
  servers: PolyserveServer[];
}


export type ExpressAppMapper = (app: express.Express, options: ServerOptions) =>
    Promise<express.Express>;


export type ServerInfo = MainlineServer|VariantServer|ControlServer;


export type StartServerResult = MainlineServer|MultipleServersInfo;


() => {
  let consoleService: ConsoleService;
  beforeAll(() => {
    consoleService = new ConsoleService();
  });

  describe('#getParameters', () => {
    it('should get valid parameters', () => {
      const argvs = [
        '/usr/bin/ts-node',
        '/blablabla inexistent parameters',
        '-h',
        '--directory',
        '/sample/path',
        '-D',
        'lala',
        'random text',
        '-f',
      ];

      const result = consoleService.getParameters(argvs);

      expect(result['help']).not.toBeFalsy();
      expect(result['directory']).toBe('/sample/path');
      expect(result['delete-all']).not.toBeFalsy();
      expect(result['lala']).toBeUndefined();
      expect(result['inexistent']).toBeUndefined();
      expect(result['full-scan']).not.toBeFalsy();
    });
    it('should get valid parameters 2', () => {
      const argvs = [
        '/usr/bin/ts-node',
        '/blablabla inexistent parameters',
        '-f',
        'lala',
        '-c',
        'red',
      ];

      const result = consoleService.getParameters(argvs);

      expect(result['help']).toBeFalsy();
      expect(result['full-scan']).not.toBeFalsy();
      expect(result['bg-color']).toBe('red');
    });
  });

  describe('#splitWordsByWidth', () => {
    it('should get array with text according to width', () => {
      const cases = [
        {
          expect: [
            'Lorem ipsum dolor sit amet, consectetur',
            'adipiscing elit. Mauris faucibus sit amet',
            'libero non vestibulum. Morbi ac tellus',
            'dolor. Duis consectetur eget lectus sed',
            'ullamcorper.',
          ],
          text:
            // tslint:disable-next-line: max-line-length
            'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris faucibus sit amet libero non vestibulum. Morbi ac tellus dolor. Duis consectetur eget lectus sed ullamcorper.',
          width: 43,
        },
        /* {
          text: 'Lorem ipsum dolor sit amet.',
          width: 2,
          expect: ['Lorem', 'ipsum', 'dolor', 'sit', 'amet.'],
        }, */
      ];

      cases.forEach(cas => {
        expect(consoleService.splitWordsByWidth(cas.text, cas.width)).toEqual(
          cas.expect,
        );
      });
    });
  });

  describe('#shortenText', () => {
    it('should short text according parameters', () => {
      const cases = [
        {
          cutFrom: 10,
          expect: '/sample/te.../service/split/this',
          text: '/sample/text/for/test how/service/split/this',
          width: 32,
        },
        {
          cutFrom: 5,
          expect: '/aaa/.../jjj/kkk',
          text: '/aaa/bbb/ccc/ddd/eee/fff/ggg/hhhh/iiii/jjj/kkk',
          width: 16,
        },
        {
          cutFrom: 3,
          expect: '/neketaro/a:desktop/folder',
          text: '/neketaro/a:desktop/folder',
          width: 50,
        },
      ];

      cases.forEach(cas => {
        const result = consoleService.shortenText(
          cas.text,
          cas.width,
          cas.cutFrom,
        );
        expect(result).toEqual(cas.expect);
      });
    });

    it('should no modify input if "cutFrom" > text length', () => {
      const text = '/sample/text/';
      const expectResult = '/sample/text/';
      const width = 5;
      const cutFrom = 50;

      const result = consoleService.shortenText(text, width, cutFrom);
      expect(result).toEqual(expectResult);
    });

    it('should no modify input if "cutFrom" > width', () => {
      const text = '/sample/text/';
      const expectResult = '/sample/text/';
      const width = 5;
      const cutFrom = 7;

      const result = consoleService.shortenText(text, width, cutFrom);
      expect(result).toEqual(expectResult);
    });

    it('should ignore negative parameters', () => {
      const cases = [
        {
          cutFrom: -10,
          expect: '/sample/text/for/test how/service/split/thisA',
          text: '/sample/text/for/test how/service/split/thisA',
          width: 5,
        },
        {
          cutFrom: 10,
          expect: '/sample/text/for/test how/service/split/thisB',
          text: '/sample/text/for/test how/service/split/thisB',
          width: -10,
        },
        {
          cutFrom: -20,
          expect: '/sample/text/for/test how/service/split/thisC',
          text: '/sample/text/for/test how/service/split/thisC',
          width: -10,
        },
      ];

      cases.forEach(cas => {
        const result = consoleService.shortenText(
          cas.text,
          cas.width,
          cas.cutFrom,
        );
        expect(result).toEqual(cas.expect);
      });
    });
  });
}


() => {
    consoleService = new ConsoleService();
  }


() => {
    it('should get valid parameters', () => {
      const argvs = [
        '/usr/bin/ts-node',
        '/blablabla inexistent parameters',
        '-h',
        '--directory',
        '/sample/path',
        '-D',
        'lala',
        'random text',
        '-f',
      ];

      const result = consoleService.getParameters(argvs);

      expect(result['help']).not.toBeFalsy();
      expect(result['directory']).toBe('/sample/path');
      expect(result['delete-all']).not.toBeFalsy();
      expect(result['lala']).toBeUndefined();
      expect(result['inexistent']).toBeUndefined();
      expect(result['full-scan']).not.toBeFalsy();
    });
    it('should get valid parameters 2', () => {
      const argvs = [
        '/usr/bin/ts-node',
        '/blablabla inexistent parameters',
        '-f',
        'lala',
        '-c',
        'red',
      ];

      const result = consoleService.getParameters(argvs);

      expect(result['help']).toBeFalsy();
      expect(result['full-scan']).not.toBeFalsy();
      expect(result['bg-color']).toBe('red');
    });
  }


() => {
      const argvs = [
        '/usr/bin/ts-node',
        '/blablabla inexistent parameters',
        '-h',
        '--directory',
        '/sample/path',
        '-D',
        'lala',
        'random text',
        '-f',
      ];

      const result = consoleService.getParameters(argvs);

      expect(result['help']).not.toBeFalsy();
      expect(result['directory']).toBe('/sample/path');
      expect(result['delete-all']).not.toBeFalsy();
      expect(result['lala']).toBeUndefined();
      expect(result['inexistent']).toBeUndefined();
      expect(result['full-scan']).not.toBeFalsy();
    }


() => {
      const argvs = [
        '/usr/bin/ts-node',
        '/blablabla inexistent parameters',
        '-f',
        'lala',
        '-c',
        'red',
      ];

      const result = consoleService.getParameters(argvs);

      expect(result['help']).toBeFalsy();
      expect(result['full-scan']).not.toBeFalsy();
      expect(result['bg-color']).toBe('red');
    }


() => {
    it('should get array with text according to width', () => {
      const cases = [
        {
          expect: [
            'Lorem ipsum dolor sit amet, consectetur',
            'adipiscing elit. Mauris faucibus sit amet',
            'libero non vestibulum. Morbi ac tellus',
            'dolor. Duis consectetur eget lectus sed',
            'ullamcorper.',
          ],
          text:
            // tslint:disable-next-line: max-line-length
            'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris faucibus sit amet libero non vestibulum. Morbi ac tellus dolor. Duis consectetur eget lectus sed ullamcorper.',
          width: 43,
        },
        /* {
          text: 'Lorem ipsum dolor sit amet.',
          width: 2,
          expect: ['Lorem', 'ipsum', 'dolor', 'sit', 'amet.'],
        }, */
      ];

      cases.forEach(cas => {
        expect(consoleService.splitWordsByWidth(cas.text, cas.width)).toEqual(
          cas.expect,
        );
      });
    });
  }


() => {
      const cases = [
        {
          expect: [
            'Lorem ipsum dolor sit amet, consectetur',
            'adipiscing elit. Mauris faucibus sit amet',
            'libero non vestibulum. Morbi ac tellus',
            'dolor. Duis consectetur eget lectus sed',
            'ullamcorper.',
          ],
          text:
            // tslint:disable-next-line: max-line-length
            'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris faucibus sit amet libero non vestibulum. Morbi ac tellus dolor. Duis consectetur eget lectus sed ullamcorper.',
          width: 43,
        },
        /* {
          text: 'Lorem ipsum dolor sit amet.',
          width: 2,
          expect: ['Lorem', 'ipsum', 'dolor', 'sit', 'amet.'],
        }, */
      ];

      cases.forEach(cas => {
        expect(consoleService.splitWordsByWidth(cas.text, cas.width)).toEqual(
          cas.expect,
        );
      });
    }


cas => {
        expect(consoleService.splitWordsByWidth(cas.text, cas.width)).toEqual(
          cas.expect,
        );
      }


() => {
    it('should short text according parameters', () => {
      const cases = [
        {
          cutFrom: 10,
          expect: '/sample/te.../service/split/this',
          text: '/sample/text/for/test how/service/split/this',
          width: 32,
        },
        {
          cutFrom: 5,
          expect: '/aaa/.../jjj/kkk',
          text: '/aaa/bbb/ccc/ddd/eee/fff/ggg/hhhh/iiii/jjj/kkk',
          width: 16,
        },
        {
          cutFrom: 3,
          expect: '/neketaro/a:desktop/folder',
          text: '/neketaro/a:desktop/folder',
          width: 50,
        },
      ];

      cases.forEach(cas => {
        const result = consoleService.shortenText(
          cas.text,
          cas.width,
          cas.cutFrom,
        );
        expect(result).toEqual(cas.expect);
      });
    });

    it('should no modify input if "cutFrom" > text length', () => {
      const text = '/sample/text/';
      const expectResult = '/sample/text/';
      const width = 5;
      const cutFrom = 50;

      const result = consoleService.shortenText(text, width, cutFrom);
      expect(result).toEqual(expectResult);
    });

    it('should no modify input if "cutFrom" > width', () => {
      const text = '/sample/text/';
      const expectResult = '/sample/text/';
      const width = 5;
      const cutFrom = 7;

      const result = consoleService.shortenText(text, width, cutFrom);
      expect(result).toEqual(expectResult);
    });

    it('should ignore negative parameters', () => {
      const cases = [
        {
          cutFrom: -10,
          expect: '/sample/text/for/test how/service/split/thisA',
          text: '/sample/text/for/test how/service/split/thisA',
          width: 5,
        },
        {
          cutFrom: 10,
          expect: '/sample/text/for/test how/service/split/thisB',
          text: '/sample/text/for/test how/service/split/thisB',
          width: -10,
        },
        {
          cutFrom: -20,
          expect: '/sample/text/for/test how/service/split/thisC',
          text: '/sample/text/for/test how/service/split/thisC',
          width: -10,
        },
      ];

      cases.forEach(cas => {
        const result = consoleService.shortenText(
          cas.text,
          cas.width,
          cas.cutFrom,
        );
        expect(result).toEqual(cas.expect);
      });
    });
  }


() => {
      const cases = [
        {
          cutFrom: 10,
          expect: '/sample/te.../service/split/this',
          text: '/sample/text/for/test how/service/split/this',
          width: 32,
        },
        {
          cutFrom: 5,
          expect: '/aaa/.../jjj/kkk',
          text: '/aaa/bbb/ccc/ddd/eee/fff/ggg/hhhh/iiii/jjj/kkk',
          width: 16,
        },
        {
          cutFrom: 3,
          expect: '/neketaro/a:desktop/folder',
          text: '/neketaro/a:desktop/folder',
          width: 50,
        },
      ];

      cases.forEach(cas => {
        const result = consoleService.shortenText(
          cas.text,
          cas.width,
          cas.cutFrom,
        );
        expect(result).toEqual(cas.expect);
      });
    }


cas => {
        const result = consoleService.shortenText(
          cas.text,
          cas.width,
          cas.cutFrom,
        );
        expect(result).toEqual(cas.expect);
      }


() => {
      const text = '/sample/text/';
      const expectResult = '/sample/text/';
      const width = 5;
      const cutFrom = 50;

      const result = consoleService.shortenText(text, width, cutFrom);
      expect(result).toEqual(expectResult);
    }


() => {
      const text = '/sample/text/';
      const expectResult = '/sample/text/';
      const width = 5;
      const cutFrom = 7;

      const result = consoleService.shortenText(text, width, cutFrom);
      expect(result).toEqual(expectResult);
    }


() => {
      const cases = [
        {
          cutFrom: -10,
          expect: '/sample/text/for/test how/service/split/thisA',
          text: '/sample/text/for/test how/service/split/thisA',
          width: 5,
        },
        {
          cutFrom: 10,
          expect: '/sample/text/for/test how/service/split/thisB',
          text: '/sample/text/for/test how/service/split/thisB',
          width: -10,
        },
        {
          cutFrom: -20,
          expect: '/sample/text/for/test how/service/split/thisC',
          text: '/sample/text/for/test how/service/split/thisC',
          width: -10,
        },
      ];

      cases.forEach(cas => {
        const result = consoleService.shortenText(
          cas.text,
          cas.width,
          cas.cutFrom,
        );
        expect(result).toEqual(cas.expect);
      });
    }


@NgModule({
  declarations: [AppComponent],
  imports: [
    AppRoutingModule,
    CoreModule,
    SharedModule,
    NgApplicationInsightsModule.forRoot({
      enabled: environment.production,
      instrumentationKey: '987654321-98765432-987654321-987654321',
    }),
  ],
  providers: [
    { provide: LOCALE_ID, useValue: 'pt-BR' },
    { provide: HTTP_INTERCEPTORS, useClass: DefaultInterceptor, multi: true },
    { provide: ErrorHandler, useClass: ErrorHandlerService },
  ],
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA],
})
export class AppModule {}


/** A directive for passing contents to small stage header. */
@Directive({
  // tslint:disable-next-line:directive-selector
  selector: 'nx-small-stage-header'
})
export class NxSmallStageHeaderDirective {}


export interface IColumnsFields {
  columns: number;
  components: IComponentType[];
}


export type IColumns = Entry<IColumnsFields>;


<TData extends Data>(
  service: Service<TData>,
  options: InfiniteScrollOptions<TData> = {},
) => {
  const {
    target,
    isNoMore,
    threshold = 100,
    reloadDeps = [],
    manual,
    onBefore,
    onSuccess,
    onError,
    onFinally,
  } = options;

  const [finalData, setFinalData] = useState<TData>();
  const [loadingMore, setLoadingMore] = useState(false);

  const noMore = useMemo(() => {
    if (!isNoMore) return false;
    return isNoMore(finalData);
  }, [finalData]);

  const { loading, run, runAsync, cancel } = useRequest(
    async (lastData?: TData) => {
      const currentData = await service(lastData);
      if (!lastData) {
        setFinalData(currentData);
      } else {
        setFinalData({
          ...currentData,
          // @ts-ignore
          list: [...lastData.list, ...currentData.list],
        });
      }
      return currentData;
    },
    {
      manual,
      onFinally: (_, d, e) => {
        setLoadingMore(false);
        onFinally?.(d, e);
      },
      onBefore: () => onBefore?.(),
      onSuccess: (d) => {
        setTimeout(() => {
          // eslint-disable-next-line @typescript-eslint/no-use-before-define
          scrollMethod();
        });
        onSuccess?.(d);
      },
      onError: (e) => onError?.(e),
    },
  );

  const loadMore = () => {
    if (noMore) return;
    setLoadingMore(true);
    run(finalData);
  };

  const loadMoreAsync = () => {
    if (noMore) return;
    setLoadingMore(true);
    return runAsync(finalData);
  };

  const mutate = (data?: TData) => {
    setFinalData(data);
  };

  const reload = () => run();
  const reloadAsync = () => runAsync();

  const scrollMethod = () => {
    const el = getTargetElement(target);
    if (!el) {
      return;
    }

    const scrollTop = getScrollTop(el);
    const scrollHeight = getScrollHeight(el);
    const clientHeight = getClientHeight(el);

    if (scrollHeight - scrollTop <= clientHeight + threshold) {
      loadMore();
    }
  };

  useEventListener(
    'scroll',
    () => {
      if (loading || loadingMore) {
        return;
      }
      scrollMethod();
    },
    { target },
  );

  useUpdateEffect(() => {
    run();
  }, [...reloadDeps]);

  return {
    data: finalData,
    loading: !loadingMore && loading,
    loadingMore,
    noMore,

    loadMore: useMemoizedFn(loadMore),
    loadMoreAsync: useMemoizedFn(loadMoreAsync),
    reload: useMemoizedFn(reload),
    reloadAsync: useMemoizedFn(reloadAsync),
    mutate: useMemoizedFn(mutate),
    cancel,
  };
}


() => {
    if (!isNoMore) return false;
    return isNoMore(finalData);
  }


async (lastData?: TData) => {
      const currentData = await service(lastData);
      if (!lastData) {
        setFinalData(currentData);
      } else {
        setFinalData({
          ...currentData,
          // @ts-ignore
          list: [...lastData.list, ...currentData.list],
        });
      }
      return currentData;
    }


(_, d, e) => {
        setLoadingMore(false);
        onFinally?.(d, e);
      }


() => onBefore?.()


(d) => {
        setTimeout(() => {
          // eslint-disable-next-line @typescript-eslint/no-use-before-define
          scrollMethod();
        });
        onSuccess?.(d);
      }


() => {
          // eslint-disable-next-line @typescript-eslint/no-use-before-define
          scrollMethod();
        }


(e) => onError?.(e)


() => {
    if (noMore) return;
    setLoadingMore(true);
    run(finalData);
  }


() => {
    if (noMore) return;
    setLoadingMore(true);
    return runAsync(finalData);
  }


(data?: TData) => {
    setFinalData(data);
  }


() => run()


() => runAsync()


() => {
    const el = getTargetElement(target);
    if (!el) {
      return;
    }

    const scrollTop = getScrollTop(el);
    const scrollHeight = getScrollHeight(el);
    const clientHeight = getClientHeight(el);

    if (scrollHeight - scrollTop <= clientHeight + threshold) {
      loadMore();
    }
  }


() => {
      if (loading || loadingMore) {
        return;
      }
      scrollMethod();
    }


() => {
    run();
  }


export function atomWithQuery<Data, Variables extends object>(
  createQueryArgs: (get: Getter) => QueryArgs<Data, Variables>,
  getClient?: (get: Getter) => Client
): WritableAtom<OperationResultWithData<Data, Variables>, AtomWithQueryAction>


export function atomWithQuery<Data, Variables extends object>(
  createQueryArgs: (get: Getter) => QueryArgsWithPause<Data, Variables>,
  getClient?: (get: Getter) => Client
): WritableAtom<
  OperationResultWithData<Data, Variables> | null,
  AtomWithQueryAction
>


export function atomWithQuery<Data, Variables extends object>(
  createQueryArgs: (get: Getter) => QueryArgs<Data, Variables>,
  getClient: (get: Getter) => Client = (get) => get(clientAtom)
) {
  type ResultAtom = PrimitiveAtom<
    | OperationResultWithData<Data, Variables>
    | Promise<OperationResultWithData<Data, Variables>>
  >
  const queryResultAtom = atom((get) => {
    const args = createQueryArgs(get)
    if ((args as { pause?: boolean }).pause) {
      return null
    }
    const client = getClient(get)
    let resolve:
      | ((result: OperationResultWithData<Data, Variables>) => void)
      | null = null
    const baseResultAtom: ResultAtom = atom<
      | OperationResultWithData<Data, Variables>
      | Promise<OperationResultWithData<Data, Variables>>
    >(
      new Promise<OperationResultWithData<Data, Variables>>((r) => {
        resolve = r
      })
    )
    let setResult: (
      result:
        | OperationResultWithData<Data, Variables>
        | Promise<OperationResultWithData<Data, Variables>>
    ) => void = () => {
      throw new Error('setting result without mount')
    }
    const listener = (
      result:
        | OperationResult<Data, Variables>
        | Promise<OperationResultWithData<Data, Variables>>
    ) => {
      if (result instanceof Promise) {
        setResult(result)
        return
      }
      if (!isOperationResultWithData(result)) {
        throw new Error('result does not have data')
      }
      if (resolve) {
        resolve(result)
        resolve = null
      } else {
        setResult(result)
      }
    }
    client
      .query(args.query, args.variables, {
        ...(args.requestPolicy && { requestPolicy: args.requestPolicy }),
        ...args.context,
      })
      .toPromise()
      .then(listener)
      .catch(() => {
        // TODO error handling
      })
    baseResultAtom.onMount = (update) => {
      setResult = update
    }
    const subscriptionAtom = atom<Subscription | null>(null)
    const resultAtom = atom(
      (get) => get(baseResultAtom),
      (get, set, callback: (cleanup: () => void) => void) => {
        const subscription = pipe(
          client.query(args.query, args.variables, {
            ...(args.requestPolicy && { requestPolicy: args.requestPolicy }),
            ...args.context,
          }),
          skip(1), // handled by toPromise
          subscribe(listener)
        )
        set(subscriptionAtom, subscription)
        callback(() => get(subscriptionAtom)?.unsubscribe())
      }
    )
    resultAtom.onMount = (init) => {
      let cleanup: (() => void) | undefined
      init((c) => {
        cleanup = c
      })
      return cleanup
    }
    return { args, client, resultAtom, subscriptionAtom, listener }
  })
  const queryAtom = atom(
    (get) => {
      const queryResult = get(queryResultAtom)
      if (!queryResult) {
        return null
      }
      const { resultAtom } = queryResult
      return get(resultAtom)
    },
    (get, set, action: AtomWithQueryAction) => {
      switch (action.type) {
        case 'reexecute': {
          const queryResult = get(queryResultAtom)
          if (!queryResult) {
            throw new Error('query is paused')
          }
          const { args, client, subscriptionAtom, listener } = queryResult
          listener(new Promise<never>(() => {})) // infinite pending
          const newSubscription = pipe(
            client.query(args.query, args.variables, {
              ...(args.requestPolicy && { requestPolicy: args.requestPolicy }),
              ...args.context,
              ...action.opts,
            }),
            subscribe(listener)
          )
          const oldSubscription = get(subscriptionAtom)
          oldSubscription?.unsubscribe()
          set(subscriptionAtom, newSubscription)
        }
      }
    }
  )
  return queryAtom
}


<Data, Variables>(
  result: OperationResult<Data, Variables>
): result is OperationResultWithData<Data, Variables> =>
  'data' in result && !result.error


(get) => get(clientAtom)


(get) => {
    const args = createQueryArgs(get)
    if ((args as { pause?: boolean }).pause) {
      return null
    }
    const client = getClient(get)
    let resolve:
      | ((result: OperationResultWithData<Data, Variables>) => void)
      | null = null
    const baseResultAtom: ResultAtom = atom<
      | OperationResultWithData<Data, Variables>
      | Promise<OperationResultWithData<Data, Variables>>
    >(
      new Promise<OperationResultWithData<Data, Variables>>((r) => {
        resolve = r
      })
    )
    let setResult: (
      result:
        | OperationResultWithData<Data, Variables>
        | Promise<OperationResultWithData<Data, Variables>>
    ) => void = () => {
      throw new Error('setting result without mount')
    }
    const listener = (
      result:
        | OperationResult<Data, Variables>
        | Promise<OperationResultWithData<Data, Variables>>
    ) => {
      if (result instanceof Promise) {
        setResult(result)
        return
      }
      if (!isOperationResultWithData(result)) {
        throw new Error('result does not have data')
      }
      if (resolve) {
        resolve(result)
        resolve = null
      } else {
        setResult(result)
      }
    }
    client
      .query(args.query, args.variables, {
        ...(args.requestPolicy && { requestPolicy: args.requestPolicy }),
        ...args.context,
      })
      .toPromise()
      .then(listener)
      .catch(() => {
        // TODO error handling
      })
    baseResultAtom.onMount = (update) => {
      setResult = update
    }
    const subscriptionAtom = atom<Subscription | null>(null)
    const resultAtom = atom(
      (get) => get(baseResultAtom),
      (get, set, callback: (cleanup: () => void) => void) => {
        const subscription = pipe(
          client.query(args.query, args.variables, {
            ...(args.requestPolicy && { requestPolicy: args.requestPolicy }),
            ...args.context,
          }),
          skip(1), // handled by toPromise
          subscribe(listener)
        )
        set(subscriptionAtom, subscription)
        callback(() => get(subscriptionAtom)?.unsubscribe())
      }
    )
    resultAtom.onMount = (init) => {
      let cleanup: (() => void) | undefined
      init((c) => {
        cleanup = c
      })
      return cleanup
    }
    return { args, client, resultAtom, subscriptionAtom, listener }
  }


(r) => {
        resolve = r
      }


() => {
      throw new Error('setting result without mount')
    }


(
      result:
        | OperationResult<Data, Variables>
        | Promise<OperationResultWithData<Data, Variables>>
    ) => {
      if (result instanceof Promise) {
        setResult(result)
        return
      }
      if (!isOperationResultWithData(result)) {
        throw new Error('result does not have data')
      }
      if (resolve) {
        resolve(result)
        resolve = null
      } else {
        setResult(result)
      }
    }


() => {
        // TODO error handling
      }


(update) => {
      setResult = update
    }


(get) => get(baseResultAtom)


(get, set, callback: (cleanup: () => void) => void) => {
        const subscription = pipe(
          client.query(args.query, args.variables, {
            ...(args.requestPolicy && { requestPolicy: args.requestPolicy }),
            ...args.context,
          }),
          skip(1), // handled by toPromise
          subscribe(listener)
        )
        set(subscriptionAtom, subscription)
        callback(() => get(subscriptionAtom)?.unsubscribe())
      }


() => get(subscriptionAtom)?.unsubscribe()


(init) => {
      let cleanup: (() => void) | undefined
      init((c) => {
        cleanup = c
      })
      return cleanup
    }


(c) => {
        cleanup = c
      }


(get) => {
      const queryResult = get(queryResultAtom)
      if (!queryResult) {
        return null
      }
      const { resultAtom } = queryResult
      return get(resultAtom)
    }


(get, set, action: AtomWithQueryAction) => {
      switch (action.type) {
        case 'reexecute': {
          const queryResult = get(queryResultAtom)
          if (!queryResult) {
            throw new Error('query is paused')
          }
          const { args, client, subscriptionAtom, listener } = queryResult
          listener(new Promise<never>(() => {})) // infinite pending
          const newSubscription = pipe(
            client.query(args.query, args.variables, {
              ...(args.requestPolicy && { requestPolicy: args.requestPolicy }),
              ...args.context,
              ...action.opts,
            }),
            subscribe(listener)
          )
          const oldSubscription = get(subscriptionAtom)
          oldSubscription?.unsubscribe()
          set(subscriptionAtom, newSubscription)
        }
      }
    }


interface AtomWithQueryAction {
  type: 'reexecute'
  opts?: Partial<OperationContext>
}


interface QueryArgs<Data, Variables extends object> {
  query: TypedDocumentNode<Data, Variables> | string
  variables?: Variables
  requestPolicy?: RequestPolicy
  context?: Partial<OperationContext>
}


type OperationResultWithData<Data, Variables> = OperationResult<
  Data,
  Variables
> & {
  data: Data
}


type QueryArgsWithPause<Data, Variables extends object> = QueryArgs<
  Data,
  Variables
> & {
  pause: boolean
}


type ResultAtom = PrimitiveAtom<
    | OperationResultWithData<Data, Variables>
    | Promise<OperationResultWithData<Data, Variables>>
  >


({ width, height, color, filled }: Props) => {
  return (
    <svg width={width} height={height} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512">
      {filled ? (
        <path
          fill={color}
          d="M259.3 17.8L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0z"
        />
      ) : (
        <path
          fill={color}
          d="M528.1 171.5L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6zM388.6 312.3l23.7 138.4L288 385.4l-124.3 65.3 23.7-138.4-100.6-98 139-20.2 62.2-126 62.2 126 139 20.2-100.6 98z"
        />


type Props = {
  width: number | string;
  height: number | string;
  color: string;
  filled: boolean;
};


filled ? (
        <path
          fill={color}
          d="M259.3 17.8L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0z"
        />
      ) : (
        <path
          fill={color}
          d="M528.1 171.5L382 150.2 316.7 17.8c-11.7-23.6-45.6-23.9-57.4 0L194 150.2 47.9 171.5c-26.2 3.8-36.7 36.1-17.7 54.6l105.7 103-25 145.5c-4.5 26.3 23.2 46 46.4 33.7L288 439.6l130.7 68.7c23.2 12.2 50.9-7.4 46.4-33.7l-25-145.5 105.7-103c19-18.5 8.5-50.8-17.7-54.6zM388.6 312.3l23.7 138.4L288 385.4l-124.3 65.3 23.7-138.4-100.6-98 139-20.2 62.2-126 62.2 126 139 20.2-100.6 98z"


export class HelloWorldModel extends Observable {
  public message: string;
  private wechat: Wechat;

  constructor() {
    super();

    this.wechat = new Wechat();
    this.message = this.wechat.message;
  }
}


export class OwnedFactory extends ContractFactory {
  constructor(signer?: Signer) {
    super(_abi, _bytecode, signer);
  }

  deploy(overrides?: TransactionOverrides): Promise<Owned> {
    return super.deploy(overrides) as Promise<Owned>;
  }
  getDeployTransaction(overrides?: TransactionOverrides): UnsignedTransaction {
    return super.getDeployTransaction(overrides);
  }
  attach(address: string): Owned {
    return super.attach(address) as Owned;
  }
  connect(signer: Signer): OwnedFactory {
    return super.connect(signer) as OwnedFactory;
  }
  static connect(address: string, signerOrProvider: Signer | Provider): Owned {
    return new Contract(address, _abi, signerOrProvider) as Owned;
  }
}


deploy(overrides?: TransactionOverrides): Promise<Owned> {
    return super.deploy(overrides) as Promise<Owned>;
  }


getDeployTransaction(overrides?: TransactionOverrides): UnsignedTransaction {
    return super.getDeployTransaction(overrides);
  }


attach(address: string): Owned {
    return super.attach(address) as Owned;
  }


connect(signer: Signer): OwnedFactory {
    return super.connect(signer) as OwnedFactory;
  }


static connect(address: string, signerOrProvider: Signer | Provider): Owned {
    return new Contract(address, _abi, signerOrProvider) as Owned;
  }


@Controller('feed')
export class FeedController {}


@Component({
  selector: "password-reset-snack",
  templateUrl: "password-reset.component.html",
  styleUrls: ["password-reset.component.css"],
})
export class PasswordResetSnackComponent {}


(props: IIconProps) => (
  <svg
    xmlns="http://www.w3.org/2000/svg"


(pos: pc.Vec3) => {
            const i = Math.floor(pos.x + 0.5);
            const j = Math.floor(pos.z + 0.5);
            const colorVec = new pc.Vec3(Math.random(), Math.random(), Math.random());
            colorVec.mulScalar(1 / colorVec.length());
            // @ts-ignore engine-tsd
            boxes[`${i}${j}`].model.material.emissive = new pc.Color(colorVec.x, colorVec.y, colorVec.z);
            highlightedBoxes.push(boxes[`${i}${j}`]);
        }


(dt) => {
            modelEntityParent.rotate(0, 13.8 * dt, 0);
        }


(event: any) => {
            // highlight the box that is under the foot's bone position
            highlightBox(modelEntity.findByName(event.bone).getPosition());
        }


(dt) => {
            // on update, iterate over any currently highlighted boxes and reduce their emissive property
            highlightedBoxes.forEach((box: pc.Entity) => {
                // @ts-ignore engine-tsd
                const emissive = box.model.material.emissive;
                emissive.lerp(emissive, pc.Color.BLACK, 0.08);
                box.model.material.update();
            });
            // remove old highlighted boxes from the update loop
            while (highlightedBoxes.length > 5) {
                highlightedBoxes.shift();
            }

            // set the camera to follow the model
            const modelPosition = modelEntity.getPosition().clone();
            modelPosition.y = 0.5;
            cameraEntity.lookAt(modelPosition);
        }


(box: pc.Entity) => {
                // @ts-ignore engine-tsd
                const emissive = box.model.material.emissive;
                emissive.lerp(emissive, pc.Color.BLACK, 0.08);
                box.model.material.update();
            }


class EventsExample extends Example {
    static CATEGORY = 'Animation';
    static NAME = 'Events';

    load() {
        return <>
            <AssetLoader name='model' type='container' url='static/assets/models/bitmoji.glb' />
            <AssetLoader name='walkAnim' type='container' url='static/assets/animations/bitmoji/walk.glb' />
            <AssetLoader name='helipad.dds' type='cubemap' url='static/assets/cubemaps/helipad.dds' data={{ type: pc.TEXTURETYPE_RGBM }}


load() {
        return <>
            <AssetLoader name='model' type='container' url='static/assets/models/bitmoji.glb' />
            <AssetLoader name='walkAnim' type='container' url='static/assets/animations/bitmoji/walk.glb' />
            <AssetLoader name='helipad.dds' type='cubemap' url='static/assets/cubemaps/helipad.dds' data={{ type: pc.TEXTURETYPE_RGBM }}


// create a floor made up of box models
for (let i = -5; i


declare class JBListTable extends Object {
	onRemoveDisposable : Disposable;
	table : JBTable;
	constructor(arg1 : JTable);
	stopEditing() : void;
	getOnRemoveDisposable() : Disposable;
	static a(arg1 : JBTableRowEditor) : void;
	getTable() : JBTable;
	getRowRenderer(arg1 : number) : JBTableRowRenderer;
	getRowEditor(arg1 : number) : JBTableRowEditor;
	getRowAt(arg1 : number) : JBTableRow;
	isRowEditable(arg1 : number) : boolean;
	isRowEmpty(arg1 : number) : boolean;
	static createEditorTextFieldPresentation(arg1 : Project, arg2 : FileType, arg3 : string, arg4 : boolean, arg5 : boolean) : JComponent;
}


class RowResizeAnimator {
		constructor(arg1 : JTable);
		resize(arg1 : number, arg2 : number) : void;
		a() : void;
		b() : void;
		a(arg1 : number) : void;
	}


class RowAnimationState extends Object {
			constructor(arg1 : number, arg2 : number);
			doAnimationStep(arg1 : number) : boolean;
		}


class MyCellEditor {
		cellEditorValue : Object;
		constructor(arg1 : JBTableRowEditor);
		a() : void;
	}


interface RowResizeAnimator extends ActionListener, Disposable {}


interface MyCellEditor extends AbstractTableCellEditor {}


stopEditing() : void;


getOnRemoveDisposable() : Disposable;


static a(arg1 : JBTableRowEditor) : void;


getTable() : JBTable;


getRowRenderer(arg1 : number) : JBTableRowRenderer;


getRowEditor(arg1 : number) : JBTableRowEditor;


getRowAt(arg1 : number) : JBTableRow;


isRowEditable(arg1 : number) : boolean;


isRowEmpty(arg1 : number) : boolean;


static createEditorTextFieldPresentation(arg1 : Project, arg2 : FileType, arg3 : string, arg4 : boolean, arg5 : boolean) : JComponent;


resize(arg1 : number, arg2 : number) : void;


a() : void;


b() : void;


a(arg1 : number) : void;


doAnimationStep(arg1 : number) : boolean;


interface Map {
    autodetectLanguage(fallbackLanguage?: string): void;
    setLanguage(language: string, noAlt?: boolean): void;
    setLanguageEnabled(enable: boolean): void;
  }


() => {
    const targetFilename = 'findThisFile12345.txt'
    let targetFilePath: string
    let tempFolder: string
    const foldersToCleanUp: string[] = []

    beforeEach(async () => {
        // Make a temp folder for all these tests
        tempFolder = await makeTemporaryToolkitFolder()
        targetFilePath = path.join(tempFolder, targetFilename)

        await writeFile(targetFilePath, 'Hello, World!', 'utf8')

        foldersToCleanUp.push(tempFolder)
    })

    afterEach(async () => {
        for (const folder of foldersToCleanUp) {
            await remove(folder)
        }
    })

    describe('makeTemporaryToolkitFolder', () => {
        it(`makes temp dirs as children to filesystemUtilities.tempDirPath ('${tempDirPath}')`, async () => {
            const parentFolder = path.dirname(tempFolder)

            assert.strictEqual(
                parentFolder,
                tempDirPath,
                `expected tempFolder ('${tempFolder}') to be in tempDirPath ('${tempDirPath}')`
            )
        })

        it('creates a folder', async () => {
            assert.ok(await fileExists(tempFolder), `expected folder to exist: ${tempFolder}`)
        })

        it('makes nested temp dirs', async () => {
            const nestedTempDirPath = await makeTemporaryToolkitFolder('nestedSubfolder', 'moreNestedSubfolder')

            foldersToCleanUp.push(nestedTempDirPath)
            foldersToCleanUp.push(path.join(tempDirPath, 'nestedSubfolder'))

            assert(
                nestedTempDirPath.startsWith(tempDirPath),
                `expected nestedTempDirPath ('${nestedTempDirPath}') to be in tempDirPath ('${tempDirPath}')`
            )
            const tmpDirExists = await fileExists(nestedTempDirPath)
            assert(tmpDirExists, `tempFolder should exist: '${nestedTempDirPath}'`)
        })
    })

    it('isInDirectory()', () => {
        const basePath = path.join('this', 'is', 'the', 'way')
        const extendedPath = path.join(basePath, 'forward')
        const filename = 'yadayadayada.log'

        assert.ok(isInDirectory(basePath, basePath))
        assert.ok(isInDirectory(basePath, extendedPath))
        assert.ok(isInDirectory(basePath, path.join(basePath, filename)))
        assert.ok(isInDirectory(basePath, path.join(extendedPath, filename)))
        assert.ok(!isInDirectory(basePath, path.join('what', 'are', 'you', 'looking', 'at')))
        assert.ok(!isInDirectory(basePath, `${basePath}point`))
        assert.ok(isInDirectory('/foo/bar/baz/', '/foo/bar/baz/a.txt'))
        assert.ok(isInDirectory('/foo/bar/baz/', ''))
        assert.ok(isInDirectory('/', ''))
        assert.ok(isInDirectory('', 'foo'))
        assert.ok(isInDirectory('foo', 'foo'))

        if (os.platform() === 'win32') {
            assert.ok(isInDirectory('/foo/bar/baz/', '/FOO/BAR/BAZ/A.TXT'))
            assert.ok(isInDirectory('C:\\foo\\bar\\baz\\', 'C:/FOO/BAR/BAZ/A.TXT'))
            assert.ok(isInDirectory('C:\\foo\\bar\\baz', 'C:\\foo\\bar\\baz\\a.txt'))
        } else {
            assert.ok(!isInDirectory('/foo/bar/baz/', '/FOO/BAR/BAZ/A.TXT'))
        }
    })
}


async () => {
        // Make a temp folder for all these tests
        tempFolder = await makeTemporaryToolkitFolder()
        targetFilePath = path.join(tempFolder, targetFilename)

        await writeFile(targetFilePath, 'Hello, World!', 'utf8')

        foldersToCleanUp.push(tempFolder)
    }


async () => {
        for (const folder of foldersToCleanUp) {
            await remove(folder)
        }
    }


() => {
        it(`makes temp dirs as children to filesystemUtilities.tempDirPath ('${tempDirPath}')`, async () => {
            const parentFolder = path.dirname(tempFolder)

            assert.strictEqual(
                parentFolder,
                tempDirPath,
                `expected tempFolder ('${tempFolder}') to be in tempDirPath ('${tempDirPath}')`
            )
        })

        it('creates a folder', async () => {
            assert.ok(await fileExists(tempFolder), `expected folder to exist: ${tempFolder}`)
        })

        it('makes nested temp dirs', async () => {
            const nestedTempDirPath = await makeTemporaryToolkitFolder('nestedSubfolder', 'moreNestedSubfolder')

            foldersToCleanUp.push(nestedTempDirPath)
            foldersToCleanUp.push(path.join(tempDirPath, 'nestedSubfolder'))

            assert(
                nestedTempDirPath.startsWith(tempDirPath),
                `expected nestedTempDirPath ('${nestedTempDirPath}') to be in tempDirPath ('${tempDirPath}')`
            )
            const tmpDirExists = await fileExists(nestedTempDirPath)
            assert(tmpDirExists, `tempFolder should exist: '${nestedTempDirPath}'`)
        })
    }


async () => {
            const parentFolder = path.dirname(tempFolder)

            assert.strictEqual(
                parentFolder,
                tempDirPath,
                `expected tempFolder ('${tempFolder}') to be in tempDirPath ('${tempDirPath}')`
            )
        }


async () => {
            assert.ok(await fileExists(tempFolder), `expected folder to exist: ${tempFolder}`)
        }


async () => {
            const nestedTempDirPath = await makeTemporaryToolkitFolder('nestedSubfolder', 'moreNestedSubfolder')

            foldersToCleanUp.push(nestedTempDirPath)
            foldersToCleanUp.push(path.join(tempDirPath, 'nestedSubfolder'))

            assert(
                nestedTempDirPath.startsWith(tempDirPath),
                `expected nestedTempDirPath ('${nestedTempDirPath}') to be in tempDirPath ('${tempDirPath}')`
            )
            const tmpDirExists = await fileExists(nestedTempDirPath)
            assert(tmpDirExists, `tempFolder should exist: '${nestedTempDirPath}'`)
        }


() => {
        const basePath = path.join('this', 'is', 'the', 'way')
        const extendedPath = path.join(basePath, 'forward')
        const filename = 'yadayadayada.log'

        assert.ok(isInDirectory(basePath, basePath))
        assert.ok(isInDirectory(basePath, extendedPath))
        assert.ok(isInDirectory(basePath, path.join(basePath, filename)))
        assert.ok(isInDirectory(basePath, path.join(extendedPath, filename)))
        assert.ok(!isInDirectory(basePath, path.join('what', 'are', 'you', 'looking', 'at')))
        assert.ok(!isInDirectory(basePath, `${basePath}point`))
        assert.ok(isInDirectory('/foo/bar/baz/', '/foo/bar/baz/a.txt'))
        assert.ok(isInDirectory('/foo/bar/baz/', ''))
        assert.ok(isInDirectory('/', ''))
        assert.ok(isInDirectory('', 'foo'))
        assert.ok(isInDirectory('foo', 'foo'))

        if (os.platform() === 'win32') {
            assert.ok(isInDirectory('/foo/bar/baz/', '/FOO/BAR/BAZ/A.TXT'))
            assert.ok(isInDirectory('C:\\foo\\bar\\baz\\', 'C:/FOO/BAR/BAZ/A.TXT'))
            assert.ok(isInDirectory('C:\\foo\\bar\\baz', 'C:\\foo\\bar\\baz\\a.txt'))
        } else {
            assert.ok(!isInDirectory('/foo/bar/baz/', '/FOO/BAR/BAZ/A.TXT'))
        }
    }


/*
 * Fast snippets that run before the all HTML gets loaded.
 */
/**
  * Set the supplied navbar class, retrieving its last value from local storage
  */
function navInit(name: string): void {
    if (JSON.parse(localStorage.getItem(name) || 'false')) document.body.classList.add(name)
}


(app: App) => {
  app.component('ALayout', ALayout);
  app.component('AHeader', AHeader);
  app.component('AContent', AContent);
  app.component('AFooter', AFooter);
  app.component('ASide', ASide);
}


(app: App) => {
  app.component('AHeader', AHeader);
}


(app: App) => {
  app.component('AContent', AContent);
}


(app: App) => {
  app.component('AFooter', AFooter);
}


(app: App) => {
  app.component('ASide', ASide);
}


() => this.doLion()


(data) => {
                    this.showDetails = data;
                    // this.log.debug('showDetails received', data);
                }


(v) => ids.push(v)


interface ButtonAttrs {
    gid: string;
    tt: string;
    path: string;
}


interface ShowDetails {
    buttons: string[];
    glyphId: string;
    id: string;
    navPath: string;
    propLabels: Object;
    propOrder: string[];
    propValues: Object;
    title: string;
}


/**
     * When the component is initializing set up the handler for callbacks of
     * ShowDetails from the WSS. Set the variable showDetails when ever a callback
     * is made
     */
ngOnInit(): void {
        this.wss.bindHandlers(new Map<string, (data) => void>([
            ['showDetails', (data) => {
                    this.showDetails = data;
                    // this.log.debug('showDetails received', data);
                }
            ]
        ]));
        this.log.debug('Topo DetailsComponent initialized');
    }


/**
     * When the component is being unloaded then unbind the WSS handler.
     */
ngOnDestroy(): void {
        this.wss.unbindHandlers(['showDetails']);
        this.log.debug('Topo DetailsComponent destroyed');
    }


/**
     * If changes are detected on the Input param selectedNode, call on WSS sendEvent
     * and expect ShowDetails to be updated from data sent back from server.
     *
     * Note the difference in call to the WSS with requestDetails between a node
     * and a link - the handling is done in TopologyViewMessageHandler#RequestDetails.process()
     *
     * When multiple items are selected fabricate the ShowDetails here, and
     * present buttons that allow custom actions
     *
     * The WSS will call back asynchronously (see fn in ngOnInit())
     *
     * @param changes Simple Changes set of updates
     */
ngOnChanges(changes: SimpleChanges): void {
        if (changes['selectedNodes']) {
            this.selectedNodes = changes['selectedNodes'].currentValue;
            let type: any;
            if (this.selectedNodes.length === 0) {
                // Selection has been cleared
                this.showDetails = <ShowDetails>{};
                return;
            } else if (this.selectedNodes.length > 1) {
                // Don't send message to WSS just form dialog here
                const propOrder: string[] = [];
                const propValues: Object = {};
                const propLabels: Object = {};
                let numHosts: number = 0;
                for (let i = 0; i < this.selectedNodes.length; i++) {
                    propOrder.push(i.toString());
                    propLabels[i.toString()] = i.toString();
                    propValues[i.toString()] = this.selectedNodes[i].id;
                    if (this.selectedNodes[i].hasOwnProperty('nodeType') &&
                        (<Host>this.selectedNodes[i]).nodeType === NodeType.HOST) {
                        numHosts++;
                    } else {
                        numHosts = -128; // Negate the whole thing so other buttons will not be shown
                    }
                }
                const buttons: string[] = [];
                if (numHosts === 2) {
                    buttons.push('createHostToHostFlow');
                } else if (numHosts > 2) {
                    buttons.push('createMultiSourceFlow');
                }
                buttons.push('relatedIntents');

                this.showDetails = <ShowDetails>{
                    buttons: buttons,
                    glyphId: undefined,
                    id: 'multiple',
                    navPath: undefined,
                    propLabels: propLabels,
                    propOrder: propOrder,
                    propValues: propValues,
                    title: this.lionFnTopo('title_selected_items')
                };
                this.log.debug('Details panel generated from multiple devices', this.showDetails);
                return;
            }

            // If only one thing has been selected then request details of that from the server
            const selectedNode = this.selectedNodes[0];
            if (selectedNode.hasOwnProperty('nodeType')) { // For Device, Host, SubRegion
                type = (<Host>selectedNode).nodeType;
                this.wss.sendEvent('requestDetails', {
                    id: selectedNode.id,
                    class: type,
                });
            } else if (selectedNode.hasOwnProperty('type')) { // Must be link
                const link: Link = <Link>selectedNode;
                if (<LinkType><unknown>LinkType[link.type] === LinkType.UiEdgeLink) { // Number based enum
                    this.wss.sendEvent('requestDetails', {
                        key: link.id,
                        class: 'link',
                        sourceId: link.epA,
                        targetId: Link.deviceNameFromEp(link.epB),
                        targetPort: link.portB,
                        isEdgeLink: true
                    });
                } else {
                    this.wss.sendEvent('requestDetails', {
                        key: link.id,
                        class: 'link',
                        sourceId: Link.deviceNameFromEp(link.epA),
                        sourcePort: link.portA,
                        targetId: Link.deviceNameFromEp(link.epB),
                        targetPort: link.portB,
                        isEdgeLink: false
                    });
                }
            } else {
                this.log.warn('Unexpected type for selected element', selectedNode);
            }
        }
    }


/**
     * Table of core button attributes to return per button icon
     * @param btnName The name of the button
     * @returns A structure with the button attributes
     */
buttonAttribs(btnName: string): ButtonAttrs {
        switch (btnName) {
            case 'showDeviceView':
                return SHOWDEVICEVIEW;
            case 'showFlowView':
                return SHOWFLOWVIEW;
            case 'showPortView':
                return SHOWPORTVIEW;
            case 'showGroupView':
                return SHOWGROUPVIEW;
            case 'showMeterView':
                return SHOWMETERVIEW;
            case 'showPipeConfView':
                return SHOWPIPECONFVIEW;
            case 'relatedIntents':
                return RELATEDINTENTS;
            case 'createHostToHostFlow':
                return CREATEHOSTTOHOSTFLOW;
            case 'createMultiSourceFlow':
                return CREATEMULTISOURCEFLOW;
            default:
                return <ButtonAttrs>{
                    gid: btnName,
                    path: btnName
                };
        }
    }


/**
     * Navigate using Angular Routing. Combines the parameters to generate a relative URL
     * e.g. if params are 'meter', 'device' and 'null:0000000000001' then the
     * navigation URL will become "http://localhost:4200/#/meter?devId=null:0000000000000002"
     *
     * When multiple hosts are selected other actions have to be accommodated
     *
     * @param path The path to navigate to
     * @param navPath The parameter name to use
     * @param selId the parameter value to use
     */
navto(path: string): void {
        this.log.debug('navigate to', path, 'for',
            this.showDetails.navPath, '=', this.showDetails.id);

        const ids: string[] = [];
        Object.values(this.showDetails.propValues).forEach((v) => ids.push(v));
        if (path === 'relatedIntents' && this.showDetails.id === 'multiple') {
            this.wss.sendEvent('topo2RequestRelatedIntents', {
                'ids': ids,
                'hover': ''
            });

        } else if (path === 'create_h2h_flow' && this.showDetails.id === 'multiple') {
            this.wss.sendEvent('topo2AddHostIntent', {
                'one': ids[0],
                'two': ids[1],
                'ids': ids
            });

        } else if (path === 'create_msrc_flow' && this.showDetails.id === 'multiple') {
            // Should only happen when there are 3 or more ids
            this.wss.sendEvent('topo2AddMultiSourceIntent', {
                'src': ids.slice(0, ids.length - 1),
                'dst': ids[ids.length - 1],
                'ids': ids
            });

        } else if (this.showDetails.id) {
            let navPath = this.showDetails.navPath;
            if (navPath === 'device') {
                navPath = 'devId';
            }
            const queryPar: Params = {};
            queryPar[navPath] = this.showDetails.id;
            this.router.navigate([path], { queryParams: queryPar });
        }
    }


/**
     * Read the LION bundle for Details panel and set up the lionFn
     */
doLion() {
        this.lionFnTopo = this.lion.bundle('core.view.Topo');
        this.lionFnFlow = this.lion.bundle('core.view.Flow');
    }


() => ({
    version: process.env.VERSION || '0.0.1',
    port: parseInt(process.env.PORT, 10) || 3000,
    jwt: {
      secret: process.env.JWT_SECRET || 'secret',
      expiresIn: process.env.JWT_EXPIRY || '600000s', //15 mins
    },
    refresh: {
      secret: process.env.REFRESH_TOKEN_SECRET || 'secret',
      expiresIn: process.env.REFRESH_TOKEN_EXPIRY || '600000s', //almost 1 week
    },
  })


export class Angular2AppPage {
  navigateTo() {
    return browser.get('/');
  }

  getHeaderText() {
    return element(by.css('h1.header')).getText();
  }

  getCardHeaderText(i) {
    return element.all(by.css('.segment .header')).get(i).getText();
  }

}


getHeaderText() {
    return element(by.css('h1.header')).getText();
  }


getCardHeaderText(i) {
    return element.all(by.css('.segment .header')).get(i).getText();
  }


(state: any) => {
    return state.profile.newPostText;
}


(state: any) => {
    return state.profile.postBox;
}


@Component({
  selector: 'app-root',
  template: `<div>
  <topnav></topnav>

  <sidebar></sidebar>

</div>`
})
export class LayoutComponent implements OnInit {

  constructor(private toastr: ToastsManager,
							private router : Router,
							private menuAuth : MenuAuth,
							vRef: ViewContainerRef) {
		this.toastr.setRootViewContainerRef(vRef);
	}

  ngOnInit() {
  	let routes : Routes = this.router.config;
  	routes = this.menuAuth.secureRoutes(routes);
  	this.router.resetConfig(routes);
  }

}


ngOnInit() {
  	let routes : Routes = this.router.config;
  	routes = this.menuAuth.secureRoutes(routes);
  	this.router.resetConfig(routes);
  }


(obj: object) => {
  return Object.keys(obj).length;
}


export class CreateAnalyzerCommand extends $Command<
  CreateAnalyzerCommandInput,
  CreateAnalyzerCommandOutput,
  AccessAnalyzerClientResolvedConfig
> {
  // Start section: command_properties
  // End section: command_properties

  constructor(readonly input: CreateAnalyzerCommandInput) {
    // Start section: command_constructor
    super();
    // End section: command_constructor
  }

  resolveMiddleware(
    clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
    configuration: AccessAnalyzerClientResolvedConfig,
    options?: __HttpHandlerOptions
  ): Handler<CreateAnalyzerCommandInput, CreateAnalyzerCommandOutput> {
    this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));

    const stack = clientStack.concat(this.middlewareStack);

    const handlerExecutionContext: HandlerExecutionContext = {
      logger: {} as any,
    };
    const { requestHandler } = configuration;
    return stack.resolve(
      (request: FinalizeHandlerArguments<any>) =>
        requestHandler.handle(request.request as __HttpRequest, options || {}),
      handlerExecutionContext
    );
  }

  private serialize(input: CreateAnalyzerCommandInput, context: __SerdeContext): Promise<__HttpRequest> {
    return serializeAws_restJson1CreateAnalyzerCommand(input, context);
  }

  private deserialize(output: __HttpResponse, context: __SerdeContext): Promise<CreateAnalyzerCommandOutput> {
    return deserializeAws_restJson1CreateAnalyzerCommand(output, context);
  }

  // Start section: command_body_extra
  // End section: command_body_extra
}


export type CreateAnalyzerCommandInput = CreateAnalyzerRequest;


export type CreateAnalyzerCommandOutput = CreateAnalyzerResponse & __MetadataBearer;


resolveMiddleware(
    clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
    configuration: AccessAnalyzerClientResolvedConfig,
    options?: __HttpHandlerOptions
  ): Handler<CreateAnalyzerCommandInput, CreateAnalyzerCommandOutput> {
    this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));

    const stack = clientStack.concat(this.middlewareStack);

    const handlerExecutionContext: HandlerExecutionContext = {
      logger: {} as any,
    };
    const { requestHandler } = configuration;
    return stack.resolve(
      (request: FinalizeHandlerArguments<any>) =>
        requestHandler.handle(request.request as __HttpRequest, options || {}),
      handlerExecutionContext
    );
  }


private serialize(input: CreateAnalyzerCommandInput, context: __SerdeContext): Promise<__HttpRequest> {
    return serializeAws_restJson1CreateAnalyzerCommand(input, context);
  }


private deserialize(output: __HttpResponse, context: __SerdeContext): Promise<CreateAnalyzerCommandOutput> {
    return deserializeAws_restJson1CreateAnalyzerCommand(output, context);
  }


/**
 * Creates a clone of `arrayBuffer`.
 *
 * @private
 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
 * @returns {ArrayBuffer} Returns the cloned array buffer.
 */
export function cloneArrayBuffer(arrayBuffer: ArrayBuffer): ArrayBuffer {
  const result = new ArrayBuffer(arrayBuffer.byteLength);
  new Uint8Array(result).set(new Uint8Array(arrayBuffer));
  return result;
}


export function UnitInputImage({ unit, faction, role, scale, style, onClick }: Props) {
    const hasAdmiral: boolean = !!unit.tags && unit.tags[UnitTag.ADMIRAL] === true;
    const hasScientist: boolean = !!unit.tags && unit.tags[UnitTag.SCIENTIST] === true;
    const keepAlive: boolean = !!unit.tags && unit.tags[UnitTag.KEEP_ALIVE] === true;

    return (
        <div
            onClick={onClick}
            style={{
                display: "inline-block",
                margin: 1,
                height: unitDefinitions[unit.type].imageSize.y * scale,
                width: unitDefinitions[unit.type].imageSize.x * scale,
                ...style,
            }}


(v, idx) => <HitCounterImage key


interface Props {
    unit: UnitInput;
    faction: Faction;
    role: ParticipantRole;
    scale: number;
    style?: React.CSSProperties;
    onClick?: (event: React.MouseEvent<HTMLDivElement>) => void;
}


export class Wallet {
  readonly version: SpecificationVersion;
  readonly name: WalletName;

  private allowList: string[];
  private logger: Logger;
  private readonly options: Required<WalletOptions>;

  constructor(
    properties: WalletProperties,
    private api: WalletApi,
    private requestAccess: RequestAccess,
    options?: WalletOptions
  ) {
    this.options = { ...defaultOptions, ...options };
    this.name = properties.name;
    this.version = properties.version;
    this.allowList = this.options.persistAllowList ? this.getAllowList() : [];
    this.logger = this.options.logger;
  }

  public getPublicApi(window: WindowMaybeWithCardano) {
    return {
      enable: this.enable.bind(this, window),
      isEnabled: this.isEnabled.bind(this, window),
      name: this.name,
      version: this.version
    };
  }

  private getAllowList(): string[] {
    // JSON.parse(null) seems to be legit
    return JSON.parse(this.options.storage.getItem(this.name)!) || [];
  }

  private allowApplication(appName: string) {
    this.allowList.push(appName);

    if (this.options.persistAllowList) {
      const currentList = this.getAllowList();
      // Todo: Encrypt
      this.options.storage?.setItem(this.name, JSON.stringify([...currentList, appName]));
      this.logger.debug(
        {
          allowList: this.getAllowList(),
          module: 'Wallet',
          walletName: this.name
        },
        'Allow list persisted'
      );
    }
  }

  /**
   * Returns true if the dApp is already connected to the user's wallet, or if requesting access
   * would return true without user confirmation (e.g. the dApp is whitelisted), and false otherwise.
   *
   * If this function returns true, then any subsequent calls to wallet.enable()
   * during the current session should succeed and return the API object.
   *
   * Errors: `ApiError`
   */
  public async isEnabled(window: WindowMaybeWithCardano): Promise<Boolean> {
    const appName = window.location.hostname;
    return this.allowList.includes(appName);
  }

  /**
   * This is the entrypoint to start communication with the user's wallet.
   *
   * The wallet should request the user's permission to connect the web page to the user's wallet,
   * and if permission has been granted, the full API will be returned to the dApp to use.
   *
   * The wallet can choose to maintain a whitelist to not necessarily ask the user's permission
   * every time access is requested, but this behavior is up to the wallet and should be transparent
   * to web pages using this API.
   *
   * If a wallet is already connected this function should not request access a second time,
   * and instead just return the API object.
   *
   * Errors: `ApiError`
   */
  public async enable(window: WindowMaybeWithCardano): Promise<WalletApi> {
    const appName = window.location.hostname;

    if (this.options.persistAllowList && this.allowList.includes(appName)) {
      this.logger.debug(
        {
          module: 'Wallet',
          walletName: this.name
        },
        `${appName} has previously been allowed`
      );
      return this.api;
    }

    // gain authorization from wallet owner
    const isAuthed = await this.requestAccess();

    if (!isAuthed) {
      throw new ApiError(APIErrorCode.Refused, 'wallet not authorized.');
    }

    this.allowApplication(appName);

    return this.api;
  }
}


/**
 * CIP30 Specification version
 */
export type SpecificationVersion = string;


/**
 * Unique identifier, used to inject into the cardano namespace
 */
export type WalletName = string;


export type WalletProperties = { name: WalletName; version: SpecificationVersion };


/**
 * Resolve true to authorise access to the WalletAPI, or resolve false to deny.
 *
 * Errors: `ApiError`
 */
export type RequestAccess = () => Promise<boolean>;


export type WalletOptions = {
  logger?: Logger;
  persistAllowList?: boolean;
  storage?: Storage;
};


export type WalletPublic = ReturnType<Wallet['getPublicApi']>;


public getPublicApi(window: WindowMaybeWithCardano) {
    return {
      enable: this.enable.bind(this, window),
      isEnabled: this.isEnabled.bind(this, window),
      name: this.name,
      version: this.version
    };
  }


private getAllowList(): string[] {
    // JSON.parse(null) seems to be legit
    return JSON.parse(this.options.storage.getItem(this.name)!) || [];
  }


private allowApplication(appName: string) {
    this.allowList.push(appName);

    if (this.options.persistAllowList) {
      const currentList = this.getAllowList();
      // Todo: Encrypt
      this.options.storage?.setItem(this.name, JSON.stringify([...currentList, appName]));
      this.logger.debug(
        {
          allowList: this.getAllowList(),
          module: 'Wallet',
          walletName: this.name
        },
        'Allow list persisted'
      );
    }
  }


/**
   * Returns true if the dApp is already connected to the user's wallet, or if requesting access
   * would return true without user confirmation (e.g. the dApp is whitelisted), and false otherwise.
   *
   * If this function returns true, then any subsequent calls to wallet.enable()
   * during the current session should succeed and return the API object.
   *
   * Errors: `ApiError`
   */
public async isEnabled(window: WindowMaybeWithCardano): Promise<Boolean> {
    const appName = window.location.hostname;
    return this.allowList.includes(appName);
  }


/**
   * This is the entrypoint to start communication with the user's wallet.
   *
   * The wallet should request the user's permission to connect the web page to the user's wallet,
   * and if permission has been granted, the full API will be returned to the dApp to use.
   *
   * The wallet can choose to maintain a whitelist to not necessarily ask the user's permission
   * every time access is requested, but this behavior is up to the wallet and should be transparent
   * to web pages using this API.
   *
   * If a wallet is already connected this function should not request access a second time,
   * and instead just return the API object.
   *
   * Errors: `ApiError`
   */
public async enable(window: WindowMaybeWithCardano): Promise<WalletApi> {
    const appName = window.location.hostname;

    if (this.options.persistAllowList && this.allowList.includes(appName)) {
      this.logger.debug(
        {
          module: 'Wallet',
          walletName: this.name
        },
        `${appName} has previously been allowed`
      );
      return this.api;
    }

    // gain authorization from wallet owner
    const isAuthed = await this.requestAccess();

    if (!isAuthed) {
      throw new ApiError(APIErrorCode.Refused, 'wallet not authorized.');
    }

    this.allowApplication(appName);

    return this.api;
  }


/**
 * A custom Error class
 * @class
 */
export class ValidationError extends SysError {

    errorCount: number;
    constructor(public validationProblems: ValidationProblem[]) {
        super("validation", SysMsgs.validation.validationErrorMsg);

        this.errorCount = validationProblems.length;
    }

    toJSON() {
        const { type, code, message, errorCount, validationProblems } = this;
        return {
            type,
            code,
            message,
            errorCount,
            validationProblems
        };
    }
}


toJSON() {
        const { type, code, message, errorCount, validationProblems } = this;
        return {
            type,
            code,
            message,
            errorCount,
            validationProblems
        };
    }


@Injectable()
export class PessoaService {
  constructor() {}

  async getAll(qtd: number): Promise<Estado[]> {
    return await Estado.find();
  }

}


async getAll(qtd: number): Promise<Estado[]> {
    return await Estado.find();
  }


x => x.eval(functionality)


export class Array extends Expression {
    constructor(
        public expressions: Expression[],
    ) {
        super();
    }
    eval(functionality: Functionality): IEvalResult {
        return {
            type: 'array',
            value: this.expressions.map(x => x.eval(functionality)),
        };
    }
}


eval(functionality: Functionality): IEvalResult {
        return {
            type: 'array',
            value: this.expressions.map(x => x.eval(functionality)),
        };
    }


export class ActorQuery extends Query<SingleActor, SingleActorVariables> {}


export default class DynamicLink {
  _analytics: AnalyticsParameters;

  _android: AndroidParameters;

  _dynamicLinkDomain: string;

  _ios: IOSParameters;

  _itunes: ITunesParameters;

  _link: string;

  _navigation: NavigationParameters;

  _social: SocialParameters;

  constructor(link: string, dynamicLinkDomain: string) {
    this._analytics = new AnalyticsParameters(this);
    this._android = new AndroidParameters(this);
    this._dynamicLinkDomain = dynamicLinkDomain;
    this._ios = new IOSParameters(this);
    this._itunes = new ITunesParameters(this);
    this._link = link;
    this._navigation = new NavigationParameters(this);
    this._social = new SocialParameters(this);
  }

  get analytics(): AnalyticsParameters {
    return this._analytics;
  }

  get android(): AndroidParameters {
    return this._android;
  }

  get ios(): IOSParameters {
    return this._ios;
  }

  get itunes(): ITunesParameters {
    return this._itunes;
  }

  get navigation(): NavigationParameters {
    return this._navigation;
  }

  get social(): SocialParameters {
    return this._social;
  }

  build(): NativeDynamicLink {
    invariant(this._link, 'DynamicLink: Missing required `link` property');
    invariant(
      this._dynamicLinkDomain,
      'DynamicLink: Missing required `dynamicLinkDomain` property'
    );

    return {
      analytics: this._analytics.build(),
      android: this._android.build(),
      dynamicLinkDomain: this._dynamicLinkDomain,
      ios: this._ios.build(),
      itunes: this._itunes.build(),
      link: this._link,
      navigation: this._navigation.build(),
      social: this._social.build(),
    };
  }
}


build(): NativeDynamicLink {
    invariant(this._link, 'DynamicLink: Missing required `link` property');
    invariant(
      this._dynamicLinkDomain,
      'DynamicLink: Missing required `dynamicLinkDomain` property'
    );

    return {
      analytics: this._analytics.build(),
      android: this._android.build(),
      dynamicLinkDomain: this._dynamicLinkDomain,
      ios: this._ios.build(),
      itunes: this._itunes.build(),
      link: this._link,
      navigation: this._navigation.build(),
      social: this._social.build(),
    };
  }


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


() => {
        return this.listByResourceGroupPagingPage(resourceGroupName, options);
      }


() => {
        return this.listCapacitiesPagingPage(resourceGroupName, name, options);
      }


() => {
        return this.changeVnetPagingPage(
          resourceGroupName,
          name,
          vnetInfo,
          options
        );
      }


() => {
        return this.getInboundNetworkDependenciesEndpointsPagingPage(
          resourceGroupName,
          name,
          options
        );
      }


() => {
        return this.listMultiRolePoolsPagingPage(
          resourceGroupName,
          name,
          options
        );
      }


() => {
        return this.listMultiRolePoolInstanceMetricDefinitionsPagingPage(
          resourceGroupName,
          name,
          instance,
          options
        );
      }


() => {
        return this.listMultiRoleMetricDefinitionsPagingPage(
          resourceGroupName,
          name,
          options
        );
      }


() => {
        return this.listMultiRolePoolSkusPagingPage(
          resourceGroupName,
          name,
          options
        );
      }


() => {
        return this.listMultiRoleUsagesPagingPage(
          resourceGroupName,
          name,
          options
        );
      }


() => {
        return this.getOutboundNetworkDependenciesEndpointsPagingPage(
          resourceGroupName,
          name,
          options
        );
      }


() => {
        return this.resumePagingPage(resourceGroupName, name, options);
      }


() => {
        return this.listAppServicePlansPagingPage(
          resourceGroupName,
          name,
          options
        );
      }


() => {
        return this.listWebAppsPagingPage(resourceGroupName, name, options);
      }


() => {
        return this.suspendPagingPage(resourceGroupName, name, options);
      }


() => {
        return this.listUsagesPagingPage(resourceGroupName, name, options);
      }


() => {
        return this.listWorkerPoolsPagingPage(resourceGroupName, name, options);
      }


() => {
        return this.listWorkerPoolInstanceMetricDefinitionsPagingPage(
          resourceGroupName,
          name,
          workerPoolName,
          instance,
          options
        );
      }


() => {
        return this.listWebWorkerMetricDefinitionsPagingPage(
          resourceGroupName,
          name,
          workerPoolName,
          options
        );
      }


() => {
        return this.listWorkerPoolSkusPagingPage(
          resourceGroupName,
          name,
          workerPoolName,
          options
        );
      }


() => {
        return this.listWebWorkerUsagesPagingPage(
          resourceGroupName,
          name,
          workerPoolName,
          options
        );
      }


async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ): Promise<AppServiceEnvironmentsCreateOrUpdateResponse> => {
      return this.client.sendOperationRequest(args, spec);
    }


async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ): Promise<AppServiceEnvironmentsChangeVnetResponse> => {
      return this.client.sendOperationRequest(args, spec);
    }


async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ): Promise<AppServiceEnvironmentsCreateOrUpdateMultiRolePoolResponse> => {
      return this.client.sendOperationRequest(args, spec);
    }


async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ): Promise<AppServiceEnvironmentsResumeResponse> => {
      return this.client.sendOperationRequest(args, spec);
    }


async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ): Promise<AppServiceEnvironmentsSuspendResponse> => {
      return this.client.sendOperationRequest(args, spec);
    }


async (
      args: coreClient.OperationArguments,
      spec: coreClient.OperationSpec
    ): Promise<AppServiceEnvironmentsCreateOrUpdateWorkerPoolResponse> => {
      return this.client.sendOperationRequest(args, spec);
    }


/**
   * Description for Get all App Service Environments for a subscription.
   * @param options The options parameters.
   */
public list(
    options?: AppServiceEnvironmentsListOptionalParams
  ): PagedAsyncIterableIterator<AppServiceEnvironmentResource> {
    const iter = this.listPagingAll(options);
    return {
      next() {
        return iter.next();
      },
      [Symbol.asyncIterator]() {
        return this;
      },
      byPage: () => {
        return this.listPagingPage(options);
      }
    };
  }