fillOrderNoThrow(
    order: Contract__fillOrderNoThrowInputOrderStruct,
    takerAssetFillAmount: BigInt,
    signature: Bytes
  ): Contract__fillOrderNoThrowResultFillResultsStruct {
    let result = super.call("fillOrderNoThrow", [
      EthereumValue.fromTuple(order),
      EthereumValue.fromUnsignedBigInt(takerAssetFillAmount),
      EthereumValue.fromBytes(signature)
    ]);

    return result[0].toTuple() as Contract__fillOrderNoThrowResultFillResultsStruct;
  }


try_fillOrderNoThrow(
    order: Contract__fillOrderNoThrowInputOrderStruct,
    takerAssetFillAmount: BigInt,
    signature: Bytes
  ): CallResult<Contract__fillOrderNoThrowResultFillResultsStruct> {
    let result = super.tryCall("fillOrderNoThrow", [
      EthereumValue.fromTuple(order),
      EthereumValue.fromUnsignedBigInt(takerAssetFillAmount),
      EthereumValue.fromBytes(signature)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(
      value[0].toTuple() as Contract__fillOrderNoThrowResultFillResultsStruct
    );
  }


assetProxies(param0: Bytes): Address {
    let result = super.call("assetProxies", [
      EthereumValue.fromFixedBytes(param0)
    ]);

    return result[0].toAddress();
  }


try_assetProxies(param0: Bytes): CallResult<Address> {
    let result = super.tryCall("assetProxies", [
      EthereumValue.fromFixedBytes(param0)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(value[0].toAddress());
  }


batchFillOrKillOrders(
    orders: Array<Contract__batchFillOrKillOrdersInputOrdersStruct>,
    takerAssetFillAmounts: Array<BigInt>,
    signatures: Array<Bytes>
  ): Contract__batchFillOrKillOrdersResultTotalFillResultsStruct {
    let result = super.call("batchFillOrKillOrders", [
      EthereumValue.fromTupleArray(orders),
      EthereumValue.fromUnsignedBigIntArray(takerAssetFillAmounts),
      EthereumValue.fromBytesArray(signatures)
    ]);

    return result[0].toTuple() as Contract__batchFillOrKillOrdersResultTotalFillResultsStruct;
  }


try_batchFillOrKillOrders(
    orders: Array<Contract__batchFillOrKillOrdersInputOrdersStruct>,
    takerAssetFillAmounts: Array<BigInt>,
    signatures: Array<Bytes>
  ): CallResult<Contract__batchFillOrKillOrdersResultTotalFillResultsStruct> {
    let result = super.tryCall("batchFillOrKillOrders", [
      EthereumValue.fromTupleArray(orders),
      EthereumValue.fromUnsignedBigIntArray(takerAssetFillAmounts),
      EthereumValue.fromBytesArray(signatures)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(
      value[0].toTuple() as Contract__batchFillOrKillOrdersResultTotalFillResultsStruct
    );
  }


batchFillOrdersNoThrow(
    orders: Array<Contract__batchFillOrdersNoThrowInputOrdersStruct>,
    takerAssetFillAmounts: Array<BigInt>,
    signatures: Array<Bytes>
  ): Contract__batchFillOrdersNoThrowResultTotalFillResultsStruct {
    let result = super.call("batchFillOrdersNoThrow", [
      EthereumValue.fromTupleArray(orders),
      EthereumValue.fromUnsignedBigIntArray(takerAssetFillAmounts),
      EthereumValue.fromBytesArray(signatures)
    ]);

    return result[0].toTuple() as Contract__batchFillOrdersNoThrowResultTotalFillResultsStruct;
  }


try_batchFillOrdersNoThrow(
    orders: Array<Contract__batchFillOrdersNoThrowInputOrdersStruct>,
    takerAssetFillAmounts: Array<BigInt>,
    signatures: Array<Bytes>
  ): CallResult<Contract__batchFillOrdersNoThrowResultTotalFillResultsStruct> {
    let result = super.tryCall("batchFillOrdersNoThrow", [
      EthereumValue.fromTupleArray(orders),
      EthereumValue.fromUnsignedBigIntArray(takerAssetFillAmounts),
      EthereumValue.fromBytesArray(signatures)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(
      value[0].toTuple() as Contract__batchFillOrdersNoThrowResultTotalFillResultsStruct
    );
  }


getAssetProxy(assetProxyId: Bytes): Address {
    let result = super.call("getAssetProxy", [
      EthereumValue.fromFixedBytes(assetProxyId)
    ]);

    return result[0].toAddress();
  }


try_getAssetProxy(assetProxyId: Bytes): CallResult<Address> {
    let result = super.tryCall("getAssetProxy", [
      EthereumValue.fromFixedBytes(assetProxyId)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(value[0].toAddress());
  }


transactions(param0: Bytes): boolean {
    let result = super.call("transactions", [
      EthereumValue.fromFixedBytes(param0)
    ]);

    return result[0].toBoolean();
  }


try_transactions(param0: Bytes): CallResult<boolean> {
    let result = super.tryCall("transactions", [
      EthereumValue.fromFixedBytes(param0)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(value[0].toBoolean());
  }


fillOrKillOrder(
    order: Contract__fillOrKillOrderInputOrderStruct,
    takerAssetFillAmount: BigInt,
    signature: Bytes
  ): Contract__fillOrKillOrderResultFillResultsStruct {
    let result = super.call("fillOrKillOrder", [
      EthereumValue.fromTuple(order),
      EthereumValue.fromUnsignedBigInt(takerAssetFillAmount),
      EthereumValue.fromBytes(signature)
    ]);

    return result[0].toTuple() as Contract__fillOrKillOrderResultFillResultsStruct;
  }


try_fillOrKillOrder(
    order: Contract__fillOrKillOrderInputOrderStruct,
    takerAssetFillAmount: BigInt,
    signature: Bytes
  ): CallResult<Contract__fillOrKillOrderResultFillResultsStruct> {
    let result = super.tryCall("fillOrKillOrder", [
      EthereumValue.fromTuple(order),
      EthereumValue.fromUnsignedBigInt(takerAssetFillAmount),
      EthereumValue.fromBytes(signature)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(
      value[0].toTuple() as Contract__fillOrKillOrderResultFillResultsStruct
    );
  }


allowedValidators(param0: Address, param1: Address): boolean {
    let result = super.call("allowedValidators", [
      EthereumValue.fromAddress(param0),
      EthereumValue.fromAddress(param1)
    ]);

    return result[0].toBoolean();
  }


try_allowedValidators(param0: Address, param1: Address): CallResult<boolean> {
    let result = super.tryCall("allowedValidators", [
      EthereumValue.fromAddress(param0),
      EthereumValue.fromAddress(param1)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(value[0].toBoolean());
  }


marketSellOrders(
    orders: Array<Contract__marketSellOrdersInputOrdersStruct>,
    takerAssetFillAmount: BigInt,
    signatures: Array<Bytes>
  ): Contract__marketSellOrdersResultTotalFillResultsStruct {
    let result = super.call("marketSellOrders", [
      EthereumValue.fromTupleArray(orders),
      EthereumValue.fromUnsignedBigInt(takerAssetFillAmount),
      EthereumValue.fromBytesArray(signatures)
    ]);

    return result[0].toTuple() as Contract__marketSellOrdersResultTotalFillResultsStruct;
  }


try_marketSellOrders(
    orders: Array<Contract__marketSellOrdersInputOrdersStruct>,
    takerAssetFillAmount: BigInt,
    signatures: Array<Bytes>
  ): CallResult<Contract__marketSellOrdersResultTotalFillResultsStruct> {
    let result = super.tryCall("marketSellOrders", [
      EthereumValue.fromTupleArray(orders),
      EthereumValue.fromUnsignedBigInt(takerAssetFillAmount),
      EthereumValue.fromBytesArray(signatures)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(
      value[0].toTuple() as Contract__marketSellOrdersResultTotalFillResultsStruct
    );
  }


getOrdersInfo(
    orders: Array<Contract__getOrdersInfoInputOrdersStruct>
  ): Array<Contract__getOrdersInfoResultValue0Struct> {
    let result = super.call("getOrdersInfo", [
      EthereumValue.fromTupleArray(orders)
    ]);

    return result[0].toTupleArray<Contract__getOrdersInfoResultValue0Struct>();
  }


try_getOrdersInfo(
    orders: Array<Contract__getOrdersInfoInputOrdersStruct>
  ): CallResult<Array<Contract__getOrdersInfoResultValue0Struct>> {
    let result = super.tryCall("getOrdersInfo", [
      EthereumValue.fromTupleArray(orders)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(
      value[0].toTupleArray<Contract__getOrdersInfoResultValue0Struct>()
    );
  }


preSigned(param0: Bytes, param1: Address): boolean {
    let result = super.call("preSigned", [
      EthereumValue.fromFixedBytes(param0),
      EthereumValue.fromAddress(param1)
    ]);

    return result[0].toBoolean();
  }


try_preSigned(param0: Bytes, param1: Address): CallResult<boolean> {
    let result = super.tryCall("preSigned", [
      EthereumValue.fromFixedBytes(param0),
      EthereumValue.fromAddress(param1)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(value[0].toBoolean());
  }


owner(): Address {
    let result = super.call("owner", []);

    return result[0].toAddress();
  }


try_owner(): CallResult<Address> {
    let result = super.tryCall("owner", []);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(value[0].toAddress());
  }


isValidSignature(
    hash: Bytes,
    signerAddress: Address,
    signature: Bytes
  ): boolean {
    let result = super.call("isValidSignature", [
      EthereumValue.fromFixedBytes(hash),
      EthereumValue.fromAddress(signerAddress),
      EthereumValue.fromBytes(signature)
    ]);

    return result[0].toBoolean();
  }


try_isValidSignature(
    hash: Bytes,
    signerAddress: Address,
    signature: Bytes
  ): CallResult<boolean> {
    let result = super.tryCall("isValidSignature", [
      EthereumValue.fromFixedBytes(hash),
      EthereumValue.fromAddress(signerAddress),
      EthereumValue.fromBytes(signature)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(value[0].toBoolean());
  }


marketBuyOrdersNoThrow(
    orders: Array<Contract__marketBuyOrdersNoThrowInputOrdersStruct>,
    makerAssetFillAmount: BigInt,
    signatures: Array<Bytes>
  ): Contract__marketBuyOrdersNoThrowResultTotalFillResultsStruct {
    let result = super.call("marketBuyOrdersNoThrow", [
      EthereumValue.fromTupleArray(orders),
      EthereumValue.fromUnsignedBigInt(makerAssetFillAmount),
      EthereumValue.fromBytesArray(signatures)
    ]);

    return result[0].toTuple() as Contract__marketBuyOrdersNoThrowResultTotalFillResultsStruct;
  }


try_marketBuyOrdersNoThrow(
    orders: Array<Contract__marketBuyOrdersNoThrowInputOrdersStruct>,
    makerAssetFillAmount: BigInt,
    signatures: Array<Bytes>
  ): CallResult<Contract__marketBuyOrdersNoThrowResultTotalFillResultsStruct> {
    let result = super.tryCall("marketBuyOrdersNoThrow", [
      EthereumValue.fromTupleArray(orders),
      EthereumValue.fromUnsignedBigInt(makerAssetFillAmount),
      EthereumValue.fromBytesArray(signatures)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(
      value[0].toTuple() as Contract__marketBuyOrdersNoThrowResultTotalFillResultsStruct
    );
  }


fillOrder(
    order: Contract__fillOrderInputOrderStruct,
    takerAssetFillAmount: BigInt,
    signature: Bytes
  ): Contract__fillOrderResultFillResultsStruct {
    let result = super.call("fillOrder", [
      EthereumValue.fromTuple(order),
      EthereumValue.fromUnsignedBigInt(takerAssetFillAmount),
      EthereumValue.fromBytes(signature)
    ]);

    return result[0].toTuple() as Contract__fillOrderResultFillResultsStruct;
  }


try_fillOrder(
    order: Contract__fillOrderInputOrderStruct,
    takerAssetFillAmount: BigInt,
    signature: Bytes
  ): CallResult<Contract__fillOrderResultFillResultsStruct> {
    let result = super.tryCall("fillOrder", [
      EthereumValue.fromTuple(order),
      EthereumValue.fromUnsignedBigInt(takerAssetFillAmount),
      EthereumValue.fromBytes(signature)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(
      value[0].toTuple() as Contract__fillOrderResultFillResultsStruct
    );
  }


getOrderInfo(
    order: Contract__getOrderInfoInputOrderStruct
  ): Contract__getOrderInfoResultOrderInfoStruct {
    let result = super.call("getOrderInfo", [EthereumValue.fromTuple(order)]);

    return result[0].toTuple() as Contract__getOrderInfoResultOrderInfoStruct;
  }


try_getOrderInfo(
    order: Contract__getOrderInfoInputOrderStruct
  ): CallResult<Contract__getOrderInfoResultOrderInfoStruct> {
    let result = super.tryCall("getOrderInfo", [
      EthereumValue.fromTuple(order)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(
      value[0].toTuple() as Contract__getOrderInfoResultOrderInfoStruct
    );
  }


orderEpoch(param0: Address, param1: Address): BigInt {
    let result = super.call("orderEpoch", [
      EthereumValue.fromAddress(param0),
      EthereumValue.fromAddress(param1)
    ]);

    return result[0].toBigInt();
  }


try_orderEpoch(param0: Address, param1: Address): CallResult<BigInt> {
    let result = super.tryCall("orderEpoch", [
      EthereumValue.fromAddress(param0),
      EthereumValue.fromAddress(param1)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(value[0].toBigInt());
  }


ZRX_ASSET_DATA(): Bytes {
    let result = super.call("ZRX_ASSET_DATA", []);

    return result[0].toBytes();
  }


try_ZRX_ASSET_DATA(): CallResult<Bytes> {
    let result = super.tryCall("ZRX_ASSET_DATA", []);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(value[0].toBytes());
  }


marketSellOrdersNoThrow(
    orders: Array<Contract__marketSellOrdersNoThrowInputOrdersStruct>,
    takerAssetFillAmount: BigInt,
    signatures: Array<Bytes>
  ): Contract__marketSellOrdersNoThrowResultTotalFillResultsStruct {
    let result = super.call("marketSellOrdersNoThrow", [
      EthereumValue.fromTupleArray(orders),
      EthereumValue.fromUnsignedBigInt(takerAssetFillAmount),
      EthereumValue.fromBytesArray(signatures)
    ]);

    return result[0].toTuple() as Contract__marketSellOrdersNoThrowResultTotalFillResultsStruct;
  }


try_marketSellOrdersNoThrow(
    orders: Array<Contract__marketSellOrdersNoThrowInputOrdersStruct>,
    takerAssetFillAmount: BigInt,
    signatures: Array<Bytes>
  ): CallResult<Contract__marketSellOrdersNoThrowResultTotalFillResultsStruct> {
    let result = super.tryCall("marketSellOrdersNoThrow", [
      EthereumValue.fromTupleArray(orders),
      EthereumValue.fromUnsignedBigInt(takerAssetFillAmount),
      EthereumValue.fromBytesArray(signatures)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(
      value[0].toTuple() as Contract__marketSellOrdersNoThrowResultTotalFillResultsStruct
    );
  }


EIP712_DOMAIN_HASH(): Bytes {
    let result = super.call("EIP712_DOMAIN_HASH", []);

    return result[0].toBytes();
  }


try_EIP712_DOMAIN_HASH(): CallResult<Bytes> {
    let result = super.tryCall("EIP712_DOMAIN_HASH", []);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(value[0].toBytes());
  }


marketBuyOrders(
    orders: Array<Contract__marketBuyOrdersInputOrdersStruct>,
    makerAssetFillAmount: BigInt,
    signatures: Array<Bytes>
  ): Contract__marketBuyOrdersResultTotalFillResultsStruct {
    let result = super.call("marketBuyOrders", [
      EthereumValue.fromTupleArray(orders),
      EthereumValue.fromUnsignedBigInt(makerAssetFillAmount),
      EthereumValue.fromBytesArray(signatures)
    ]);

    return result[0].toTuple() as Contract__marketBuyOrdersResultTotalFillResultsStruct;
  }


try_marketBuyOrders(
    orders: Array<Contract__marketBuyOrdersInputOrdersStruct>,
    makerAssetFillAmount: BigInt,
    signatures: Array<Bytes>
  ): CallResult<Contract__marketBuyOrdersResultTotalFillResultsStruct> {
    let result = super.tryCall("marketBuyOrders", [
      EthereumValue.fromTupleArray(orders),
      EthereumValue.fromUnsignedBigInt(makerAssetFillAmount),
      EthereumValue.fromBytesArray(signatures)
    ]);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(
      value[0].toTuple() as Contract__marketBuyOrdersResultTotalFillResultsStruct
    );
  }


currentContextAddress(): Address {
    let result = super.call("currentContextAddress", []);

    return result[0].toAddress();
  }


try_currentContextAddress(): CallResult<Address> {
    let result = super.tryCall("currentContextAddress", []);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(value[0].toAddress());
  }


VERSION(): string {
    let result = super.call("VERSION", []);

    return result[0].toString();
  }


try_VERSION(): CallResult<string> {
    let result = super.tryCall("VERSION", []);
    if (result.reverted) {
      return new CallResult();
    }
    let value = result.value;
    return CallResult.fromValue(value[0].toString());
  }


({ onClose, content, children, ...props }) => {
  const ref = useRef(document.createElement('div'));

  useEffect(() => {
    document.body.appendChild(ref.current);
    return () => {
      document.body.removeChild(ref.current);
    };
  }, []);

  return createPortal(
    <DialogOuter fullScreen={!content}


() => {
    document.body.appendChild(ref.current);
    return () => {
      document.body.removeChild(ref.current);
    };
  }


() => {
      document.body.removeChild(ref.current);
    }


export interface IDialogContent {
  title: React.ReactNode;
  body: React.ReactNode;
  cancel?: string;
  confirm?: string;
  onCancel?(): void;
  onConfirm?(): void;
}


interface IDialogPropsBase extends Omit<BoxProps, 'content'> {
  onClose(): void;
}


interface IDialogPropsWithChildren extends IDialogPropsBase {
  children: ReactNode;
  content?: undefined;
}


interface IDialogPropsWithContent extends IDialogPropsBase {
  content: IDialogContent;
  children?: undefined;
}


export type IDialogProps = IDialogPropsWithChildren | IDialogPropsWithContent;


export type TDialog = FC<IDialogProps> & {
  Submit: typeof DialogSubmit;
  Cancel: typeof DialogCancel;
  Title: typeof DialogTitle;
  Subtitle: typeof DialogSubtitle;
  Header: typeof DialogHeader;
  Body: typeof DialogBody;
  Footer: typeof DialogFooter;
};


() =>
  combineReducers<ReducersMapObject<RootReducerState, any>>({
    locale: localeReducer
  })


(): Middleware[] => {
  const middlewares = [thunk, logger]
  isProd && middlewares.pop()

  return middlewares
}


(middlewares: Middleware[]) =>
  applyMiddleware(...middlewares)


() => {
  const middlewares = [
    composeWithDevTools,
    applyMiddlewares,
    getBaseMiddlewares
  ]
  isProd && middlewares.shift()
  return middlewares
}


(initialState?: RootReducerState) => {
  const rootReducer = createRootReducer()
  const persistedReducer = persistReducer(persistConfig, rootReducer)
  const store = createStore(persistedReducer, initialState, enhancer())
  const persistor = persistStore(store)

  return { store, persistor }
}


// Formatting DateTime by pattern
@Pipe({
  name: "ynDateFormatter",
  pure: true
})
export class DateFormatterPipe {
  transform(date: any, pattern: string): string {
    let mask: Mask = new Mask(this.intl);
    mask.pattern = pattern;

    return DateParserFormatter.format(date, mask);
  }

  constructor(private intl: InternationalizationService) {
    //
  }
}


transform(date: any, pattern: string): string {
    let mask: Mask = new Mask(this.intl);
    mask.pattern = pattern;

    return DateParserFormatter.format(date, mask);
  }


(
    sequelize: Sequelize.Sequelize,
    DataTypes: Sequelize.DataTypes
) => {
    const AddressLog = sequelize.define(
        "AddressLog",
        {
            id: {
                allowNull: false,
                autoIncrement: true,
                primaryKey: true,
                type: DataTypes.BIGINT
            },
            transactionHash: {
                allowNull: false,
                type: DataTypes.STRING,
                onDelete: "CASCADE",
                validate: {
                    is: ["^[a-f0-9]{64}$"]
                },
                references: {
                    model: "Transactions",
                    key: "hash"
                }
            },
            transactionType: {
                allowNull: false,
                type: DataTypes.STRING
            },
            transactionTracker: {
                type: DataTypes.STRING,
                validate: {
                    is: ["^[a-f0-9]{64}$"]
                }
            },
            blockNumber: {
                type: DataTypes.INTEGER
            },
            transactionIndex: {
                type: DataTypes.INTEGER
            },
            success: {
                type: DataTypes.BOOLEAN
            },
            isPending: {
                allowNull: false,
                type: DataTypes.BOOLEAN
            },
            address: {
                allowNull: false,
                type: DataTypes.STRING
            },
            type: {
                allowNull: false,
                type: DataTypes.STRING
            },
            createdAt: {
                allowNull: false,
                type: DataTypes.DATE
            },
            updatedAt: {
                allowNull: false,
                type: DataTypes.DATE
            }
        },
        {}
    );
    AddressLog.associate = () => {
        // associations can be defined here
    };
    return AddressLog;
}


() => {
        // associations can be defined here
    }


export interface AddressLogAttribute {
    id?: number;
    transactionHash: string;
    transactionTracker?: string | null;
    transactionType: string | null;
    blockNumber?: number | null;
    transactionIndex?: number | null;
    success?: boolean | null;
    isPending: boolean;
    address: string;
    type: AddressLogType;
}


export type AddressLogType =
    | "TransactionSigner"
    | "TransactionApprover"
    | "AssetOwner"
    | "Approver"
    | "Registrar";


export type AddressLogInstance = Sequelize.Instance<AddressLogAttribute>;


export class AgentTransportDto {
    id: number;
    idagent: number;
    idtransport: number;
}


function maxDepth(root: MyNode | null): number {
  if (root === null) return 0;
  if (root.children.length === 0) return 1;
  return (
    1 +
    Math.max(
      ...root.children.map((child) => maxDepth(child))
    )
  );
}


(child) => maxDepth(child)


class MyNode {
  val: number;
  children: MyNode[];
  constructor(val?: number, children?: MyNode[]) {
    this.val = val === undefined ? 0 : val;
    this.children = children === undefined ? [] : children;
  }
}


declare function configure(config?: TranslatorConfig): Translator;


declare function addTranslation(key: string, translations: string[]): void;


declare function addTranslations(translations: Translations): void;


declare function addLocaleData(data: LocaleData): void;


declare function t(input: string, ...args: unknown[]): string;


declare function tn(key: string, ...args: unknown[]): string;


/** Return path if accessible, blank if not accessible */
export function pathAccessible(path: string): Observable<string> {
  return defer(() => isPathAccessible(path)).pipe(
    map(exists => exists ? normalize(path) : ''),
  )
}


// support relative file ('./foo')
export function isPathAccessible(path: string): Promise<boolean> {
  return path
    ? new Promise(resolve => access(path, err => resolve(err ? false : true)))
    : Promise.resolve(false)
}


/**
 * Generate random integer
 *
 * @see https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Math/random
 */
export function genRandomInt(max: number): number {
  return Math.floor(Math.random() * Math.floor(max))
}


export async function cpGlobalConfigsToPkgs(
  baseDir: string,
  configPaths: string[],
  pkgBase: string,
): Promise<string[]> {

  const pkgs = await readDirAsync(pkgBase)
  const ret: string[] = []

  for (const pkg of pkgs) {
    for (const path of configPaths) {
      try {
        const dst = `${pkg}/${path}`
        const dstDir = dirname(join(pkgBase, dst))
        if ( ! await isPathAccessible(dstDir)) {
          await mkdirAsync(dstDir)
        }
        await copyFileAsync(
          join(baseDir, path),
          join(pkgBase, dst),
        )
        ret.push(dst)
      }
      catch (ex) {
        console.log((ex as Error).message)
      }
    }
  }

  return ret
}


() => isPathAccessible(path)


exists => exists ? normalize(path) : ''


resolve => access(path, err => resolve(err ? false : true))


err => resolve(err ? false : true)


function advance(fixture: ComponentFixture<any>): void {
  tick();
  fixture.detectChanges();
}


function compileRoot(tcb: TestComponentBuilder): Promise<ComponentFixture<any>> {
  return tcb.createAsync(RootCmp);
}


() => [
      {provide: RouterUrlSerializer, useClass: DefaultRouterUrlSerializer},
      RouterOutletMap,
      {provide: Location, useClass: SpyLocation},
      {provide: RouteSegment, useFactory: (r: any /** TODO #9100 */) => r.routeTree.root, deps: [Router]},
      {
        provide: Router,
        useFactory: (resolver: any /** TODO #9100 */, urlParser: any /** TODO #9100 */, outletMap: any /** TODO #9100 */, location: any /** TODO #9100 */) => new Router(
                        "RootComponent", RootCmp, resolver, urlParser, outletMap, location),
        deps: [ComponentResolver, RouterUrlSerializer, RouterOutletMap, Location]
      }
    ]


(r: any /** TODO #9100 */) => r.routeTree.root


(resolver: any /** TODO #9100 */, urlParser: any /** TODO #9100 */, outletMap: any /** TODO #9100 */, location: any /** TODO #9100 */) => new Router(
                        "RootComponent", RootCmp, resolver, urlParser, outletMap, location)


(router: any /** TODO #9100 */, tcb: any /** TODO #9100 */, location: any /** TODO #9100 */) => {
         let fixture = tcb.createFakeAsync(RootCmp);

         router.navigateByUrl('/team/22/user/victor');
         advance(fixture);
         expect(location.path()).toEqual('/team/22/user/victor');

         router.navigateByUrl('/team/33/simple');
         advance(fixture);

         expect(location.path()).toEqual('/team/33/simple');
       }


(router: any /** TODO #9100 */, tcb: any /** TODO #9100 */, location: any /** TODO #9100 */) => {
        let fixture = tcb.createFakeAsync(RootCmp);

        router.navigateByUrl('/team/33/simple');
        advance(fixture);

        router.navigateByUrl('/team/22/user/victor');
        advance(fixture);

        location.back();
        advance(fixture);
        expect(location.path()).toEqual('/team/33/simple');

        location.forward();
        advance(fixture);
        expect(location.path()).toEqual('/team/22/user/victor');
      }


(router: any /** TODO #9100 */, tcb: any /** TODO #9100 */, location: any /** TODO #9100 */) => {
         let fixture = tcb.createFakeAsync(RootCmp);

         router.navigateByUrl('/team/22/user/victor');
         advance(fixture);

         location.simulateHashChange("/team/22/user/fedor");
         advance(fixture);

         expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello fedor, aux:  }');
       }


(router: any /** TODO #9100 */, tcb: any /** TODO #9100 */) => {
         let fixture = tcb.createFakeAsync(RootCmp);

         router.navigateByUrl('/team/22/user/victor');
         advance(fixture);

         expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello victor, aux:  }');
       }


(router: any /** TODO #9100 */, tcb: any /** TODO #9100 */) => {
         let fixture = tcb.createFakeAsync(RootCmp);

         router.navigateByUrl('/team/22/user/victor(/simple)');
         advance(fixture);

         expect(fixture.debugElement.nativeElement)
             .toHaveText('team 22 { hello victor, aux: simple }');
       }


(router: any /** TODO #9100 */, tcb: any /** TODO #9100 */) => {
         let fixture = tcb.createFakeAsync(RootCmp);

         router.navigateByUrl('/team/22/user/victor(/simple)');
         advance(fixture);

         router.navigateByUrl('/team/22/user/victor');
         advance(fixture);

         expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello victor, aux:  }');
       }


(router: any /** TODO #9100 */, tcb: any /** TODO #9100 */) => {
         let fixture = tcb.createFakeAsync(RootCmp);

         router.navigateByUrl('/team/22/user/victor(/simple)');
         advance(fixture);

         router.navigateByUrl('/');
         advance(fixture);

         expect(fixture.debugElement.nativeElement).toHaveText('');
       }


(router: any /** TODO #9100 */, tcb: any /** TODO #9100 */) => {
         let fixture = tcb.createFakeAsync(RootCmp);

         router.navigateByUrl('/team/22/user/victor');
         advance(fixture);
         let team1 = fixture.debugElement.children[1].componentInstance;

         router.navigateByUrl('/team/22/user/fedor');
         advance(fixture);
         let team2 = fixture.debugElement.children[1].componentInstance;

         expect(team1).toBe(team2);
         expect(fixture.debugElement.nativeElement).toHaveText('team 22 { hello fedor, aux:  }');
       }


(router: any /** TODO #9100 */, tcb: any /** TODO #9100 */, location: any /** TODO #9100 */) => {
         let fixture = tcb.createFakeAsync(RootCmp);

         router.navigateByUrl('/team/22/cannotDeactivate');
         advance(fixture);

         router.navigateByUrl('/team/22/user/fedor');
         advance(fixture);

         expect(fixture.debugElement.nativeElement)
             .toHaveText('team 22 { cannotDeactivate, aux:  }');

         expect(location.path()).toEqual('/team/22/cannotDeactivate');
       }


(router: any /** TODO #9100 */, tcb: any /** TODO #9100 */) => {
           let fixture = tcb.createFakeAsync(RootCmp);
           advance(fixture);

           router.navigateByUrl('/team/22/link');
           advance(fixture);
           expect(fixture.debugElement.nativeElement).toHaveText('team 22 { link, aux:  }');

           let native = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
           expect(getDOM().getAttribute(native, "href")).toEqual("/team/33/simple");
           getDOM().dispatchEvent(native, getDOM().createMouseEvent('click'));
           advance(fixture);

           expect(fixture.debugElement.nativeElement).toHaveText('team 33 { simple, aux:  }');
         }


(router: any /** TODO #9100 */, tcb: any /** TODO #9100 */) => {
           let fixture = tcb.createFakeAsync(RootCmp);
           advance(fixture);

           router.navigateByUrl('/team/22/relativelink');
           advance(fixture);
           expect(fixture.debugElement.nativeElement)
               .toHaveText('team 22 { relativelink {  }, aux:  }');

           let native = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
           expect(getDOM().getAttribute(native, "href")).toEqual("/team/22/relativelink/simple");
           getDOM().dispatchEvent(native, getDOM().createMouseEvent('click'));
           advance(fixture);

           expect(fixture.debugElement.nativeElement)
               .toHaveText('team 22 { relativelink { simple }, aux:  }');
         }


(router: any /** TODO #9100 */, tcb: any /** TODO #9100 */) => {
           let fixture = tcb.createFakeAsync(RootCmp);
           advance(fixture);

           router.navigateByUrl('/team/22/relativelink');
           advance(fixture);
           expect(fixture.debugElement.nativeElement)
               .toHaveText('team 22 { relativelink {  }, aux:  }');
           let link = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
           expect(getDOM().hasClass(link, "router-link-active")).toEqual(false);

           getDOM().dispatchEvent(link, getDOM().createMouseEvent('click'));
           advance(fixture);

           expect(getDOM().hasClass(link, "router-link-active")).toEqual(true);
         }


(router: any /** TODO #9100 */, tcb: any /** TODO #9100 */) => {
           let fixture = tcb.createFakeAsync(RootCmp);
           advance(fixture);

           router.navigateByUrl('/team/22/link(simple)');
           advance(fixture);
           expect(fixture.debugElement.nativeElement).toHaveText('team 22 { link, aux: simple }');

           let native = getDOM().querySelector(fixture.debugElement.nativeElement, "a");
           expect(getDOM().getAttribute(native, "href")).toEqual("/team/33/simple(aux:simple)");

           router.navigateByUrl('/team/22/link(simple2)');
           advance(fixture);

           expect(getDOM().getAttribute(native, "href")).toEqual("/team/33/simple(aux:simple2)");
         }


(router: any /** TODO #9100 */, tcb: any /** TODO #9100 */) => {
           let fixture = tcb.createFakeAsync(LinkCmp);
           advance(fixture);
           expect(fixture.debugElement.nativeElement).toHaveText('link');
         }


(router: any /** TODO #9100 */, tcb: any /** TODO #9100 */, location: any /** TODO #9100 */) => {
          let fixture = tcb.createFakeAsync(RootCmp);

          router.navigateByUrl('/team/33/simple');
          advance(fixture);

          router.navigateByUrl('/team/22/user/victor');
          advance(fixture);

          router.navigateByUrl('/team/22/user/victor');
          advance(fixture);

          location.back();
          advance(fixture);
          expect(location.path()).toEqual('/team/33/simple');
        }


@Component({selector: 'user-cmp', template: `hello {{user}}`})
class UserCmp implements OnActivate {
  user: string;
  routerOnActivate(s: RouteSegment, a?: any /** TODO #9100 */, b?: any /** TODO #9100 */, c?: any /** TODO #9100 */) { this.user = s.getParam('name'); }
}


@Component({selector: 'cannot-deactivate', template: `cannotDeactivate`})
class CanDeactivateCmp implements CanDeactivate {
  routerCanDeactivate(a?: any /** TODO #9100 */, b?: any /** TODO #9100 */): Promise<boolean> { return PromiseWrapper.resolve(false); }
}


@Component({selector: 'simple-cmp', template: `simple`})
class SimpleCmp {
}


@Component({selector: 'simple2-cmp', template: `simple2`})
class Simple2Cmp {
}


@Component({
  selector: 'link-cmp',
  template: `<a [routerLink]="['/team', '33', 'simple']">link</a>`,
  directives: ROUTER_DIRECTIVES
})
class LinkCmp {
}


@Component({
  selector: 'link-cmp',
  template: `<a [routerLink]="['./simple']">relativelink</a> { <router-outlet></router-outlet> }`,
  directives: ROUTER_DIRECTIVES
})
@Routes([new Route({path: 'simple', component: SimpleCmp})])
class RelativeLinkCmp {
}


@Component({
  selector: 'team-cmp',
  template: `team {{id}} { <router-outlet></router-outlet>, aux: <router-outlet name="aux"></router-outlet> }`,
  directives: [ROUTER_DIRECTIVES]
})
@Routes([
  new Route({path: 'user/:name', component: UserCmp}),
  new Route({path: 'simple', component: SimpleCmp}),
  new Route({path: 'simple2', component: Simple2Cmp}),
  new Route({path: 'link', component: LinkCmp}),
  new Route({path: 'relativelink', component: RelativeLinkCmp}),
  new Route({path: 'cannotDeactivate', component: CanDeactivateCmp})
])
class TeamCmp implements OnActivate {
  id: string;
  routerOnActivate(s: RouteSegment, a?: any /** TODO #9100 */, b?: any /** TODO #9100 */, c?: any /** TODO #9100 */) { this.id = s.getParam('id'); }
}


@Component({
  selector: 'root-cmp',
  template: `<router-outlet></router-outlet>`,
  directives: [ROUTER_DIRECTIVES]
})
@Routes([new Route({path: 'team/:id', component: TeamCmp})])
class RootCmp {
}


routerOnActivate(s: RouteSegment, a?: any /** TODO #9100 */, b?: any /** TODO #9100 */, c?: any /** TODO #9100 */) { this.user = s.getParam('name'); }


routerCanDeactivate(a?: any /** TODO #9100 */, b?: any /** TODO #9100 */): Promise<boolean> { return PromiseWrapper.resolve(false); }


routerOnActivate(s: RouteSegment, a?: any /** TODO #9100 */, b?: any /** TODO #9100 */, c?: any /** TODO #9100 */) { this.id = s.getParam('id'); }


() => DepartmentModule


@Module({
  imports: [
    forwardRef(() => DepartmentModule),
    MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]),
  ],
  controllers: [UserController],
  providers: [
    {
      provide: APP_GUARD,
      useClass: JwtAuthGuard,
    },
    UserService
  ],
  exports: [UserService],
})
export class UsersModule {}


(error: RetryObject['error']): error is HTTPError | ParseError | MaxRedirectsError => (
	error instanceof HTTPError || error instanceof ParseError || error instanceof MaxRedirectsError
)


({attemptCount, retryOptions, error}) => {
	if (attemptCount > retryOptions.limit) {
		return 0;
	}

	const hasMethod = retryOptions.methods.includes(error.options.method);
	const hasErrorCode = Reflect.has(error, 'code') && retryOptions.errorCodes.includes(error.code);
	const hasStatusCode = isErrorWithResponse(error) && Reflect.has(error, 'response') && retryOptions.statusCodes.includes(error.response?.statusCode);
	if (!hasMethod || (!hasErrorCode && !hasStatusCode)) {
		return 0;
	}

	if (isErrorWithResponse(error)) {
		const {response} = error;
		if (response && Reflect.has(response.headers, 'retry-after') && retryAfterStatusCodes.has(response.statusCode)) {
			let after = Number(response.headers['retry-after']);
			if (is.nan(after)) {
				after = Date.parse(response.headers['retry-after']!) - Date.now();
			} else {
				after *= 1000;
			}

			if (after > retryOptions.maxRetryAfter) {
				return 0;
			}

			return after;
		}

		if (response?.statusCode === 413) {
			return 0;
		}
	}

	const noise = Math.random() * 100;
	return ((2 ** (attemptCount - 1)) * 1000) + noise;
}


@Component({
  selector: 'app-related',
  templateUrl: './related.component.html',
  styleUrls: ['./related.component.css'],
  encapsulation: ViewEncapsulation.None,
})
export class RelatedComponent implements OnInit {
  constructor(
    public shared: SharedService,
    public globals: GlobalsService,
    public carouselOne: NguCarouselConfig
  ) {}

  ngOnInit() {
    this.carouselOne = {
      grid: { xs: 2, sm: 4, md: 4, lg: 4, all: 0 },
      slide: 4,
      speed: 250,
      loop: true,
      velocity: 0,
      touch: false,
      point: {
        visible: true,
        hideOnSingleSlide: true,
      },
    };
  }
}


ngOnInit() {
    this.carouselOne = {
      grid: { xs: 2, sm: 4, md: 4, lg: 4, all: 0 },
      slide: 4,
      speed: 250,
      loop: true,
      velocity: 0,
      touch: false,
      point: {
        visible: true,
        hideOnSingleSlide: true,
      },
    };
  }


({ imageName }) => {
  const { t } = useTranslation();

  const labelImage = () => {
    const os = {
      [RHEL7]: RHEL7_EXAMPLE_CONTAINER,
      [RHEL8]: RHEL8_EXAMPLE_CONTAINER,
      [CENTOS7]: CENTOS7_EXAMPLE_CONTAINER,
      [CENTOS8]: CENTOS8_EXAMPLE_CONTAINER,
      [WIN2k]: NO_LABEL,
      [WIN10]: NO_LABEL,
    };

    const label =
      os[Object.keys(os).find((name) => imageName?.includes(name))] || FEDORA_EXAMPLE_CONTAINER;

    return label;
  };

  const container = isUpstream() ? FEDORA_EXAMPLE_CONTAINER : labelImage();

  return (
    <div className="pf-c-form__helper-text" aria-live="polite" data-test="ContainerSourceHelp">
      {container !== NO_LABEL && t('kubevirt-plugin~Example: {{container}}', { container })}


() => {
    const os = {
      [RHEL7]: RHEL7_EXAMPLE_CONTAINER,
      [RHEL8]: RHEL8_EXAMPLE_CONTAINER,
      [CENTOS7]: CENTOS7_EXAMPLE_CONTAINER,
      [CENTOS8]: CENTOS8_EXAMPLE_CONTAINER,
      [WIN2k]: NO_LABEL,
      [WIN10]: NO_LABEL,
    };

    const label =
      os[Object.keys(os).find((name) => imageName?.includes(name))] || FEDORA_EXAMPLE_CONTAINER;

    return label;
  }


(name) => imageName?.includes(name)


type ContainerSourceHelpProps = {
  imageName: string;
};


@Component({
  selector: 'clr-notification-demo',
  styleUrls: ['./notification.demo.scss'],
  templateUrl: './notification.demo.html',
})
export class NotificationDemo {
  constructor(private clrNotificationService: ClrNotificationService) {}

  onClose(): void {
    console.log('notification closed');
  }

  showAlert(): void {
    alert('Button was clicked');
  }

  openInfo(content): void {
    this.clrNotificationService
      .openNotification(content, { timeout: 100000, notificationType: 'info', dismissable: true, progressbar: true })
      .result.then(this.onClose);
  }

  openWarning(content): void {
    this.clrNotificationService
      .openNotification(content, { timeout: 20000, notificationType: 'warning', dismissable: true, progressbar: true })
      .result.then(this.onClose);
  }

  openSuccess(content): void {
    this.clrNotificationService
      .openNotification(content, { timeout: 30000, notificationType: 'success', dismissable: true, progressbar: true })
      .result.then(this.onClose);
  }

  openDanger(content): void {
    this.clrNotificationService
      .openNotification(content, { timeout: 40000, notificationType: 'danger', dismissable: true, progressbar: true })
      .result.then(this.onClose);
  }
}


onClose(): void {
    console.log('notification closed');
  }


showAlert(): void {
    alert('Button was clicked');
  }


openInfo(content): void {
    this.clrNotificationService
      .openNotification(content, { timeout: 100000, notificationType: 'info', dismissable: true, progressbar: true })
      .result.then(this.onClose);
  }


openWarning(content): void {
    this.clrNotificationService
      .openNotification(content, { timeout: 20000, notificationType: 'warning', dismissable: true, progressbar: true })
      .result.then(this.onClose);
  }


openSuccess(content): void {
    this.clrNotificationService
      .openNotification(content, { timeout: 30000, notificationType: 'success', dismissable: true, progressbar: true })
      .result.then(this.onClose);
  }


openDanger(content): void {
    this.clrNotificationService
      .openNotification(content, { timeout: 40000, notificationType: 'danger', dismissable: true, progressbar: true })
      .result.then(this.onClose);
  }


() => {
    const query1 = Query.atPath(path('collection')).withLimit(2);
    const doc1 = doc('collection/a', 1000, { key: 'a' });
    const doc2 = doc('collection/b', 1002, { key: 'b' });
    const doc3 = doc('collection/c', 1001, { key: 'c' });
    return spec()
      .userListens(query1)
      .watchAcksFull(query1, 1001, doc1, doc3)
      .expectEvents(query1, {
        added: [doc1, doc3]
      })
      .watchSends({ affects: [query1] }, doc2)
      .watchSends({ removed: [query1] }, doc3)
      .watchSnapshots(1002)
      .expectEvents(query1, {
        added: [doc2],
        removed: [doc3]
      });
  }


() => {
      const query1 = Query.atPath(path('collection')).withLimit(2);
      const doc1 = doc('collection/a', 1000, { key: 'a' });
      const doc2 = doc('collection/b', 1000, { key: 'b' });

      return spec()
        .withGCEnabled(false)
        .userListens(query1)
        .watchAcksFull(query1, 1000, doc1, doc2)
        .expectEvents(query1, {
          added: [doc1, doc2]
        })
        .userUnlistens(query1)
        .userSets('collection/c', { key: 'c' })
        .userListens(query1, 'resume-token-1000')
        .expectEvents(query1, {
          added: [doc1, doc2],
          fromCache: true
        });
    }


() => {
    const query = Query.atPath(path('collection')).withLimit(2);
    const doc1 = doc('collection/a', 1000, { key: 'a' });
    const doc2 = doc('collection/b', 1001, { key: 'b' });
    const doc3 = doc('collection/c', 1002, { key: 'c' });
    return (
      spec()
        .userListens(query)
        .watchAcksFull(query, 1002, doc1, doc2)
        .expectEvents(query, {
          added: [doc1, doc2]
        })
        .watchResets(query)
        .watchSends({ affects: [query] }, doc2, doc3)
        .watchCurrents(query, 'resume-token-' + 2000)
        .watchSnapshots(2000)
        .expectLimboDocs(doc1.key)
        // Limbo document causes query to be "inconsistent"
        .expectEvents(query, { fromCache: true })
        .ackLimbo(2000, deletedDoc('collection/a', 2000))
        .expectLimboDocs()
        .expectEvents(query, {
          added: [doc3],
          removed: [doc1]
        })
    );
  }


() => {
    const query1 = Query.atPath(path('collection')).withLimit(2);
    const doc1 = doc('collection/a', 1000, { key: 'a' });
    const doc2 = doc('collection/b', 1002, { key: 'b' });
    const doc3 = doc('collection/c', 1001, { key: 'c' });
    return (
      spec()
        .userListens(query1)
        .watchAcksFull(query1, 1001, doc1, doc3)
        .expectEvents(query1, {
          added: [doc1, doc3]
        })
        .watchSends({ affects: [query1] }, doc2)
        .watchRemovesDoc(doc3.key, query1)
        .watchSnapshots(1002)
        // No limbo docs expected because doc3 was removed
        .expectLimboDocs()
        .expectEvents(query1, {
          added: [doc2],
          removed: [doc3]
        })
    );
  }


() => {
      const query1 = Query.atPath(path('collection')).withLimit(2);
      const query2 = Query.atPath(path('collection')).withLimit(3);
      const doc1 = doc('collection/a', 1000, { key: 'a' });
      const doc2 = doc('collection/b', 1002, { key: 'b' });
      const doc3 = doc('collection/c', 1001, { key: 'c' });
      return (
        spec()
          .userListens(query1)
          .userListens(query2)
          .watchAcks(query1)
          .watchAcks(query2)
          .watchSends({ affects: [query1] }, doc1, doc3)
          .watchSends({ affects: [query2] }, doc1, doc3)
          .watchCurrents(query1, 'resume-token-1001')
          .watchCurrents(query2, 'resume-token-1001')
          .watchSnapshots(1001)
          .expectEvents(query1, { added: [doc1, doc3] })
          .expectEvents(query2, { added: [doc1, doc3] })
          .watchSends({ affects: [query1, query2] }, doc2)
          .watchRemovesDoc(doc3.key, query1)
          .watchSnapshots(1002)
          // No limbo docs expected because doc3 was removed from query1
          .expectLimboDocs()
          .expectEvents(query1, {
            added: [doc2],
            removed: [doc3]
          })
          .expectEvents(query2, { added: [doc2] })
      );
    }


() => {
    const query1 = Query.atPath(path('collection')).withLimit(2);
    const query2 = Query.atPath(path('collection'));
    const docA = doc('collection/a', 1000, { key: 'a' });
    const docB = doc('collection/b', 1001, { key: 'b' });
    const docC = doc('collection/c', 1002, { key: 'c' });
    const docD = doc('collection/d', 1003, { key: 'd' });
    const docE = doc('collection/e', 1004, { key: 'e' });
    const docF = doc('collection/f', 1005, { key: 'f' });
    return (
      spec()
        .userListens(query1)
        .watchAcksFull(query1, 1001, docA, docB)
        .expectEvents(query1, {
          added: [docA, docB]
        })
        .userListens(query2)
        .expectEvents(query2, {
          fromCache: true,
          added: [docA, docB]
        })
        .watchAcksFull(query2, 1005, docA, docB, docC, docD, docE, docF)
        .expectEvents(query2, {
          added: [docC, docD, docE, docF]
        })
        .watchResets(query1)
        .watchSends({ affects: [query1] }, docE, docF)
        /**
         * Technically, this sequence can't happen in reality, because the
         * backend can't ack version 2000 without updating the state for C and
         * D, since they are results for query2. query2 is just a hack to make
         * sure that C and D are in the local cache.
         */
        .watchCurrents(query1, 'resume-token-' + 2000)
        .watchSnapshots(2000)
        .expectLimboDocs(docA.key, docB.key)
        // Limbo document causes query to be "inconsistent"
        .expectEvents(query1, { fromCache: true })
        /**
         * The current implementation resolves limbo documents one at a time.
         * However, if we decide to change this in the future to resolve them
         * all at once, it's okay to change this test to match that.
         */
        .ackLimbo(2000, deletedDoc('collection/a', 2000))
        .expectLimboDocs(docB.key, docC.key)
        .expectEvents(query2, {
          removed: [docA]
        })
        .expectEvents(query1, {
          fromCache: true,
          added: [docC],
          removed: [docA]
        })
        .watchRemovesLimboTarget(docA)
        .ackLimbo(2001, deletedDoc('collection/b', 2001))
        .expectLimboDocs(docC.key, docD.key)
        .expectEvents(query2, {
          removed: [docB]
        })
        .expectEvents(query1, {
          fromCache: true,
          added: [docD],
          removed: [docB]
        })
        .watchRemovesLimboTarget(docB)
        .ackLimbo(2002, deletedDoc('collection/c', 2002))
        .expectLimboDocs(docD.key)
        .expectEvents(query2, {
          removed: [docC]
        })
        .expectEvents(query1, {
          fromCache: true,
          added: [docE],
          removed: [docC]
        })
        .watchRemovesLimboTarget(docC)
        .ackLimbo(2003, deletedDoc('collection/d', 2003))
        .expectLimboDocs()
        .expectEvents(query2, {
          removed: [docD]
        })
        .expectEvents(query1, {
          added: [docF],
          removed: [docD]
        })
        .watchRemovesLimboTarget(docD)
    );
  }


() => {
      const query1 = Query.atPath(path('collection')).withLimit(2);
      const doc1 = doc('collection/a', 1000, { key: 'a' });
      const doc2 = doc('collection/b', 1002, { key: 'b' });
      const doc3 = doc('collection/c', 1001, { key: 'c' });
      return client(0)
        .becomeVisible()
        .client(1)
        .userListens(query1)
        .client(0)
        .expectListen(query1)
        .watchAcksFull(query1, 1001, doc1, doc3)
        .client(1)
        .expectEvents(query1, {
          added: [doc1, doc3]
        })
        .client(0)
        .watchSends({ affects: [query1] }, doc2)
        .watchSends({ removed: [query1] }, doc3)
        .watchSnapshots(1002)
        .client(1)
        .expectEvents(query1, {
          added: [doc2],
          removed: [doc3]
        });
    }


() => {
      const query1 = Query.atPath(path('collection')).withLimit(2);
      const doc1 = doc('collection/a', 1003, { key: 'a' });
      const doc1Local = doc(
        'collection/a',
        0,
        { key: 'a' },
        { hasLocalMutations: true }
      );
      const doc2 = doc('collection/b', 1001, { key: 'b' });
      const doc3 = doc('collection/c', 1002, { key: 'c' });
      return client(0)
        .becomeVisible()
        .client(1)
        .userListens(query1)
        .client(0)
        .expectListen(query1)
        .watchAcksFull(query1, 1002, doc2, doc3)
        .client(1)
        .expectEvents(query1, {
          added: [doc2, doc3]
        })
        .client(2)
        .userSets('collection/a', { key: 'a' })
        .client(1)
        .expectEvents(query1, {
          hasPendingWrites: true,
          added: [doc1Local],
          removed: [doc3]
        })
        .client(0)
        .writeAcks('collection/a', 1003, { expectUserCallback: false })
        .watchSends({ affects: [query1] }, doc1)
        .watchSends({ removed: [query1] }, doc3)
        .watchSnapshots(1003)
        .client(1)
        .expectEvents(query1, {
          metadata: [doc1]
        })
        .client(2)
        .expectUserCallbacks({
          acknowledged: ['collection/a']
        });
    }


type => Client


type => ProjectSector


type => MOU


@Entity()
export class Project {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'text' })
  projectName: string;

  @ManyToOne(type => Client)
  client: Client;

  @ManyToOne(type => ProjectSector)
  projectSector: ProjectSector;

  @Column({ type: 'text', nullable: true })
  commodityCode: string;

  @Column({ type: 'date', nullable: true })
  dueDate: Date;

  @Column({ type: 'date', nullable: true })
  completionDate: Date;

  @Column({ type: 'double precision', nullable: true })
  contractValue: number;

  @Column({ type: 'double precision', nullable: true })
  mouAmount: number;

  @Column({ type: 'uuid', nullable: true })
  leadUserId: string;
  @Column({ type: 'uuid', nullable: true })
  backupUserId: string;

  @Column({ type: 'text', nullable: true })
  description: string;

  @Column({ type: 'timestamp', nullable: true })
  dateCreated: Date;

  @Column({ type: 'timestamp', nullable: true })
  dateModified: Date;

  @Column({ type: 'uuid', nullable: true })
  createdUserId: string;

  @Column({ type: 'uuid', nullable: true })
  modifiedUserId: string;

  @Column({ type: 'boolean', nullable: true })
  is_archived: boolean;

  @Column({ type: 'boolean', nullable: true })
  isReprocurement: boolean;

  @Column({ type: 'boolean', nullable: true })
  isMinistry: boolean;

  @Column({ type: 'date', nullable: true })
  dateOfReprocurement: Date;

  @Column({ type: 'text', nullable: true })
  previousContractBackground: string;

  @Column({ type: 'text', nullable: true })
  projectFailImpact: string;

  @Column({ type: 'text', nullable: true })
  projectSuccess: string;

  @Column({ type: 'boolean', nullable: true })
  teamWideProject: boolean;

  @Column({ type: 'text', nullable: true })
  otherProjectSectorName: string;

  @ManyToOne(type => MOU)
  mou: MOU;

  @Column({ type: 'int', nullable: true })
  categoryId: ProjectCategory
}


export enum ProjectCategory {
  CSA = 1,
  ITQ = 2,
  CostRecoverable = 3,
  NonRecoverable = 4
}


async function run() {
    let jobs: LocalApi.JobEntry[];
    try {
        if (!config.jobs) {
            throw new Error(`Please provide 'jobs' argument. See [-h] for help.`);
        }

        jobs = JSON.parse(fs.readFileSync(config.jobs, 'utf-8'));
    } catch (e) {
        console.error('' + e);
        return;
    }

    await LocalApi.run(jobs);
}


() =>
                    import('./component-docs/platform-button/platform-button.module').then(
                        (m) => m.PlatformButtonDocsModule
                    )


(m) => m.PlatformButtonDocsModule


() =>
                    import('./component-docs/platform-action-bar/platform-action-bar.module').then(
                        (m) => m.PlatformActionBarDocsModule
                    )


(m) => m.PlatformActionBarDocsModule


() =>
                    import('./component-docs/platform-forms/checkbox/platform-checkbox-docs.module').then(
                        (m) => m.CheckboxDocsModule
                    )


(m) => m.CheckboxDocsModule


() =>
                    import(
                        './component-docs/platform-forms/platform-checkbox-group/platform-checkbox-group-docs.module'
                    ).then((m) => m.PlatformCheckboxGroupDocsModule)


(m) => m.PlatformCheckboxGroupDocsModule


() =>
                    import('./component-docs/platform-link/platform-link.module').then((m) => m.PlatformLinkDocsModule)


(m) => m.PlatformLinkDocsModule


() =>
                    import('./component-docs/platform-menu/platform-menu.module').then((m) => m.PlatformMenuDocsModule)


(m) => m.PlatformMenuDocsModule


() =>
                    import('./component-docs/platform-menu-button/platform-menu-button.module').then(
                        (m) => m.PlatformMenuButtonDocsModule
                    )


(m) => m.PlatformMenuButtonDocsModule


() =>
                    import('./component-docs/platform-search-field/platform-search-field.module').then(
                        (m) => m.PlatformSearchFieldDocsModule
                    )


(m) => m.PlatformSearchFieldDocsModule


() =>
                    import('./component-docs/platform-select/platform-select.module').then(
                        (m) => m.PlatformSelectDocsModule
                    )


(m) => m.PlatformSelectDocsModule


() =>
                    import('./component-docs/platform-forms/radio-group/platform-radio-group.module').then(
                        (m) => m.PlatformRadioGroupDocsModule
                    )


(m) => m.PlatformRadioGroupDocsModule


() =>
                    import('./component-docs/platform-split-menu-button/platform-split-menu-button.module').then(
                        (m) => m.PlatformSplitMenuButtonDocsModule
                    )


(m) => m.PlatformSplitMenuButtonDocsModule


() =>
                    import('./component-docs/platform-info-label/platform-info-label-docs-module').then(
                        (m) => m.PlatformInfoLabelDocsModule
                    )


(m) => m.PlatformInfoLabelDocsModule


() =>
                    import('./component-docs/platform-forms/platform-textarea/platform-textarea-docs.module').then(
                        (m) => m.PlatformTextareaDocsModule
                    )


(m) => m.PlatformTextareaDocsModule


() =>
                    import('./component-docs/platform-panel/platform-panel.module').then(
                        (m) => m.PlatformPanelDocsModule
                    )


(m) => m.PlatformPanelDocsModule


() =>
                    import('./component-docs/platform-forms/switch/platform-switch-docs.module').then(
                        (m) => m.PlatformSwitchDocsModule
                    )


(m) => m.PlatformSwitchDocsModule


() =>
                    import('./component-docs/platform-forms/platform-input/platform-input-docs.module').then(
                        (m) => m.PlatformInputDocsModule
                    )


(m) => m.PlatformInputDocsModule


() =>
                    import('./component-docs/platform-forms/step-input/platform-step-input.module').then(
                        (m) => m.PlatformStepInputDocsModule
                    )


(m) => m.PlatformStepInputDocsModule


() =>
                    import('./component-docs/platform-object-status/platform-object-status-docs.module').then(
                        (m) => m.PlatformObjectStatusDocsModule
                    )


(m) => m.PlatformObjectStatusDocsModule


() =>
                    import('./component-docs/platform-forms/input-group/platform-input-group-docs.module').then(
                        (m) => m.PlatformInputGroupDocsModule
                    )


(m) => m.PlatformInputGroupDocsModule


() =>
                    import('./component-docs/platform-combobox/platform-combobox-docs.module')
                        .then(m => m.PlatformComboboxDocsModule)


m => m.PlatformComboboxDocsModule


() =>
                    import('./component-docs/platform-list/platform-list-docs.module').then((m) => m.PlatformListDocsModule)


(m) => m.PlatformListDocsModule


() =>
                    import('./component-docs/platform-standard-list-item/platform-standard-list-item-docs.module').then((m) =>
                        m.PlatformStandardListItemDocsModule)


(m) =>
                        m.PlatformStandardListItemDocsModule


export type CreateArgs = {
  songName: string;
  artistName: string;
  transcriberId: string;
  tagIds: string[];
  thumbnail: FileUpload;
  video: FileUpload;
};


export type UpdateArgs = {
  songName?: string;
  artistName?: string;
  deadTimeMs?: number;
  durationMs?: number;
  private?: boolean;
  videoUrl?: string;
  thumbnail?: FileUpload;
  musicXml?: FileUpload;
};


/**
 * A utility for estimating the remaining time for an action.
 * @public
 */
export class TimeEstimator extends GCObject {

  private M$cacheSize: number
  private M$snapshotStack: Array<[progress: number, timeStamp: number]> = []
  private M$alreadyCompleted = false

  /**
   * @param cacheSize - Number of snapshots to store. (Default: `2`)
   * @example
   * const myTimeEstimator = new TimeEstimator()
   */
  constructor(cacheSize = MINIMUM_TIME_ESTIMATOR_CACHE_SIZE) {
    super()
    // Error is not thrown because this is just a time estimation utility.
    // Even with a decent cache size, the estimation might still be wrong.
    // It makes more sense to throw an error only when we rather prefer the
    // application to stop working than to display wrong information.
    if (cacheSize < MINIMUM_TIME_ESTIMATOR_CACHE_SIZE) {
      devError(
        `Expected \`cacheSize\` to be at least ${MINIMUM_TIME_ESTIMATOR_CACHE_SIZE}` +
        `but got ${cacheSize}. Automatically setting to ${MINIMUM_TIME_ESTIMATOR_CACHE_SIZE}.`
      )
    }
    this.M$cacheSize = Math.max(cacheSize, MINIMUM_TIME_ESTIMATOR_CACHE_SIZE)
  }

  /**
   * Insert a snapshot of the current progress.
   * @param progress - The current progress in percentage. Value must be between
   * `0` and `100`.
   */
  mark(progress: number): void {
    if (progress === MAX_PROGRESS) {
      this.M$alreadyCompleted = true
      return // Early exit
    }
    this.M$snapshotStack = clampedPush(this.M$cacheSize, [[
      clamp(progress, MIN_PROGRESS, MAX_PROGRESS),
      Date.now() // TESTSAFE_getDateNow(),
    ]], this.M$snapshotStack)
  }

  /**
   * Get the time estimation in milliseconds.
   * @returns
   * - The time estimation in milliseconds under ordinary circumstances,
   * - or `Infinity` if:
   *   - there are not enough snapshots yet,
   *   - all snapshots in memory have the same progress value, since this
   *     theoritically means it will take forever to complete.
   */
  getEstimation(): number {
    if (this.M$alreadyCompleted) {
      return 0 // Early exit
    }
    if (this.M$snapshotStack.length < MINIMUM_TIME_ESTIMATOR_CACHE_SIZE) {
      return Infinity // Early exit
    }
    let summedProgressRatePerMs = 0
    for (let i = 1; i < this.M$snapshotStack.length; i++) {
      const [previousProgress, previousTimestamp] = this.M$snapshotStack[i - 1]
      const [currentProgress, currentTimestamp] = this.M$snapshotStack[i]
      const progressDiff = currentProgress - previousProgress
      const timeDiffInMs = currentTimestamp - previousTimestamp
      // KIV
      // const timeDiffInMs = withMinimumLimit(currentTimestamp - previousTimestamp, 1)
      // // ^ Force minimum value of `timeDiff` to be `1`.
      const progressRatePerMs = progressDiff / timeDiffInMs
      summedProgressRatePerMs += progressRatePerMs
    }
    const averageProgressPerMs = summedProgressRatePerMs / (this.M$snapshotStack.length - 1)
    // ^ Must be `snapshotStack.length - 1` because we are calculating the differences
    // ^ Take note: Loop above is written `for (let i = 1; ...`

    if (averageProgressPerMs <= 0) { return Infinity } // Early exit

    const [latestProgress] = this.M$snapshotStack[this.M$snapshotStack.length - 1]
    const remainingProgess = MAX_PROGRESS - latestProgress
    // Formula:
    // rate = progress / time
    // time = progress / rate
    const estimatedRemainingTimeInMs = remainingProgess / averageProgressPerMs
    return Math.round(estimatedRemainingTimeInMs)
  }

  /**
   * Clears all snapshots in the cache.
   */
  reset(): void {
    this.M$alreadyCompleted = false
    this.M$snapshotStack = []
  }

}


/**
   * Insert a snapshot of the current progress.
   * @param progress - The current progress in percentage. Value must be between
   * `0` and `100`.
   */
mark(progress: number): void {
    if (progress === MAX_PROGRESS) {
      this.M$alreadyCompleted = true
      return // Early exit
    }
    this.M$snapshotStack = clampedPush(this.M$cacheSize, [[
      clamp(progress, MIN_PROGRESS, MAX_PROGRESS),
      Date.now() // TESTSAFE_getDateNow(),
    ]], this.M$snapshotStack)
  }


/**
   * Get the time estimation in milliseconds.
   * @returns
   * - The time estimation in milliseconds under ordinary circumstances,
   * - or `Infinity` if:
   *   - there are not enough snapshots yet,
   *   - all snapshots in memory have the same progress value, since this
   *     theoritically means it will take forever to complete.
   */
getEstimation(): number {
    if (this.M$alreadyCompleted) {
      return 0 // Early exit
    }
    if (this.M$snapshotStack.length < MINIMUM_TIME_ESTIMATOR_CACHE_SIZE) {
      return Infinity // Early exit
    }
    let summedProgressRatePerMs = 0
    for (let i = 1; i < this.M$snapshotStack.length; i++) {
      const [previousProgress, previousTimestamp] = this.M$snapshotStack[i - 1]
      const [currentProgress, currentTimestamp] = this.M$snapshotStack[i]
      const progressDiff = currentProgress - previousProgress
      const timeDiffInMs = currentTimestamp - previousTimestamp
      // KIV
      // const timeDiffInMs = withMinimumLimit(currentTimestamp - previousTimestamp, 1)
      // // ^ Force minimum value of `timeDiff` to be `1`.
      const progressRatePerMs = progressDiff / timeDiffInMs
      summedProgressRatePerMs += progressRatePerMs
    }
    const averageProgressPerMs = summedProgressRatePerMs / (this.M$snapshotStack.length - 1)
    // ^ Must be `snapshotStack.length - 1` because we are calculating the differences
    // ^ Take note: Loop above is written `for (let i = 1; ...`

    if (averageProgressPerMs <= 0) { return Infinity } // Early exit

    const [latestProgress] = this.M$snapshotStack[this.M$snapshotStack.length - 1]
    const remainingProgess = MAX_PROGRESS - latestProgress
    // Formula:
    // rate = progress / time
    // time = progress / rate
    const estimatedRemainingTimeInMs = remainingProgess / averageProgressPerMs
    return Math.round(estimatedRemainingTimeInMs)
  }


/**
   * Clears all snapshots in the cache.
   */
reset(): void {
    this.M$alreadyCompleted = false
    this.M$snapshotStack = []
  }


(obj) => ({
      value: obj.x,
      duration: obj.source.actionDuration || 0,
      lane: obj.y.toString(),
      data: {
        name: (obj.source && obj.source.name) || '',
        type: (obj.source && obj.source.type) || '',
      },
    })


(l) => l.name === name


export class EasyTravelDataSource implements EventChartDemoDataSource {
  getEvents(): EventChartDemoEvent[] {
    return EASY_TRAVEL_TEST_DATA[0].data.map((obj) => ({
      value: obj.x,
      duration: obj.source.actionDuration || 0,
      lane: obj.y.toString(),
      data: {
        name: (obj.source && obj.source.name) || '',
        type: (obj.source && obj.source.type) || '',
      },
    }));
  }

  getLanes(): EventChartDemoLane[] {
    const lanes: EventChartDemoLane[] = [];
    for (const event of EASY_TRAVEL_TEST_DATA[0].data) {
      const name = event.y.toString();
      if (!lanes.find((l) => l.name === name)) {
        // tslint:disable-next-line: no-any
        let color: any = 'default';
        if (event.marker.fillColor === '#dc172a') {
          color = 'error';
        }
        lanes.push({ name, label: name, color });
      }
    }
    return lanes;
  }

  getLegendItems(): EventChartDemoLegendItem[] {
    const lanesPerColor = new Map<string, EventChartDemoLegendItem>();
    for (const lane of this.getLanes()) {
      const item = lanesPerColor.get(lane.color);
      if (item && item.lanes.indexOf(lane.name) === -1) {
        item.lanes.push(lane.name);
      } else if (!item) {
        const label =
          lane.color !== 'default' ? lane.label : 'User action or event';
        lanesPerColor.set(lane.color, { label, lanes: [lane.name] });
      }
    }
    return Array.from(lanesPerColor.values());
  }
}


getEvents(): EventChartDemoEvent[] {
    return EASY_TRAVEL_TEST_DATA[0].data.map((obj) => ({
      value: obj.x,
      duration: obj.source.actionDuration || 0,
      lane: obj.y.toString(),
      data: {
        name: (obj.source && obj.source.name) || '',
        type: (obj.source && obj.source.type) || '',
      },
    }));
  }


getLanes(): EventChartDemoLane[] {
    const lanes: EventChartDemoLane[] = [];
    for (const event of EASY_TRAVEL_TEST_DATA[0].data) {
      const name = event.y.toString();
      if (!lanes.find((l) => l.name === name)) {
        // tslint:disable-next-line: no-any
        let color: any = 'default';
        if (event.marker.fillColor === '#dc172a') {
          color = 'error';
        }
        lanes.push({ name, label: name, color });
      }
    }
    return lanes;
  }


getLegendItems(): EventChartDemoLegendItem[] {
    const lanesPerColor = new Map<string, EventChartDemoLegendItem>();
    for (const lane of this.getLanes()) {
      const item = lanesPerColor.get(lane.color);
      if (item && item.lanes.indexOf(lane.name) === -1) {
        item.lanes.push(lane.name);
      } else if (!item) {
        const label =
          lane.color !== 'default' ? lane.label : 'User action or event';
        lanesPerColor.set(lane.color, { label, lanes: [lane.name] });
      }
    }
    return Array.from(lanesPerColor.values());
  }


@Component({
	selector: 'app-root',
	templateUrl: './app.component.html',
	styleUrls: ['./app.component.scss']
})
export class AppComponent {
	val: string = '🐘';
	title = 'app works!';
	emojiAdded(v) {
		this.val = v;
	}
}


emojiAdded(v) {
		this.val = v;
	}


() => {
  return (

        <StaticImage
          src="../../images/github-icon.png"
          alt="Github Icon"
          width={20}
          height={20}
          placeholder="blurred"
        />


() => {
            this._eventObject.removeListener(this._name, callback)
        }


export class Event<T> implements IEvent<T> {

    private _name: string
    private _eventObject: EventEmitter

    constructor(name: string) {
        this._name = name
        if (!eventsCache.has(name)) {
            let emitter = new EventEmitter()
            emitter.setMaxListeners(100)
            eventsCache.set(name, emitter)
        }
        this._eventObject = eventsCache.get(name)!
    }

    public subscribe(callback: EventCallback<T>): IDisposable {
        this._eventObject.addListener(this._name, callback)

        const dispose = () => {
            this._eventObject.removeListener(this._name, callback)
        }

        return { dispose }
    }

    public dispatch(val?: T): void {
        this._eventObject.emit(this._name, val)
    }
}


export interface IDisposable {
    dispose(): void
}


export interface IEvent<T> {
    subscribe(callback: EventCallback<T>): IDisposable
}


export type DisposeFunction = () => void


export type EventCallback<T> = (value: T) => void


public subscribe(callback: EventCallback<T>): IDisposable {
        this._eventObject.addListener(this._name, callback)

        const dispose = () => {
            this._eventObject.removeListener(this._name, callback)
        }

        return { dispose }
    }


public dispatch(val?: T): void {
        this._eventObject.emit(this._name, val)
    }


@Injectable({providedIn: 'root'})
export class UserService {

    constructor(private http: HttpClient) {

    }

    /**
     * Find users based on the given pagination parameters.
     *
     * @param size Page size.
     * @param page The number of the page.
     * @param sort Sort column.
     * @param direction Sort direction.
     */
    findAll(size: number, page: number, sort: string, direction: string): Observable<PageDTO<UserDTO>> {
        return this.http.get<PageDTO<UserDTO>>(Constants.API + '/users?size=' + size + '&page=' + page + '&sort=' + sort + ',' + direction);
    }

    /**
     * Get The User with the given id.
     *
     * @param id The User id.
     */
    getUser(id: string): Observable<UserDTO> {
        return this.http.get<UserDTO>(Constants.API + '/users/' + id);
    }

    /**
     * Save the given user.
     *
     * @param user  The User to be saved.
     */
    save(user: UserDTO) {
        return this.http.post<UserDTO>(Constants.API + '/users', user);
    }

    /**
     * Delete the User with the given id.
     *
     * @param id The User id.
     */
    delete(id: string): Observable<any> {
        return this.http.delete(Constants.API + '/users/' + id);
    }

}


/**
     * Find users based on the given pagination parameters.
     *
     * @param size Page size.
     * @param page The number of the page.
     * @param sort Sort column.
     * @param direction Sort direction.
     */
findAll(size: number, page: number, sort: string, direction: string): Observable<PageDTO<UserDTO>> {
        return this.http.get<PageDTO<UserDTO>>(Constants.API + '/users?size=' + size + '&page=' + page + '&sort=' + sort + ',' + direction);
    }


/**
     * Get The User with the given id.
     *
     * @param id The User id.
     */
getUser(id: string): Observable<UserDTO> {
        return this.http.get<UserDTO>(Constants.API + '/users/' + id);
    }


/**
     * Save the given user.
     *
     * @param user  The User to be saved.
     */
save(user: UserDTO) {
        return this.http.post<UserDTO>(Constants.API + '/users', user);
    }


/**
     * Delete the User with the given id.
     *
     * @param id The User id.
     */
delete(id: string): Observable<any> {
        return this.http.delete(Constants.API + '/users/' + id);
    }


(props) => {
    const { form: { getFieldDecorator }, data, form } = props;

    const permissionType = [
        { id: 'default', text: '默认' },
        { id: 'system', text: '系统' },
        { id: 'business', text: '业务功能' },
        { id: 'api', text: 'API接口' },
        { id: 'tenant', text: '多租户' }
    ];

    var defaultActionData: PermissionAction[] = [
        { "action": "query", "describe": "查询列表", defaultCheck: true, name: '' },
        { "action": "get", "describe": "查询明细", defaultCheck: true, name: '' },
        { "action": "add", "describe": "新增", defaultCheck: true, name: '' },
        { "action": "update", "describe": "修改", defaultCheck: true, name: '' },
        { "action": "delete", "describe": "删除", defaultCheck: false, name: '' },
        { "action": "import", "describe": "导入", defaultCheck: true, name: '' },
        { "action": "export", "describe": "导出", defaultCheck: true, name: '' }
    ];

    PubSub.unsubscribe("permission-basic-save");
    PubSub.subscribe('permission-basic-save', (topic: any, data: any) => {
        form.validateFields((err, fieldValue) => {
            if (err) {
                data.callback('error');
            } else {
                // fieldValue.type = fieldValue.type.toString();
                data.callback(fieldValue);
            }
        });
    });

    return (
        <div>
            <Form
                labelAlign={'right'}
                className={style['ant-form-item']}
            >
                <Row>
                    <Col span={12}>
                        <Form.Item
                            key="id"
                            label="权限标识（ID）"
                            labelCol={{ span: 12 }}


(topic: any, data: any) => {
        form.validateFields((err, fieldValue) => {
            if (err) {
                data.callback('error');
            } else {
                // fieldValue.type = fieldValue.type.toString();
                data.callback(fieldValue);
            }
        });
    }


(err, fieldValue) => {
            if (err) {
                data.callback('error');
            } else {
                // fieldValue.type = fieldValue.type.toString();
                data.callback(fieldValue);
            }
        }


option =>
                                            <Select.Option value


interface Props extends FormComponentProps {
    data: Partial<PermissionItem>;
    save: Function;
}


getFieldDecorator('id', {
                                initialValue: data


getFieldDecorator('name', {
                                initialValue: data


getFieldDecorator('status', {
                                initialValue: data


getFieldDecorator('properties.type', {
                                initialValue:


(size: Size): string => theme.borderWidth[size]


type Size = 'none' | 'sm' | 'md' | 'lg' | 'xl' | 'xxl';


export abstract class PartialAddressBase implements IPartialAddress {
  public readonly company: string;
  public readonly addressLines: ReadonlyArray<string>;
  public readonly cityLocality: string;
  public readonly stateProvince: string;
  public readonly postalCode: string;
  public readonly country?: Country;
  public readonly isResidential?: boolean;
  public readonly coordinates?: GeoCoordinate;

  public constructor(pojo: PartialAddressPOJO) {
    this.company = pojo.company || "";
    this.addressLines = pojo.addressLines || [];
    this.cityLocality = pojo.cityLocality || "";
    this.stateProvince = pojo.stateProvince || "";
    this.postalCode = pojo.postalCode || "";
    this.country = pojo.country;
    this.isResidential = pojo.isResidential;
    this.coordinates = pojo.coordinates && new GeoCoordinate(pojo.coordinates);
  }
}


export class PartialAddress extends PartialAddressBase {
  public static readonly [_internal] = {
    label: "address",
    schema: Joi.object({
      company: Joi.string().trim().singleLine().allow("").max(100),
      addressLines: Joi.array().items(Joi.string().trim().singleLine().min(1).max(100)),
      cityLocality: Joi.string().trim().singleLine().max(100),
      stateProvince: Joi.string().trim().singleLine().max(100),
      postalCode: Joi.string().trim().singleLine().max(100),
      country: Joi.string().enum(Country),
      isResidential: Joi.boolean(),
      coordinates: GeoCoordinate[_internal].schema,
    }),
  };

  public constructor(pojo: PartialAddressPOJO) {
    super(pojo);

    // Make this object immutable
    hideAndFreeze(this);
  }
}


({ searchText, numberOfItems }) => this.api.fetch(searchText, numberOfItems)


response => {
    // …
}


(props: {
  children: React.ReactNode,
  result: Result<string>|null,
  loading: boolean,
  onRequestClose: () => void,
  onSubmit: (e: React.FormEvent) => void,
  submitText?: string,
  title: string,
  submitDanger?:boolean,
  cancelText?: string,
}) => (
  <Modal title={props.title}


() => {
  it(`can be constructed with CustomFontEmbedder.for(...)`, async () => {
    const embedder = await CustomFontEmbedder.for(fontkit, ubuntuFont);
    expect(embedder).toBeInstanceOf(CustomFontEmbedder);
  });

  it(`exposes the font's name`, async () => {
    const embedder = await CustomFontEmbedder.for(
      fontkit,
      new Uint8Array(ubuntuFont),
    );
    expect(embedder.fontName).toBe('Ubuntu');
  });

  it(`can embed font dictionaries into PDFContexts without a predefined ref`, async () => {
    const context = PDFContext.create();
    const embedder = await CustomFontEmbedder.for(
      fontkit,
      new Uint8Array(ubuntuFont),
    );

    expect(context.enumerateIndirectObjects().length).toBe(0);
    const ref = await embedder.embedIntoContext(context);
    expect(context.enumerateIndirectObjects().length).toBe(5);
    expect(context.lookup(ref)).toBeInstanceOf(PDFDict);
  });

  it(`can embed font dictionaries into PDFContexts with a predefined ref`, async () => {
    const context = PDFContext.create();
    const predefinedRef = PDFRef.of(9999);
    const embedder = await CustomFontEmbedder.for(
      fontkit,
      new Uint8Array(ubuntuFont),
    );

    expect(context.enumerateIndirectObjects().length).toBe(0);
    const ref = await embedder.embedIntoContext(context, predefinedRef);
    expect(context.enumerateIndirectObjects().length).toBe(5);
    expect(context.lookup(predefinedRef)).toBeInstanceOf(PDFDict);
    expect(ref).toBe(predefinedRef);
  });

  it(`can encode text strings into PDFHexString objects`, async () => {
    const text = 'Stuff and thingz!';
    const hexCodes =
      '00360057005801AA000300440051004700030057004B004C0051004A005D0004';
    const embedder = await CustomFontEmbedder.for(fontkit, ubuntuFont);

    expect(embedder.encodeText(text)).toBeInstanceOf(PDFHexString);
    expect(String(embedder.encodeText(text))).toBe(
      String(PDFHexString.of(hexCodes)),
    );
  });

  it(`can measure the width of text strings at the given font size`, async () => {
    const text = 'Stuff and thingz!';
    const embedder = await CustomFontEmbedder.for(fontkit, ubuntuFont);
    expect(embedder.widthOfTextAtSize(text, 12)).toBe(90.672);
    expect(embedder.widthOfTextAtSize(text, 24)).toBe(181.344);
  });

  it(`can measure the height of the font at the given size`, async () => {
    const embedder = await CustomFontEmbedder.for(fontkit, ubuntuFont);
    expect(embedder.heightOfFontAtSize(12)).toBeCloseTo(13.452);
    expect(embedder.heightOfFontAtSize(24)).toBeCloseTo(26.904);
  });

  it(`can measure the size of the font at a given height`, async () => {
    const embedder = await CustomFontEmbedder.for(fontkit, ubuntuFont);
    expect(embedder.sizeOfFontAtHeight(12)).toBeCloseTo(10.705);
    expect(embedder.sizeOfFontAtHeight(24)).toBeCloseTo(21.409);
  });
}


async () => {
    const embedder = await CustomFontEmbedder.for(fontkit, ubuntuFont);
    expect(embedder).toBeInstanceOf(CustomFontEmbedder);
  }


async () => {
    const embedder = await CustomFontEmbedder.for(
      fontkit,
      new Uint8Array(ubuntuFont),
    );
    expect(embedder.fontName).toBe('Ubuntu');
  }


async () => {
    const context = PDFContext.create();
    const embedder = await CustomFontEmbedder.for(
      fontkit,
      new Uint8Array(ubuntuFont),
    );

    expect(context.enumerateIndirectObjects().length).toBe(0);
    const ref = await embedder.embedIntoContext(context);
    expect(context.enumerateIndirectObjects().length).toBe(5);
    expect(context.lookup(ref)).toBeInstanceOf(PDFDict);
  }


async () => {
    const context = PDFContext.create();
    const predefinedRef = PDFRef.of(9999);
    const embedder = await CustomFontEmbedder.for(
      fontkit,
      new Uint8Array(ubuntuFont),
    );

    expect(context.enumerateIndirectObjects().length).toBe(0);
    const ref = await embedder.embedIntoContext(context, predefinedRef);
    expect(context.enumerateIndirectObjects().length).toBe(5);
    expect(context.lookup(predefinedRef)).toBeInstanceOf(PDFDict);
    expect(ref).toBe(predefinedRef);
  }


async () => {
    const text = 'Stuff and thingz!';
    const hexCodes =
      '00360057005801AA000300440051004700030057004B004C0051004A005D0004';
    const embedder = await CustomFontEmbedder.for(fontkit, ubuntuFont);

    expect(embedder.encodeText(text)).toBeInstanceOf(PDFHexString);
    expect(String(embedder.encodeText(text))).toBe(
      String(PDFHexString.of(hexCodes)),
    );
  }


async () => {
    const text = 'Stuff and thingz!';
    const embedder = await CustomFontEmbedder.for(fontkit, ubuntuFont);
    expect(embedder.widthOfTextAtSize(text, 12)).toBe(90.672);
    expect(embedder.widthOfTextAtSize(text, 24)).toBe(181.344);
  }


async () => {
    const embedder = await CustomFontEmbedder.for(fontkit, ubuntuFont);
    expect(embedder.heightOfFontAtSize(12)).toBeCloseTo(13.452);
    expect(embedder.heightOfFontAtSize(24)).toBeCloseTo(26.904);
  }


async () => {
    const embedder = await CustomFontEmbedder.for(fontkit, ubuntuFont);
    expect(embedder.sizeOfFontAtHeight(12)).toBeCloseTo(10.705);
    expect(embedder.sizeOfFontAtHeight(24)).toBeCloseTo(21.409);
  }


export interface FormGroupWithInfoProps {
  label?: React.ReactNode;
  info?: JSX.Element | string;
  inlineInfo?: boolean;
  children?: React.ReactNode;
}


/**
 * Move movie.promotional.salesPitch to movie.promotional.videos.salesPitch
 * Change video type 'pitch' to 'other'
 * @param db
 * @param storage
 * @returns
 */
export async function upgrade(db: Firestore) {

  const movies = await db.collection('movies').get();
  await runChunks(movies.docs, async doc => {
    const movie = doc.data();

    if (!movie.promotional.videos) {
      movie.promotional.videos = createMovieVideos({});
    }

    movie.promotional.videos.salesPitch = createMovieVideo(movie.promotional.salesPitch);
    delete movie.promotional.salesPitch;

    if (movie.promotional.videos?.otherVideos?.length) {
      movie.promotional.videos.otherVideos.forEach(video => {
        if (video.type === 'pitch') {
          video.type = 'other';
        }
      });
    }

    await doc.ref.set(movie);
  })

  console.log('movie data model updated !');
}


async doc => {
    const movie = doc.data();

    if (!movie.promotional.videos) {
      movie.promotional.videos = createMovieVideos({});
    }

    movie.promotional.videos.salesPitch = createMovieVideo(movie.promotional.salesPitch);
    delete movie.promotional.salesPitch;

    if (movie.promotional.videos?.otherVideos?.length) {
      movie.promotional.videos.otherVideos.forEach(video => {
        if (video.type === 'pitch') {
          video.type = 'other';
        }
      });
    }

    await doc.ref.set(movie);
  }


video => {
        if (video.type === 'pitch') {
          video.type = 'other';
        }
      }


() => {
      this.getNewSeries(this.lastDate, {min: 10, max: 90});
      this.apexEvent.eventChangeSeriesData();
    }


() => {
      this.resetData();
      this.apexEvent.eventChangeSeriesData();
    }


() => {
      this.apexEvent.eventChangeTimeRange();
    }


@Component({
  selector: 'app-crt-apex',
  templateUrl: './crt-apex.component.html',
  styleUrls: ['./crt-apex.component.scss']
})
export class CrtApexComponent implements OnInit, OnDestroy {
  public chartDB: any;

  public lastDate: number;
  public line2CAC: any;
  public data: any;

  public intervalSub: any;
  public intervalMain: any;

  public dailyVisitorStatus: string;
  public dailyVisitorAxis: any;

  constructor(public apexEvent: ApexChartService) {
    this.chartDB = ChartDB;

    this.lastDate = 0;
    this.data = [];

    this.getDayWiseTimeSeries(new Date('11 Feb 2017 GMT').getTime(), 10, {min: 10, max: 90});
    this.line2CAC = {
      chart: {
        height: 300,
        type: 'line',
        animations: {
          enabled: true,
          easing: 'linear',
          dynamicAnimation: {
            speed: 2000
          }
        },
        toolbar: {
          show: false
        },
        zoom: {
          enabled: false
        }
      },
      dataLabels: {
        enabled: false
      },
      stroke: {
        curve: 'smooth'
      },
      series: [{
        data: this.data
      }],
      colors: ['#1abc9c'],
      title: {
        text: 'Dynamic Updating Chart',
        align: 'left'
      },
      markers: {
        size: 0
      },
      xaxis: {
        type: 'datetime',
        range: 777600000,
      },
      yaxis: {
        max: 100
      },
      legend: {
        show: false
      }
    };

    this.dailyVisitorStatus = '1y';
  }

  ngOnInit() {
    this.intervalSub = setInterval(() => {
      this.getNewSeries(this.lastDate, {min: 10, max: 90});
      this.apexEvent.eventChangeSeriesData();
    }, 2000);

    this.intervalMain = setInterval(() => {
      this.resetData();
      this.apexEvent.eventChangeSeriesData();
    }, 60000);
  }

  dailyVisitorEvent(status) {
    this.dailyVisitorStatus = status;
    switch (status) {
      case '1m':
        this.dailyVisitorAxis = {
          min: new Date('28 Jan 2013').getTime(),
          max: new Date('27 Feb 2013').getTime(),
        };
        break;
      case '6m':
        this.dailyVisitorAxis = {
          min: new Date('27 Sep 2012').getTime(),
          max: new Date('27 Feb 2013').getTime()
        };
        break;
      case '1y':
        this.dailyVisitorAxis = {
          min: new Date('27 Feb 2012').getTime(),
          max: new Date('27 Feb 2013').getTime()
        };
        break;
      case 'ytd':
        this.dailyVisitorAxis = {
          min: new Date('01 Jan 2013').getTime(),
          max: new Date('27 Feb 2013').getTime()
        };
        break;
      case 'all':
        this.dailyVisitorAxis = {
          min: undefined,
          max: undefined
        };
        break;
    }

    setTimeout(() => {
      this.apexEvent.eventChangeTimeRange();
    });
  }

  ngOnDestroy() {
    if (this.intervalSub) {
      clearInterval(this.intervalSub);
    }
    if (this.intervalMain) {
      clearInterval(this.intervalMain);
    }
  }

  getDayWiseTimeSeries(baseval, count, yrange) {
    let i = 0;
    while (i < count) {
      const x = baseval;
      const y = Math.floor(Math.random() * (yrange.max - yrange.min + 1)) + yrange.min;

      this.data.push({x, y});
      this.lastDate = baseval;
      baseval += 86400000;
      i++;
    }
  }

  resetData() {
    this.data = this.data.slice(this.data.length - 10, this.data.length);
  }

  getNewSeries(baseval, yrange) {
    const newDate = baseval + 86400000;
    this.lastDate = newDate;
    this.data.push({
      x: newDate,
      y: Math.floor(Math.random() * (yrange.max - yrange.min + 1)) + yrange.min
    });
  }

}


ngOnInit() {
    this.intervalSub = setInterval(() => {
      this.getNewSeries(this.lastDate, {min: 10, max: 90});
      this.apexEvent.eventChangeSeriesData();
    }, 2000);

    this.intervalMain = setInterval(() => {
      this.resetData();
      this.apexEvent.eventChangeSeriesData();
    }, 60000);
  }


dailyVisitorEvent(status) {
    this.dailyVisitorStatus = status;
    switch (status) {
      case '1m':
        this.dailyVisitorAxis = {
          min: new Date('28 Jan 2013').getTime(),
          max: new Date('27 Feb 2013').getTime(),
        };
        break;
      case '6m':
        this.dailyVisitorAxis = {
          min: new Date('27 Sep 2012').getTime(),
          max: new Date('27 Feb 2013').getTime()
        };
        break;
      case '1y':
        this.dailyVisitorAxis = {
          min: new Date('27 Feb 2012').getTime(),
          max: new Date('27 Feb 2013').getTime()
        };
        break;
      case 'ytd':
        this.dailyVisitorAxis = {
          min: new Date('01 Jan 2013').getTime(),
          max: new Date('27 Feb 2013').getTime()
        };
        break;
      case 'all':
        this.dailyVisitorAxis = {
          min: undefined,
          max: undefined
        };
        break;
    }

    setTimeout(() => {
      this.apexEvent.eventChangeTimeRange();
    });
  }


ngOnDestroy() {
    if (this.intervalSub) {
      clearInterval(this.intervalSub);
    }
    if (this.intervalMain) {
      clearInterval(this.intervalMain);
    }
  }


getDayWiseTimeSeries(baseval, count, yrange) {
    let i = 0;
    while (i < count) {
      const x = baseval;
      const y = Math.floor(Math.random() * (yrange.max - yrange.min + 1)) + yrange.min;

      this.data.push({x, y});
      this.lastDate = baseval;
      baseval += 86400000;
      i++;
    }
  }


resetData() {
    this.data = this.data.slice(this.data.length - 10, this.data.length);
  }


getNewSeries(baseval, yrange) {
    const newDate = baseval + 86400000;
    this.lastDate = newDate;
    this.data.push({
      x: newDate,
      y: Math.floor(Math.random() * (yrange.max - yrange.min + 1)) + yrange.min
    });
  }


declare class QueueManager extends Collection {
    constructor();

    textChannel: TextChannel;
    voiceChannel: VoiceChannel;
    connection: VoiceConnection;
    dispatcher?: AudioPlayer;
    songs: Array<PlayerSong>;
    volume: number;

    loop: {
        song: boolean;
        queue: boolean;
    }

    startStream: number;
    playing: boolean;
    filter: string;
}


export function main() {
  describe('NameList Service', () => {
    let nameListService: ProjectService;
    let mockBackend: MockBackend;
    let initialResponse: any;

    beforeEach(() => {

      let injector = ReflectiveInjector.resolveAndCreate([
        ProjectService,
        BaseRequestOptions,
        MockBackend,
        {provide: Http,
          useFactory: function(backend: ConnectionBackend, defaultOptions: BaseRequestOptions) {
            return new Http(backend, defaultOptions);
          },
          deps: [MockBackend, BaseRequestOptions]
        },
      ]);
      nameListService = injector.get(ProjectService);
      mockBackend = injector.get(MockBackend);

      let connection: any;
      mockBackend.connections.subscribe((c: any) => connection = c);
      initialResponse = nameListService.get();
      connection.mockRespond(new Response(new ResponseOptions({ body: '["Dijkstra", "Hopper"]' })));
    });

    it('should return an Observable when get called', () => {
      expect(initialResponse).toEqual(jasmine.any(Observable));
    });

    it('should resolve to list of names when get called', () => {
      let names: any;
      initialResponse.subscribe((data: any) => names = data);
      expect(names).toEqual(['Dijkstra', 'Hopper']);
    });
  });
}


() => {
    let nameListService: ProjectService;
    let mockBackend: MockBackend;
    let initialResponse: any;

    beforeEach(() => {

      let injector = ReflectiveInjector.resolveAndCreate([
        ProjectService,
        BaseRequestOptions,
        MockBackend,
        {provide: Http,
          useFactory: function(backend: ConnectionBackend, defaultOptions: BaseRequestOptions) {
            return new Http(backend, defaultOptions);
          },
          deps: [MockBackend, BaseRequestOptions]
        },
      ]);
      nameListService = injector.get(ProjectService);
      mockBackend = injector.get(MockBackend);

      let connection: any;
      mockBackend.connections.subscribe((c: any) => connection = c);
      initialResponse = nameListService.get();
      connection.mockRespond(new Response(new ResponseOptions({ body: '["Dijkstra", "Hopper"]' })));
    });

    it('should return an Observable when get called', () => {
      expect(initialResponse).toEqual(jasmine.any(Observable));
    });

    it('should resolve to list of names when get called', () => {
      let names: any;
      initialResponse.subscribe((data: any) => names = data);
      expect(names).toEqual(['Dijkstra', 'Hopper']);
    });
  }


() => {

      let injector = ReflectiveInjector.resolveAndCreate([
        ProjectService,
        BaseRequestOptions,
        MockBackend,
        {provide: Http,
          useFactory: function(backend: ConnectionBackend, defaultOptions: BaseRequestOptions) {
            return new Http(backend, defaultOptions);
          },
          deps: [MockBackend, BaseRequestOptions]
        },
      ]);
      nameListService = injector.get(ProjectService);
      mockBackend = injector.get(MockBackend);

      let connection: any;
      mockBackend.connections.subscribe((c: any) => connection = c);
      initialResponse = nameListService.get();
      connection.mockRespond(new Response(new ResponseOptions({ body: '["Dijkstra", "Hopper"]' })));
    }


(c: any) => connection = c


() => {
      expect(initialResponse).toEqual(jasmine.any(Observable));
    }


() => {
      let names: any;
      initialResponse.subscribe((data: any) => names = data);
      expect(names).toEqual(['Dijkstra', 'Hopper']);
    }


(data: any) => names = data


(): Promise<ICoin[]> => {
  return apiGet('supported-coins');
}


(accountCode: AccountCode, active: boolean): Promise<ISuccess> => {
  return apiPost('set-account-active', { accountCode, active });
}


(accountCode: AccountCode, tokenCode: string, active: boolean): Promise<ISuccess> => {
  return apiPost('set-token-active', { accountCode, tokenCode, active });
}


(accountCode: AccountCode, name: string): Promise<ISuccess> => {
  return apiPost('rename-account', { accountCode, name });
}


(): Promise<null> => {
  return apiPost('accounts/reinitialize');
}


(): Promise<boolean> => {
  return apiGet('testing');
}


(data: string) => {
  return (): Promise<string> => {
    return apiGet(`qr?data=${encodeURIComponent(data)}`);
  };
}


(): Promise<string> => {
    return apiGet(`qr?data=${encodeURIComponent(data)}`);
  }


export interface ICoin {
    coinCode: CoinCode;
    name: string;
    canAddAccount: boolean;
    suggestedAccountName: string;
}


export interface ISuccess {
    success: boolean;
    errorMessage?: string;
    errorCode?: string;
}


(props: UserAvatarProps): JSX.Element => {
    const {
        authState,
        gravatarInfoPopoverText,
        name,
        image,
        showGravatarLabel,
        showEdit,
        profileUrl,
        urlSchema,
        onAlertFired,
        ...rest
    } = props;

    const [userImage, setUserImage] = useState(null);
    const [showPopup, setShowPopup] = useState(false);
    const [showEditOverlay, setShowEditOverlay] = useState(false);
    const [showEditModal, setShowEditModal] = useState(false);
    const [url, setUrl] = useState("");
    const [urlError, setUrlError] = useState(Error.NONE);

    const { t } = useTranslation();
    const dispatch = useDispatch();

    // Check if the image is a promise, and resolve.
    useEffect(() => {
        if (image instanceof Promise) {
            image
                .then((response) => {
                    setUserImage(response);
                })
                .catch(() => {
                    setUserImage(null);
                });
        } else if (!_.isEmpty(image)) {
            setUserImage(image);
        }
    }, [image]);

    /**
     * Resolves the top label image.
     *
     * @return {string}
     */
    const resolveTopLabel = (): string => {
        if (isGravatarURL()) {
            return ThirdPartyLogos.gravatar;
        }

        return null;
    };

    /**
     * Checks if the image is from `Gravatar`.
     *
     * @return {boolean}
     */
    const isGravatarURL = (): boolean => {
        return (userImage && userImage.includes(UIConstants.GRAVATAR_URL))
            || (authState && authState.profileInfo && authState.profileInfo.userImage
                && authState.profileInfo.userImage.includes(UIConstants.GRAVATAR_URL))
            || (authState && authState.profileInfo && authState.profileInfo.profileUrl
                && authState.profileInfo.profileUrl.includes(UIConstants.GRAVATAR_URL));
    };

    /**
     * Handles the mouse over event.
     *
     * @param {MouseEvent} e - Mouse event.
     */
    const handleOnMouseOver = (e: MouseEvent) => {
        setShowPopup(true);
    };

    /**
     * Handles the mouse out event.
     *
     * @param {MouseEvent} e - Mouse event.
     */
    const handleOnMouseOut = (e: MouseEvent) => {
        setShowPopup(false);
    };

    /**
     * This contains the Avatar component
     */
    const avatar = (
        <Avatar
            avatar
            avatarType="user"
            bordered={ false }
            image={
                (authState && authState.profileInfo
                    && (authState.profileInfo.profileUrl || authState.profileInfo.userImage))
                    ?
                    authState.profileInfo.profileUrl
                        ? authState.profileInfo.profileUrl
                        : authState.profileInfo.userImage
                    :
                    userImage
            }


() => {
        if (image instanceof Promise) {
            image
                .then((response) => {
                    setUserImage(response);
                })
                .catch(() => {
                    setUserImage(null);
                });
        } else if (!_.isEmpty(image)) {
            setUserImage(image);
        }
    }


(response) => {
                    setUserImage(response);
                }


() => {
                    setUserImage(null);
                }