interface WebSocket extends EventTarget {
    binaryType: string;
    bufferedAmount: number;
    extensions: string;
    onclose: (ev: CloseEvent) => any;
    onerror: (ev: Event) => any;
    onmessage: (ev: MessageEvent) => any;
    onopen: (ev: Event) => any;
    protocol: string;
    readyState: number;
    url: string;
    close(code?: number, reason?: string): void;
    send(data: any): void;
    CLOSED: number;
    CLOSING: number;
    CONNECTING: number;
    OPEN: number;
    addEventListener(type: "close", listener: (ev: CloseEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "open", listener: (ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}


interface WheelEvent extends MouseEvent {
    deltaMode: number;
    deltaX: number;
    deltaY: number;
    deltaZ: number;
    getCurrentPoint(element: Element): void;
    initWheelEvent(typeArg: string, canBubbleArg: boolean, cancelableArg: boolean, viewArg: Window, detailArg: number, screenXArg: number, screenYArg: number, clientXArg: number, clientYArg: number, buttonArg: number, relatedTargetArg: EventTarget, modifiersListArg: string, deltaXArg: number, deltaYArg: number, deltaZArg: number, deltaMode: number): void;
    DOM_DELTA_LINE: number;
    DOM_DELTA_PAGE: number;
    DOM_DELTA_PIXEL: number;
}


interface Worker extends EventTarget, AbstractWorker {
    onmessage: (ev: MessageEvent) => any;
    postMessage(message: any, ports?: any): void;
    terminate(): void;
    addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}


interface XMLDocument extends Document {
}


interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget {
    msCaching: string;
    onreadystatechange: (ev: ProgressEvent) => any;
    readyState: number;
    response: any;
    responseBody: any;
    responseText: string;
    responseType: string;
    responseXML: any;
    status: number;
    statusText: string;
    timeout: number;
    upload: XMLHttpRequestUpload;
    withCredentials: boolean;
    abort(): void;
    getAllResponseHeaders(): string;
    getResponseHeader(header: string): string;
    msCachingEnabled(): boolean;
    open(method: string, url: string, async?: boolean, user?: string, password?: string): void;
    overrideMimeType(mime: string): void;
    send(data?: Document): void;
    send(data?: string): void;
    send(data?: any): void;
    setRequestHeader(header: string, value: string): void;
    DONE: number;
    HEADERS_RECEIVED: number;
    LOADING: number;
    OPENED: number;
    UNSENT: number;
    addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "readystatechange", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "timeout", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}


interface XMLHttpRequestUpload extends EventTarget, XMLHttpRequestEventTarget {
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}


interface XMLSerializer {
    serializeToString(target: Node): string;
}


interface XPathEvaluator {
    createExpression(expression: string, resolver: XPathNSResolver): XPathExpression;
    createNSResolver(nodeResolver?: Node): XPathNSResolver;
    evaluate(expression: string, contextNode: Node, resolver: XPathNSResolver, type: number, result: XPathResult): XPathResult;
}


interface XPathExpression {
    evaluate(contextNode: Node, type: number, result: XPathResult): XPathExpression;
}


interface XPathNSResolver {
    lookupNamespaceURI(prefix: string): string;
}


interface XPathResult {
    booleanValue: boolean;
    invalidIteratorState: boolean;
    numberValue: number;
    resultType: number;
    singleNodeValue: Node;
    snapshotLength: number;
    stringValue: string;
    iterateNext(): Node;
    snapshotItem(index: number): Node;
    ANY_TYPE: number;
    ANY_UNORDERED_NODE_TYPE: number;
    BOOLEAN_TYPE: number;
    FIRST_ORDERED_NODE_TYPE: number;
    NUMBER_TYPE: number;
    ORDERED_NODE_ITERATOR_TYPE: number;
    ORDERED_NODE_SNAPSHOT_TYPE: number;
    STRING_TYPE: number;
    UNORDERED_NODE_ITERATOR_TYPE: number;
    UNORDERED_NODE_SNAPSHOT_TYPE: number;
}


interface XSLTProcessor {
    clearParameters(): void;
    getParameter(namespaceURI: string, localName: string): any;
    importStylesheet(style: Node): void;
    removeParameter(namespaceURI: string, localName: string): void;
    reset(): void;
    setParameter(namespaceURI: string, localName: string, value: any): void;
    transformToDocument(source: Node): Document;
    transformToFragment(source: Node, document: Document): DocumentFragment;
}


interface AbstractWorker {
    onerror: (ev: Event) => any;
    addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}


interface ChildNode {
    remove(): void;
}


interface DOML2DeprecatedColorProperty {
    color: string;
}


interface DOML2DeprecatedSizeProperty {
    size: number;
}


interface DocumentEvent {
    createEvent(eventInterface:"AnimationEvent"): AnimationEvent;
    createEvent(eventInterface:"AriaRequestEvent"): AriaRequestEvent;
    createEvent(eventInterface:"AudioProcessingEvent"): AudioProcessingEvent;
    createEvent(eventInterface:"BeforeUnloadEvent"): BeforeUnloadEvent;
    createEvent(eventInterface:"ClipboardEvent"): ClipboardEvent;
    createEvent(eventInterface:"CloseEvent"): CloseEvent;
    createEvent(eventInterface:"CommandEvent"): CommandEvent;
    createEvent(eventInterface:"CompositionEvent"): CompositionEvent;
    createEvent(eventInterface:"CustomEvent"): CustomEvent;
    createEvent(eventInterface:"DeviceMotionEvent"): DeviceMotionEvent;
    createEvent(eventInterface:"DeviceOrientationEvent"): DeviceOrientationEvent;
    createEvent(eventInterface:"DragEvent"): DragEvent;
    createEvent(eventInterface:"ErrorEvent"): ErrorEvent;
    createEvent(eventInterface:"Event"): Event;
    createEvent(eventInterface:"Events"): Event;
    createEvent(eventInterface:"FocusEvent"): FocusEvent;
    createEvent(eventInterface:"GamepadEvent"): GamepadEvent;
    createEvent(eventInterface:"HashChangeEvent"): HashChangeEvent;
    createEvent(eventInterface:"IDBVersionChangeEvent"): IDBVersionChangeEvent;
    createEvent(eventInterface:"KeyboardEvent"): KeyboardEvent;
    createEvent(eventInterface:"LongRunningScriptDetectedEvent"): LongRunningScriptDetectedEvent;
    createEvent(eventInterface:"MSGestureEvent"): MSGestureEvent;
    createEvent(eventInterface:"MSManipulationEvent"): MSManipulationEvent;
    createEvent(eventInterface:"MSMediaKeyMessageEvent"): MSMediaKeyMessageEvent;
    createEvent(eventInterface:"MSMediaKeyNeededEvent"): MSMediaKeyNeededEvent;
    createEvent(eventInterface:"MSPointerEvent"): MSPointerEvent;
    createEvent(eventInterface:"MSSiteModeEvent"): MSSiteModeEvent;
    createEvent(eventInterface:"MessageEvent"): MessageEvent;
    createEvent(eventInterface:"MouseEvent"): MouseEvent;
    createEvent(eventInterface:"MouseEvents"): MouseEvent;
    createEvent(eventInterface:"MouseWheelEvent"): MouseWheelEvent;
    createEvent(eventInterface:"MutationEvent"): MutationEvent;
    createEvent(eventInterface:"MutationEvents"): MutationEvent;
    createEvent(eventInterface:"NavigationCompletedEvent"): NavigationCompletedEvent;
    createEvent(eventInterface:"NavigationEvent"): NavigationEvent;
    createEvent(eventInterface:"NavigationEventWithReferrer"): NavigationEventWithReferrer;
    createEvent(eventInterface:"OfflineAudioCompletionEvent"): OfflineAudioCompletionEvent;
    createEvent(eventInterface:"PageTransitionEvent"): PageTransitionEvent;
    createEvent(eventInterface:"PermissionRequestedEvent"): PermissionRequestedEvent;
    createEvent(eventInterface:"PointerEvent"): PointerEvent;
    createEvent(eventInterface:"PopStateEvent"): PopStateEvent;
    createEvent(eventInterface:"ProgressEvent"): ProgressEvent;
    createEvent(eventInterface:"SVGZoomEvent"): SVGZoomEvent;
    createEvent(eventInterface:"SVGZoomEvents"): SVGZoomEvent;
    createEvent(eventInterface:"ScriptNotifyEvent"): ScriptNotifyEvent;
    createEvent(eventInterface:"StorageEvent"): StorageEvent;
    createEvent(eventInterface:"TextEvent"): TextEvent;
    createEvent(eventInterface:"TouchEvent"): TouchEvent;
    createEvent(eventInterface:"TrackEvent"): TrackEvent;
    createEvent(eventInterface:"TransitionEvent"): TransitionEvent;
    createEvent(eventInterface:"UIEvent"): UIEvent;
    createEvent(eventInterface:"UIEvents"): UIEvent;
    createEvent(eventInterface:"UnviewableContentIdentifiedEvent"): UnviewableContentIdentifiedEvent;
    createEvent(eventInterface:"WebGLContextEvent"): WebGLContextEvent;
    createEvent(eventInterface:"WheelEvent"): WheelEvent;
    createEvent(eventInterface: string): Event;
}


interface ElementTraversal {
    childElementCount: number;
    firstElementChild: Element;
    lastElementChild: Element;
    nextElementSibling: Element;
    previousElementSibling: Element;
}


interface GetSVGDocument {
    getSVGDocument(): Document;
}


interface GlobalEventHandlers {
    onpointercancel: (ev: PointerEvent) => any;
    onpointerdown: (ev: PointerEvent) => any;
    onpointerenter: (ev: PointerEvent) => any;
    onpointerleave: (ev: PointerEvent) => any;
    onpointermove: (ev: PointerEvent) => any;
    onpointerout: (ev: PointerEvent) => any;
    onpointerover: (ev: PointerEvent) => any;
    onpointerup: (ev: PointerEvent) => any;
    onwheel: (ev: WheelEvent) => any;
    addEventListener(type: "pointercancel", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "pointerdown", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "pointerenter", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "pointerleave", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "pointermove", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "pointerout", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "pointerover", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "pointerup", listener: (ev: PointerEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "wheel", listener: (ev: WheelEvent) => any, useCapture?: boolean): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}


interface HTMLTableAlignment {
    /**
      * Sets or retrieves a value that you can use to implement your own ch functionality for the object.
      */
    ch: string;
    /**
      * Sets or retrieves a value that you can use to implement your own chOff functionality for the object.
      */
    chOff: string;
    /**
      * Sets or retrieves how text and other content are vertically aligned within the object that contains them.
      */
    vAlign: string;
}


interface IDBEnvironment {
    indexedDB: IDBFactory;
    msIndexedDB: IDBFactory;
}


interface LinkStyle {
    sheet: StyleSheet;
}


interface MSBaseReader {
    onabort: (ev: Event) => any;
    onerror: (ev: Event) => any;
    onload: (ev: Event) => any;
    onloadend: (ev: ProgressEvent) => any;
    onloadstart: (ev: Event) => any;
    onprogress: (ev: ProgressEvent) => any;
    readyState: number;
    result: any;
    abort(): void;
    DONE: number;
    EMPTY: number;
    LOADING: number;
    addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}


interface MSFileSaver {
    msSaveBlob(blob: any, defaultName?: string): boolean;
    msSaveOrOpenBlob(blob: any, defaultName?: string): boolean;
}


interface MSNavigatorDoNotTrack {
    confirmSiteSpecificTrackingException(args: ConfirmSiteSpecificExceptionsInformation): boolean;
    confirmWebWideTrackingException(args: ExceptionInformation): boolean;
    removeSiteSpecificTrackingException(args: ExceptionInformation): void;
    removeWebWideTrackingException(args: ExceptionInformation): void;
    storeSiteSpecificTrackingException(args: StoreSiteSpecificExceptionsInformation): void;
    storeWebWideTrackingException(args: StoreExceptionsInformation): void;
}


interface NavigatorContentUtils {
}


interface NavigatorGeolocation {
    geolocation: Geolocation;
}


interface NavigatorID {
    appName: string;
    appVersion: string;
    platform: string;
    product: string;
    productSub: string;
    userAgent: string;
    vendor: string;
    vendorSub: string;
}


interface NavigatorOnLine {
    onLine: boolean;
}


interface NavigatorStorageUtils {
}


interface NodeSelector {
    querySelector(selectors: string): Element;
    querySelectorAll(selectors: string): NodeListOf<Element>;
}


interface RandomSource {
    getRandomValues(array: ArrayBufferView): ArrayBufferView;
}


interface SVGAnimatedPathData {
    pathSegList: SVGPathSegList;
}


interface SVGAnimatedPoints {
    animatedPoints: SVGPointList;
    points: SVGPointList;
}


interface SVGExternalResourcesRequired {
    externalResourcesRequired: SVGAnimatedBoolean;
}


interface SVGFilterPrimitiveStandardAttributes extends SVGStylable {
    height: SVGAnimatedLength;
    result: SVGAnimatedString;
    width: SVGAnimatedLength;
    x: SVGAnimatedLength;
    y: SVGAnimatedLength;
}


interface SVGFitToViewBox {
    preserveAspectRatio: SVGAnimatedPreserveAspectRatio;
    viewBox: SVGAnimatedRect;
}


interface SVGLangSpace {
    xmllang: string;
    xmlspace: string;
}


interface SVGLocatable {
    farthestViewportElement: SVGElement;
    nearestViewportElement: SVGElement;
    getBBox(): SVGRect;
    getCTM(): SVGMatrix;
    getScreenCTM(): SVGMatrix;
    getTransformToElement(element: SVGElement): SVGMatrix;
}


interface SVGStylable {
    className: any;
    style: CSSStyleDeclaration;
}


interface SVGTests {
    requiredExtensions: SVGStringList;
    requiredFeatures: SVGStringList;
    systemLanguage: SVGStringList;
    hasExtension(extension: string): boolean;
}


interface SVGTransformable extends SVGLocatable {
    transform: SVGAnimatedTransformList;
}


interface SVGURIReference {
    href: SVGAnimatedString;
}


interface WindowBase64 {
    atob(encodedString: string): string;
    btoa(rawString: string): string;
}


interface WindowConsole {
    console: Console;
}


interface WindowLocalStorage {
    localStorage: Storage;
}


interface WindowSessionStorage {
    sessionStorage: Storage;
}


interface WindowTimers extends Object, WindowTimersExtension {
    clearInterval(handle: number): void;
    clearTimeout(handle: number): void;
    setInterval(handler: any, timeout?: any, ...args: any[]): number;
    setTimeout(handler: any, timeout?: any, ...args: any[]): number;
}


interface WindowTimersExtension {
    clearImmediate(handle: number): void;
    msClearImmediate(handle: number): void;
    msSetImmediate(expression: any, ...args: any[]): number;
    setImmediate(expression: any, ...args: any[]): number;
}


interface XMLHttpRequestEventTarget {
    onabort: (ev: Event) => any;
    onerror: (ev: Event) => any;
    onload: (ev: Event) => any;
    onloadend: (ev: ProgressEvent) => any;
    onloadstart: (ev: Event) => any;
    onprogress: (ev: ProgressEvent) => any;
    ontimeout: (ev: ProgressEvent) => any;
    addEventListener(type: "abort", listener: (ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: "error", listener: (ev: ErrorEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "load", listener: (ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: "loadend", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "loadstart", listener: (ev: Event) => any, useCapture?: boolean): void;
    addEventListener(type: "progress", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
    addEventListener(type: "timeout", listener: (ev: ProgressEvent) => any, useCapture?: boolean): void;
    addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void;
}


interface StorageEventInit extends EventInit {
    key?: string;
    oldValue?: string;
    newValue?: string;
    url: string;
    storageArea?: Storage;
}


interface IDBObjectStoreParameters {
    keyPath?: string | string[];
    autoIncrement?: boolean;
}


interface IDBIndexParameters {
    unique?: boolean;
    multiEntry?: boolean;
}


interface NodeListOf<TNode extends Node> extends NodeList {
    length: number;
    item(index: number): TNode;
    [index: number]: TNode;
}


interface BlobPropertyBag {
    type?: string;
    endings?: string;
}


interface FilePropertyBag {
    type?: string;
    lastModified?: number;
}


interface EventListenerObject {
    handleEvent(evt: Event): void;
}


interface MessageEventInit extends EventInit {
    data?: any;
    origin?: string;
    lastEventId?: string;
    channel?: string;
    source?: any;
    ports?: MessagePort[];
}


interface ProgressEventInit extends EventInit {
    lengthComputable?: boolean;
    loaded?: number;
    total?: number;
}


interface HTMLTemplateElement extends HTMLElement {
    content: DocumentFragment;
}


interface HTMLPictureElement extends HTMLElement {
}


interface ErrorEventHandler {
    (message: string, filename?: string, lineno?: number, colno?: number, error?:Error): void;
}


interface PositionCallback {
    (position: Position): void;
}


interface PositionErrorCallback {
    (error: PositionError): void;
}


interface MediaQueryListListener {
    (mql: MediaQueryList): void;
}


interface MSLaunchUriCallback {
    (): void;
}


interface FrameRequestCallback {
    (time: number): void;
}


interface MSUnsafeFunctionCallback {
    (): any;
}


interface MSExecAtPriorityFunctionCallback {
    (...args: any[]): any;
}


interface MutationCallback {
    (mutations: MutationRecord[], observer: MutationObserver): void;
}


interface DecodeSuccessCallback {
    (decodedData: AudioBuffer): void;
}


interface DecodeErrorCallback {
    (): void;
}


interface FunctionStringCallback {
    (data: string): void;
}


declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject;


//  Reducer
export default function reducer(
    state: InnloggingsstatusState = initialState,
    action: Handling
): InnloggingsstatusState {
    switch (action.type) {
        case ActionType.HENT_INNLOGGINGSSTATUS_OK: {
            return { ...state, status: Status.OK, data: action.data };
        }
        case ActionType.HENT_INNLOGGINGSSTATUS_PENDING:
            if (state.status === Status.OK) {
                return { ...state, status: Status.RELOADING };
            }
            return { ...state, status: Status.PENDING };
        case ActionType.HENT_INNLOGGINGSSTATUS_FEILET:
            return { ...state, status: Status.FEILET };
        default:
            return state;
    }
}


export function hentInnloggingsstatus(
    API_INNLOGGINGSLINJE_URL: string
): (dispatch: Dispatch) => Promise<void> {
    return fetchThenDispatch<Data>(
        () => hentInnloggingsstatusFetch(API_INNLOGGINGSLINJE_URL),
        {
            ok: hentInnloggingsstatusOk,
            feilet: hentnnloggingsstatusFeilet,
            pending: hentnnloggingsstatusPending,
        }
    );
}


export function hentInnloggingsstatusOk(
    data: Data
): HentInnloggingsstatusOKAction {
    return {
        type: ActionType.HENT_INNLOGGINGSSTATUS_OK,
        data: data,
    };
}


export function hentnnloggingsstatusFeilet(): HentInnloggingsstatusFEILETAction {
    return {
        type: ActionType.HENT_INNLOGGINGSSTATUS_FEILET,
    };
}


export function hentnnloggingsstatusPending(): HentInnloggingsstatusPENDINGAction {
    return {
        type: ActionType.HENT_INNLOGGINGSSTATUS_PENDING,
    };
}


() => hentInnloggingsstatusFetch(API_INNLOGGINGSLINJE_URL)


export interface InnloggingsstatusState extends DataElement {
    data: Data;
}


export interface Data {
    authenticated: boolean;
    name: string;
    securityLevel: string;
}


() => <img src


(props: {path?: string}) => {
    const [loading, setLoading] = React.useState(true);
    React.useEffect(() => {
        setTimeout(() => setLoading(false), 500);
    }, []);

    const showWelcome = loading && !props.path;
    return (
        <Link to='/' className='rollouts-header__brand'>
            <Logo />

                <div className='rollouts-header__welcome' style={{opacity: showWelcome ? 1 : 0, transform: showWelcome ? 'none' : 'scaleX(0.01)'}}


() => {
        setTimeout(() => setLoading(false), 500);
    }


(props: {pageHasShortcuts: boolean; showHelp: () => void}) => {
    const getNs = React.useCallback(() => new RolloutServiceApi().rolloutServiceGetNamespace(), []);
    const namespace = useServerData<RolloutNamespaceInfo>(getNs).namespace || 'Unknown';
    const {name} = useParams<{name: string}>();
    const api = React.useContext(RolloutAPIContext);
    const [version, setVersion] = React.useState('v?');
    React.useEffect(() => {
        const getVersion = async () => {
            const v = await api.rolloutServiceVersion();
            setVersion(v.rolloutsVersion);
        };
        getVersion();
    });
    return (
        <header className='rollouts-header'>
            <Brand path={name} />
            <div className='rollouts-header__info'>
                {props.pageHasShortcuts && (
                    <Tooltip content='Keyboard Shortcuts' inverted>
                        <ActionButton icon={faKeyboard} action={props.showHelp} dark />
                    </Tooltip>


() => new RolloutServiceApi().rolloutServiceGetNamespace()


() => {
        const getVersion = async () => {
            const v = await api.rolloutServiceVersion();
            setVersion(v.rolloutsVersion);
        };
        getVersion();
    }


async () => {
            const v = await api.rolloutServiceVersion();
            setVersion(v.rolloutsVersion);
        }


export class MenuState extends State {
    prefabHandle!: TGroupHandle;

    activate(actions: ITransitionActions) {
        actions.getResource(GameStore).currentState = this;
        this.prefabHandle = actions.commands.load(SerialFormat.fromArray(menuPrefab));
        actions.commands.maintain();
    }

    deactivate(actions: ITransitionActions) {
        actions.commands.unloadPrefab(this.prefabHandle);
        actions.commands.maintain();
    }
}


activate(actions: ITransitionActions) {
        actions.getResource(GameStore).currentState = this;
        this.prefabHandle = actions.commands.load(SerialFormat.fromArray(menuPrefab));
        actions.commands.maintain();
    }


deactivate(actions: ITransitionActions) {
        actions.commands.unloadPrefab(this.prefabHandle);
        actions.commands.maintain();
    }


@Component({
  selector: 'core-shell-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class ShellHeaderComponent implements OnInit {
  moviesCount: Observable<number>;
  actorsCount: Observable<number>;

  constructor(
    private router: Router,
    private actorsStore: Store<ActorsState>,
    private moviesStore: Store<MoviesState>
  ) {
    this.actorsCount = this.actorsStore.select(ActorsReducer.getActorsCount);
    this.moviesCount = this.moviesStore.select(MoviesReducer.getMoviesCount);
  }

  ngOnInit() {}

  navigate(url: string) {
    this.router.navigate([url]);
  }
}


navigate(url: string) {
    this.router.navigate([url]);
  }


/**
 * Created by dattaram on 13/2/19.
 */
export class PageInfo {
  pageNumber:  number;
  startIndex: number;
  endIndex: number;
  constructor(pN: number, eI: number, rows: number) {
    this.pageNumber = pN;
    this.endIndex = eI;
    this.startIndex = (this.endIndex - rows + 1);
  }
}


(theme) => ({
    buttonInterior: {
        textAlign: 'center',
        width: 'inherit',
        height: 'inherit',
    },
    label: {
        fontSize: 70,
        color: theme.palette.type === 'dark' ? lighten(theme.palette.text.primary, 1) : theme.palette.text.primary,
        //'Primary' in dark mode is not white, which creates too low of a contrast
    },
    button: {
        textTransform: 'none',
        width: '100%',
        height: '100%',
        background: theme.palette.background.paper,
    },
    buttonSubtext: {
        fontSize: 30,
        marginBottom: 32,
        paddingLeft: theme.spacing(1),
        paddingRight: theme.spacing(1),
        color: theme.palette.text.disabled,
    },
    productIcon: {
        marginTop: 24, //Icon is in a 32 x 32 box so adjust its origin before expanding it (this centers the icon inline)
        fontSize: 70,
    },
    circleCheckIcon: {
        top: '0px',
        right: '0px',
        position: 'absolute',
        margin: '7px',
        color: 'LimeGreen',
    },
})


({
    label,
    enabled,
    onToggle,
    subtext,
    ProductIcon,
}) => {
    const classes = useStyles();

    const handleToggle = useCallback(() => {
        onToggle(!enabled);
    }, [enabled, onToggle]);

    return (
        <Tooltip title={enabled ? `Disable ${label} features` : `Enable ${label} features`}


() => {
        onToggle(!enabled);
    }


export type AltProductEnablerProps = {
    label: string;
    enabled: boolean;
    onToggle: (enabled: boolean) => void;
    subtext: string;
    ProductIcon: React.ReactNode;
};


export class Settings {
    public buildId: number;
    public projectId: string;
    public releaseId: number | null;
    public definitionId: number | null;
    public definitionEnvironmentId: number | null;
    public requestedFor: string;
    public workitemsSource: string;
    public workitemsSourceQuery: string;
    public workItemType: string;
    public allWorkItemsSinceLastRelease: boolean;
    public workItemState: string;
    public workItemCurrentState: string;
    public workItemKanbanLane: string;
    public workItemKanbanState: string;
    public workItemDone: boolean;
    public linkBuild: boolean;
    public updateAssignedTo: string;
    public updateAssignedToWith: string;
    public assignedTo: string;
    public addTags: string;
    public removeTags: string;
}


[Mutations.SET_LOAD_FLAG] (state: any, value: boolean) {
      state.loadFlag = value
    }


[Mutations.SET_FILE_PATH] (state: any, value: string) {
      state.filePath = value
    }


[Mutations.SET_LAYOUT] (state: any, value: string) {
      state.layout = value
    }


[Mutations.SET_THEME] (state: any, value: string) {
      state.theme = value
    }


[Mutations.SET_LINE_WRAPPING] (state: any, value: boolean) {
      state.lineWrapping = value
    }


/**
 * @name Launch Navigator
 * @description
 * Requires Cordova plugin: uk.co.workingedge.phonegap.plugin.launchnavigator. For more info, please see the [LaunchNavigator plugin docs](https://github.com/dpa99c/phonegap-launch-navigator).
 *
 * @usage
 * Please refer to the plugin's repo for detailed usage. This docs page only explains the Native wrapper.
 *
 * ```typescript
 * import { LaunchNavigator, LaunchNavigatorOptions } from '@ionic-native/launch-navigator';
 *
 * constructor(private launchNavigator: LaunchNavigator) { }
 *
 * ...
 *
 * let options: LaunchNavigatorOptions = {
 *   start: 'London, ON',
 *   app: LaunchNavigator.APPS.UBER
 * };
 *
 * this.launchNavigator.navigate('Toronto, ON', options)
 *   .then(
 *     success => console.log('Launched navigator'),
 *     error => console.log('Error launching navigator', error)
 *   );
 * ```
 * @interfaces
 * LaunchNavigatorOptions
 * PromptsOptions
 * RememberChoiceOptions
 * AppSelectionOptions
 * UserChoice
 * UserPrompted
 * AppSelection
 */
@Plugin({
  pluginName: 'LaunchNavigator',
  plugin: 'uk.co.workingedge.phonegap.plugin.launchnavigator',
  pluginRef: 'launchnavigator',
  repo: 'https://github.com/dpa99c/phonegap-launch-navigator',
  platforms: ['Android', 'iOS', 'Windows', 'Windows Phone 8']
})
@Injectable()
export class LaunchNavigator extends IonicNativePlugin {

  APP: any = {
    USER_SELECT: 'user_select',
    APPLE_MAPS: 'apple_maps',
    GOOGLE_MAPS: 'google_maps',
    WAZE: 'waze',
    CITYMAPPER: 'citymapper',
    NAVIGON: 'navigon',
    TRANSIT_APP: 'transit_app',
    YANDEX: 'yandex',
    UBER: 'uber',
    TOMTOM: 'tomtom',
    BING_MAPS: 'bing_maps',
    SYGIC: 'sygic',
    HERE_MAPS: 'here_maps',
    MOOVIT: 'moovit'
  };

  TRANSPORT_MODE: any = {
    DRIVING: 'driving',
    WALKING: 'walking',
    BICYCLING: 'bicycling',
    TRANSIT: 'transit'
  };

  /**
   * Launches navigator app
   * @param destination {string|number[]} Location name or coordinates (as string or array)
   * @param options {LaunchNavigatorOptions}
   * @returns {Promise<any>}
   */
  @Cordova({
    successIndex: 2,
    errorIndex: 3
  })
  navigate(destination: string | number[], options?: LaunchNavigatorOptions): Promise<any> { return; }

  /**
   * Determines if the given app is installed and available on the current device.
   * @param app {string}
   * @returns {Promise<any>}
   */
  @Cordova()
  isAppAvailable(app: string): Promise<any> { return; }

  /**
   * Returns a list indicating which apps are installed and available on the current device.
   * @returns {Promise<string[]>}
   */
  @Cordova()
  availableApps(): Promise<string[]> { return; }

  /**
   * Returns the display name of the specified app.
   * @param app {string}
   * @returns {string}
   */
  @Cordova({ sync: true })
  getAppDisplayName(app: string): string { return; }

  /**
   * Returns list of supported apps on a given platform.
   * @param platform {string}
   * @returns {string[]}
   */
  @Cordova({ sync: true })
  getAppsForPlatform(platform: string): string[] { return; }

  /**
   * Indicates if an app on a given platform supports specification of transport mode.
   * @param app {string} specified as a string, you can use one of the constants, e.g `LaunchNavigator.APP.GOOGLE_MAPS`
   * @param platform {string}
   * @returns {boolean}
   */
  @Cordova({ sync: true })
  supportsTransportMode(app: string, platform: string): boolean { return; }

  /**
   * Returns the list of transport modes supported by an app on a given platform.
   * @param app {string}
   * @param platform {string}
   * @returns {string[]}
   */
  @Cordova({ sync: true })
  getTransportModes(app: string, platform: string): string[] { return; }

  /**
   * @param app {string}
   * @param platform {string}
   * @returns {boolean}
   */
  @Cordova({ sync: true })
  supportsDestName(app: string, platform: string): boolean { return; }

  /**
   * Indicates if an app on a given platform supports specification of start location.
   * @param app {string}
   * @param platform {string}
   * @returns {boolean}
   */
  @Cordova({ sync: true })
  supportsStart(app: string, platform: string): boolean { return; }

  /**
   * @param app {string}
   * @param platform {string}
   * @returns {boolean}
   */
  @Cordova({ sync: true })
  supportsStartName(app: string, platform: string): boolean { return; }

  /**
   * Indicates if an app on a given platform supports specification of launch mode.
   * Note that currently only Google Maps on Android does.
   * @param app {string}
   * @param platform {string}
   * @returns {boolean}
   */
  @Cordova({ sync: true })
  supportsLaunchMode(app: string, platform: string): boolean { return; }

  /**
   * @param destination {string | number[]}
   * @param options {LaunchNavigatorOptions}
   */
  @Cordova({ sync: true })
  userSelect(destination: string | number[], options: LaunchNavigatorOptions): void {}

  appSelection: AppSelection;
}


export interface PromptsOptions {

  /**
   * a function to pass the user's decision whether to remember their choice of app.
   * This will be passed a single boolean value indicating the user's decision.
   * @param rememberChoice
   */
  callback?: (rememberChoice: boolean) => void;

  /**
   * text to display in the native prompt header asking user whether to remember their choice.
   * Defaults to "Remember your choice?" if not specified.
   */
  headerText?: string;

  /**
   * text to display in the native prompt body asking user whether to remember their choice.
   * Defaults to "Use the same app for navigating next time?" if not specified.
   */
  bodyText?: string;

  /**
   * text to display for the Yes button.
   * Defaults to "Yes" if not specified.
   */
  yesButtonText?: string;

  /**
   * text to display for the No button.
   * Defaults to "No" if not specified.
   */
  noButtonText?: string;
}


export interface RememberChoiceOptions {

  /**
   * whether to remember user choice of app for next time, instead of asking again for user choice.
   * `"prompt"` - Prompt user to decide whether to remember choice.
   *  - Default value if unspecified.
   *  - If `promptFn` is defined, this will be used for user confirmation.
   *  - Otherwise (by default), a native dialog will be displayed to ask user.
   * `false` - Do not remember user choice.
   * `true` - Remember user choice.
   */
  enabled?: boolean | string;

  /**
   * a function which asks the user whether to remember their choice of app.
   * If this is defined, then the default dialog prompt will not be shown, allowing for a custom UI for asking the user.
   * This will be passed a callback function which should be invoked with a single boolean argument which indicates the user's decision to remember their choice.
   * @param callback
   */
  promptFn?: (callback: (rememberChoice: boolean) => void) => void;

  /**
   * options related to the default dialog prompt used to ask the user whether to remember their choice of app.
   */
  prompt?: PromptsOptions;
}


export interface AppSelectionOptions {
  /**
   * text to display in the native picker which enables user to select which navigation app to launch.
   * Defaults to "Select app for navigation" if not specified.
   */
  dialogHeaderText?: string;

  /**
   * text to display for the cancel button in the native picker which enables user to select which navigation app to launch.
   * Defaults to "Cancel" if not specified.
   */
  cancelButtonText?: string;

  /**
   * List of apps, defined as `launchnavigator.APP` constants, which should be displayed in the picker if the app is available.
   * This can be used to restrict which apps are displayed, even if they are installed.
   * By default, all available apps will be displayed.
   */
  list?: string[];

  /**
   * Callback to invoke when the user selects an app in the native picker.
   * A single string argument is passed which is the app what was selected defined as a `launchnavigator.APP` constant.
   */
  callback?: (app: string) => void;

  /**
   * (Android only) native picker theme. Specify using `actionsheet.ANDROID_THEMES` constants.
   * Default `actionsheet.ANDROID_THEMES.THEME_HOLO_LIGHT`
   */
  androidTheme?: number;

  /**
   * options related to whether to remember user choice of app for next time, instead of asking again for user choice.
   */
  rememberChoice?: RememberChoiceOptions;
}


export interface LaunchNavigatorOptions {

  /**
   * A callback to invoke when the navigation app is successfully launched.
   */
  successCallback?: Function;

  /**
   * A callback to invoke if an error is encountered while launching the app.
   * A single string argument containing the error message will be passed in.
   */
  errorCallback?: (error: string) => void;

  /**
   * name of the navigation app to use for directions.
   * Specify using launchnavigator.APP constants.
   * e.g. `launchnavigator.APP.GOOGLE_MAPS`.
   * If not specified, defaults to User Selection.
   */
  app?: string;

  /**
   * nickname to display in app for destination. e.g. "Bob's House".
   */
  destinationName?: string;

  /**
   * Start point of the navigation.
   * If not specified, the current device location will be used.
   * Either:
   *  - a {string} containing the address. e.g. "Buckingham Palace, London"
   *  - a {string} containing a latitude/longitude coordinate. e.g. "50.1. -4.0"
   *  - an {array}, where the first element is the latitude and the second element is a longitude, as decimal numbers. e.g. [50.1, -4.0]
   */
  start?: string | number[];

  /**
   * nickname to display in app for start . e.g. "My House".
   */
  startName?: string;

  /**
   * Transportation mode for navigation: "driving", "walking" or "transit". Defaults to "driving" if not specified.
   */
  transportMode?: string;

  /**
   * If true, debug log output will be generated by the plugin. Defaults to false.
   */
  enableDebug?: boolean;

  /**
   * a key/value map of extra app-specific parameters. For example, to tell Google Maps on Android to display Satellite view in "maps" launch mode: `{"t": "k"}`
   */
  extras?: any;

  /**
   * (Android only) mode in which to open Google Maps app.
   * `launchnavigator.LAUNCH_MODE.MAPS` or `launchnavigator.LAUNCH_MODE.TURN_BY_TURN`
   * Defaults to `launchnavigator.LAUNCH_MODE.MAPS` if not specified.
   */
  launchModeGoogleMaps?: string;

  /**
   * (iOS only) method to use to open Apple Maps app.
   * `launchnavigator.LAUNCH_MODE.URI_SCHEME` or `launchnavigator.LAUNCH_MODE.MAPKIT`
   * Defaults to `launchnavigator.LAUNCH_MODE.URI_SCHEME` if not specified.
   */
  launchModeAppleMaps?: string;

  /**
   * If true, and input location type(s) doesn't match those required by the app, use geocoding to obtain the address/coords as required. Defaults to true.
   */
  enableGeolocation?: boolean;

  /**
   * options related to the default native actionsheet picker which enables user to select which navigation app to launch if `app` is not specified.
   */
  appSelection?: AppSelectionOptions;
}


export interface UserChoice {

  /**
   * Indicates whether a user choice exists for a preferred navigator app.
   * @param callback - function to pass result to: will receive a boolean argument.
   */
  exists: (callback: (exists: boolean) => void) => void;

  /**
   * Returns current user choice of preferred navigator app.
   * @param callback - function to pass result to: will receive a string argument indicating the app, which is a constant in `launchnavigator.APP`.
   */
  get: (callback: (app: string) => void) => void;

  /**
   * Sets the current user choice of preferred navigator app.
   * @param app - app to set as preferred choice as a constant in `launchnavigator.APP`.
   * @param callback - function to call once operation is complete.
   */
  set: (app: string, callback: () => void) => void;

  /**
   * Clears the current user choice of preferred navigator app.
   * @param callback - function to call once operation is complete.
   */
  clear: (callback: () => void) => void;
}


export interface UserPrompted {
  /**
   * Indicates whether user has already been prompted whether to remember their choice a preferred navigator app.
   * @param callback - function to pass result to: will receive a boolean argument.
   */
  get: (callback: (exists: boolean) => void) => void;

  /**
   * Sets flag indicating user has already been prompted whether to remember their choice a preferred navigator app.
   * @param callback - function to call once operation is complete.
   */
  set: ( callback: () => void) => void;

  /**
   * Clears flag which indicates if user has already been prompted whether to remember their choice a preferred navigator app.
   * @param callback - function to call once operation is complete.
   */
  clear: ( callback: () => void) => void;
}


export interface AppSelection {
  userChoice: UserChoice;
  userPrompted: UserPrompted;
}


/**
   * Launches navigator app
   * @param destination {string|number[]} Location name or coordinates (as string or array)
   * @param options {LaunchNavigatorOptions}
   * @returns {Promise<any>}
   */
@Cordova({
    successIndex: 2,
    errorIndex: 3
  })
  navigate(destination: string | number[], options?: LaunchNavigatorOptions): Promise<any> { return; }


/**
   * Determines if the given app is installed and available on the current device.
   * @param app {string}
   * @returns {Promise<any>}
   */
@Cordova()
  isAppAvailable(app: string): Promise<any> { return; }


/**
   * Returns a list indicating which apps are installed and available on the current device.
   * @returns {Promise<string[]>}
   */
@Cordova()
  availableApps(): Promise<string[]> { return; }


/**
   * Returns the display name of the specified app.
   * @param app {string}
   * @returns {string}
   */
@Cordova({ sync: true })
  getAppDisplayName(app: string): string { return; }


/**
   * Returns list of supported apps on a given platform.
   * @param platform {string}
   * @returns {string[]}
   */
@Cordova({ sync: true })
  getAppsForPlatform(platform: string): string[] { return; }


/**
   * Indicates if an app on a given platform supports specification of transport mode.
   * @param app {string} specified as a string, you can use one of the constants, e.g `LaunchNavigator.APP.GOOGLE_MAPS`
   * @param platform {string}
   * @returns {boolean}
   */
@Cordova({ sync: true })
  supportsTransportMode(app: string, platform: string): boolean { return; }


/**
   * Returns the list of transport modes supported by an app on a given platform.
   * @param app {string}
   * @param platform {string}
   * @returns {string[]}
   */
@Cordova({ sync: true })
  getTransportModes(app: string, platform: string): string[] { return; }


/**
   * @param app {string}
   * @param platform {string}
   * @returns {boolean}
   */
@Cordova({ sync: true })
  supportsDestName(app: string, platform: string): boolean { return; }


/**
   * Indicates if an app on a given platform supports specification of start location.
   * @param app {string}
   * @param platform {string}
   * @returns {boolean}
   */
@Cordova({ sync: true })
  supportsStart(app: string, platform: string): boolean { return; }


/**
   * @param app {string}
   * @param platform {string}
   * @returns {boolean}
   */
@Cordova({ sync: true })
  supportsStartName(app: string, platform: string): boolean { return; }


/**
   * Indicates if an app on a given platform supports specification of launch mode.
   * Note that currently only Google Maps on Android does.
   * @param app {string}
   * @param platform {string}
   * @returns {boolean}
   */
@Cordova({ sync: true })
  supportsLaunchMode(app: string, platform: string): boolean { return; }


/**
   * @param destination {string | number[]}
   * @param options {LaunchNavigatorOptions}
   */
@Cordova({ sync: true })
  userSelect(destination: string | number[], options: LaunchNavigatorOptions): void {}


function SomeComponent() {
	return <Text>SomeComponent</Text>;
}


() => {
	test('should render a screen component', async () => {
		const navigator = {
			type: 'stack',
			routes: [
				{
					name: 'Home',
					path: '',
					screen: SomeComponent,
				},
			],
		};

		const component = mount(
			<BlueBaseApp>
				<Navigation navigator={navigator} />
			</BlueBaseApp>
		);

		// Wait for render
		await waitForElement(component as any, SomeComponent);

		expect(component.exists('Navigation SomeComponent')).toBe(true);
	});

	test('should render a screen component from component registry', async () => {
		const navigator = {
			type: 'stack',
			routes: [
				{
					name: 'Home',
					path: '',
					screen: 'EmptyState',
				},
			],
		};

		const component = mount(
			<BlueBaseApp>
				<Navigation navigator={navigator} />
			</BlueBaseApp>
		);

		// Wait for render
		await waitForElement(component as any, EmptyState);

		expect(component.exists('Navigation EmptyState')).toBe(true);
	});

	test('should render a screen component in a nested navigator', async () => {
		const navigator = {
			type: 'stack',
			routes: [
				{
					name: 'Home',
					path: '',
					navigator: {
						type: 'stack',
						routes: [
							{
								name: 'Nested',
								path: '',
								screen: SomeComponent,
							},
						],
					},
				},
			],
		};

		const component = mount(
			<BlueBaseApp>
				<Navigation navigator={navigator} />
			</BlueBaseApp>
		);

		// Wait for render
		await waitForElement(component as any, SomeComponent);

		expect(component.exists('Navigation SomeComponent')).toBe(true);
	});

	test('should render null if theres no screen or navigator prop in route', async () => {
		const navigator = {
			type: 'stack',
			routes: [
				{
					name: 'Home',
					path: '',
				},
			],
		};

		const component = mount(
			<BlueBaseApp>
				<Navigation navigator={navigator} />
			</BlueBaseApp>
		);

		// Wait for render
		await waitForElement(component as any, Navigation);

		expect(component.find('Navigation').children()).toHaveLength(0);
	});

	test('should render null if theres no route', async () => {
		const navigator = {
			type: 'stack',
		} as any;

		const component = mount(
			<BlueBaseApp>
				<Navigation navigator={navigator} />
			</BlueBaseApp>
		);

		// Wait for render
		await waitForElement(component as any, Navigation);

		expect(component.find('Navigation').children()).toHaveLength(0);
	});
}


async () => {
		const navigator = {
			type: 'stack',
			routes: [
				{
					name: 'Home',
					path: '',
					screen: SomeComponent,
				},
			],
		};

		const component = mount(
			<BlueBaseApp>
				<Navigation navigator={navigator} />
			</BlueBaseApp>
		);

		// Wait for render
		await waitForElement(component as any, SomeComponent);

		expect(component.exists('Navigation SomeComponent')).toBe(true);
	}


async () => {
		const navigator = {
			type: 'stack',
			routes: [
				{
					name: 'Home',
					path: '',
					screen: 'EmptyState',
				},
			],
		};

		const component = mount(
			<BlueBaseApp>
				<Navigation navigator={navigator} />
			</BlueBaseApp>
		);

		// Wait for render
		await waitForElement(component as any, EmptyState);

		expect(component.exists('Navigation EmptyState')).toBe(true);
	}


async () => {
		const navigator = {
			type: 'stack',
			routes: [
				{
					name: 'Home',
					path: '',
					navigator: {
						type: 'stack',
						routes: [
							{
								name: 'Nested',
								path: '',
								screen: SomeComponent,
							},
						],
					},
				},
			],
		};

		const component = mount(
			<BlueBaseApp>
				<Navigation navigator={navigator} />
			</BlueBaseApp>
		);

		// Wait for render
		await waitForElement(component as any, SomeComponent);

		expect(component.exists('Navigation SomeComponent')).toBe(true);
	}


async () => {
		const navigator = {
			type: 'stack',
			routes: [
				{
					name: 'Home',
					path: '',
				},
			],
		};

		const component = mount(
			<BlueBaseApp>
				<Navigation navigator={navigator} />
			</BlueBaseApp>
		);

		// Wait for render
		await waitForElement(component as any, Navigation);

		expect(component.find('Navigation').children()).toHaveLength(0);
	}


async () => {
		const navigator = {
			type: 'stack',
		} as any;

		const component = mount(
			<BlueBaseApp>
				<Navigation navigator={navigator} />
			</BlueBaseApp>
		);

		// Wait for render
		await waitForElement(component as any, Navigation);

		expect(component.find('Navigation').children()).toHaveLength(0);
	}


(props) => {
  return (
    <div>
      <Head>
        <title>0euvreAI</title>
        <meta
          name="description"
          content="0euvreAI"
        />
      </Head>
      <HomeView />
    </div>


@Component({
  selector: 'app-result-item',
  templateUrl: './result-item.component.html',
  styleUrls: ['./result-item.component.scss'],
})
export class ResultItemComponent implements OnInit {
  @Input() result!: number;
  @Input() title!: string;
  constructor() {}

  ngOnInit(): void {}
}


(raw: string) => {
  const lines = raw.split("\n").map(BigInt);
  const queue: bigint[] = [...lines.splice(0, 25)];
  for (const num of lines) {
    let match = false;
    for (let i = 0; i < queue.length - 1; i++) {
      for (let j = i + 1; j < queue.length; j++) {
        if (queue[i] + queue[j] === num) match = true;
      }
    }
    if (!match) return num;
    queue.shift();
    queue.push(num);
  }
  return -1n;
}


(list: bigint[]) => {
  let max = list[0];
  let min = list[0];
  for (const num of list) {
    if (min > num) min = num;
    if (max < num) max = num;
  }
  return min + max;
}


(to: bigint, raw: string) => {
  const lines = raw.split("\n").map(BigInt);
  for (let i = 0; i < lines.length - 1; i++) {
    let sum = lines[i];
    for (let j = i + 1; j < lines.length; j++) {
      sum += lines[j];
      if (sum === to) {
        return minmax(lines.slice(i, j));
      } else if (sum > to) break;
    }
  }
}


() => {
    let component: HomePageComponent;
    let fixture: ComponentFixture<HomePageComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [HomePageComponent]
        })
            .compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(HomePageComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

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


() => {
        TestBed.configureTestingModule({
            declarations: [HomePageComponent]
        })
            .compileComponents();
    }


() => {
        fixture = TestBed.createComponent(HomePageComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    }


// @useDefineForClassFields: false
// @target: es2015
class C {
  static #_1 = 1;
  static #_3 = 1;
  static #_5 = 1;

  static {}
  static {}
  static {}
  static {}
  static {}
  static {}
}


/**
 * Produces a component which internally loads the target component before first mount.
 * The component passes all props through to the loaded component.
 *
 * This overload accepts a module with a default export for the component.
 */
export function asAsync<TProps>(options: IAsAsyncOptions<TProps>) {
  class Async extends React.Component<
    TProps & {
      asyncPlaceholder?: React.ElementType;
      forwardedRef: React.Ref<React.ElementType<TProps>>;
    },
    { Component?: React.ElementType<TProps> }
  > {
    public state = {
      Component: _syncModuleCache ? (_syncModuleCache.get(options.load) as React.ElementType<TProps>) : undefined,
    };

    public render(): JSX.Element | null {
      // Typescript issue: the rest can't be pulled without the any cast, as TypeScript fails with rest on generics.
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { forwardedRef, asyncPlaceholder: Placeholder, ...rest } = this.props as any;
      const { Component } = this.state;
      return Component ? (
        React.createElement(Component, { ...rest, ref: forwardedRef })
      ) : Placeholder ? (
        <Placeholder />
      ) : null;
    }

    public componentDidMount(): void {
      let { Component } = this.state;

      if (!Component) {
        options
          .load()
          .then((LoadedComponent: React.ElementType<TProps>) => {
            if (LoadedComponent) {
              // Cache component for future reference.
              _syncModuleCache && _syncModuleCache.set(options.load, LoadedComponent);

              // Set state.
              this.setState(
                {
                  Component: LoadedComponent,
                },
                options.onLoad,
              );
            }
          })
          .catch(options.onError);
      }
    }
  }

  return React.forwardRef<React.ElementType<TProps>, TProps & { asyncPlaceholder?: React.ElementType }>(
    (props, ref) => <Async {...props} forwardedRef={ref} />,
  );
}


(LoadedComponent: React.ElementType<TProps>) => {
            if (LoadedComponent) {
              // Cache component for future reference.
              _syncModuleCache && _syncModuleCache.set(options.load, LoadedComponent);

              // Set state.
              this.setState(
                {
                  Component: LoadedComponent,
                },
                options.onLoad,
              );
            }
          }


(props, ref) => <Async {...props}


class Async extends React.Component<
    TProps & {
      asyncPlaceholder?: React.ElementType;
      forwardedRef: React.Ref<React.ElementType<TProps>>;
    },
    { Component?: React.ElementType<TProps> }
  > {
    public state = {
      Component: _syncModuleCache ? (_syncModuleCache.get(options.load) as React.ElementType<TProps>) : undefined,
    };

    public render(): JSX.Element | null {
      // Typescript issue: the rest can't be pulled without the any cast, as TypeScript fails with rest on generics.
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { forwardedRef, asyncPlaceholder: Placeholder, ...rest } = this.props as any;
      const { Component } = this.state;
      return Component ? (
        React.createElement(Component, { ...rest, ref: forwardedRef })
      ) : Placeholder ? (
        <Placeholder />
      ) : null;
    }

    public componentDidMount(): void {
      let { Component } = this.state;

      if (!Component) {
        options
          .load()
          .then((LoadedComponent: React.ElementType<TProps>) => {
            if (LoadedComponent) {
              // Cache component for future reference.
              _syncModuleCache && _syncModuleCache.set(options.load, LoadedComponent);

              // Set state.
              this.setState(
                {
                  Component: LoadedComponent,
                },
                options.onLoad,
              );
            }
          })
          .catch(options.onError);
      }
    }
  }


export interface IAsAsyncOptions<TProps> {
  /**
   * Callback which returns a promise resolving an object which exports the component.
   */
  load: () => Promise<React.ElementType<TProps>>;

  /**
   * Callback executed when async loading is complete.
   */
  onLoad?: () => void;

  /**
   * Callback when async loading fails.
   */
  onError?: (error: Error) => void;
}


public render(): JSX.Element | null {
      // Typescript issue: the rest can't be pulled without the any cast, as TypeScript fails with rest on generics.
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const { forwardedRef, asyncPlaceholder: Placeholder, ...rest } = this.props as any;
      const { Component } = this.state;
      return Component ? (
        React.createElement(Component, { ...rest, ref: forwardedRef })
      ) : Placeholder ? (
        <Placeholder />
      ) : null;
    }


public componentDidMount(): void {
      let { Component } = this.state;

      if (!Component) {
        options
          .load()
          .then((LoadedComponent: React.ElementType<TProps>) => {
            if (LoadedComponent) {
              // Cache component for future reference.
              _syncModuleCache && _syncModuleCache.set(options.load, LoadedComponent);

              // Set state.
              this.setState(
                {
                  Component: LoadedComponent,
                },
                options.onLoad,
              );
            }
          })
          .catch(options.onError);
      }
    }


() => {
            addressSpace = mainTest.addressSpace;
            should(addressSpace).be.instanceof(AddressSpace);
        }


() => {
            const multiStateDiscreteType = addressSpace.findVariableType("MultiStateDiscreteType")!;
            multiStateDiscreteType.isAbstract.should.eql(false);
        }


() => {
            const namespace = addressSpace.getOwnNamespace();

            const objectsFolder = addressSpace.findNode("ObjectsFolder")!;
            objectsFolder.browseName.toString().should.eql("Objects");

            const multiStateDiscreteVariable = namespace.addMultiStateDiscrete<number, DataType.UInt32>({
                browseName: "MyMultiStateVariable",
                enumStrings: ["Red", "Orange", "Green"],
                organizedBy: objectsFolder,
                value: 1 // Orange
            });
            multiStateDiscreteVariable.browseName.toString().should.eql("1:MyMultiStateVariable");

            multiStateDiscreteVariable.valueRank.should.eql(-2);

            multiStateDiscreteVariable
                .getPropertyByName("EnumStrings")!
                .readValue()
                .value.toString()
                .should.eql(
                    "Variant(Array<LocalizedText>, l= 3, value=[locale=null text=Red,locale=null text=Orange,locale=null text=Green])"
                );

            multiStateDiscreteVariable.enumStrings.readValue().value.dataType.should.eql(DataType.LocalizedText);

            multiStateDiscreteVariable.readValue().value.toString().should.eql("Variant(Scalar<UInt32>, value: 1)");
            multiStateDiscreteVariable.readValue().value.dataType.should.eql(DataType.UInt32);
        }


async () => {
            const namespace = addressSpace.getOwnNamespace();

            let _theValue = 0; // Red

            const timestamped_get_raw = (callback: CallbackT<DataValue>) => {
                // using getCurrentClock will guaranty that clock value is different each time
                const clock = getCurrentClock();
                setTimeout(() => {
                    const myDataValue = new DataValue({
                        serverPicoseconds: clock.picoseconds,
                        serverTimestamp: clock.timestamp,
                        sourcePicoseconds: clock.picoseconds,
                        sourceTimestamp: clock.timestamp,
                        statusCode: StatusCodes.Good,
                        value: { dataType: DataType.UInt32, value: _theValue }
                    });
                    callback(null, myDataValue);
                }, 10); //simulate some delay
            };
            const timestamped_set_raw = (dataValue: DataValue, callback: CallbackT<StatusCode>) => {
                if (dataValue.value.dataType !== DataType.UInt32) {
                    return callback(new Error("Invalid DataType"));
                }
                setTimeout(() => {
                    _theValue = dataValue.value.value;
                    callback(null, StatusCodes.Good);
                }, 10);
            };
            const timestamped_set = sinon.spy(timestamped_set_raw);
            const timestamped_get = sinon.spy(timestamped_get_raw);

            const multiStateDiscreteVariable = namespace.addMultiStateDiscrete({
                browseName: "MultiStateDiscreteVariableWithGetterAndSetter",
                organizedBy: addressSpace.rootFolder.objects,
                enumStrings: ["Red", "Orange", "Green"],

                value: {
                    timestamped_get,
                    timestamped_set
                }
            });

            // because we use getter and setter, we need to call at least readValueAsync once
            // to get the initial value....
            const dv0 = await multiStateDiscreteVariable.readValueAsync(SessionContext.defaultContext);

            multiStateDiscreteVariable.getValue().should.eql(0);
            multiStateDiscreteVariable.readValue().statusCode.should.eql(StatusCodes.Good);
            multiStateDiscreteVariable.getValueAsString().should.eql("Red");
            // ----------------

            _theValue = 2;
            const dv1 = await multiStateDiscreteVariable.readValueAsync(SessionContext.defaultContext);
            multiStateDiscreteVariable.getValueAsString().should.eql("Green");
            //
            _theValue = 1;
            await multiStateDiscreteVariable.readValueAsync(SessionContext.defaultContext);
            multiStateDiscreteVariable.getValueAsString().should.eql("Orange");
            //

            // external write
            const clock = getCurrentClock();
            await multiStateDiscreteVariable.writeValue(
                SessionContext.defaultContext,
                new DataValue({
                    serverPicoseconds: clock.picoseconds,
                    serverTimestamp: clock.timestamp,
                    sourcePicoseconds: clock.picoseconds,
                    sourceTimestamp: clock.timestamp,
                    statusCode: StatusCodes.Good,
                    value: { dataType: DataType.UInt32, value: 2 }
                })
            );

            multiStateDiscreteVariable.getValueAsString().should.eql("Green");
            timestamped_set.callCount.should.eql(1);
            timestamped_get.callCount.should.eql(3);

            /// now trying with invalid values to see how
            const sc1 = await multiStateDiscreteVariable.writeValue(
                SessionContext.defaultContext,
                new DataValue({
                    serverPicoseconds: clock.picoseconds,
                    serverTimestamp: clock.timestamp,
                    sourcePicoseconds: clock.picoseconds,
                    sourceTimestamp: clock.timestamp,
                    statusCode: StatusCodes.Good,
                    value: { dataType: DataType.UInt32, value: 0xaaaaaa }
                })
            );
            multiStateDiscreteVariable.getValueAsString().should.eql("Green");
            sc1.should.not.eql(StatusCodes.Good);
            sc1.should.eql(StatusCodes.BadOutOfRange);
        }


(callback: CallbackT<DataValue>) => {
                // using getCurrentClock will guaranty that clock value is different each time
                const clock = getCurrentClock();
                setTimeout(() => {
                    const myDataValue = new DataValue({
                        serverPicoseconds: clock.picoseconds,
                        serverTimestamp: clock.timestamp,
                        sourcePicoseconds: clock.picoseconds,
                        sourceTimestamp: clock.timestamp,
                        statusCode: StatusCodes.Good,
                        value: { dataType: DataType.UInt32, value: _theValue }
                    });
                    callback(null, myDataValue);
                }, 10); //simulate some delay
            }


() => {
                    const myDataValue = new DataValue({
                        serverPicoseconds: clock.picoseconds,
                        serverTimestamp: clock.timestamp,
                        sourcePicoseconds: clock.picoseconds,
                        sourceTimestamp: clock.timestamp,
                        statusCode: StatusCodes.Good,
                        value: { dataType: DataType.UInt32, value: _theValue }
                    });
                    callback(null, myDataValue);
                }


(dataValue: DataValue, callback: CallbackT<StatusCode>) => {
                if (dataValue.value.dataType !== DataType.UInt32) {
                    return callback(new Error("Invalid DataType"));
                }
                setTimeout(() => {
                    _theValue = dataValue.value.value;
                    callback(null, StatusCodes.Good);
                }, 10);
            }


() => {
                    _theValue = dataValue.value.value;
                    callback(null, StatusCodes.Good);
                }


() => {
            let multiStateDiscreteVariable: UAMultiStateDiscreteEx<number, DataType.UInt32>;
            before(() => {
                const namespace = addressSpace.getOwnNamespace();

                const objectsFolder = addressSpace.rootFolder.objects;

                multiStateDiscreteVariable = namespace.addMultiStateDiscrete({
                    browseName: "MyMultiStateVariable3",
                    enumStrings: ["Red", "Orange", "Green"],
                    organizedBy: objectsFolder,
                    value: 1 // Orange
                });
            });

            it("writing a value exceeding EnumString length shall return BadOutOfRange", async () => {
                const dataValue = new DataValueT<number, DataType.UInt32>({
                    value: new Variant({ dataType: DataType.UInt32, value: 100 }) // out of range
                });
                const statusCode = await multiStateDiscreteVariable.writeValue(SessionContext.defaultContext, dataValue);
                statusCode.should.eql(StatusCodes.BadOutOfRange);
            });

            it("writing a value within EnumString length shall return Good", async () => {
                const dataValue = new DataValueT<number, DataType.UInt32>({
                    value: { dataType: DataType.UInt32, value: 2 } // OK
                });
                const statusCode = await multiStateDiscreteVariable.writeValue(SessionContext.defaultContext, dataValue);
                statusCode.should.eql(StatusCodes.Good);
            });
            it("writing a value which has not the correct type shall return BadTypeMismatch", async () => {
                const dataValue = new DataValueT<string, DataType.String>({
                    value: {
                        dataType: DataType.String,
                        value: "2"
                    } // OK
                });
                const statusCode = await multiStateDiscreteVariable.writeValue(
                    SessionContext.defaultContext,
                    dataValue as any /* to force wrong value to be sent */
                );
                statusCode.should.eql(StatusCodes.BadTypeMismatch);
            });

            it("using setValue", () => {
                multiStateDiscreteVariable.setValue("Green");
                multiStateDiscreteVariable.getValue().should.eql(2);
                multiStateDiscreteVariable.getValueAsString().should.eql("Green");
                multiStateDiscreteVariable.setValue("Red");
                multiStateDiscreteVariable.getValue().should.eql(0);
                multiStateDiscreteVariable.getValueAsString().should.eql("Red");
            });
        }


() => {
                const namespace = addressSpace.getOwnNamespace();

                const objectsFolder = addressSpace.rootFolder.objects;

                multiStateDiscreteVariable = namespace.addMultiStateDiscrete({
                    browseName: "MyMultiStateVariable3",
                    enumStrings: ["Red", "Orange", "Green"],
                    organizedBy: objectsFolder,
                    value: 1 // Orange
                });
            }


async () => {
                const dataValue = new DataValueT<number, DataType.UInt32>({
                    value: new Variant({ dataType: DataType.UInt32, value: 100 }) // out of range
                });
                const statusCode = await multiStateDiscreteVariable.writeValue(SessionContext.defaultContext, dataValue);
                statusCode.should.eql(StatusCodes.BadOutOfRange);
            }


async () => {
                const dataValue = new DataValueT<number, DataType.UInt32>({
                    value: { dataType: DataType.UInt32, value: 2 } // OK
                });
                const statusCode = await multiStateDiscreteVariable.writeValue(SessionContext.defaultContext, dataValue);
                statusCode.should.eql(StatusCodes.Good);
            }


async () => {
                const dataValue = new DataValueT<string, DataType.String>({
                    value: {
                        dataType: DataType.String,
                        value: "2"
                    } // OK
                });
                const statusCode = await multiStateDiscreteVariable.writeValue(
                    SessionContext.defaultContext,
                    dataValue as any /* to force wrong value to be sent */
                );
                statusCode.should.eql(StatusCodes.BadTypeMismatch);
            }


() => {
                multiStateDiscreteVariable.setValue("Green");
                multiStateDiscreteVariable.getValue().should.eql(2);
                multiStateDiscreteVariable.getValueAsString().should.eql("Green");
                multiStateDiscreteVariable.setValue("Red");
                multiStateDiscreteVariable.getValue().should.eql(0);
                multiStateDiscreteVariable.getValueAsString().should.eql("Red");
            }


export function Logger(scope: string): ParameterDecorator {
    return (object, propertyKey, index): any => {
        const logger = new WinstonLogger(scope);
        const propertyName = propertyKey ? propertyKey.toString() : '';
        const castedObject: Constructable<object> = object as any;
        Container.registerHandler({ object: castedObject, propertyName, index, value: () => logger });
    };
}


(object, propertyKey, index): any => {
        const logger = new WinstonLogger(scope);
        const propertyName = propertyKey ? propertyKey.toString() : '';
        const castedObject: Constructable<object> = object as any;
        Container.registerHandler({ object: castedObject, propertyName, index, value: () => logger });
    }


() => logger


export class TableMetadata {
  size = PageSize.TWENTY_FIVE;
  tableColumns: ColumnMetadata[];

  static fromJSON(obj: any): TableMetadata {
    let tableMetadata = new TableMetadata();
    if (obj) {
      tableMetadata.size = obj.size;
      tableMetadata.tableColumns = (typeof (obj.tableColumns) === 'string') ? JSON.parse(obj.tableColumns) : obj.tableColumns;
    }

    return tableMetadata;
  }
}


static fromJSON(obj: any): TableMetadata {
    let tableMetadata = new TableMetadata();
    if (obj) {
      tableMetadata.size = obj.size;
      tableMetadata.tableColumns = (typeof (obj.tableColumns) === 'string') ? JSON.parse(obj.tableColumns) : obj.tableColumns;
    }

    return tableMetadata;
  }


export declare class TimePickerButtonComponent {
    locale: NzCalendarI18nInterface;
    timePickerDisabled: boolean;
    showTimePicker: boolean;
    readonly showTimePickerChange: EventEmitter<boolean>;
    prefixCls: string;
    onClick(): void;
}


onClick(): void;


/**
 * Create a declaration reflection from the given TypeScript node.
 *
 * @param context  The context object describing the current state the converter is in. The
 *   scope of the context will be the parent of the generated reflection.
 * @param node  The TypeScript node that should be converted to a reflection.
 * @param kind  The desired kind of the reflection.
 * @param name  The desired name of the reflection.
 * @returns The resulting reflection or undefined if an error is encountered.
 */
export function createDeclaration(context: Context, node: ts.Declaration, kind: ReflectionKind, name?: string): DeclarationReflection | undefined {
    if (!(context.scope instanceof ContainerReflection)) {
        throw new Error('Expected container reflection.');
    }
    const container = context.scope;

    // Ensure we have a name for the reflection
    if (!name) {
        if (node.localSymbol) {
            name = node.localSymbol.name;
        } else if (node.symbol) {
            name = node.symbol.name;
        } else {
            return;
        }

        // rename built-in symbols
        const match = builtInSymbolRegExp.exec(name);
        if (match) {
            name = `[Symbol.${match[1]}]`;
        } else if (kind & (ReflectionKind.ClassMember | ReflectionKind.VariableOrProperty) && name === '__computed') {
            // rename computed properties
            const declName = ts.getNameOfDeclaration(node);
            const symbol = declName && context.checker.getSymbolAtLocation(declName);
            if (symbol) {
                name = context.checker.symbolToString(symbol, /*enclosingDeclaration*/ undefined, ts.SymbolFlags.ClassMember);
            } else if (declName) {
                name = declName.getText();
            }
        }
    }

    const modifiers = ts.getCombinedModifierFlags(node);

    let hasComment: boolean = Boolean(getRawComment(node));
    // Test whether the node is exported
    let isExported: boolean;
    if (kind === ReflectionKind.Module || kind === ReflectionKind.Global) {
        isExported = true;
        hasComment = true;
    } else if (container.kind === ReflectionKind.Global) {
        // In file mode, everything is exported.
        isExported = true;
    } else if (container.kindOf([ReflectionKind.Namespace, ReflectionKind.Module])) {
        const symbol = context.getSymbolAtLocation(node);
        if (!symbol) {
            isExported = false;
        } else {
            let parentNode = node.parent;
            while (![ts.SyntaxKind.SourceFile, ts.SyntaxKind.ModuleDeclaration].includes(parentNode.kind)) {
                parentNode = parentNode.parent;
            }
            const parentSymbol = context.getSymbolAtLocation(parentNode);
            if (!parentSymbol) {
                // This is a file with no imports/exports, so everything is
                // global and therefore exported.
                isExported = true;
            } else {
                isExported = !!parentSymbol.exports?.get(symbol.escapedName);
            }
        }
    } else {
        isExported = container.flags.isExported;
    }

    if (
        (!isExported && context.converter.excludeNotExported)
        ||
        (context.converter.excludeNotDocumented && kind !== ReflectionKind.EnumMember && !hasComment)
    ) {
        return;
    }

    // Test whether the node is private, when inheriting ignore private members
    const isPrivate = !!(modifiers & ts.ModifierFlags.Private);
    if (context.isInherit && isPrivate) {
        return;
    }

    // Test whether the node is static, when merging a module to a class make the node static
    let isConstructorProperty = false;
    let isStatic = false;
    if (!nonStaticKinds.includes(kind)) {
        isStatic = !!(modifiers & ts.ModifierFlags.Static);
        if (container.kind === ReflectionKind.Class) {
            if (node.parent && node.parent.kind === ts.SyntaxKind.Constructor) {
                isConstructorProperty = true;
            } else if (!node.parent || !nonStaticMergeKinds.includes(node.parent.kind)) {
                isStatic = true;
            }
        }
    }

    // Check if we already have a child of the same kind, with the same name and static flag
    let child: DeclarationReflection | undefined;
    const children = container.children = container.children || [];
    children.forEach((n: DeclarationReflection) => {
        if (n.name === name && n.flags.isStatic === isStatic && canMergeReflectionsByKind(n.kind, kind)) {
            child = n;
        }
    });

    if (!child) {
        // Child does not exist, create a new reflection
        child = new DeclarationReflection(name, kind, container);
        child.setFlag(ReflectionFlag.Static, isStatic);
        child.setFlag(ReflectionFlag.Private, isPrivate);
        child.setFlag(ReflectionFlag.ConstructorProperty, isConstructorProperty);
        child.setFlag(ReflectionFlag.Exported,  isExported);
        child = setupDeclaration(context, child, node);

        if (child) {
            children.push(child);
            context.registerReflection(child, context.getSymbolAtLocation(node) ?? node.symbol);
        }
    } else {
        // Merge the existent reflection with the given node
        child = mergeDeclarations(context, child, node, kind);
    }

    // If we have a reflection, trigger the corresponding event
    if (child) {
        context.trigger(Converter.EVENT_CREATE_DECLARATION, child, node);
    }

    return child;
}


/**
 * Setup a newly created declaration reflection.
 *
 * @param context  The context object describing the current state the converter is in.
 * @param reflection  The newly created blank reflection.
 * @param node  The TypeScript node whose properties should be applies to the given reflection.
 * @returns The reflection populated with the values of the given node.
 */
function setupDeclaration(context: Context, reflection: DeclarationReflection, node: ts.Declaration) {
    const modifiers = ts.getCombinedModifierFlags(node);

    reflection.setFlag(ReflectionFlag.External,  context.isExternal);
    reflection.setFlag(ReflectionFlag.Protected, !!(modifiers & ts.ModifierFlags.Protected));
    reflection.setFlag(ReflectionFlag.Public,    !!(modifiers & ts.ModifierFlags.Public));
    reflection.setFlag(ReflectionFlag.Optional,  !!(node['questionToken']));
    reflection.setFlag(ReflectionFlag.Readonly,  !!(modifiers & ts.ModifierFlags.Readonly));

    if (
        context.isInherit &&
        (node.parent === context.inheritParent || reflection.flags.isConstructorProperty)
    ) {
        if (!reflection.inheritedFrom) {
            reflection.inheritedFrom = createReferenceType(context, node.symbol, true);
            reflection.getAllSignatures().forEach((signature) => {
                signature.inheritedFrom = createReferenceType(context, node.symbol, true);
            });
        }
    }

    return reflection;
}


// we should not be merging type and value with the same name,
// because TypeScript has different namespaces for these two categories
function canMergeReflectionsByKind(kind1: ReflectionKind, kind2: ReflectionKind): boolean {
    if (
        (kind1 & ReflectionKind.SomeType && kind2 & ReflectionKind.SomeValue)
        ||
        (kind2 & ReflectionKind.SomeType && kind1 & ReflectionKind.SomeValue)
    ) {
        return false;
    }

    return true;
}


/**
 * Merge the properties of the given TypeScript node with the pre existent reflection.
 *
 * @param context  The context object describing the current state the converter is in.
 * @param reflection  The pre existent reflection.
 * @param node  The TypeScript node whose properties should be merged with the given reflection.
 * @param kind  The desired kind of the reflection.
 * @returns The reflection merged with the values of the given node or NULL if the merge is invalid.
 */
function mergeDeclarations(context: Context, reflection: DeclarationReflection, node: ts.Node, kind: ReflectionKind) {
    if (reflection.kind !== kind) {
        const weights = [ReflectionKind.Namespace, ReflectionKind.Enum, ReflectionKind.Class];
        const kindWeight = weights.indexOf(kind);
        const childKindWeight = weights.indexOf(reflection.kind);
        if (kindWeight > childKindWeight) {
            reflection.kind = kind;
        }
    }

    if (
        context.isInherit &&
        (context.inherited || []).includes(reflection.name) &&
        (node.parent === context.inheritParent || reflection.flags.isConstructorProperty)
    ) {
        if (!reflection.overwrites) {
            reflection.overwrites = createReferenceType(context, node.symbol, true);
            reflection.getAllSignatures().forEach((signature) => {
                signature.overwrites = createReferenceType(context, node.symbol, true);
            });
        }
        return;
    }

    return reflection;
}


(n: DeclarationReflection) => {
        if (n.name === name && n.flags.isStatic === isStatic && canMergeReflectionsByKind(n.kind, kind)) {
            child = n;
        }
    }


(signature) => {
                signature.inheritedFrom = createReferenceType(context, node.symbol, true);
            }


(signature) => {
                signature.overwrites = createReferenceType(context, node.symbol, true);
            }


export class ExitError extends CLIError implements OclifError {
  oclif!: { exit: number }

  code = 'EEXIT'

  constructor(exitCode = 0) {
    super(`EEXIT: ${exitCode}`, {exit: exitCode})
  }

  render(): string {
    return ''
  }
}


render(): string {
    return ''
  }


({inputFile, helpers}) => this.renderer.render(inputFile, {mddoc: helpers})


html => writeFileCreateDir(self.outputFile, html)


_ => console.log(green('We wrote ') + grey(self.outputFile))


class HtmlWriterFile {
    inputFile: string;
    outputFile: string;
    renderer: any;
    helpers: unknown;

    constructor (options: HtmlWriterFileOptions) {
        // TODO: This shouldnt be necesary here, it should be cached way above
        if (!('inputFile' in options)) {
            throw new Error('You need to specify an input file');
        }
        if (!('outputFile' in options)) {
            throw new Error('You need to specify an output file');
        }

        this.inputFile = options.inputFile;
        this.outputFile = options.outputFile;
        this.renderer = options.renderer;
    }

    setHelpers (helpers: unknown) {
        this.helpers = helpers;
    }

    render () {
        const self = this;
        return Task.resolve(this)
            .map(({inputFile, helpers}) => this.renderer.render(inputFile, {mddoc: helpers}))
            .chain(html => writeFileCreateDir(self.outputFile, html))
            .map(tap(_ => console.log(green('We wrote ') + grey(self.outputFile))));
    }
}


class CustomGenerator {
    renderer: any;

    constructor (private generatorSettings: CustomGeneratorSettings) {
        // TODO: this should be in the HtmlWriterFile, but i dont want to create
        // one every time
        const ECT = require('ect');
        this.renderer = ECT({ root : generatorSettings.templateDir });

    }

    copyAssets () {
        const inputDir = this.generatorSettings.templateDir;
        const outputDir = this.generatorSettings.outputDir;
        // Not sure about the partials one...
        const assetRe = /\/(css|js|images|fonts)\//;

        return copyDir(inputDir, outputDir, assetRe);
    }

    generate (helpers: unknown) {
        const self = this;
        const tasks: Task<unknown, NodeJS.ErrnoException | UnknownError>[] = [];

        if (self.generatorSettings.copyAssets) {
            tasks.push(self.copyAssets());
        }

        // TODO: Remove the files settings, probably walk the dir for .tpl files
        for (let i = 0; i < self.generatorSettings.files.length; i++) {
            // Create the object in charge of rendering the html
            const renderObject = new HtmlWriterFile({
                inputFile: self.generatorSettings.files[i] + '.tpl',
                outputFile: self.generatorSettings.outputDir + '/' + self.generatorSettings.files[i] + '.html',
                renderer: self.renderer
            });

            // ...
            renderObject.setHelpers(helpers);

            // Generate the html
            tasks.push(renderObject.render());
        }

        return Task.all(tasks);
    }
}


interface CustomGeneratorSettings extends BaseGeneratorSettings {
    templateDir: string;
    outputDir: string;
    copyAssets: boolean;
    files: string[];
}


interface HtmlWriterFileOptions {
    inputFile: string;
    outputFile: string;
    renderer: any;
}


setHelpers (helpers: unknown) {
        this.helpers = helpers;
    }


render () {
        const self = this;
        return Task.resolve(this)
            .map(({inputFile, helpers}) => this.renderer.render(inputFile, {mddoc: helpers}))
            .chain(html => writeFileCreateDir(self.outputFile, html))
            .map(tap(_ => console.log(green('We wrote ') + grey(self.outputFile))));
    }


copyAssets () {
        const inputDir = this.generatorSettings.templateDir;
        const outputDir = this.generatorSettings.outputDir;
        // Not sure about the partials one...
        const assetRe = /\/(css|js|images|fonts)\//;

        return copyDir(inputDir, outputDir, assetRe);
    }


generate (helpers: unknown) {
        const self = this;
        const tasks: Task<unknown, NodeJS.ErrnoException | UnknownError>[] = [];

        if (self.generatorSettings.copyAssets) {
            tasks.push(self.copyAssets());
        }

        // TODO: Remove the files settings, probably walk the dir for .tpl files
        for (let i = 0; i < self.generatorSettings.files.length; i++) {
            // Create the object in charge of rendering the html
            const renderObject = new HtmlWriterFile({
                inputFile: self.generatorSettings.files[i] + '.tpl',
                outputFile: self.generatorSettings.outputDir + '/' + self.generatorSettings.files[i] + '.html',
                renderer: self.renderer
            });

            // ...
            renderObject.setHelpers(helpers);

            // Generate the html
            tasks.push(renderObject.render());
        }

        return Task.all(tasks);
    }


@Component({
  template: '',
})
export class AbstractTableEntryRendererComponent {
  @Input() entry: any;
  @Input() entryEventHandler: any;
  protected action: any[] = [];
  constructor(protected injector: Injector) {
    this.entry = this.injector.get<any>('entry' as any);
    this.entryEventHandler = this.injector.get<any>('entryEventHandler' as any);
  }
}


(location) => {
      this.getdata(location);
    }


(error) => {
      this.loading.dismiss();
      let language = this.translate.currentLang;
      if (language === 'th') {
        this.alert.onAlert('ตำแหน่ง', 'ค้นหาตำแหน่งผิดพลาด กรุณาตรวจสอบ GPS', 'ตกลง');
      } else if (language === 'en') {
        this.alert.onAlert('Location', 'Error! Please check your GPS.', 'OK');
      }
    }


() => {
      this.home.getHomeData(location).then(data => {
        this.homeData = data;
        this.loading.dismiss();
      }, (err) => {
        this.loading.dismiss();
      })
    }


data => {
        this.homeData = data;
        this.loading.dismiss();
      }


(err) => {
        this.loading.dismiss();
      }


@IonicPage()
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  @ViewChild('ads') ads: Slides;
  homeData: HomeModel = new HomeModel();
  user: UserModel = new UserModel();
  pages: any = 0;
  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    private home: HomeProvider,
    private modalCtrl: ModalController,
    private app: App,
    private loading: LoadingProvider,
    private geolocation: Geolocation,
    private translate: TranslateService,
    private alert: AlertProvider,
    private platform: Platform
  ) {
  }

  ionViewWillEnter() {
    this.user = JSON.parse(window.localStorage.getItem('user@' + Constants.URL));
    this.getCurrentPosition();
  }

  getCurrentPosition() {
    this.loading.onLoading();

    if (!this.platform.is('cordova')) { // serve test location in lumlukka
      let location = {
        coords: {
          latitude: 13.9323555,
          longitude: 100.7178317
        }
      }
      this.getdata(location);
      console.log('Browser debugger');
      return;
    }

    this.geolocation.getCurrentPosition().then((location) => {
      this.getdata(location);
    }).catch((error) => {
      this.loading.dismiss();
      let language = this.translate.currentLang;
      if (language === 'th') {
        this.alert.onAlert('ตำแหน่ง', 'ค้นหาตำแหน่งผิดพลาด กรุณาตรวจสอบ GPS', 'ตกลง');
      } else if (language === 'en') {
        this.alert.onAlert('Location', 'Error! Please check your GPS.', 'OK');
      }
    });
  }

  getdata(location) {
    setTimeout(() => {
      this.home.getHomeData(location).then(data => {
        this.homeData = data;
        this.loading.dismiss();
      }, (err) => {
        this.loading.dismiss();
      })
    }, 1000);
  }

  doRefresh(refresher) {
    this.getCurrentPosition();
    refresher.complete();
  }

  onSelectedPage(index) { // selected category
    this.pages = index;
  }

  openAds(item) {
    console.log(item);
    if (item.isvideo === true) {
      let profileModal = this.modalCtrl.create('VideoContentPage', { _id: item._id });
      profileModal.present();
    } else {
      let profileModal = this.modalCtrl.create('ImageContentPage', { _id: item._id });
      profileModal.present();
    }
  }

  seeAllHotPrice() {
    this.app.getRootNav().push('HotpriceListPage');
  }

  categoryPage(index, item) {
    this.app.getRootNav().push('CategoryListPage', { index: index, item: item });
  }

  seeAllByCondition(condition) {
    this.app.getRootNav().push('ShopSeeAllPage', condition);
  }

  goToProfile() {
    this.app.getRootNav().push('ProfilePage');
  }

  goHotpriceShop(e) {
    this.app.getRootNav().push('ShopPage', e.shop);
  }

  goToShop(e) {
    this.app.getRootNav().push('ShopPage', e._id);
  }

}


ionViewWillEnter() {
    this.user = JSON.parse(window.localStorage.getItem('user@' + Constants.URL));
    this.getCurrentPosition();
  }


getCurrentPosition() {
    this.loading.onLoading();

    if (!this.platform.is('cordova')) { // serve test location in lumlukka
      let location = {
        coords: {
          latitude: 13.9323555,
          longitude: 100.7178317
        }
      }
      this.getdata(location);
      console.log('Browser debugger');
      return;
    }

    this.geolocation.getCurrentPosition().then((location) => {
      this.getdata(location);
    }).catch((error) => {
      this.loading.dismiss();
      let language = this.translate.currentLang;
      if (language === 'th') {
        this.alert.onAlert('ตำแหน่ง', 'ค้นหาตำแหน่งผิดพลาด กรุณาตรวจสอบ GPS', 'ตกลง');
      } else if (language === 'en') {
        this.alert.onAlert('Location', 'Error! Please check your GPS.', 'OK');
      }
    });
  }


getdata(location) {
    setTimeout(() => {
      this.home.getHomeData(location).then(data => {
        this.homeData = data;
        this.loading.dismiss();
      }, (err) => {
        this.loading.dismiss();
      })
    }, 1000);
  }


doRefresh(refresher) {
    this.getCurrentPosition();
    refresher.complete();
  }


onSelectedPage(index) { // selected category
    this.pages = index;
  }


openAds(item) {
    console.log(item);
    if (item.isvideo === true) {
      let profileModal = this.modalCtrl.create('VideoContentPage', { _id: item._id });
      profileModal.present();
    } else {
      let profileModal = this.modalCtrl.create('ImageContentPage', { _id: item._id });
      profileModal.present();
    }
  }


seeAllHotPrice() {
    this.app.getRootNav().push('HotpriceListPage');
  }


categoryPage(index, item) {
    this.app.getRootNav().push('CategoryListPage', { index: index, item: item });
  }


seeAllByCondition(condition) {
    this.app.getRootNav().push('ShopSeeAllPage', condition);
  }


goToProfile() {
    this.app.getRootNav().push('ProfilePage');
  }


goHotpriceShop(e) {
    this.app.getRootNav().push('ShopPage', e.shop);
  }


goToShop(e) {
    this.app.getRootNav().push('ShopPage', e._id);
  }


@Component({
  selector: 'app-about',
  templateUrl: './about.component.html',
  styleUrls: ['./about.component.scss']
})
export class AboutComponent implements OnInit {
  faDollarSign = faDollarSign;
  faAtom = faAtom;
  faSchool = faSchool;
  faBook = faBook;
  faDatabase = faDatabase;
  faHeart = faHeart;
  faSearch = faSearch;

  constructor() {
  }

  ngOnInit(): void {
  }

}


() => {
    const { isAuth } = useAppSelector((state) => state.auth)

    useEffect(() => {
        if (!isAuth) {
            EventBus.dispatch('logout')
        }
    }, [isAuth])

    return (
        <div style={{ boxSizing: 'border-box', minHeight: '100vh' }}


(state) => state.auth


() => {
        if (!isAuth) {
            EventBus.dispatch('logout')
        }
    }


export default function App({ Component, pageProps }: AppProps) {

	useEffect(() => {
		const jssStyles = document.querySelector("#jss-server-side");
		if (jssStyles) jssStyles.parentElement?.removeChild(jssStyles);
	}, []);

	return (
		<CacheProvider value={cache}>
			<Head>
				<title>Take Ludwig to Space!</title>
				<meta
					name="viewport"
					content="initial-scale=1, width=device-width"
				/>
				<meta name="title" content="🚀 Take Ludwig to the moon!"/ >
				<meta name="description" content="🚀 Take Ludwig to space and beyond! " />

				{/* <!-- Open Graph / Facebook --> */}
				<meta property="og:type" content="website" />
				<meta property="og:url" content="https://takeludwigto.space/"/>
				<meta property="og:title" content="🚀 Take Ludwig to the moon!"/>
				<meta property="og:description" content="🚀 Take Ludwig to space and beyond! "/>
				<meta property="og:image" content="" />

				{/* <!-- Twitter --> */}
				<meta property="twitter:card" content="summary_large_image"/>
				<meta property="twitter:url" content="https://takeludwigto.space/"/>
				<meta property="twitter:title" content="🚀 Take Ludwig to the moon!"/>
				<meta property="twitter:description" content="🚀 Take Ludwig to space and beyond! "/>
				<meta property="twitter:image" content="" />
			</Head>
			<ThemeProvider theme={theme}>
				<CssBaseline />
				{
					<Component {...pageProps} />
				}
			</ThemeProvider>
		</CacheProvider>
	);
}


() => {
		const jssStyles = document.querySelector("#jss-server-side");
		if (jssStyles) jssStyles.parentElement?.removeChild(jssStyles);
	}


@Injectable()
export class JwtTwoFactorStrategy extends PassportStrategy(
  Strategy,
  'jwt-two-factor',
) {
  constructor(
    private readonly userService: UserService,
    @Inject(authenticationConfig.KEY)
    private authConfig: ConfigType<typeof authenticationConfig>,
  ) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: authConfig.secret,
    });
  }

  async validate(payload: JwtPayload) {
    if (!payload.isSecondFactorAuthenticated) {
      throw new InvalidCredentialsException();
    }

    if (payload.refresh) {
      throw new WrongTokenException();
    }

    const user = await this.userService.getByEmail(payload.email);

    if (!user) {
      throw new InvalidCredentialsException();
    }

    return user;
  }
}


async validate(payload: JwtPayload) {
    if (!payload.isSecondFactorAuthenticated) {
      throw new InvalidCredentialsException();
    }

    if (payload.refresh) {
      throw new WrongTokenException();
    }

    const user = await this.userService.getByEmail(payload.email);

    if (!user) {
      throw new InvalidCredentialsException();
    }

    return user;
  }


function createComponent(results: FlowFileResult[], totalCount: number):
      ComponentFixture<TestHostComponent> {
    const fixture = TestBed.createComponent(TestHostComponent);
    fixture.componentInstance.results = results;
    fixture.componentInstance.totalCount = totalCount;
    fixture.detectChanges();

    return fixture;
  }


function createStatEntry(index: number): StatEntry {
    return translateStatEntry({
      pathspec: newPathSpec(`/home/foo/bar/${index}`),
      stMode: '420',  // 0644
      stDev: 16777220 + index,
      stNlink: 1 + index,
      stSize: `${index + 1}42`,
      stAtime: `${index + 1}40000`,
      stMtime: `${index + 1}400000`,
      stCtime: `${index + 1}4000000`,
      stBtime: `${index + 1}40000000`,
    });
  }


function getFileNames() {
      const p1 = fixture.debugElement.query(
          By.css('tbody tr:nth-child(1) td:nth-child(2)'));
      const p2 = fixture.debugElement.query(
          By.css('tbody tr:nth-child(2) td:nth-child(2)'));
      return [
        p1.nativeElement.innerText.trim(), p2.nativeElement.innerText.trim()
      ];
    }


() => {
    TestBed
        .configureTestingModule({
          imports: [
            NoopAnimationsModule,
            HelpersModule,
            RouterTestingModule,
            TimestampTestingModule,
          ],
          declarations: [
            TestHostComponent,
          ],
          teardown: {destroyAfterEach: false}
        })
        .compileComponents();
  }


() => {
    const fixture = createComponent(
        [flowFileResultFromStatEntry(createStatEntry(0))],
        1,
    );
    enum CellIndexOf { PATH = 1, MODE, SIZE, ATIME, MTIME, CTIME, BTIME }

    const rows = fixture.nativeElement.querySelectorAll('tr');
    // Rows include the header.
    expect(rows.length).toBe(2);

    const cells = rows[1].querySelectorAll('td');
    expect(cells[CellIndexOf.PATH].innerText.trim())
        .toContain('/home/foo/bar/0');
    expect(cells[CellIndexOf.MODE].innerText).toContain('-rw-r--r--');
    expect(cells[CellIndexOf.SIZE].innerText).toContain('142 B');
    expect(cells[CellIndexOf.ATIME].innerText)
        .toContain('1970-01-02 14:53:20 UTC');
    expect(cells[CellIndexOf.MTIME].innerText)
        .toContain('1970-01-17 04:53:20 UTC');
    expect(cells[CellIndexOf.CTIME].innerText)
        .toContain('1970-06-12 00:53:20 UTC');
    expect(cells[CellIndexOf.BTIME].innerText)
        .toContain('1974-06-09 08:53:20 UTC');
  }