async execute({
    filePath,
  }: RequestLoadTransactionDTO): Promise<Transaction[]> {
    const readFileStream = createReadStream(filePath);

    const parser = csvParser({ from_line: 2 });
    const parseCSV = readFileStream.pipe(parser);

    const csvTransactions: TransactionData[] = [];
    const csvCategories: string[] = [];

    parseCSV.on('data', async line => {
      const [title, type, value, category] = line.map((cell: string) =>
        cell.trim(),
      );

      if (!(title || type || value || category)) {
        throw new AppError('Invalid CSV format');
      }

      csvCategories.push(category);
      csvTransactions.push({ title, type, value, category });
    });

    await new Promise(resolve => parseCSV.on('end', resolve));

    const categoriesRepository = getRepository(Category);

    const existentCategories = await categoriesRepository.find({
      where: { title: In(csvCategories) },
    });

    const existentCategoriesTitle = existentCategories.map(
      category => category.title,
    );

    const addCategoriesTitles = csvCategories
      .filter(category => !existentCategoriesTitle.includes(category))
      .filter((value, index, self) => self.indexOf(value) === index);

    const newCategories = await categoriesRepository.create(
      addCategoriesTitles.map(title => ({ title })),
    );

    await categoriesRepository.save(newCategories);

    const categories = [...newCategories, ...existentCategories];

    const transactionRepository = getCustomRepository(TransactionRepository);

    const transactions = await transactionRepository.create(
      csvTransactions.map(({ title, type, value, category }) => ({
        title,
        type,
        value,
        category: categories.find(
          categoryItem => categoryItem.title === category,
        ),
      })),
    );

    await transactionRepository.save(transactions);

    await access(filePath, async error => {
      if (!error) {
        await promises.unlink(filePath);
      }
    });
    return transactions;
  }


class CreateTransactionService {
  private transactionsRepository: TransactionsRepository;

  constructor(transactionsRepository: TransactionsRepository) {
    this.transactionsRepository = transactionsRepository;
  }

  public execute({ value, title, type }: Request): Transaction {
    if (!['income', 'outcome'].includes(type)) {
      throw new Error('Transaction Type Invalid');
    }
    const { total } = this.transactionsRepository.getBalance();
    if (type === 'outcome' && total < value) {
      throw new Error('You have insufficient funds');
    }

    const operation = this.transactionsRepository.create({
      title,
      value,
      type,
    });
    return operation;
  }
}


interface Request {
  title: string;
  value: number;
  type: 'income' | 'outcome';
}


public execute({ value, title, type }: Request): Transaction {
    if (!['income', 'outcome'].includes(type)) {
      throw new Error('Transaction Type Invalid');
    }
    const { total } = this.transactionsRepository.getBalance();
    if (type === 'outcome' && total < value) {
      throw new Error('You have insufficient funds');
    }

    const operation = this.transactionsRepository.create({
      title,
      value,
      type,
    });
    return operation;
  }


(預設值: 100)


() => {
  it("should provide exports", () => {
    expect(typeof out.compile).toEqual("function");
    expect(typeof out.filterSass).toEqual("function");
  });
}


() => {
    expect(typeof out.compile).toEqual("function");
    expect(typeof out.filterSass).toEqual("function");
  }


/**
 * Analyze XXSSProtection header in response
 * If this header is not present, add warning
 */
export class XXSSProtectionAnalyzer implements IAnalyzer {

    /**
     * Analyze response source code
     * @param context query context
     */
    public analyze(context: Context): void {
        throw new Error("Method not implemented.");
    }

    public get NAME() {
        return "XXSS_PROTECTION";
    }
}


/**
     * Analyze response source code
     * @param context query context
     */
public analyze(context: Context): void {
        throw new Error("Method not implemented.");
    }


async (knex: Knex): Promise<void> => {
  /* eslint-disable prettier/prettier */
  /* eslint-enable */
}


async (knex: Knex): Promise<void> => {}


({ value, onChange, removable = true }) => {
    const [filter, setFilter] = useState("");

    const onFilterChange = useCallback(
        (value, cb) => {
            setFilter(value.trim());
            cb();
        },
        [filter]
    );

    const { prefix: selectedIconPrefix, name: selectedIconName } = useMemo(() => {
        if (!value || Array.isArray(value) === false || !removable) {
            return {
                prefix: undefined,
                name: undefined
            };
        }
        return {
            prefix: value[0],
            name: value[1]
        };
    }, [value]);

    const allIcons: PbIcon[] = useMemo(() => {
        const plugins = getPlugins<PbIconsPlugin>("pb-icons");
        let selectedIconItem = null;
        const allIconItems = plugins.reduce((icons: Array<PbIcon>, pl) => {
            const pluginIcons = pl.getIcons().filter(({ id }) => {
                const [prefix, name] = id;
                if (!selectedIconPrefix || !selectedIconName || prefix !== selectedIconPrefix) {
                    return true;
                }
                return name !== selectedIconName;
            });
            const selectedIcon = pl.getIcons().find(({ name }) => {
                return name === selectedIconName;
            });
            if (selectedIcon) {
                selectedIconItem = selectedIcon;
            }
            return icons.concat(pluginIcons);
        }, []);
        if (selectedIconItem) {
            allIconItems.unshift(selectedIconItem);
        }
        return allIconItems;
    }, [selectedIconPrefix, selectedIconName]);

    const icons = useMemo(() => {
        return filter ? allIcons.filter(ic => ic.name.includes(filter)) : allIcons;
    }, [filter, selectedIconPrefix, selectedIconName]);

    const renderCell = useCallback(
        ({ closeMenu }) => {
            return function renderCell({ columnIndex, key, rowIndex, style }) {
                const item = icons[rowIndex * COLUMN_COUNT + columnIndex];
                if (!item) {
                    return null;
                }
                const isSelectedIcon =
                    item.id[0] === selectedIconPrefix && item.id[1] === selectedIconName;
                const gridItemClassName = classNames(gridItem, {
                    [gridItemSelected]: isSelectedIcon
                });
                return (
                    <div
                        key={key}
                        style={style}
                        className={gridItemClassName}
                        onClick={()


(value, cb) => {
            setFilter(value.trim());
            cb();
        }


() => {
        if (!value || Array.isArray(value) === false || !removable) {
            return {
                prefix: undefined,
                name: undefined
            };
        }
        return {
            prefix: value[0],
            name: value[1]
        };
    }


() => {
        const plugins = getPlugins<PbIconsPlugin>("pb-icons");
        let selectedIconItem = null;
        const allIconItems = plugins.reduce((icons: Array<PbIcon>, pl) => {
            const pluginIcons = pl.getIcons().filter(({ id }) => {
                const [prefix, name] = id;
                if (!selectedIconPrefix || !selectedIconName || prefix !== selectedIconPrefix) {
                    return true;
                }
                return name !== selectedIconName;
            });
            const selectedIcon = pl.getIcons().find(({ name }) => {
                return name === selectedIconName;
            });
            if (selectedIcon) {
                selectedIconItem = selectedIcon;
            }
            return icons.concat(pluginIcons);
        }, []);
        if (selectedIconItem) {
            allIconItems.unshift(selectedIconItem);
        }
        return allIconItems;
    }


(icons: Array<PbIcon>, pl) => {
            const pluginIcons = pl.getIcons().filter(({ id }) => {
                const [prefix, name] = id;
                if (!selectedIconPrefix || !selectedIconName || prefix !== selectedIconPrefix) {
                    return true;
                }
                return name !== selectedIconName;
            });
            const selectedIcon = pl.getIcons().find(({ name }) => {
                return name === selectedIconName;
            });
            if (selectedIcon) {
                selectedIconItem = selectedIcon;
            }
            return icons.concat(pluginIcons);
        }


({ id }) => {
                const [prefix, name] = id;
                if (!selectedIconPrefix || !selectedIconName || prefix !== selectedIconPrefix) {
                    return true;
                }
                return name !== selectedIconName;
            }


({ name }) => {
                return name === selectedIconName;
            }


() => {
        return filter ? allIcons.filter(ic => ic.name.includes(filter)) : allIcons;
    }


ic => ic.name.includes(filter)


({ closeMenu }) => {
            return function renderCell({ columnIndex, key, rowIndex, style }) {
                const item = icons[rowIndex * COLUMN_COUNT + columnIndex];
                if (!item) {
                    return null;
                }
                const isSelectedIcon =
                    item.id[0] === selectedIconPrefix && item.id[1] === selectedIconName;
                const gridItemClassName = classNames(gridItem, {
                    [gridItemSelected]: isSelectedIcon
                });
                return (
                    <div
                        key={key}
                        style={style}
                        className={gridItemClassName}
                        onClick={()


({ closeMenu }) => {
            return (
                <Fragment>
                    <DelayedOnChange value={filter} onChange={onFilterChange}>
                        {({ value, onChange })


renderCell({ closeMenu })


@NgModule({
  imports: [
    CommonModule,
    DatatableRoutingModule,
    FormsModule,
    FlexLayoutModule,
    ScrollbarModule,
    PageHeaderModule,
    BreadcrumbsModule,
    MatTableModule,
    CdkTableModule,
    MatInputModule,
    MatPaginatorModule,
    MatSortModule,
    MatProgressSpinnerModule
  ],
  declarations: [DatatableComponent]
})
export class DatatableModule { }


(view) => {
      return view;
    }


export class VideoComponent extends Component {
  public static tagName = "rv-video";

  protected autobind = true;

  static get observedAttributes() {
    return ["mp4-src"];
  }

  public get muted() {
    return this.video && this.video.muted;
  }

  public set muted(muted: boolean) {
    this.video.muted = muted;
    this.scope.muted = this.video.muted;
    if (muted) {
      this.video.setAttribute("muted", "");
    } else {
      this.video.removeAttribute("muted");
    }
  }

  /**
   * * 1.0 is highest volume (100%. This is default)
   * * 0.5 is half volume (50%)
   * * 0.0 is silent (same as mute)
   */
  public get volume() {
    return this.video ? this.video.volume : 0;
  }

  public set volume(volume: number) {
    this.video.volume = volume;
    this.scope.volume = this.video.volume;
  }

  public get loop() {
    return this.video && this.video.loop;
  }

  public set loop(loop: boolean) {
    this.video.loop = loop;
    this.scope.loop = this.video.loop;
    if (loop) {
      this.video.setAttribute("loop", "");
    } else {
      this.video.removeAttribute("loop");
    }
  }

  public get controls() {
    return this.video && this.video.controls;
  }

  public set controls(controls: boolean) {
    this.video.controls = controls;
    this.scope.controls = this.video.controls;
    if (controls) {
      this.video.setAttribute("controls", "");
      // show controls
      this.video.dispatchEvent(new Event("mouseover"));
      this.video.dispatchEvent(new Event("mouseenter"));
      this.video.dispatchEvent(new Event("mousemove"));
    } else {
      this.video.removeAttribute("controls");
    }
  }

  public get currentTime() {
    return this.video ? this.video.currentTime : 0;
  }

  public set currentTime(currentTime: number) {
    this.video.currentTime = currentTime;
    this.scope.currentTime = this.video.currentTime;
  }

  /**
   * @readonly
   */
  public get paused() {
    return this.video && this.video.paused;
  }

  protected video: HTMLVideoElement;

  protected scope: Scope = {
    // properties
    muted: this.muted,
    volume: this.volume,
    loop: this.loop,
    controls: this.controls,
    currentTime: this.currentTime,
    /**
     * @readonly
     */
    paused: this.paused,
    // methods
    toggleMute: this.toggleMute,
    toggleControls: this.toggleControls,
    play: this.play,
    pause: this.pause,
    togglePlay: this.togglePlay,
    mp4Src: "",
  };

  constructor(element?: HTMLElement) {
    super(element);
    const video = this.el.querySelector("video") as HTMLVideoElement;
    this.video = video;
  }

  public toggleMute() {
    this.muted = !this.muted;
  }

  public toggleControls() {
    this.controls = !this.controls;
  }

  public play() {
    this.video.play();
  }

  public pause() {
    this.video.pause();
  }

  public togglePlay() {
    if (this.paused) {
      this.play();
    } else {
      this.pause();
    }
  }

  protected connectedCallback() {
    super.connectedCallback();
    const video = this.el.querySelector("video");
    if (!video) {
      throw new Error("The video child element is required!");
    }
    this.video = video;
    this.scope.muted = this.video.muted;
    this.scope.volume = this.video.volume;
    this.scope.loop = this.video.loop;
    this.scope.controls = this.video.controls;
    this.scope.currentTime = this.video.currentTime;
    this.scope.paused = this.video.paused;
    this.init(VideoComponent.observedAttributes);
  }

  protected async init(observedAttributes: string[]) {
    return super.init(observedAttributes).then((view) => {
      return view;
    });
  }

  // deconstructor
  protected disconnectedCallback() {
    super.disconnectedCallback();
  }

  protected template() {
    return null;
  }
}


interface Scope {
  // properties
  muted: boolean;
  volume: number;
  loop: boolean;
  controls: boolean;
  currentTime: number;
  /**
   * @readonly
   */
  paused: boolean;
  // methods
  toggleMute: VideoComponent["toggleMute"];
  toggleControls: VideoComponent["toggleControls"];
  play: VideoComponent["play"];
  pause: VideoComponent["pause"];
  togglePlay: VideoComponent["togglePlay"];

  // custom
  /** If the user will pass the mp4 source for some reason */
  mp4Src?: string;
}


public toggleMute() {
    this.muted = !this.muted;
  }


public toggleControls() {
    this.controls = !this.controls;
  }


public play() {
    this.video.play();
  }


public pause() {
    this.video.pause();
  }


public togglePlay() {
    if (this.paused) {
      this.play();
    } else {
      this.pause();
    }
  }


protected connectedCallback() {
    super.connectedCallback();
    const video = this.el.querySelector("video");
    if (!video) {
      throw new Error("The video child element is required!");
    }
    this.video = video;
    this.scope.muted = this.video.muted;
    this.scope.volume = this.video.volume;
    this.scope.loop = this.video.loop;
    this.scope.controls = this.video.controls;
    this.scope.currentTime = this.video.currentTime;
    this.scope.paused = this.video.paused;
    this.init(VideoComponent.observedAttributes);
  }


protected async init(observedAttributes: string[]) {
    return super.init(observedAttributes).then((view) => {
      return view;
    });
  }


// deconstructor
protected disconnectedCallback() {
    super.disconnectedCallback();
  }


protected template() {
    return null;
  }


({
    resterendeStønadskonter,
    brukteDager,
    navnPåForeldre,
    erDeltUttak,
    erFarMedmor,
}) => {
    const intl = useIntl();
    // TODO utled situasjon
    const situasjon = ForeldreparSituasjon.farOgMor;
    const info = getSituasjonForelderSvg(situasjon);
    const bem = BEMHelper('oversiktBrukteDager');
    return (

                <Undertittel tag="h2" className="blokk-xs">
                    <FormattedMessage
                        id="oversiktBrukteDager.tittel.foreldre"
                        values={{ antall: erDeltUttak ? 2 : 1 }}


export interface NavnPåForeldre {
    mor: string;
    farMedmor: string;
}


interface Props {
    erDeltUttak: boolean;
    erFarMedmor: boolean;
    resterendeStønadskonter: TilgjengeligStønadskonto[];
    brukteDager: {
        mor: number;
        farMedmor: number;
    };
    navnPåForeldre: NavnPåForeldre;
}


getVarighetString(brukteDager


() => {
  const theme = useTheme();
  const hello = "Hello";
  return (
    <>
      <div style={{ color: theme.palette.primary.main }}


() => {

    beforeEach(nsTestBedBeforeEach([ItemsComponent]));
    afterEach(nsTestBedAfterEach(false));

    it('should be defined', () => {

        nsTestBedRender(ItemsComponent).then((fixture) => {
            fixture.detectChanges();
            const component = fixture.componentInstance;
            expect(component).toBeTruthy();
        });

    });

}


() => {

        nsTestBedRender(ItemsComponent).then((fixture) => {
            fixture.detectChanges();
            const component = fixture.componentInstance;
            expect(component).toBeTruthy();
        });

    }


(fixture) => {
            fixture.detectChanges();
            const component = fixture.componentInstance;
            expect(component).toBeTruthy();
        }


() => {

    let component: ItemsComponent;

    beforeEach(() => { component = new ItemsComponent(new ItemService())});

    it('should be defined', () => {
        expect(component).toBeTruthy();
    });

}


() => { component = new ItemsComponent(new ItemService())}


() => {
        expect(component).toBeTruthy();
    }


export interface Sizes {
  '2xs': string;
  xs: string;
  s: string;
  m: string;
  l: string;
  xl: string;
  '2xl': string;
  none: string;
}


export interface SizeProps extends BaseSizeProps {}


export type Size = keyof Sizes;


type BaseSizeProps = {
  [K in typeof sizesMap[number]]: Size;
};


export type SizeProperty = keyof SizeProps;


(db: SQLiteObject) => {
      this.database = db;
      db.executeSql('CREATE TABLE IF NOT EXISTS note (id VARCHAR(40) , time STRING , content TEXT )', [])
        .catch((e) => {
          console.error(e);
        });
    }


(e) => {
          console.error(e);
        }


(e) => {
        console.log(e);
      }


e => console.log(e)


(resolve, reject) => {
      this.sqlite.create({
        name: 'data.db',
        location: 'default'
      }).then((db: SQLiteObject) => {
        this.database = db;
        this.database.executeSql('SELECT * FROM note ORDER BY time DESC', []).then((data) => {
          let activityValues = [];
          if (data.rows.length > 0) {
            for (let i = 0; i < data.rows.length; i++) {
              activityValues.push(data.rows.item(i));
            }
          }
          resolve(activityValues);
        }, (error) => {
          console.log(error);
        }).catch(e => console.log(e));
      });
    }


(db: SQLiteObject) => {
        this.database = db;
        this.database.executeSql('SELECT * FROM note ORDER BY time DESC', []).then((data) => {
          let activityValues = [];
          if (data.rows.length > 0) {
            for (let i = 0; i < data.rows.length; i++) {
              activityValues.push(data.rows.item(i));
            }
          }
          resolve(activityValues);
        }, (error) => {
          console.log(error);
        }).catch(e => console.log(e));
      }


(data) => {
          let activityValues = [];
          if (data.rows.length > 0) {
            for (let i = 0; i < data.rows.length; i++) {
              activityValues.push(data.rows.item(i));
            }
          }
          resolve(activityValues);
        }


/*
  Generated class for the DaoProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class DaoProvider {

  database: SQLiteObject;
  constructor(public http: HttpClient, private sqlite: SQLite) {
  }

  dbInit() {
    this.sqlite.create({
      name: 'data.db',
      location: 'default'
    }).then((db: SQLiteObject) => {
      this.database = db;
      db.executeSql('CREATE TABLE IF NOT EXISTS note (id VARCHAR(40) , time STRING , content TEXT )', [])
        .catch((e) => {
          console.error(e);
        });
    });
  }

  insertNote(note: noteInfoModel) {
    let time = note.time.getTime();
    this.database.executeSql('INSERT INTO note VALUES(?,?,?)', [note.id, time, note.content])
      .catch((e) => {
        console.log(e);
      })
  }

  updateNote(note: noteInfoModel) {
    let time = note.time.getTime();
    this.database.executeSql('UPDATE note SET time=?,content=? WHERE id=?', [time, note.content, note.id])
      .catch(e => console.log(e));
  }

  deleteNote(id: string) {
    this.database.executeSql('DELETE FROM note WHERE id=?', [id])
      .catch(e => console.log(e));
  }

  async searchNote() {  //这里需要重新打开数据库是因为刚进入程序就是这个页面，此时init函数可能还没有执行完，这样会直接导致database的值为空。
    let promise = new Promise((resolve, reject) => {
      this.sqlite.create({
        name: 'data.db',
        location: 'default'
      }).then((db: SQLiteObject) => {
        this.database = db;
        this.database.executeSql('SELECT * FROM note ORDER BY time DESC', []).then((data) => {
          let activityValues = [];
          if (data.rows.length > 0) {
            for (let i = 0; i < data.rows.length; i++) {
              activityValues.push(data.rows.item(i));
            }
          }
          resolve(activityValues);
        }, (error) => {
          console.log(error);
        }).catch(e => console.log(e));
      });
    });
    return await promise;
  };

}


dbInit() {
    this.sqlite.create({
      name: 'data.db',
      location: 'default'
    }).then((db: SQLiteObject) => {
      this.database = db;
      db.executeSql('CREATE TABLE IF NOT EXISTS note (id VARCHAR(40) , time STRING , content TEXT )', [])
        .catch((e) => {
          console.error(e);
        });
    });
  }


insertNote(note: noteInfoModel) {
    let time = note.time.getTime();
    this.database.executeSql('INSERT INTO note VALUES(?,?,?)', [note.id, time, note.content])
      .catch((e) => {
        console.log(e);
      })
  }


updateNote(note: noteInfoModel) {
    let time = note.time.getTime();
    this.database.executeSql('UPDATE note SET time=?,content=? WHERE id=?', [time, note.content, note.id])
      .catch(e => console.log(e));
  }


deleteNote(id: string) {
    this.database.executeSql('DELETE FROM note WHERE id=?', [id])
      .catch(e => console.log(e));
  }


async searchNote() {  //这里需要重新打开数据库是因为刚进入程序就是这个页面，此时init函数可能还没有执行完，这样会直接导致database的值为空。
    let promise = new Promise((resolve, reject) => {
      this.sqlite.create({
        name: 'data.db',
        location: 'default'
      }).then((db: SQLiteObject) => {
        this.database = db;
        this.database.executeSql('SELECT * FROM note ORDER BY time DESC', []).then((data) => {
          let activityValues = [];
          if (data.rows.length > 0) {
            for (let i = 0; i < data.rows.length; i++) {
              activityValues.push(data.rows.item(i));
            }
          }
          resolve(activityValues);
        }, (error) => {
          console.log(error);
        }).catch(e => console.log(e));
      });
    });
    return await promise;
  }


function runFixtures() {
  let hadErrors = false;
  const fixtures = fs.readdirSync(fixturesPath, { withFileTypes: true });
  for (const fixture of fixtures) {
    if (!fixture.isDirectory()) continue;
    const fixturePath = path.resolve(fixturesPath, fixture.name);

    const command = path.resolve(fixturePath, "command.ts");
    const expected = path.resolve(fixturePath, "expected.ts");
    const output = path.resolve(fixturePath, "output.ts");
    const options = path.resolve(fixturePath, "options.json");

    const args: string[] = [];
    if (fs.existsSync(options)) {
      const parsedOptions = JSON.parse(fs.readFileSync(options, { encoding: "utf8" }));
      if (parsedOptions.flags) args.push(parsedOptions.flags);
      args.push(parsedOptions.subcommandName || "generate-fig-spec");
    } else {
      args.push("generate-fig-spec"); // default generate subcommand
    }

    if (!fs.existsSync(command)) {
      hadErrors = true;
      continue;
    }
    try {
      const cmd = `node -r ts-node/register ${command} ${args.join(" ")} > ${output}`;
      child.execSync(cmd);
    } catch {
      report(fixture.name, "errored");
      hadErrors = true;
      continue;
    }

    if (!fs.existsSync(expected) || process.env.OVERWRITE) {
      fs.copyFileSync(output, expected);
      report(fixture.name, process.env.OVERWRITE ? "regenerated" : "generated");
      continue;
    }

    const outputFile = fs.readFileSync(output);
    const expectedFile = fs.readFileSync(expected);

    const successful = outputFile.equals(expectedFile);
    if (!successful) {
      hadErrors = true;
    }
    report(fixture.name, successful ? "successful" : "failed");
  }

  if (hadErrors) {
    process.exit(1);
  }
}


(options: HelmetOptions = {}) => express(_helmet(options))


interface HelmetOptions {
  contentSecurityPolicy?: MiddlewareOption<ContentSecurityPolicyOptions>;
  dnsPrefetchControl?: MiddlewareOption<XDnsPrefetchControlOptions>;
  expectCt?: MiddlewareOption<ExpectCtOptions>;
  frameguard?: MiddlewareOption<XFrameOptionsOptions>;
  hidePoweredBy?: MiddlewareOption<never>;
  hsts?: MiddlewareOption<StrictTransportSecurityOptions>;
  ieNoOpen?: MiddlewareOption<never>;
  noSniff?: MiddlewareOption<never>;
  originAgentCluster?: boolean;
  permittedCrossDomainPolicies?: MiddlewareOption<XPermittedCrossDomainPoliciesOptions>;
  referrerPolicy?: MiddlewareOption<ReferrerPolicyOptions>;
  xssFilter?: MiddlewareOption<never>;
}


type MiddlewareOption<T> = false | T;


export abstract class MetadataTransfer<Status extends MetadataRequestStatus, Result extends MetadataTransferResult> {
  protected components: ComponentSet;
  protected logger: Logger;
  protected canceled = false;
  private transferId?: string;
  private event = new EventEmitter();
  private usernameOrConnection: string | Connection;
  private apiVersion: string;

  public constructor({ usernameOrConnection, components, apiVersion, id }: MetadataTransferOptions) {
    this.usernameOrConnection = usernameOrConnection;
    this.components = components;
    this.apiVersion = apiVersion;
    this.transferId = id;
    this.logger = Logger.childFromRoot(this.constructor.name);
  }

  public get id(): string | undefined {
    return this.transferId;
  }

  /**
   * Send the metadata transfer request to the org.
   *
   * @returns AsyncResult from the deploy or retrieve response.
   */
  public async start(): Promise<AsyncResult> {
    this.canceled = false;
    const asyncResult = await this.pre();
    this.transferId = asyncResult.id;
    this.logger.debug(`Started metadata transfer. ID = ${this.id}`);
    return asyncResult;
  }

  /**
   * Poll for the status of the metadata transfer request.
   * Default frequency is 100 ms.
   * Default timeout is 60 minutes.
   *
   * @param options Polling options; frequency, timeout, polling function.
   * @returns The result of the deploy or retrieve.
   */
  public async pollStatus(options?: Partial<PollingClient.Options>): Promise<Result>;
  /**
   * Poll for the status of the metadata transfer request.
   * Default frequency is 100 ms.
   * Default timeout is 60 minutes.
   *
   * @param frequency Polling frequency in milliseconds.
   * @param timeout Polling timeout in seconds.
   * @returns The result of the deploy or retrieve.
   */
  public async pollStatus(frequency?: number, timeout?: number): Promise<Result>;
  public async pollStatus(
    frequencyOrOptions?: number | Partial<PollingClient.Options>,
    timeout?: number
  ): Promise<Result> {
    let pollingOptions: PollingClient.Options = {
      frequency: Duration.milliseconds(100),
      timeout: Duration.minutes(60),
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      poll: this.poll.bind(this),
    };
    if (isNumber(frequencyOrOptions)) {
      pollingOptions.frequency = Duration.milliseconds(frequencyOrOptions);
    } else if (frequencyOrOptions !== undefined) {
      pollingOptions = { ...pollingOptions, ...frequencyOrOptions };
    }
    if (isNumber(timeout)) {
      pollingOptions.timeout = Duration.seconds(timeout);
    }

    const pollingClient = await PollingClient.create(pollingOptions);

    try {
      this.logger.debug(`Polling for metadata transfer status. ID = ${this.id}`);
      this.logger.debug(`Polling frequency (ms): ${pollingOptions.frequency.milliseconds}`);
      this.logger.debug(`Polling timeout (min): ${pollingOptions.timeout.minutes}`);
      const completedMdapiStatus = (await pollingClient.subscribe()) as unknown as Status;
      const result = await this.post(completedMdapiStatus);
      if (completedMdapiStatus.status === RequestStatus.Canceled) {
        this.event.emit('cancel', completedMdapiStatus);
      } else {
        this.event.emit('finish', result);
      }
      return result;
    } catch (e) {
      const err = e as Error;
      const error = new MetadataTransferError('md_request_fail', err.message);
      if (error.stack && err.stack) {
        // append the original stack to this new error
        error.stack += `\nDUE TO:\n${err.stack}`;
      }
      if (this.event.listenerCount('error') === 0) {
        throw error;
      }
      this.event.emit('error', error);
    }
  }

  public onUpdate(subscriber: (result: Status) => void): void {
    this.event.on('update', subscriber);
  }

  public onFinish(subscriber: (result: Result) => void): void {
    this.event.on('finish', subscriber);
  }

  public onCancel(subscriber: (result: Status | undefined) => void): void {
    this.event.on('cancel', subscriber);
  }

  public onError(subscriber: (result: Error) => void): void {
    this.event.on('error', subscriber);
  }

  protected async maybeSaveTempDirectory(target: SfdxFileFormat, cs?: ComponentSet): Promise<void> {
    const mdapiTempDir = process.env.SFDX_MDAPI_TEMP_DIR;
    if (mdapiTempDir) {
      process.emitWarning('The SFDX_MDAPI_TEMP_DIR environment variable is set, which may degrade performance');
      this.logger.debug(
        `Converting metadata to: ${mdapiTempDir} because the SFDX_MDAPI_TEMP_DIR environment variable is set`
      );
      try {
        const source = cs || this.components || new ComponentSet();
        const converter = new MetadataConverter();
        await converter.convert(source, target, {
          type: 'directory',
          outputDirectory: mdapiTempDir,
        });
        if (target === 'source') {
          // for source convert the package.xml isn't included so write it separately
          fs.writeFileSync(join(mdapiTempDir, 'package.xml'), source.getPackageXml());
        }
      } catch (e) {
        this.logger.debug(e);
      }
    }
  }

  protected async getConnection(): Promise<Connection> {
    if (typeof this.usernameOrConnection === 'string') {
      this.usernameOrConnection = await Connection.create({
        authInfo: await AuthInfo.create({ username: this.usernameOrConnection }),
      });
      if (this.apiVersion && this.apiVersion !== this.usernameOrConnection.version) {
        this.usernameOrConnection.setApiVersion(this.apiVersion);
        this.logger.debug(`Overriding apiVersion to: ${this.apiVersion}`);
      }
    }
    return this.usernameOrConnection;
  }

  private async poll(): Promise<StatusResult> {
    let completed = false;
    let mdapiStatus: Status;

    if (this.canceled) {
      // This only happens for a canceled retrieve. Canceled deploys are
      // handled via checkStatus response.
      if (!mdapiStatus) {
        mdapiStatus = { id: this.id, success: false, done: true } as Status;
      }
      mdapiStatus.status = RequestStatus.Canceled;
      completed = true;
      this.canceled = false;
    } else {
      mdapiStatus = await this.checkStatus();
      completed = mdapiStatus?.done;
      if (!completed) {
        this.event.emit('update', mdapiStatus);
      }
    }
    this.logger.debug(`MDAPI status update: ${mdapiStatus.status}`);

    return { completed, payload: mdapiStatus as unknown as AnyJson };
  }

  public abstract checkStatus(): Promise<Status>;
  public abstract cancel(): Promise<void>;
  protected abstract pre(): Promise<AsyncResult>;
  protected abstract post(result: Status): Promise<Result>;
}


export interface MetadataTransferOptions {
  usernameOrConnection: string | Connection;
  components?: ComponentSet;
  apiVersion?: string;
  id?: string;
}


/**
   * Send the metadata transfer request to the org.
   *
   * @returns AsyncResult from the deploy or retrieve response.
   */
public async start(): Promise<AsyncResult> {
    this.canceled = false;
    const asyncResult = await this.pre();
    this.transferId = asyncResult.id;
    this.logger.debug(`Started metadata transfer. ID = ${this.id}`);
    return asyncResult;
  }


/**
   * Poll for the status of the metadata transfer request.
   * Default frequency is 100 ms.
   * Default timeout is 60 minutes.
   *
   * @param options Polling options; frequency, timeout, polling function.
   * @returns The result of the deploy or retrieve.
   */
public async pollStatus(options?: Partial<PollingClient.Options>): Promise<Result>;


/**
   * Poll for the status of the metadata transfer request.
   * Default frequency is 100 ms.
   * Default timeout is 60 minutes.
   *
   * @param frequency Polling frequency in milliseconds.
   * @param timeout Polling timeout in seconds.
   * @returns The result of the deploy or retrieve.
   */
public async pollStatus(frequency?: number, timeout?: number): Promise<Result>;


public async pollStatus(
    frequencyOrOptions?: number | Partial<PollingClient.Options>,
    timeout?: number
  ): Promise<Result> {
    let pollingOptions: PollingClient.Options = {
      frequency: Duration.milliseconds(100),
      timeout: Duration.minutes(60),
      // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
      poll: this.poll.bind(this),
    };
    if (isNumber(frequencyOrOptions)) {
      pollingOptions.frequency = Duration.milliseconds(frequencyOrOptions);
    } else if (frequencyOrOptions !== undefined) {
      pollingOptions = { ...pollingOptions, ...frequencyOrOptions };
    }
    if (isNumber(timeout)) {
      pollingOptions.timeout = Duration.seconds(timeout);
    }

    const pollingClient = await PollingClient.create(pollingOptions);

    try {
      this.logger.debug(`Polling for metadata transfer status. ID = ${this.id}`);
      this.logger.debug(`Polling frequency (ms): ${pollingOptions.frequency.milliseconds}`);
      this.logger.debug(`Polling timeout (min): ${pollingOptions.timeout.minutes}`);
      const completedMdapiStatus = (await pollingClient.subscribe()) as unknown as Status;
      const result = await this.post(completedMdapiStatus);
      if (completedMdapiStatus.status === RequestStatus.Canceled) {
        this.event.emit('cancel', completedMdapiStatus);
      } else {
        this.event.emit('finish', result);
      }
      return result;
    } catch (e) {
      const err = e as Error;
      const error = new MetadataTransferError('md_request_fail', err.message);
      if (error.stack && err.stack) {
        // append the original stack to this new error
        error.stack += `\nDUE TO:\n${err.stack}`;
      }
      if (this.event.listenerCount('error') === 0) {
        throw error;
      }
      this.event.emit('error', error);
    }
  }


public onUpdate(subscriber: (result: Status) => void): void {
    this.event.on('update', subscriber);
  }


public onFinish(subscriber: (result: Result) => void): void {
    this.event.on('finish', subscriber);
  }


public onCancel(subscriber: (result: Status | undefined) => void): void {
    this.event.on('cancel', subscriber);
  }


public onError(subscriber: (result: Error) => void): void {
    this.event.on('error', subscriber);
  }


protected async maybeSaveTempDirectory(target: SfdxFileFormat, cs?: ComponentSet): Promise<void> {
    const mdapiTempDir = process.env.SFDX_MDAPI_TEMP_DIR;
    if (mdapiTempDir) {
      process.emitWarning('The SFDX_MDAPI_TEMP_DIR environment variable is set, which may degrade performance');
      this.logger.debug(
        `Converting metadata to: ${mdapiTempDir} because the SFDX_MDAPI_TEMP_DIR environment variable is set`
      );
      try {
        const source = cs || this.components || new ComponentSet();
        const converter = new MetadataConverter();
        await converter.convert(source, target, {
          type: 'directory',
          outputDirectory: mdapiTempDir,
        });
        if (target === 'source') {
          // for source convert the package.xml isn't included so write it separately
          fs.writeFileSync(join(mdapiTempDir, 'package.xml'), source.getPackageXml());
        }
      } catch (e) {
        this.logger.debug(e);
      }
    }
  }


protected async getConnection(): Promise<Connection> {
    if (typeof this.usernameOrConnection === 'string') {
      this.usernameOrConnection = await Connection.create({
        authInfo: await AuthInfo.create({ username: this.usernameOrConnection }),
      });
      if (this.apiVersion && this.apiVersion !== this.usernameOrConnection.version) {
        this.usernameOrConnection.setApiVersion(this.apiVersion);
        this.logger.debug(`Overriding apiVersion to: ${this.apiVersion}`);
      }
    }
    return this.usernameOrConnection;
  }


private async poll(): Promise<StatusResult> {
    let completed = false;
    let mdapiStatus: Status;

    if (this.canceled) {
      // This only happens for a canceled retrieve. Canceled deploys are
      // handled via checkStatus response.
      if (!mdapiStatus) {
        mdapiStatus = { id: this.id, success: false, done: true } as Status;
      }
      mdapiStatus.status = RequestStatus.Canceled;
      completed = true;
      this.canceled = false;
    } else {
      mdapiStatus = await this.checkStatus();
      completed = mdapiStatus?.done;
      if (!completed) {
        this.event.emit('update', mdapiStatus);
      }
    }
    this.logger.debug(`MDAPI status update: ${mdapiStatus.status}`);

    return { completed, payload: mdapiStatus as unknown as AnyJson };
  }


public abstract checkStatus(): Promise<Status>;


public abstract cancel(): Promise<void>;


protected abstract pre(): Promise<AsyncResult>;


protected abstract post(result: Status): Promise<Result>;


() => {
  return <><Button kind="primary">Primary</Button> <Button kind="danger">Danger</Button> <Button kind="warning">Warning</Button> <Button kind="success">Success</Button> <Button kind="secondary">Secondary</Button> <Button kind="light">Light</Button></>;
}


(html: string) => {
  html = html.replace(COMMENT_PSEUDO_COMMENT_OR_LT_BANG, '')
  try {
    return format(html, {
      htmlWhitespaceSensitivity: 'css',
      proseWrap: 'always',
      printWidth: 80,
      tabWidth: 2,
      useTabs: false,
      parser: 'html'
    })
  } catch {
    // console.warn(`unable to format the following html\n${html}`)
    return html
  }
}


(filter) => {
        if (filter.symbols !== undefined && filter.channel !== 'market24h') {
          return filter.symbols.map((symbol) => {
            return {
              id: id++,
              method: this.channelsMap[filter.channel],
              params: [symbol]
            }
          })
        } else {
          return [
            {
              id: id++,
              method: this.channelsMap[filter.channel],
              params: []
            }
          ]
        }
      }


(symbol) => {
            return {
              id: id++,
              method: this.channelsMap[filter.channel],
              params: [symbol]
            }
          }


(f) => f


export class PhemexRealTimeFeed extends RealTimeFeedBase {
  protected readonly wssURL = 'wss://phemex.com/ws'
  protected readonly channelsMap = {
    book: 'orderbook.subscribe',
    trades: 'trade.subscribe',
    market24h: 'market24h.subscribe'
  } as any

  protected mapToSubscribeMessages(filters: Filter<string>[]) {
    let id = 0
    return filters
      .map((filter) => {
        if (filter.symbols !== undefined && filter.channel !== 'market24h') {
          return filter.symbols.map((symbol) => {
            return {
              id: id++,
              method: this.channelsMap[filter.channel],
              params: [symbol]
            }
          })
        } else {
          return [
            {
              id: id++,
              method: this.channelsMap[filter.channel],
              params: []
            }
          ]
        }
      })
      .flatMap((f) => f)
  }

  protected messageIsError(message: any): boolean {
    return message.error !== undefined && message.error !== null
  }
}


protected mapToSubscribeMessages(filters: Filter<string>[]) {
    let id = 0
    return filters
      .map((filter) => {
        if (filter.symbols !== undefined && filter.channel !== 'market24h') {
          return filter.symbols.map((symbol) => {
            return {
              id: id++,
              method: this.channelsMap[filter.channel],
              params: [symbol]
            }
          })
        } else {
          return [
            {
              id: id++,
              method: this.channelsMap[filter.channel],
              params: []
            }
          ]
        }
      })
      .flatMap((f) => f)
  }


protected messageIsError(message: any): boolean {
    return message.error !== undefined && message.error !== null
  }


declare class ConcordModulesPlugin {
    constructor(source: any, options: any, target: any);
    source: any;
    options: any;
    target: any;
    apply(resolver: any): void;
}


apply(resolver: any): void;


() => {
  expect(relativeTarball('https://registry.com/foo/bar.tgz', 'https://registry.com/foo')).toBe('bar.tgz')
  expect(relativeTarball('https://registry.com/foo/bar.tgz', 'https://registry.com/foo/')).toBe('bar.tgz')
}


function fsA(): void {
    //读取文件信息
    let stats = fs.statSync(filePath);
    console.log(stats);
    /**
     * Stats {
          dev: 608526645,
          mode: 33206,
          nlink: 1,
          uid: 0,
          gid: 0,
          rdev: 0,
          blksize: 4096,
          ino: 87375216640,
          size: 864,
          blocks: 512,
          atimeMs: 1634053132000,
          mtimeMs: 1634053132000,
          ctimeMs: 1240428288000,
          birthtimeMs: 1634052563600,
          atime: 2021-10-12T15:38:52.000Z,
          mtime: 2021-10-12T15:38:52.000Z,
          ctime: 2009-04-22T19:24:48.000Z,
          birthtime: 2021-10-12T15:29:23.600Z
        }
     */
    //异步操作
    fs.stat(filePath, (err, stats) => {
        if (err) {
            console.log(err);
            return
        }
        console.log(stats);
    })

    //promise方式获取文件信息
    fs.promises.stat(filePath).then(info => {
        console.log(info);
    }).catch(err => {
        console.log("read file err!", err)
    })
}


function fileDescriptor(): void {
    fs.open(filePath, 'r', (err, fd) => {
        if (err) {
            console.log(err);
            return
        }
        console.clear()
        console.log(fd) //3
        //根据文件描述符获取文件信息
        fs.fstat(fd, (err, info) => {
            if (err) {
                console.log(err);
                return
            }
            console.log(info)
        })
    })
}


/**
 * 文件读写
 */
function write() {
    fs.writeFile("./write.txt", "hello world", {
        flag: 'a+'
    }, (err) => {
        if (err) {
            console.error(err)
            return
        }
    })
}


function read() {
    fs.readFile(filePath, {
        encoding: 'utf8'
    }, (err, data) => {
        if (err) {
            console.error(err)
            return
        }
        console.log(data)
    })
}


/**
 * 文件夹操作
 */
function mkdir(): void {
    const myDir = "./My"
    if (!fs.existsSync(myDir)) {
        fs.mkdir(myDir, err => {
            if (err) {
                console.error(err)
                return
            }
        })
    }
}


function readdir() {
    const dir = path.resolve(__dirname)
    fs.readdir(dir, (err, files) => {
        if (err) {
            console.error(err)
            return
        }
        console.log(files)
        fs.writeFile('./write.txt', files.toString(), (err: NodeJS.ErrnoException | null): void => {
            if (err) {
                console.error(err)
                return
            }
            console.log("write file success")
        })
    })
}


function getAllFiles(dirName: string): void {
    fs.readdir(dirName, {
        withFileTypes: true
    }, (err, files) => {
        if (err) {
            console.error(err)
            return
        }
        files.forEach(file => {
            if (file.isDirectory()) {
                getAllFiles(path.resolve(dirName, file.name))
            } else {
                fs.writeFile("./write.txt", file.toString(), err => {
                    if (err) {
                        console.error(err)
                        return
                    }
                })
            }
        })
    })
}


function reName() {
    fs.rename("./write.txt", "new.txt", err => {
        if (!err) {
            console.log("rename success")
        } else {
            console.log(err)
        }
    });
}


(err, stats) => {
        if (err) {
            console.log(err);
            return
        }
        console.log(stats);
    }


info => {
        console.log(info);
    }


err => {
        console.log("read file err!", err)
    }


(err, fd) => {
        if (err) {
            console.log(err);
            return
        }
        console.clear()
        console.log(fd) //3
        //根据文件描述符获取文件信息
        fs.fstat(fd, (err, info) => {
            if (err) {
                console.log(err);
                return
            }
            console.log(info)
        })
    }


(err, info) => {
            if (err) {
                console.log(err);
                return
            }
            console.log(info)
        }


(err) => {
        if (err) {
            console.error(err)
            return
        }
    }


(err, data) => {
        if (err) {
            console.error(err)
            return
        }
        console.log(data)
    }


err => {
            if (err) {
                console.error(err)
                return
            }
        }


(err, files) => {
        if (err) {
            console.error(err)
            return
        }
        console.log(files)
        fs.writeFile('./write.txt', files.toString(), (err: NodeJS.ErrnoException | null): void => {
            if (err) {
                console.error(err)
                return
            }
            console.log("write file success")
        })
    }


(err: NodeJS.ErrnoException | null): void => {
            if (err) {
                console.error(err)
                return
            }
            console.log("write file success")
        }


(err, files) => {
        if (err) {
            console.error(err)
            return
        }
        files.forEach(file => {
            if (file.isDirectory()) {
                getAllFiles(path.resolve(dirName, file.name))
            } else {
                fs.writeFile("./write.txt", file.toString(), err => {
                    if (err) {
                        console.error(err)
                        return
                    }
                })
            }
        })
    }


file => {
            if (file.isDirectory()) {
                getAllFiles(path.resolve(dirName, file.name))
            } else {
                fs.writeFile("./write.txt", file.toString(), err => {
                    if (err) {
                        console.error(err)
                        return
                    }
                })
            }
        }


err => {
                    if (err) {
                        console.error(err)
                        return
                    }
                }


err => {
        if (!err) {
            console.log("rename success")
        } else {
            console.log(err)
        }
    }


(app: Application) => {
  const Sequelize = app.Sequelize
  const { INTEGER, STRING, TEXT, DATE } = Sequelize
  const Blogs = app.model.define<Blogs, BlogAttributes>('blogs', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    user_id: { type: INTEGER, allowNull: false },
    username: {
      type: STRING(30),
      allowNull: false,
    },
    title: {
      type: STRING,
      allowNull: false,
    },
    content: TEXT,
    visi_count: {
      type: INTEGER,
      allowNull: false,
      defaultValue: 0,
    },
    create_time: {
      type: DATE,
      allowNull: false,
      defaultValue: new Date(),
      get() {
        return moment(this.getDataValue('create_time')).format('YYYY-MM-DD hh:mm:ss')
      },
    },
    update_time: {
      type: DATE,
      allowNull: false,
      defaultValue: new Date(),
      get() {
        return moment(this.getDataValue('update_time')).format('YYYY-MM-DD hh:mm:ss')
      },
    },
  }, {
    createdAt: false,
    updatedAt: false,
  })

  Blogs.prototype.associate = function() {
    app.model.Blogs.hasMany(app.model.Likes, {
      as: 'likes',
    })
  }

  return Blogs
}


export class Blogs extends Model<BlogAttributes, BlogCreationAttributes> implements BlogAttributes {
  user_id: number
  create_time: Date
  update_time: Date
  id: number
  username: string
  title: string
  content: string
  visi_count: number
}


export interface BlogAttributes {
  id: number
  user_id: number
  username: string
  title: string
  content: string
  visi_count?: number
  create_time?: Date
  update_time?: Date
}


export interface BlogCreationAttributes extends Optional<BlogAttributes, 'id'> {}


get() {
        return moment(this.getDataValue('create_time')).format('YYYY-MM-DD hh:mm:ss')
      }


get() {
        return moment(this.getDataValue('update_time')).format('YYYY-MM-DD hh:mm:ss')
      }


export function OptionChoiceItem(props: Props) {
  function RightArrowIcon() {
    return (
      <svg
        width="24"
        height="24"
        viewBox="0 0 24 24"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path d="M12 4L10.59 5.41L16.17 11H4V13H16.17L10.59 18.59L12 20L20 12L12 4Z" />
      </svg>
    );
  }
  return (
    <Wrapper>
      <Row>
        <StyledArrow selected={props.selected}>
          <RightArrowIcon />
        </StyledArrow>
        <Column>
          <Title>{props.choice.title}</Title>
          <SubTitle>{props.choice.explanation}</SubTitle>
        </Column>
      </Row>
    </Wrapper>
  );
}


function RightArrowIcon() {
    return (
      <svg
        width="24"
        height="24"
        viewBox="0 0 24 24"
        fill="none"
        xmlns="http://www.w3.org/2000/svg"
      >
        <path d="M12 4L10.59 5.41L16.17 11H4V13H16.17L10.59 18.59L12 20L20 12L12 4Z" />
      </svg>
    );
  }


(props) =>
    props.selected
      ? css`
          fill: "#000";
        `
      : props.placeholder
      ? css`
          fill: "#DEDEDE";
        `
      : css`
          fill: "rgba(255,255,255,0)";

          &:hover {
            fill: "#8B8B8B;";
          }
        `


interface Props {
  selected: boolean;
  placeholder?: boolean;
  choice: {
    title: string;
    explanation: string;
  };
}


export default function PlotNFTCard(props: Props) {
  const {
    nft,
    nft: {
      pool_state: {
        p2_singleton_puzzle_hash,
        pool_config: { launcher_id, pool_url },
        points_found_24h,
        points_acknowledged_24h,
      },
      pool_wallet_status: { wallet_id },
    },
  } = props;

  const { loading, payoutAddress } = usePayoutAddress(nft);

  const percentPointsSuccessful24 = getPercentPointsSuccessfull(
    points_acknowledged_24h,
    points_found_24h,
  );

  const history = useHistory();
  const openDialog = useOpenDialog();
  const dispatch = useDispatch();
  const { isSelfPooling, isSynced, plots, balance } = usePlotNFTDetails(nft);
  const totalPointsFound24 = points_found_24h.reduce(
    (accumulator, item) => accumulator + item[1],
    0,
  );

  function handleAddPlot() {
    history.push({
      pathname: '/dashboard/plot/add',
      state: {
        p2_singleton_puzzle_hash,
      },
    });
  }

  async function handleDeleteUnconfirmedTransactions() {
    const deleteConfirmed = await openDialog(
      <ConfirmDialog
        title={<Trans>Confirmation</Trans>}
        confirmTitle={<Trans>Delete</Trans>}
        confirmColor="danger"
      >
        <Trans>Are you sure you want to delete unconfirmed transactions?</Trans>
      </ConfirmDialog>,
    );

    if (deleteConfirmed) {
      dispatch(deleteUnconfirmedTransactions(wallet_id));
    }
  }

  function handleGetPoolLoginLink() {
    openDialog(<PlotNFTGetPoolLoginLinkDialog nft={nft} />);
  }

  function handlePayoutInstructions() {
    openDialog(<PlotNFTPayoutInstructionsDialog nft={nft} />);
  }

  const rows = [
    {
      key: 'status',
      label: <Trans>Status</Trans>,
      value: <PlotNFTStatus nft={nft} />,
    }


function handleAddPlot() {
    history.push({
      pathname: '/dashboard/plot/add',
      state: {
        p2_singleton_puzzle_hash,
      },
    });
  }


async function handleDeleteUnconfirmedTransactions() {
    const deleteConfirmed = await openDialog(
      <ConfirmDialog
        title={<Trans>Confirmation</Trans>}
        confirmTitle={<Trans>Delete</Trans>}
        confirmColor="danger"
      >
        <Trans>Are you sure you want to delete unconfirmed transactions?</Trans>
      </ConfirmDialog>,
    );

    if (deleteConfirmed) {
      dispatch(deleteUnconfirmedTransactions(wallet_id));
    }
  }


function handleGetPoolLoginLink() {
    openDialog(<PlotNFTGetPoolLoginLinkDialog nft={nft} />);
  }


function handlePayoutInstructions() {
    openDialog(<PlotNFTPayoutInstructionsDialog nft={nft} />);
  }


({ theme }) =>
    theme.palette.type === 'dark' ? '#515151' : '#F6F6F6'


(accumulator, item) => accumulator + item[1]


(row) => !!row


({ onClose }) => (
                  <Box>
                    <MenuItem
                      onClick={()


() => {
                          onClose();
                          handleGetPoolLoginLink();
                        }


() => {
                          onClose();
                          handlePayoutInstructions();
                        }


() => {
                        onClose();
                        handleDeleteUnconfirmedTransactions();
                      }


type Props = {
  nft: PlotNFT;
};


Rewards<


Number(percentPointsSuccessful24 * 100)


loading ? <Loading size="1rem"


isSelfPooling ? (
                            <Trans


export function createApplicationEntity(data: JumpCloudApplication) {
  const appId = data.id || (data._id as string);
  delete data.config; //this has SAML certs in it

  return createIntegrationEntity({
    entityData: {
      source: data,
      assign: {
        _key: appId,
        _type: ApplicationEntities.APPLICATION._type,
        _class: ApplicationEntities.APPLICATION._class,
        id: data.id as string,
        name: data.name as string,
        displayName: data.displayName as string,
        description: data.description,
        createdOn: parseTimePropertyValue(data.created),
        ssoUrl: data.ssoUrl,
        webLink: getConsoleUrl(`/#/sso/${data.id}/details`),
      },
    },
  });
}


interface BrowseResult {
    target: string;
    private: boolean;
    dirs: string[];
    privateDirs: string[];
    files: string[];
    gridSize?: number;
    extensions: [];
  }


interface BrowsingOptions {
    /**
     * A bucket within which to search, if using the S3 source
     * @defaultValue `""`
     */
    bucket?: string;

    /**
     * An Array of file extensions to filter on
     * @defaultValue `[]` (do not filter on extension)
     */
    extensions?: string[];

    /**
     * The requested dir represents a wildcard path
     * @defaultValue false
     */
    wildcard?: boolean;
  }


interface ConfigurePathOptions {
    /**
     * A bucket to use, if using the S3 source
     * @defaultValue `""`
     */
    bucket?: string;

    /**
     * Set the privacy mode on this path
     * @defaultValue true
     */
    private?: boolean;

    /**
     * Set the grid size
     * @defaultValue `undefined`
     */
    gridSize?: number;
  }


interface ConfigurePathResult {
    private: boolean;
    gridSize?: number;
  }


interface CreateDirectoryOptions {
    /**
     * A bucket to use, if using the S3 source
     * @defaultValue `""`
     */
    bucket?: string;
  }


interface Data {
    bucket: string | null;
    canGoBack: boolean;
    canUpload: boolean;
    canSelect: boolean;
    cssClass: string;
    dirs: Dir[];
    displayMode: FilePicker.DisplayMode;
    extensions: string[] | undefined;
    files: File[];
    isS3: boolean;
    noResults: boolean;
    request: string;
    selected: string | undefined;
    source: Source;
    sources: Sources;
    target: string;
    tileSize: number | null;
    user: Game['user'];
    submitText: 'FILES.SelectFolder' | 'FILES.SelectFile';
  }


interface Dir {
    name: string;
    path: string;
    private: boolean;
  }


interface File {
    name: string;
    url: string;
    img: string;
  }


interface ManageData {
    action: 'browseFiles' | 'configurePath' | 'createDirectory' | 'manageFiles';
    source: string;
    target: string;
  }


/**
   * Options for configuring FilePicker
   */
interface Options extends Application.Options {
    /**
     * The current file path being modified, if any
     */
    current?: FilePicker['request'];

    /**
     * A current file source in "data", "public", or "s3"
     */
    activeSource?: DataSource;

    /**
     * A type of file to target, in "audio", "image", "video", "imagevideo" or "folder"
     */
    type?: FilePicker['type'];

    /**
     * An HTML form field that the result of this selection is applied to
     */
    field?: FilePicker['field'];

    /**
     * An HTML button element which triggers the display of this picker
     */
    button?: FilePicker['button'];

    /**
     * A callback function to trigger once a file has been selected
     */
    callback?: Callback;

    /**
     * @defaultValue `'templates/apps/filepicker.html'`
     */
    template: Application.Options['template'];

    /**
     * @defaultValue `['filepicker']`
     */
    classes: Application.Options['classes'];

    /**
     * @defaultValue `520`
     */
    width: Application.Options['width'];

    /**
     * @defaultValue `[{navSelector: ".tabs"}]`
     */
    tabs: Application.Options['tabs'];

    /**
     * @defaultValue `[{dragSelector: '.file', dropSelector: '.filepicker-body'}]`
     */
    dragDrop: Application.Options['dragDrop'];

    /**
     * @defaultValue `false`
     */
    tileSize: boolean;

    /**
     * @defaultValue `[{ inputSelector: 'input[name="filter"]', contentSelector: ".filepicker-body" }]`
     */
    filters: Application.Options['filters'];
  }


interface Source {
    target: string;
    label: string;
    icon: string;
  }


interface Sources {
    data: Source;
    public: Source;
    s3: Source & {
      buckets: string[];
      bucket: string;
    };
  }


/**
   * Optional arguments for the `upload` method
   */
interface UploadOptions {
    /**
     * A bucket to upload to, if using the S3 source
     * @defaultValue `""`
     */
    bucket?: string;
  }


/**
   * A callback function to trigger once a file has been selected
   * @param path - The path that was chosen
   */
type Callback = (path: string) => void;


type DataSource = 'data' | 'public' | 's3';


type DisplayMode = ValueOf<typeof FilePicker['DISPLAY_MODES']>;


type Type = 'audio' | 'image' | 'video' | 'imagevideo' | 'folder';


/**
   * Given a current file path, determine the directory it belongs to
   * @param target - The currently requested target path
   * @returns An array of the inferred source and target directory path
   */
protected _inferCurrentDirectory(target: string | undefined): [string, string];


/**
   * Get the valid file extensions for a given named file picker type
   * @param type - The general type of file
   * @returns A list of file extensions
   */
protected _getExtensions(type: FilePicker.Type): string[] | undefined;


/**
   * Test a URL to see if it matches a well known s3 key pattern
   * @param url - An input URL to test
   * @returns A regular expression match
   */
static matchS3URL(url: string): RegExpMatchArray | null;


/**
   * Parse a s3 key to learn the bucket and the key prefix used for the request
   * @param key - A fully qualified key name or prefix path
   */
static parseS3URL(key: string): { bucket: string | null; keyPrefix: string };


/**
   * @param options - (unused)
   * @override
   */
getData(options?: Partial<P>): Promise<FilePicker.Data>;


/**
   * Browse to a specific location for this FilePicker instance
   * @param target - The target within the currently active source location.
   * @param options - Browsing options (default: `{}`)
   */
browse(target?: string, options?: FilePicker.BrowsingOptions): Promise<FilePicker.BrowseResult | undefined>;


/**
   * Browse files for a certain directory location
   * @param source  - The source location in which to browse. See FilePicker#sources for details
   * @param target  - The target within the source location (default: `""`)
   * @param options - Optional arguments (default: `{}`)
   *
   * @returns A Promise which resolves to the directories and files contained in the location
   */
static browse(
    source: FilePicker.DataSource,
    target?: string,
    options?: FilePicker.BrowsingOptions
  ): Promise<FilePicker.BrowseResult | undefined>;


/**
   * Configure metadata settings regarding a certain file system path
   * @param source  - The source location in which to browse. See FilePicker#sources for details
   * @param target  - The target within the source location
   * @param options - Optional arguments which modify the request (default: `{}`)
   */
static configurePath(
    source: FilePicker.DataSource,
    target: string,
    options?: FilePicker.ConfigurePathOptions
  ): Promise<FilePicker.ConfigurePathResult>;


/**
   * Create a subdirectory within a given source. The requested subdirectory path must not already exist.
   * @param source  - The source location in which to browse. See FilePicker#sources for details
   * @param target  - The target within the source location
   * @param options - Optional arguments which modify the request (default: `{}`)
   */
static createDirectory(
    source: FilePicker.DataSource,
    target: string,
    options?: FilePicker.CreateDirectoryOptions
  ): Promise<string>;


/**
   * General dispatcher method to submit file management commands to the server
   */
protected static _manageFiles(
    data: FilePicker.ManageData,
    options?: Record<string, unknown>
  ): Promise<Record<string, unknown> | undefined>;


/**
   * Dispatch a POST request to the server containing a directory path and a file to upload
   * @param source  - The data source to which the file should be uploaded
   * @param path    - The destination path
   * @param file    - The File object to upload
   * @param options - Additional file upload options passed as form data (default `{}`)
   * @returns The response object
   */
static upload(
    source: FilePicker.DataSource,
    path: string,
    file: File,
    options?: FilePicker.UploadOptions
  ): Promise<(Response & { path: string; message?: string }) | false | void>;


/**
   * Additional actions performed when the file-picker UI is rendered
   */
render(force?: boolean, options?: Application.RenderOptions<P>): ReturnType<this['browse']> | void;


/** @override */
activateListeners(html: JQuery): void;


/**
   * Handle a click event to change the display mode of the File Picker
   * @param event - The triggering click event
   */
protected _onChangeDisplayMode(event: JQuery.ClickEvent): void;


/**
   * @param event - (unused)
   * @param event - (unused)
   * @override
   */
protected _onChangeTab(event: MouseEvent | null, tabs: Tabs, active: this['activeSource']): void;


/**
   * @param selector - (unused)
   * @override
   */
protected _canDragStart(selector: string | null): boolean;


/**
   * @param selector - (unused)
   * @override
   */
protected _canDragDrop(selector: string | null): this['canUpload'];


/**
   * @override
   */
protected _onDragStart(event: DragEvent): void;


/**
   * @override
   */
protected _onDrop(event: DragEvent): Promise<PromisedType<ReturnType<this['browse']>> | void>;


/**
   * Handle user submission of the address bar to request an explicit target
   * @param event - The originating keydown event
   */
protected _onRequestTarget(event: KeyboardEvent): ReturnType<this['browse']> | void;


/**
   * Handle requests from the IntersectionObserver to lazily load an image file
   * @param entries  - The entries which are now observed
   * @param observer - The intersection observer instance
   */
protected _onLazyLoadImages(entries: IntersectionObserverEntry[], observer: IntersectionObserver): void;


/**
   * Handle file or folder selection within the file picker
   * @param event - The originating click event
   */
protected _onPick(event: JQuery.ClickEvent): ReturnType<this['browse']> | void;


/**
   * Handle backwards navigation of the fol6der structure
   */
protected _onClickDirectoryControl(
    event: JQuery.ClickEvent
  ):
    | ReturnType<this['browse']>
    | Promise<ReturnType<this['browse']> | void | null>
    | ReturnType<typeof FilePicker['configurePath']>;


/**
   * Present the user with a dialog to create a subdirectory within their currently browsed file storate location.
   */
protected _createDirectoryDialog(source: FilePicker.Source): Promise<ReturnType<this['browse']> | void | null>;


/**
   * Handle changes to the bucket selector
   */
protected _onChangeBucket(event: JQuery.ChangeEvent): ReturnType<this['browse']>;


/**
   * @param event - (unused)
   * @override
   */
protected _onSearchFilter(event: KeyboardEvent, query: string, rgx: RegExp, html: HTMLElement): void;


/**
   * Handle file picker form submission
   */
protected _onSubmit(ev: Event): void;


/**
   * Handle file upload
   */
protected _onUpload(ev: Event): Promise<void>;


/**
   * Bind the file picker to a new target field.
   * Assumes the user will provide a <button> HTMLElement which has the data-target and data-type attributes
   * The data-target attribute should provide the name of the input field which should receive the selected file
   * The data-type attribute is a string in ["image", "audio"] which sets the file extensions which will be accepted
   *
   * @param button  - The button element
   */
static fromButton(button: HTMLButtonElement): FilePicker;


/** @docs-private */
export declare function MAT_AUTOCOMPLETE_SCROLL_STRATEGY_FACTORY(overlay: Overlay): () => ScrollStrategy;


/**
 * Creates an error to be thrown when attempting to use an autocomplete trigger without a panel.
 * @docs-private
 */
export declare function getMatAutocompleteMissingPanelError(): Error;


export declare class MatAutocompleteTrigger implements ControlValueAccessor, AfterViewInit, OnChanges, OnDestroy {
    private _element;
    private _overlay;
    private _viewContainerRef;
    private _zone;
    private _changeDetectorRef;
    private _dir;
    private _formField;
    private _document;
    private _viewportRuler?;
    private _overlayRef;
    private _portal;
    private _componentDestroyed;
    private _autocompleteDisabled;
    private _scrollStrategy;
    /** Old value of the native input. Used to work around issues with the `input` event on IE. */
    private _previousValue;
    /** Strategy that is used to position the panel. */
    private _positionStrategy;
    /** Whether or not the label state is being overridden. */
    private _manuallyFloatingLabel;
    /** The subscription for closing actions (some are bound to document). */
    private _closingActionsSubscription;
    /** Subscription to viewport size changes. */
    private _viewportSubscription;
    /**
     * Whether the autocomplete can open the next time it is focused. Used to prevent a focused,
     * closed autocomplete from being reopened if the user switches to another browser tab and then
     * comes back.
     */
    private _canOpenOnNextFocus;
    /** Whether the element is inside of a ShadowRoot component. */
    private _isInsideShadowRoot;
    /** Stream of keyboard events that can close the panel. */
    private readonly _closeKeyEventStream;
    /**
     * Event handler for when the window is blurred. Needs to be an
     * arrow function in order to preserve the context.
     */
    private _windowBlurHandler;
    /** `View -> model callback called when value changes` */
    _onChange: (value: any) => void;
    /** `View -> model callback called when autocomplete has been touched` */
    _onTouched: () => void;
    /** The autocomplete panel to be attached to this trigger. */
    autocomplete: MatAutocomplete;
    /**
     * Position of the autocomplete panel relative to the trigger element. A position of `auto`
     * will render the panel underneath the trigger if there is enough space for it to fit in
     * the viewport, otherwise the panel will be shown above it. If the position is set to
     * `above` or `below`, the panel will always be shown above or below the trigger. no matter
     * whether it fits completely in the viewport.
     */
    position: 'auto' | 'above' | 'below';
    /**
     * Reference relative to which to position the autocomplete panel.
     * Defaults to the autocomplete trigger element.
     */
    connectedTo: MatAutocompleteOrigin;
    /**
     * `autocomplete` attribute to be set on the input element.
     * @docs-private
     */
    autocompleteAttribute: string;
    /**
     * Whether the autocomplete is disabled. When disabled, the element will
     * act as a regular input and the user won't be able to open the panel.
     */
    get autocompleteDisabled(): boolean;
    set autocompleteDisabled(value: boolean);
    constructor(_element: ElementRef<HTMLInputElement>, _overlay: Overlay, _viewContainerRef: ViewContainerRef, _zone: NgZone, _changeDetectorRef: ChangeDetectorRef, scrollStrategy: any, _dir: Directionality, _formField: MatFormField, _document: any, _viewportRuler?: ViewportRuler | undefined);
    ngAfterViewInit(): void;
    ngOnChanges(changes: SimpleChanges): void;
    ngOnDestroy(): void;
    /** Whether or not the autocomplete panel is open. */
    get panelOpen(): boolean;
    private _overlayAttached;
    /** Opens the autocomplete suggestion panel. */
    openPanel(): void;
    /** Closes the autocomplete suggestion panel. */
    closePanel(): void;
    /**
     * Updates the position of the autocomplete suggestion panel to ensure that it fits all options
     * within the viewport.
     */
    updatePosition(): void;
    /**
     * A stream of actions that should close the autocomplete panel, including
     * when an option is selected, on blur, and when TAB is pressed.
     */
    get panelClosingActions(): Observable<MatOptionSelectionChange | null>;
    /** Stream of autocomplete option selections. */
    readonly optionSelections: Observable<MatOptionSelectionChange>;
    /** The currently active option, coerced to MatOption type. */
    get activeOption(): MatOption | null;
    /** Stream of clicks outside of the autocomplete panel. */
    private _getOutsideClickStream;
    writeValue(value: any): void;
    registerOnChange(fn: (value: any) => {}): void;
    registerOnTouched(fn: () => {}): void;
    setDisabledState(isDisabled: boolean): void;
    _handleKeydown(event: KeyboardEvent): void;
    _handleInput(event: KeyboardEvent): void;
    _handleFocus(): void;
    /**
     * In "auto" mode, the label will animate down as soon as focus is lost.
     * This causes the value to jump when selecting an option with the mouse.
     * This method manually floats the label until the panel can be closed.
     * @param shouldAnimate Whether the label should be animated when it is floated.
     */
    private _floatLabel;
    /** If the label has been manually elevated, return it to its normal state. */
    private _resetLabel;
    /**
     * Given that we are not actually focusing active options, we must manually adjust scroll
     * to reveal options below the fold. First, we find the offset of the option from the top
     * of the panel. If that offset is below the fold, the new scrollTop will be the offset -
     * the panel height + the option height, so the active option will be just visible at the
     * bottom of the panel. If that offset is above the top of the visible panel, the new scrollTop
     * will become the offset. If that offset is visible within the panel already, the scrollTop is
     * not adjusted.
     */
    private _scrollToOption;
    /**
     * This method listens to a stream of panel closing actions and resets the
     * stream every time the option list changes.
     */
    private _subscribeToClosingActions;
    /** Destroys the autocomplete suggestion panel. */
    private _destroyPanel;
    private _setTriggerValue;
    /**
     * This method closes the panel, and if a value is specified, also sets the associated
     * control to that value. It will also mark the control as dirty if this interaction
     * stemmed from the user.
     */
    private _setValueAndClose;
    /**
     * Clear any previous selected option and emit a selection change event for this option
     */
    private _clearPreviousSelectedOption;
    private _attachOverlay;
    private _getOverlayConfig;
    private _getOverlayPosition;
    /** Sets the positions on a position strategy based on the directive's input state. */
    private _setStrategyPositions;
    private _getConnectedElement;
    private _getPanelWidth;
    /** Returns the width of the input element, so the panel width can match it. */
    private _getHostWidth;
    /**
     * Resets the active item to -1 so arrow events will activate the
     * correct options, or to 0 if the consumer opted into it.
     */
    private _resetActiveItem;
    /** Determines whether the panel can be opened. */
    private _canOpen;
    static ngAcceptInputType_autocompleteDisabled: BooleanInput;
}


ngAfterViewInit(): void;


ngOnChanges(changes: SimpleChanges): void;


ngOnDestroy(): void;


/** Opens the autocomplete suggestion panel. */
openPanel(): void;


/** Closes the autocomplete suggestion panel. */
closePanel(): void;


/**
     * Updates the position of the autocomplete suggestion panel to ensure that it fits all options
     * within the viewport.
     */
updatePosition(): void;


writeValue(value: any): void;


registerOnChange(fn: (value: any) => {}): void;


registerOnTouched(fn: () => {}): void;


setDisabledState(isDisabled: boolean): void;


_handleKeydown(event: KeyboardEvent): void;


_handleInput(event: KeyboardEvent): void;


_handleFocus(): void;


ev => {
            return ev.event === 'requested' && ev.notification instanceof ToastUiNotification;
          }


ev => {
            this.toastsList.push(ev.notification);

            return this.toastsList;
          }


ev => {
            return ev.event === 'resolved' && ev.notification instanceof ToastUiNotification;
          }


ev => {
            pull(this.toastsList, ev.notification);

            return this.toastsList;
          }


() => this.cdr.detectChanges()


ev => {
            return ev.event === 'requested' && ev.notification instanceof DialogUiNotification;
          }


ev => {
            this.dialogsList.push(ev.notification);

            return this.dialogsList;
          }


ev => {
            return ev.event === 'resolved' && ev.notification instanceof DialogUiNotification;
          }


ev => {
            pull(this.dialogsList, ev.notification);

            return this.dialogsList;
          }


() => {
        this.overlayVisible = this.dialogsList.length > 0;
        this.cdr.detectChanges();
      }


@Component({
  changeDetection: ChangeDetectionStrategy.OnPush,
  selector: 'app-ui-notifications',
  animations: [ dialogAnimations, overlayAnimations ],
  templateUrl: './ui-notifications.component.html'
})
export class UiNotificationsComponent implements OnInit {

  toasts$: Observable<Array<ToastUiNotification>>;
  dialogs$: Observable<Array<UiNotification>>;

  overlayVisible = false;

  private toastsList: Array<ToastUiNotification> = [];
  private dialogsList: Array<UiNotification> = [];

  constructor(
    private cdr: ChangeDetectorRef,
    private notifications: UiNotificationsService
  ) { }

  ngOnInit(): void {
    this.subscribeToToasts();
    this.subscribeToDialogs();
  }

  ngOnDestroy(): void {

  }

  getIndexOf(item: any): number {
    if (item instanceof DialogUiNotification) {
      return this.dialogsList.lastIndexOf(item);
    } else {
      return this.toastsList.lastIndexOf(item);
    }
  }

  isOnTop(item: any): boolean {
    if (item instanceof DialogUiNotification) {
      const topEl = this.dialogsList[this.dialogsList.length - 1];

      return (typeof topEl === 'undefined') || topEl.uniqId === item.uniqId;
    } else {
      const topEl = this.toastsList[this.toastsList.length - 1];

      return (typeof topEl === 'undefined') || topEl.uniqId === item.uniqId;
    }
  }

  closeDialog(dialog: any): void {}

  private subscribeToToasts(): void {
    this.toasts$ = ObservableMerge(
      this.notifications
        .events
        .pipe(
          filter(ev => {
            return ev.event === 'requested' && ev.notification instanceof ToastUiNotification;
          }),
          map(ev => {
            this.toastsList.push(ev.notification);

            return this.toastsList;
          })
        ),
      this.notifications
        .events
        .pipe(
          filter(ev => {
            return ev.event === 'resolved' && ev.notification instanceof ToastUiNotification;
          }),
          map(ev => {
            pull(this.toastsList, ev.notification);

            return this.toastsList;
          })
        )
    )
      .pipe(
      tap(() => this.cdr.detectChanges())
    );
  }

  private subscribeToDialogs(): void {
    this.dialogs$ = ObservableMerge(
      this.notifications
        .events
        .pipe(
          filter(ev => {
            return ev.event === 'requested' && ev.notification instanceof DialogUiNotification;
          }),
          map(ev => {
            this.dialogsList.push(ev.notification);

            return this.dialogsList;
          })
        ),
      this.notifications
        .events
        .pipe(
          filter(ev => {
            return ev.event === 'resolved' && ev.notification instanceof DialogUiNotification;
          }),
          map(ev => {
            pull(this.dialogsList, ev.notification);

            return this.dialogsList;
          })
        )
    )
      .pipe(
      tap(() => {
        this.overlayVisible = this.dialogsList.length > 0;
        this.cdr.detectChanges();
      })
    );
  }
}


ngOnInit(): void {
    this.subscribeToToasts();
    this.subscribeToDialogs();
  }


ngOnDestroy(): void {

  }


getIndexOf(item: any): number {
    if (item instanceof DialogUiNotification) {
      return this.dialogsList.lastIndexOf(item);
    } else {
      return this.toastsList.lastIndexOf(item);
    }
  }


isOnTop(item: any): boolean {
    if (item instanceof DialogUiNotification) {
      const topEl = this.dialogsList[this.dialogsList.length - 1];

      return (typeof topEl === 'undefined') || topEl.uniqId === item.uniqId;
    } else {
      const topEl = this.toastsList[this.toastsList.length - 1];

      return (typeof topEl === 'undefined') || topEl.uniqId === item.uniqId;
    }
  }


closeDialog(dialog: any): void {}


private subscribeToToasts(): void {
    this.toasts$ = ObservableMerge(
      this.notifications
        .events
        .pipe(
          filter(ev => {
            return ev.event === 'requested' && ev.notification instanceof ToastUiNotification;
          }),
          map(ev => {
            this.toastsList.push(ev.notification);

            return this.toastsList;
          })
        ),
      this.notifications
        .events
        .pipe(
          filter(ev => {
            return ev.event === 'resolved' && ev.notification instanceof ToastUiNotification;
          }),
          map(ev => {
            pull(this.toastsList, ev.notification);

            return this.toastsList;
          })
        )
    )
      .pipe(
      tap(() => this.cdr.detectChanges())
    );
  }


private subscribeToDialogs(): void {
    this.dialogs$ = ObservableMerge(
      this.notifications
        .events
        .pipe(
          filter(ev => {
            return ev.event === 'requested' && ev.notification instanceof DialogUiNotification;
          }),
          map(ev => {
            this.dialogsList.push(ev.notification);

            return this.dialogsList;
          })
        ),
      this.notifications
        .events
        .pipe(
          filter(ev => {
            return ev.event === 'resolved' && ev.notification instanceof DialogUiNotification;
          }),
          map(ev => {
            pull(this.dialogsList, ev.notification);

            return this.dialogsList;
          })
        )
    )
      .pipe(
      tap(() => {
        this.overlayVisible = this.dialogsList.length > 0;
        this.cdr.detectChanges();
      })
    );
  }


type => ID


() => [StudentType]


// this file is the type of lesson item
@ObjectType('Lesson') // decorate with object decorator
export class LessonType {
  @Field(type => ID)
  id: string;

  @Field()
  name: string;

  @Field()
  startDate: string;

  @Field()
  endDate: string;

  @Field(() => [StudentType])
  students: string[];
}


export function addValue<T extends StimulusController>(controller: T, valueKey: string, valueType: ValueType) {
  const constructor = controller.constructor as typeof StimulusController;

  if (!Object.prototype.hasOwnProperty.call(constructor, 'values')) {
    constructor.values = {};
  }

  constructor.values[valueKey] = valueType;
}


export class SignUpController implements Controller {
  constructor (
    private readonly addAccount: AddAccount,
    private readonly validation: Validation,
    private readonly authentication: Authentication
  ) {}

  async handle (httpRequest: HttpRequest): Promise<HttpResponse> {
    try {
      const error = this.validation.validate(httpRequest.body)
      if (error) {
        return badRequest(error)
      }

      const { name, email, password } = httpRequest.body
      const account = await this.addAccount.add({
        name,
        email,
        password
      })

      if (!account) {
        return forbidden(new EmailInUseError())
      }

      const accessToken = await this.authentication.auth({ email, password })

      return ok({ accessToken })
    } catch (error) {
      return serverError(error)
    }
  }
}


async handle (httpRequest: HttpRequest): Promise<HttpResponse> {
    try {
      const error = this.validation.validate(httpRequest.body)
      if (error) {
        return badRequest(error)
      }

      const { name, email, password } = httpRequest.body
      const account = await this.addAccount.add({
        name,
        email,
        password
      })

      if (!account) {
        return forbidden(new EmailInUseError())
      }

      const accessToken = await this.authentication.auth({ email, password })

      return ok({ accessToken })
    } catch (error) {
      return serverError(error)
    }
  }


function LinearProgressWithLabel(props: LinearProgressProps & { value: number }) {
  return (
    <Box sx={{ display: 'flex', alignItems: 'center' }}


export default function LinearWithValueLabel() {
  const [progress, setProgress] = React.useState(10);

  React.useEffect(() => {
    const timer = setInterval(() => {
      setProgress((prevProgress) => (prevProgress >= 100 ? 10 : prevProgress + 10));
    }, 800);
    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <Box sx={{ width: '100%' }}


() => {
    const timer = setInterval(() => {
      setProgress((prevProgress) => (prevProgress >= 100 ? 10 : prevProgress + 10));
    }, 800);
    return () => {
      clearInterval(timer);
    };
  }


() => {
      setProgress((prevProgress) => (prevProgress >= 100 ? 10 : prevProgress + 10));
    }


(prevProgress) => (prevProgress >= 100 ? 10 : prevProgress + 10)


() => {
      clearInterval(timer);
    }


export default class ResponseSerializer {
  private readonly headersSerializer: HeadersSerializer;
  constructor() {}

  async serialize(res: Response): Promise<SerializedResponse> {
    return {
      body: JSON.stringify(await res.json()),
      ok: res.ok,
      redirected: res.redirected,
      status: res.status,
      statusText: res.statusText,
      type: res.type,
      headers: this.headersSerializer.serialize(res.headers),
      url: res.url,
    };
  }
  deserialize(res: SerializedResponse): Response {
    return new Response(res.body, {
      headers: this.headersSerializer.deserialize(res.headers),
      status: res.status,
      statusText: res.statusText,
    });
  }
}


export interface SerializedResponse {
  body: string;
  ok: boolean;
  redirected: boolean;
  status: number;
  statusText: string;
  type: ResponseType;
  headers: SerializedHeaders;
  url: string;
}


async serialize(res: Response): Promise<SerializedResponse> {
    return {
      body: JSON.stringify(await res.json()),
      ok: res.ok,
      redirected: res.redirected,
      status: res.status,
      statusText: res.statusText,
      type: res.type,
      headers: this.headersSerializer.serialize(res.headers),
      url: res.url,
    };
  }


deserialize(res: SerializedResponse): Response {
    return new Response(res.body, {
      headers: this.headersSerializer.deserialize(res.headers),
      status: res.status,
      statusText: res.statusText,
    });
  }


(err: any, caught: Observable<Response>) => {
        this.errorMsg = 'Failed to login';

        return Observable.throw(err);
      }


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

  public user = new User('','');
  public errorMsg = '';

  constructor(private _service: AuthenticationService) {}

  login() {
    this._service.login(this.user.userMail, this.user.password)
      .catch((err: any, caught: Observable<Response>) => {
        this.errorMsg = 'Failed to login';

        return Observable.throw(err);
      })
      .subscribe();
  }

  ngOnInit(): void {
  }

}


login() {
    this._service.login(this.user.userMail, this.user.password)
      .catch((err: any, caught: Observable<Response>) => {
        this.errorMsg = 'Failed to login';

        return Observable.throw(err);
      })
      .subscribe();
  }


(
  filterQuery: string | ESTermQuery | undefined,
  anomaliesFilterQuery: object = {},
  siemJobs: SiemJob[] = [],
  anomalyScore: number,
  flowTarget?: FlowTarget,
  ip?: string
): string => {
  const siemJobIds = siemJobs
    .filter(job => job.isInstalled)
    .map(job => job.id)
    .map(jobId => ({
      match_phrase: {
        job_id: jobId,
      },
    }));

  const filterQueryString = createFilter(filterQuery);
  const filterQueryObject = filterQueryString ? JSON.parse(filterQueryString) : {};
  const mergedFilterQuery = deepmerge.all([
    filterQueryObject,
    anomaliesFilterQuery,
    {
      bool: {
        filter: [
          {
            bool: {
              should: siemJobIds,
              minimum_should_match: 1,
            },
          },
          {
            match_phrase: {
              result_type: 'record',
            },
          },
          flowTarget &&
            ip && {
              match_phrase: {
                [`${flowTarget}.ip`]: ip,
              },
            },
          {
            range: {
              record_score: {
                gte: anomalyScore,
              },
            },
          },
        ],
      },
    },
  ]);

  return JSON.stringify(mergedFilterQuery);
}


job => job.isInstalled


job => job.id


jobId => ({
      match_phrase: {
        job_id: jobId,
      },
    })


(state, action: PayloadAction<ChatMessage>) => {
      state.messages.push(action.payload);
    }


/**
 * Sets the env this api should serve
 * @param {EnvType} env The envType to use
 */
export function setenv(env: EnvType) {
  envType = env
}


/**
 * returns the appropriate directions object, based on the environment
 * @return {any}
 */
export function getDirectionsObject() {
  switch (envType) {
    case EnvType.VN:
      return VNDirection
    case EnvType.Moore:
      return Direction
  }
}


/**
 * returns a pseudo random direction from the direction object, excluding some directions
 * @param {number} seed The psaudo random seed
 * @param {TDirection} current directions to exclude
 * @return {TDirection} new direction
 */
export function randomDirection(seed: number, ...current: TDirection[]): TDirection {
  let directions = Object.keys(getDirectionsObject())
  if (current.length) {
    directions = directions.filter(k => current.indexOf(k as TDirection) === -1)
  }

  let directionsCount = directions.length
  let index = seed % directionsCount
  return directions[index] as TDirection
}


/**
 * returns the next direction in the direction list
 * @param {TDirection} current the current direction
 * @return {TDirection} next direction
 */
export function nextDirection(current: TDirection): TDirection {
  let directions = Object.keys(getDirectionsObject())
  let index = directions.indexOf(current)
  let nextIndex = (index + 1) % directions.length
  return directions[nextIndex] as TDirection
}


k => current.indexOf(k as TDirection) === -1


export enum EnvType {
  VN,
  Moore,
}


export type TDirection = keyof typeof Direction


/**
 * Checks whether we're in the Node.js or Browser environment
 *
 * @returns Answer to given question
 */
export function isNodeEnv(): boolean {
  return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]';
}


/**
 * Requires a module which is protected against bundler minification.
 *
 * @param request The module path to resolve
 */
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any
export function dynamicRequire(mod: any, request: string): any {
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
  return mod.require(request);
}


async (req:any, res) => {
  try {
    const ordersFound = await order.findByOwner(req.user.username);
    res.status(200).json(ordersFound);
  }
  catch(err) {
    const error = verifyIfIsAnInternalException(err);
    res.status(error.status).json(error.message);
  }
}


/** URL query params that adjust scope / purpose of the page */
export enum QUERY_PROPERTIES {
  /** For defining a contextual application group (ie, add new workload into this application group) */
  APPLICATION = 'application',
  /** For defining a contextual source of the redirect (ie, connect a new workload from this contextual source) */
  CONTEXT_SOURCE = 'contextSource',
  CONTEXT_ACTION = 'action',
}


export enum CONNECTOR_INCONTEXT_ACTIONS {
  /** connects to action for resources */
  connectsTo = 'connectsTo',
}


@Component({
  selector: 'ex-clear',
  templateUrl: './clear.component.html',
  styleUrls: ['./clear.component.scss']
})
export class ExClearComponent implements OnInit {
  model = 'clear data';
  constructor() {}

  ngOnInit() {}
}


@Component({
    templateUrl: './radio-button-demo.component.html',
    styleUrls: ['./radio-button-demo.component.scss']
})
export class RadioButtonDemoComponent
{
    formModel: FormGroup;
    model1: string = 'blue';
    model2: string = 'red';
    model3: string;

    constructor()
    {
        this.formModel = new FormGroup({});
        this.formModel.registerControl('color2', new FormControl(this.model2));

    }

    onChange(event: any): void
    {
        this.model3 = event;
    }
}


onChange(event: any): void
    {
        this.model3 = event;
    }


props => {
  const {
    platform,
    maximize,
    minimize,
    restore,
    enterFullscreen,
    leaveFullscreen,
    isLoading,
    close,
    closeDuringLoad,
  } = props

  const [ isMaximized, setIsMaximized ] = React.useState (win .isMaximized ())
  const [ isFullScreen, setIsFullScreen ] = React.useState (win .isFullScreen ())
  const [ isFocused, setIsFocused ] = React.useState (win .isFocused ())

  const handleMaximized = React.useCallback (
    () => setIsMaximized (remote.getCurrentWindow () .isMaximized ()),
    []
  )

  const handleFullScreen = React.useCallback (
    () => setIsFullScreen (remote.getCurrentWindow () .isFullScreen ()),
    []
  )

  const handleFocused = React.useCallback (
    () => setIsFocused (remote.getCurrentWindow () .isFocused ()),
    []
  )

  React.useEffect (
    () => {
      remote.getCurrentWindow ()
        .addListener ("maximize", handleMaximized)
        .addListener ("unmaximize", handleMaximized)
        .addListener ("enter-full-screen", handleFullScreen)
        .addListener ("leave-full-screen", handleFullScreen)
        .addListener ("blur", handleFocused)
        .addListener ("focus", handleFocused)

      return () => {
        remote.getCurrentWindow ()
          .removeListener ("maximize", handleMaximized)
          .removeListener ("unmaximize", handleMaximized)
          .removeListener ("enter-full-screen", handleFullScreen)
          .removeListener ("leave-full-screen", handleFullScreen)
          .removeListener ("blur", handleFocused)
          .removeListener ("focus", handleFocused)
      }
    },
    [ handleMaximized, handleFullScreen, handleFocused ]
  )

  const handleClose = React.useCallback (
    () => {
      if (isLoading === true) {
        closeDuringLoad ()
      }
      else {
        close ()
      }
    },
    [ isLoading, close, closeDuringLoad ]
  )

  if (platform === "darwin") {
    return (
      <TitleBarWrapper isFocused={isFocused}>
        <div className="macos-hover-area">
          <TitleBarButton icon="" onClick={handleClose} className="close" />
          <TitleBarButton icon="" onClick={minimize} className="minimize" />
          {
            isFullScreen
            ? <TitleBarButton icon="" onClick={leaveFullscreen} className="fullscreen" />


() => setIsMaximized (remote.getCurrentWindow () .isMaximized ())


() => setIsFullScreen (remote.getCurrentWindow () .isFullScreen ())


() => setIsFocused (remote.getCurrentWindow () .isFocused ())


() => {
      remote.getCurrentWindow ()
        .addListener ("maximize", handleMaximized)
        .addListener ("unmaximize", handleMaximized)
        .addListener ("enter-full-screen", handleFullScreen)
        .addListener ("leave-full-screen", handleFullScreen)
        .addListener ("blur", handleFocused)
        .addListener ("focus", handleFocused)

      return () => {
        remote.getCurrentWindow ()
          .removeListener ("maximize", handleMaximized)
          .removeListener ("unmaximize", handleMaximized)
          .removeListener ("enter-full-screen", handleFullScreen)
          .removeListener ("leave-full-screen", handleFullScreen)
          .removeListener ("blur", handleFocused)
          .removeListener ("focus", handleFocused)
      }
    }


() => {
        remote.getCurrentWindow ()
          .removeListener ("maximize", handleMaximized)
          .removeListener ("unmaximize", handleMaximized)
          .removeListener ("enter-full-screen", handleFullScreen)
          .removeListener ("leave-full-screen", handleFullScreen)
          .removeListener ("blur", handleFocused)
          .removeListener ("focus", handleFocused)
      }


() => {
      if (isLoading === true) {
        closeDuringLoad ()
      }
      else {
        close ()
      }
    }


interface Props {
  platform: string
  isLoading?: boolean
  minimize (): void
  maximize (): void
  restore (): void
  close (): void
  closeDuringLoad (): void
  enterFullscreen (): void
  leaveFullscreen (): void
}


isFullScreen
            ? <TitleBarButton icon="" onClick={leaveFullscreen} className="fullscreen"


/**
 * Check if a given object implements the FalconxStream interface.
 */
export function instanceOfFalconxStream(value: object): boolean {
    let isInstance = true;

    return isInstance;
}


export function FalconxStreamFromJSON(json: any): FalconxStream {
    return FalconxStreamFromJSONTyped(json, false);
}


export function FalconxStreamFromJSONTyped(json: any, ignoreDiscriminator: boolean): FalconxStream {
    if (json === undefined || json === null) {
        return json;
    }
    return {
        executed: !exists(json, "executed") ? undefined : json["executed"],
        fileName: !exists(json, "file_name") ? undefined : json["file_name"],
        humanKeywords: !exists(json, "human_keywords") ? undefined : json["human_keywords"],
        instructionsArtifactId: !exists(json, "instructions_artifact_id") ? undefined : json["instructions_artifact_id"],
        matchedSignatures: !exists(json, "matched_signatures") ? undefined : (json["matched_signatures"] as Array<any>).map(FalconxMatchedSignatureFromJSON),
        uid: !exists(json, "uid") ? undefined : json["uid"],
    };
}


export function FalconxStreamToJSON(value?: FalconxStream | null): any {
    if (value === undefined) {
        return undefined;
    }
    if (value === null) {
        return null;
    }
    return {
        executed: value.executed,
        file_name: value.fileName,
        human_keywords: value.humanKeywords,
        instructions_artifact_id: value.instructionsArtifactId,
        matched_signatures: value.matchedSignatures === undefined ? undefined : (value.matchedSignatures as Array<any>).map(FalconxMatchedSignatureToJSON),
        uid: value.uid,
    };
}