declare class HMDVRDevice implements WebVRApi.VRDevice {
    /**
     * An identifier for the distinct hardware unit that this VRDevice is a part of.
     */
    hardwareUnitId: string;
    /**
     * An identifier for this distinct sensor/device on a physical hardware device.
     */
    deviceId: string;
    /**
     * A user-readable name identifying the device.
     */
    deviceName: string;

    /**
     * Return the current VREyeParameters for the given eye.
     */
    getEyeParameters(whichEye: VREye): WebVRApi.VREyeParameters;
    /**
     * Set the field of view for both eyes. If
     */
    setFieldOfView(leftFOV?: WebVRApi.VRFieldOfViewInit, rightFOV?: WebVRApi.VRFieldOfViewInit, zNear?: number, zFar?: number): void;
}


declare class PositionSensorVRDevice implements WebVRApi.VRDevice {
    /**
     * An identifier for the distinct hardware unit that this VRDevice is a part of.
     */
    hardwareUnitId: string;
    /**
     * An identifier for this distinct sensor/device on a physical hardware device.
     */
    deviceId: string;
    /**
     * A user-readable name identifying the device.
     */
    deviceName: string;

    /**
     * Return a VRPositionState dictionary containing the state of this position sensor state for the current frame (if within a requestAnimationFrame context) or for the previous frame.
     */
    getState(): WebVRApi.VRPositionState;
    /**
     * Return the current instantaneous sensor state.
     */
    getImmediateState(): WebVRApi.VRPositionState;

    /**
     * Reset this sensor, treating its current position and orientation yaw as the "origin/zero" values.
     */
    resetSensor(): void;
}


export interface VRFieldOfViewReadOnly {
        upDegrees: number;
        rightDegrees: number;
        downDegrees: number;
        leftDegrees: number;
    }


export interface VRFieldOfViewInit {
        upDegrees: number;
        rightDegrees: number;
        downDegrees: number;
        leftDegrees: number;
    }


export interface VRFieldOfView extends VRFieldOfViewReadOnly {
        constructor(upDegrees:number, rightDegrees:number, downDegrees:number, leftDegrees:number): VRFieldOfView;
        upDegrees: number;
        rightDegrees: number;
        downDegrees: number;
        leftDegrees: number;
    }


export interface VRPositionState {
        /**
         * Monotonically increasing value that allows the author to determine if position state data been updated from the hardware.
         */
        timeStamp: number;
        /**
         * True if the position attribute is valid. If false position MUST be null.
         */
        hasPosition: boolean;
        /**
         * Position of the sensor at timeStamp as a 3D vector.
         */
        position?: GeometryDom.DOMPoint;
        /**
         * Linear velocity of the sensor at timeStamp.
         */
        linearVelocity?: GeometryDom.DOMPoint;
        /**
         * Linear acceleration of the sensor at timeStamp.
         */
        linearAcceleration?: GeometryDom.DOMPoint;
        /**
         * True if the orientation attribute is valid. If false orientation MUST be null.
         */
        hasOrientation: boolean;
        /**
         * Orientation of the sensor at timeStamp as a quaternion.
         */
        orientation?: GeometryDom.DOMPoint;
        /**
         * Angular velocity of the sensor at timeStamp.
         */
        angularVelocity?: GeometryDom.DOMPoint;
        /**
         * Angular acceleration of the sensor at timeStamp.
         */
        angularAcceleration?: GeometryDom.DOMPoint;
    }


export interface VREyeParameters {
        /**
         * Describes the minimum supported field of view for the eye.
         */
        minimumFieldOfView: VRFieldOfView;
        /**
         * Describes the maximum supported field of view for the eye.
         */
        maximumFieldOfView: VRFieldOfView;
        /**
         * Describes the recommended field of view for the eye.
         */
        recommendedFieldOfView: VRFieldOfView;
        /**
         * Offset from the center of the users head to the eye in meters.
         */
        eyeTranslation: GeometryDom.DOMPoint;
        /**
         * The current field of view for the eye, as specified by setFieldOfView.
         */
        currentFieldOfView: VRFieldOfView;
        /**
         * Describes the viewport of a canvas into which visuals for this eye should be rendered.
         */
        renderRect: GeometryDom.DOMRect;
    }


export interface VRDevice {
        /**
         * An identifier for the distinct hardware unit that this VRDevice is a part of.
         */
        hardwareUnitId: string;
        /**
         * An identifier for this distinct sensor/device on a physical hardware device.
         */
        deviceId: string;
        /**
         * A user-readable name identifying the device.
         */
        deviceName: string;
    }


interface Navigator {
    /**
     * Return a Promise which resolves to a list of available VRDevices.
     */
    getVRDevices(): Promise<Array<WebVRApi.VRDevice>>;
}


// Type definitions for WebVR API
// Project: http://mozvr.github.io/webvr-spec/webvr.html
// Definitions by: Toshiya Nakakura <https://github.com/nakakura>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference path="../geometry-dom/geometry-dom.d.ts" />
declare type VREye = string;


/**
     * Return the current VREyeParameters for the given eye.
     */
getEyeParameters(whichEye: VREye): WebVRApi.VREyeParameters;


/**
     * Set the field of view for both eyes. If
     */
setFieldOfView(leftFOV?: WebVRApi.VRFieldOfViewInit, rightFOV?: WebVRApi.VRFieldOfViewInit, zNear?: number, zFar?: number): void;


/**
     * Return a VRPositionState dictionary containing the state of this position sensor state for the current frame (if within a requestAnimationFrame context) or for the previous frame.
     */
getState(): WebVRApi.VRPositionState;


/**
     * Return the current instantaneous sensor state.
     */
getImmediateState(): WebVRApi.VRPositionState;


/**
     * Reset this sensor, treating its current position and orientation yaw as the "origin/zero" values.
     */
resetSensor(): void;


@NgModule({
  imports: [CommonModule, ...NB_MODULES],
  exports: [CommonModule, ...PIPES, ...COMPONENTS],
  declarations: [...COMPONENTS, ...PIPES],
})
export class ThemeModule {
  static forRoot(): ModuleWithProviders {
    return <ModuleWithProviders>{
      ngModule: ThemeModule,
      providers: [
        ...NbThemeModule.forRoot(
          {
            name: 'default',
          },
          [ DEFAULT_THEME, COSMIC_THEME, CORPORATE_THEME, DARK_THEME ],
        ).providers,
      ],
    };
  }
}


static forRoot(): ModuleWithProviders {
    return <ModuleWithProviders>{
      ngModule: ThemeModule,
      providers: [
        ...NbThemeModule.forRoot(
          {
            name: 'default',
          },
          [ DEFAULT_THEME, COSMIC_THEME, CORPORATE_THEME, DARK_THEME ],
        ).providers,
      ],
    };
  }


/**
 * The Chat Message class is a type of :class:`Entity` which represents individual messages in the chat log.
 *
 */
declare class ChatMessage extends Entity<ChatMessage.Data> {
  /**
   * Get a reference to the user who sent the chat message
   */
  user: User;

  /**
   * If the Message contains a dice roll, store it here
   */
  _roll: Roll | null;

  /**
   * Configure the attributes of the ChatMessage Entity
   */
  static get config(): Entity.Config<ChatMessage>;

  /* -------------------------------------------- */
  /*  Properties and Attributes                   */
  /* -------------------------------------------- */

  /**
   * Return the recommended String alias for this message.
   * The alias could be a Token name in the case of in-character messages or dice rolls.
   * Alternatively it could be a User name in the case of OOC chat or whispers.
   */
  get alias(): string;

  /** @override */
  static can(user: User, action: string, target: ChatMessage): boolean;

  /**
   * Return whether the ChatMessage is visible to the current user
   * Messages may not be visible if they are private whispers
   */
  get visible(): boolean;

  /**
   * Is the current User the author of this message?
   */
  get isAuthor(): boolean;

  /**
   * Test whether the chat message contains a dice roll
   */
  get isRoll(): boolean;

  /**
   * Return whether the content of the message is visible to the current user
   */
  get isContentVisible(): boolean;

  /** @override */
  get permission(): number;

  /**
   * Return the Roll instance contained in this chat message, if one is present
   */
  get roll(): Roll;

  /* -------------------------------------------- */
  /*  HTML Rendering                              */
  /* -------------------------------------------- */

  /**
   * Render the HTML for the ChatMessage which should be added to the log
   */
  render(force?: boolean, options?: any): Promise<HTMLElement>;

  /* -------------------------------------------- */
  /*  Socket Listeners and Handlers               */
  /* -------------------------------------------- */

  /** @override */
  static create<T extends ChatMessage, U>(
    this: ConstructorOf<T>,
    data: Expanded<U> extends DeepPartial<ChatMessage.CreateData> ? U : DeepPartial<ChatMessage.CreateData>,
    options?: Entity.CreateOptions
  ): Promise<T | null>;
  static create<T extends ChatMessage, U>(
    this: ConstructorOf<T>,
    data: Expanded<U> extends DeepPartial<ChatMessage.CreateData>
      ? ReadonlyArray<U>
      : ReadonlyArray<DeepPartial<ChatMessage.CreateData>>,
    options?: Entity.CreateOptions
  ): Promise<T | T[] | null>;

  /**
   * Preprocess the data object used to create a new Chat Message to automatically convert some Objects to the
   * data format expected by the database handler.
   * @param data     - Single ChatMessage creation data
   * @param rollMode - The visibility mode applied to all dice rolls
   * @returns Processed message creation data
   */
  protected static _preprocessCreateData(
    data: DeepPartial<ChatMessage.CreateData>,
    {
      rollMode
    }?: {
      rollMode?: string | null;
    }
  ): ChatMessage.Data;

  /** @override */
  protected _onCreate(data: DeepPartial<ChatMessage.Data>, options: Entity.CreateOptions, userId: string): void;

  /** @override */
  protected _onUpdate(data: DeepPartial<ChatMessage.Data>, options: Entity.UpdateOptions, userId: string): void;

  /** @override */
  protected _onDelete(options: Entity.DeleteOptions, userId: string): void;

  /* -------------------------------------------- */
  /*  Saving and Loading                          */
  /* -------------------------------------------- */

  /**
   * Export the content of the chat message into a standardized log format
   */
  export(): string;

  /**
   * Transform a provided object of ChatMessage data by applying a certain rollMode to the data object.
   * @param chatData - The object of ChatMessage data prior to applying a rollMode preference
   * @param rollMode - The rollMode preference to apply to this message data
   * @returns The modified ChatMessage data with rollMode preferences applied
   */
  static applyRollMode(chatData: ChatMessage.Data, rollMode: string): ChatMessage.Data;

  /**
   * Given a string whisper target, return an Array of the user IDs which should be targeted for the whisper
   *
   * @param name - The target name of the whisper target
   * @returns An array of User instances
   */
  static getWhisperRecipients(name: string): User[];

  /**
   * Attempt to determine who is the speaking character (and token) for a certain Chat Message
   * First assume that the currently controlled Token is the speaker
   *
   * @param scene - The Scene in which the speaker resides
   * @param actor - The Actor whom is speaking
   * @param token - The Token whom is speaking
   * @param alias - The name of the speaker to display
   *
   * @returns The identified speaker data
   */
  static getSpeaker(speaker?: ChatMessage.SpeakerCreateData): ChatMessage.SpeakerData;

  /**
   * A helper to prepare the speaker object based on a target Token
   */
  protected static _getSpeakerFromToken({ token, alias }: { token: Token; alias?: string }): ChatMessage.SpeakerData;

  /**
   * A helper to prepare the speaker object based on a target Actor
   */
  protected static _getSpeakerFromActor({
    scene,
    actor,
    alias
  }: {
    scene?: Scene;
    actor: Actor;
    alias?: string;
  }): ChatMessage.SpeakerData;

  /**
   * A helper to prepare the speaker object based on a target User
   */
  protected static _getSpeakerFromUser({
    scene,
    user,
    alias
  }: {
    scene?: Scene;
    user: User;
    alias?: string;
  }): ChatMessage.SpeakerData;

  /* -------------------------------------------- */
  /*  Roll Data Preparation                       */
  /* -------------------------------------------- */

  /**
   * Obtain a data object used to evaluate any dice rolls associated with this particular chat message
   * @remarks
   * Returns Actor.data.data
   */
  getRollData(): any; // Actor.data.data

  /**
   * Obtain an Actor instance which represents the speaker of this message (if any)
   * @param speaker - The speaker data object
   */
  static getSpeakerActor(speaker: ChatMessage.SpeakerData): Actor | null;
}


interface Data extends Entity.Data {
    content: string;
    roll?: string;
    speaker: SpeakerData;
    timestamp: number;
    type: number;
    user: string;
    whisper: string[];
  }


/**
   * Variant of ChatMessage.Data for use in the `create` method
   */
interface CreateData extends Entity.Data {
    content: string;
    roll?: string | Roll;
    speaker: SpeakerData | SpeakerCreateData;
    timestamp: number;
    type: number;
    user: string | User;
    whisper: Array<string | User>;
  }


interface ChatData {
    user: string;
    speaker: SpeakerData;
  }


interface MessageData {
    alias: string;
    author: User;
    borderColor: string;
    cssClass: string;
    isWhisper: boolean;
    message: object;
    user: User;
    whisperTo: string;
  }


interface SpeakerData {
    scene: string | null;
    token: string | null;
    actor: string | null;
    alias: string;
  }


interface SpeakerCreateData {
    scene?: Scene | null;
    token?: Token | null;
    actor?: Actor | null;
    alias?: string;
  }


/** @override */
static can(user: User, action: string, target: ChatMessage): boolean;


/* -------------------------------------------- */
/*  HTML Rendering                              */
/* -------------------------------------------- */
/**
   * Render the HTML for the ChatMessage which should be added to the log
   */
render(force?: boolean, options?: any): Promise<HTMLElement>;


/* -------------------------------------------- */
/*  Socket Listeners and Handlers               */
/* -------------------------------------------- */
/** @override */
static create<T extends ChatMessage, U>(
    this: ConstructorOf<T>,
    data: Expanded<U> extends DeepPartial<ChatMessage.CreateData> ? U : DeepPartial<ChatMessage.CreateData>,
    options?: Entity.CreateOptions
  ): Promise<T | null>;


static create<T extends ChatMessage, U>(
    this: ConstructorOf<T>,
    data: Expanded<U> extends DeepPartial<ChatMessage.CreateData>
      ? ReadonlyArray<U>
      : ReadonlyArray<DeepPartial<ChatMessage.CreateData>>,
    options?: Entity.CreateOptions
  ): Promise<T | T[] | null>;


/**
   * Preprocess the data object used to create a new Chat Message to automatically convert some Objects to the
   * data format expected by the database handler.
   * @param data     - Single ChatMessage creation data
   * @param rollMode - The visibility mode applied to all dice rolls
   * @returns Processed message creation data
   */
protected static _preprocessCreateData(
    data: DeepPartial<ChatMessage.CreateData>,
    {
      rollMode
    }?: {
      rollMode?: string | null;
    }
  ): ChatMessage.Data;


/** @override */
protected _onCreate(data: DeepPartial<ChatMessage.Data>, options: Entity.CreateOptions, userId: string): void;


/** @override */
protected _onUpdate(data: DeepPartial<ChatMessage.Data>, options: Entity.UpdateOptions, userId: string): void;


/** @override */
protected _onDelete(options: Entity.DeleteOptions, userId: string): void;


/* -------------------------------------------- */
/*  Saving and Loading                          */
/* -------------------------------------------- */
/**
   * Export the content of the chat message into a standardized log format
   */
export(): string;


/**
   * Transform a provided object of ChatMessage data by applying a certain rollMode to the data object.
   * @param chatData - The object of ChatMessage data prior to applying a rollMode preference
   * @param rollMode - The rollMode preference to apply to this message data
   * @returns The modified ChatMessage data with rollMode preferences applied
   */
static applyRollMode(chatData: ChatMessage.Data, rollMode: string): ChatMessage.Data;


/**
   * Given a string whisper target, return an Array of the user IDs which should be targeted for the whisper
   *
   * @param name - The target name of the whisper target
   * @returns An array of User instances
   */
static getWhisperRecipients(name: string): User[];


/**
   * Attempt to determine who is the speaking character (and token) for a certain Chat Message
   * First assume that the currently controlled Token is the speaker
   *
   * @param scene - The Scene in which the speaker resides
   * @param actor - The Actor whom is speaking
   * @param token - The Token whom is speaking
   * @param alias - The name of the speaker to display
   *
   * @returns The identified speaker data
   */
static getSpeaker(speaker?: ChatMessage.SpeakerCreateData): ChatMessage.SpeakerData;


/**
   * A helper to prepare the speaker object based on a target Token
   */
protected static _getSpeakerFromToken({ token, alias }: { token: Token; alias?: string }): ChatMessage.SpeakerData;


/**
   * A helper to prepare the speaker object based on a target Actor
   */
protected static _getSpeakerFromActor({
    scene,
    actor,
    alias
  }: {
    scene?: Scene;
    actor: Actor;
    alias?: string;
  }): ChatMessage.SpeakerData;


/**
   * A helper to prepare the speaker object based on a target User
   */
protected static _getSpeakerFromUser({
    scene,
    user,
    alias
  }: {
    scene?: Scene;
    user: User;
    alias?: string;
  }): ChatMessage.SpeakerData;


/* -------------------------------------------- */
/*  Roll Data Preparation                       */
/* -------------------------------------------- */
/**
   * Obtain a data object used to evaluate any dice rolls associated with this particular chat message
   * @remarks
   * Returns Actor.data.data
   */
getRollData(): any;


/**
   * Obtain an Actor instance which represents the speaker of this message (if any)
   * @param speaker - The speaker data object
   */
static getSpeakerActor(speaker: ChatMessage.SpeakerData): Actor | null;


// -----------------------------------------------------------------------
// Utility functions for finding dimensions and locations of DOM elements
// -----------------------------------------------------------------------
// Returns the ratio that an element has been scaled (for example, by CSS
// transforms) in the x and y directions.
function findScalingRatio($el: JQuery<HTMLElement>) {
  const boundingRect = $el[0].getBoundingClientRect();

  return {
    x: boundingRect.width / $el.outerWidth(),
    y: boundingRect.height / $el.outerHeight(),
  };
}


function findOrigin($el: JQuery<HTMLElement>): Offset {
  const offset = $el.offset();
  const scalingRatio = findScalingRatio($el);

  // Find the size of the padding and border, for the top and left. This is
  // before any transforms.
  const paddingBorder = {
    left:
      parseInt($el.css("border-left-width")) +
      parseInt($el.css("padding-left")),
    top:
      parseInt($el.css("border-top-width")) + parseInt($el.css("padding-top")),
  };

  // offset() returns the upper left corner of the element relative to the
  // page, but it includes padding and border. Here we find the upper left
  // of the element, not including padding and border.
  return {
    x: offset.left + scalingRatio.x * paddingBorder.left,
    y: offset.top + scalingRatio.y * paddingBorder.top,
  };
}


// Find the dimensions of a tag, after transforms, and without padding and
// border.
function findDims($el: JQuery<HTMLElement>) {
  // If there's any padding/border, we need to find the ratio of the actual
  // element content compared to the element plus padding and border.
  const contentRatio = {
    x: $el.width() / $el.outerWidth(),
    y: $el.height() / $el.outerHeight(),
  };

  // Get the dimensions of the element _after_ any CSS transforms. This
  // includes the padding and border.
  const boundingRect = $el[0].getBoundingClientRect();

  // Dimensions of the element after any CSS transforms, and without
  // padding/border.
  return {
    x: contentRatio.x * boundingRect.width,
    y: contentRatio.y * boundingRect.height,
  };
}


// Given an offset in an img in CSS pixels, return the corresponding offset
// in source image pixels. The offsetCss can have properties like "x",
// "xmin", "y", and "ymax" -- anything that starts with "x" and "y". If the
// img content is 1000 pixels wide, but is scaled to 400 pixels on screen,
// and the input is x:400, then this will return x:1000.
function scaleCssToImg(offsetCss: Bounds): Bounds;


function scaleCssToImg(offsetCss: Offset): Offset;


function scaleCssToImg(offsetCss: OffsetCss): OffsetImg;


function scaleCssToImg(offsetCss) {
    const pixelScaling = coordmap.imgToCssScalingRatio();

    const result = mapValues(offsetCss, (value, key) => {
      const prefix = key.substring(0, 1);

      if (prefix === "x") {
        return offsetCss[key] / pixelScaling.x;
      } else if (prefix === "y") {
        return offsetCss[key] / pixelScaling.y;
      }
      return null;
    });

    return result;
  }


// Given an offset in an img, in source image pixels, return the
// corresponding offset in CSS pixels. If the img content is 1000 pixels
// wide, but is scaled to 400 pixels on screen, and the input is x:1000,
// then this will return x:400.
function scaleImgToCss(offsetImg: Bounds): Bounds;


function scaleImgToCss(offsetImg: Offset): Offset;


function scaleImgToCss(offsetImg: OffsetImg): OffsetCss;


function scaleImgToCss(offsetImg: { [key: string]: number }): {
    [key: string]: number;
  } {
    const pixelScaling = coordmap.imgToCssScalingRatio();

    const result = mapValues(offsetImg, (value, key) => {
      const prefix = key.substring(0, 1);

      if (prefix === "x") {
        return offsetImg[key] * pixelScaling.x;
      } else if (prefix === "y") {
        return offsetImg[key] * pixelScaling.y;
      }
      return null;
    });

    return result;
  }


(value, key) => {
      const prefix = key.substring(0, 1);

      if (prefix === "x") {
        return offsetCss[key] / pixelScaling.x;
      } else if (prefix === "y") {
        return offsetCss[key] / pixelScaling.y;
      }
      return null;
    }


(value, key) => {
      const prefix = key.substring(0, 1);

      if (prefix === "x") {
        return offsetImg[key] * pixelScaling.x;
      } else if (prefix === "y") {
        return offsetImg[key] * pixelScaling.y;
      }
      return null;
    }


type OffsetCss = { [key: string]: number };


type OffsetImg = { [key: string]: number };


type Coords = {
  // eslint-disable-next-line @typescript-eslint/naming-convention
  coords_css: Offset;
  // eslint-disable-next-line @typescript-eslint/naming-convention
  coords_img: Offset;
  x?: number;
  y?: number;
  // eslint-disable-next-line @typescript-eslint/naming-convention
  img_css_ratio?: Offset;
  mapping?: Panel["mapping"];
  domain?: Panel["domain"];
  range?: Panel["range"];
  log?: Panel["log"];
};


type CoordmapInit = {
  panels: Panel[];
  dims: {
    height: number;
    width: number;
  };
};


type Coordmap = {
  panels: Panel[];
  dims: {
    height: number;
    width: number;
  };
  mouseOffsetCss: (evt: JQuery.MouseEventBase) => Offset;
  scaleCssToImg: {
    (offsetCss: Bounds): Bounds;
    (offsetCss: Offset): Offset;
    (offsetCss: OffsetCss): OffsetImg;
  };
  scaleImgToCss: {
    (offsetImg: Bounds): Bounds;
    (offsetImg: Offset): Offset;
    (offsetImg: OffsetImg): OffsetCss;
  };
  imgToCssScalingRatio: () => Offset;
  cssToImgScalingRatio: () => Offset;

  getPanelCss: (offsetCss: OffsetCss, expand?: number) => Panel;
  isInPanelCss: (offsetCss: OffsetCss, expand?: number) => boolean;

  mouseCoordinateSender: (
    inputId: string,
    clip?: boolean,
    nullOutside?: boolean
  ) => (e: JQuery.MouseDownEvent | JQuery.MouseMoveEvent) => void;
};


/**
 * <p>
 *          Executes a budget action.
 *       </p>
 * @example
 * Use a bare-bones client and the command you need to make an API call.
 * ```javascript
 * import { BudgetsClient, ExecuteBudgetActionCommand } from "@aws-sdk/client-budgets"; // ES Modules import
 * // const { BudgetsClient, ExecuteBudgetActionCommand } = require("@aws-sdk/client-budgets"); // CommonJS import
 * const client = new BudgetsClient(config);
 * const command = new ExecuteBudgetActionCommand(input);
 * const response = await client.send(command);
 * ```
 *
 * @see {@link ExecuteBudgetActionCommandInput} for command's `input` shape.
 * @see {@link ExecuteBudgetActionCommandOutput} for command's `response` shape.
 * @see {@link BudgetsClientResolvedConfig | config} for command's `input` shape.
 *
 */
export class ExecuteBudgetActionCommand extends $Command<
  ExecuteBudgetActionCommandInput,
  ExecuteBudgetActionCommandOutput,
  BudgetsClientResolvedConfig
> {
  // Start section: command_properties
  // End section: command_properties

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

  /**
   * @internal
   */
  resolveMiddleware(
    clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
    configuration: BudgetsClientResolvedConfig,
    options?: __HttpHandlerOptions
  ): Handler<ExecuteBudgetActionCommandInput, ExecuteBudgetActionCommandOutput> {
    this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));

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

    const { logger } = configuration;
    const clientName = "BudgetsClient";
    const commandName = "ExecuteBudgetActionCommand";
    const handlerExecutionContext: HandlerExecutionContext = {
      logger,
      clientName,
      commandName,
      inputFilterSensitiveLog: ExecuteBudgetActionRequest.filterSensitiveLog,
      outputFilterSensitiveLog: ExecuteBudgetActionResponse.filterSensitiveLog,
    };
    const { requestHandler } = configuration;
    return stack.resolve(
      (request: FinalizeHandlerArguments<any>) =>
        requestHandler.handle(request.request as __HttpRequest, options || {}),
      handlerExecutionContext
    );
  }

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

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

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


export interface ExecuteBudgetActionCommandInput extends ExecuteBudgetActionRequest {}


export interface ExecuteBudgetActionCommandOutput extends ExecuteBudgetActionResponse, __MetadataBearer {}


/**
   * @internal
   */
resolveMiddleware(
    clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>,
    configuration: BudgetsClientResolvedConfig,
    options?: __HttpHandlerOptions
  ): Handler<ExecuteBudgetActionCommandInput, ExecuteBudgetActionCommandOutput> {
    this.middlewareStack.use(getSerdePlugin(configuration, this.serialize, this.deserialize));

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

    const { logger } = configuration;
    const clientName = "BudgetsClient";
    const commandName = "ExecuteBudgetActionCommand";
    const handlerExecutionContext: HandlerExecutionContext = {
      logger,
      clientName,
      commandName,
      inputFilterSensitiveLog: ExecuteBudgetActionRequest.filterSensitiveLog,
      outputFilterSensitiveLog: ExecuteBudgetActionResponse.filterSensitiveLog,
    };
    const { requestHandler } = configuration;
    return stack.resolve(
      (request: FinalizeHandlerArguments<any>) =>
        requestHandler.handle(request.request as __HttpRequest, options || {}),
      handlerExecutionContext
    );
  }


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


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


() => props.disabled || elForm?.disabled


() => {
    const totalHeight = filteredOptions.value.length * 34
    return totalHeight > props.height ? props.height : totalHeight
  }


() => {
    return (
      props.modelValue !== undefined &&
      props.modelValue !== null &&
      props.modelValue !== ''
    )
  }


() => {
    const hasValue = props.multiple
      ? Array.isArray(props.modelValue) && props.modelValue.length > 0
      : hasModelValue.value

    const criteria =
      props.clearable &&
      !selectDisabled.value &&
      states.comboBoxHovering &&
      hasValue
    return criteria
  }


() =>
    props.remote && props.filterable ? '' : ArrowUp


() => iconComponent.value && nsSelectV2.is('reverse', expanded.value)


() => elFormItem?.validateState || ''


() => ValidateComponentsMap[validateState.value]


() => (props.remote ? 300 : 0)


() => {
    const options = filteredOptions.value
    if (props.loading) {
      return props.loadingText || t('el.select.loading')
    } else {
      if (props.remote && states.inputValue === '' && options.length === 0)
        return false
      if (props.filterable && states.inputValue && options.length > 0) {
        return props.noMatchText || t('el.select.noMatch')
      }
      if (options.length === 0) {
        return props.noDataText || t('el.select.noData')
      }
    }
    return null
  }


() => {
    const isValidOption = (o: Option): boolean => {
      // fill the conditions here.
      const query = states.inputValue
      // when query was given, we should test on the label see whether the label contains the given query
      const containsQueryString = query ? o.label.includes(query) : true
      return containsQueryString
    }
    if (props.loading) {
      return []
    }
    return flattenOptions(
      (props.options as OptionType[])
        .concat(states.createdOptions)
        .map((v) => {
          if (isArray(v.options)) {
            const filtered = v.options.filter(isValidOption)
            if (filtered.length > 0) {
              return {
                ...v,
                options: filtered,
              }
            }
          } else {
            if (props.remote || isValidOption(v as Option)) {
              return v
            }
          }
          return null
        })
        .filter((v) => v !== null)
    )
  }


(o: Option): boolean => {
      // fill the conditions here.
      const query = states.inputValue
      // when query was given, we should test on the label see whether the label contains the given query
      const containsQueryString = query ? o.label.includes(query) : true
      return containsQueryString
    }


(v) => {
          if (isArray(v.options)) {
            const filtered = v.options.filter(isValidOption)
            if (filtered.length > 0) {
              return {
                ...v,
                options: filtered,
              }
            }
          } else {
            if (props.remote || isValidOption(v as Option)) {
              return v
            }
          }
          return null
        }


(v) => v !== null


() =>
    filteredOptions.value.every((option) => option.disabled)


(option) => option.disabled


() =>
    'small' === selectSize.value ? 'small' : 'default'


() => {
    const select = selectionRef.value
    const size = collapseTagSize.value || 'default'
    const paddingLeft = select
      ? parseInt(getComputedStyle(select).paddingLeft)
      : 0
    const paddingRight = select
      ? parseInt(getComputedStyle(select).paddingRight)
      : 0
    return (
      states.selectWidth - paddingRight - paddingLeft - TAG_BASE_WIDTH[size]
    )
  }


() => {
    popperSize.value = selectRef.value?.getBoundingClientRect?.()?.width || 200
  }


() => {
    return {
      width: `${
        states.calculatedWidth === 0
          ? MINIMUM_INPUT_WIDTH
          : Math.ceil(states.calculatedWidth) + MINIMUM_INPUT_WIDTH
      }px`,
    } as CSSProperties
  }


() => {
    if (isArray(props.modelValue)) {
      return props.modelValue.length === 0 && !states.displayInputValue
    }

    // when it's not multiple mode, we only determine this flag based on filterable and expanded
    // when filterable flag is true, which means we have input box on the screen
    return props.filterable ? states.displayInputValue.length === 0 : true
  }


() => {
    const _placeholder = props.placeholder || t('el.select.placeholder')
    return props.multiple ? _placeholder : states.selectedLabel || _placeholder
  }


() => popper.value?.popperRef?.contentRef


() => {
    if (props.multiple) {
      const len = (props.modelValue as []).length
      if ((props.modelValue as Array<any>).length > 0) {
        return filteredOptions.value.findIndex(
          (o) => o.value === props.modelValue[len - 1]
        )
      }
    } else {
      if (props.modelValue) {
        return filteredOptions.value.findIndex(
          (o) => o.value === props.modelValue
        )
      }
    }
    return -1
  }


(o) => o.value === props.modelValue[len - 1]


(o) => o.value === props.modelValue


() => {
    return expanded.value && emptyText.value !== false
  }


(e) => onInput(e)


() => {
    inputRef.value.focus?.()
    popper.value?.updatePopper()
  }


() => {
    if (props.automaticDropdown) return
    if (!selectDisabled.value) {
      if (states.isComposing) states.softFocus = true
      return nextTick(() => {
        expanded.value = !expanded.value
        inputRef.value?.focus?.()
      })
    }
  }


() => {
        expanded.value = !expanded.value
        inputRef.value?.focus?.()
      }


() => {
    if (props.filterable && states.inputValue !== states.selectedLabel) {
      states.query = states.selectedLabel
    }
    handleQueryChange(states.inputValue)
    return nextTick(() => {
      createNewOption(states.inputValue)
    })
  }


() => {
      createNewOption(states.inputValue)
    }


(val: string) => {
    if (states.previousQuery === val) {
      return
    }
    states.previousQuery = val
    if (props.filterable && isFunction(props.filterMethod)) {
      props.filterMethod(val)
    } else if (
      props.filterable &&
      props.remote &&
      isFunction(props.remoteMethod)
    ) {
      props.remoteMethod(val)
    }
  }


(val: any | any[]) => {
    if (!isEqual(props.modelValue, val)) {
      emit(CHANGE_EVENT, val)
    }
  }


(val: any) => {
    emit(UPDATE_MODEL_EVENT, val)
    emitChange(val)
    states.previousValue = val.toString()
  }


(arr = [], value: unknown) => {
    if (!isObject(value)) {
      return arr.indexOf(value)
    }
    const valueKey = props.valueKey
    let index = -1
    arr.some((item, i) => {
      if (get(item, valueKey) === get(value, valueKey)) {
        index = i
        return true
      }
      return false
    })
    return index
  }


(item, i) => {
      if (get(item, valueKey) === get(value, valueKey)) {
        index = i
        return true
      }
      return false
    }


(item: unknown) => {
    return isObject(item) ? get(item, props.valueKey) : item
  }


(item: unknown) => {
    return isObject(item) ? item.label : item
  }


() => {
    if (props.collapseTags && !props.filterable) {
      return
    }
    return nextTick(() => {
      if (!inputRef.value) return
      const selection = selectionRef.value

      selectRef.value.height = selection.offsetHeight
      if (expanded.value && emptyText.value !== false) {
        popper.value?.updatePopper?.()
      }
    })
  }


() => {
      if (!inputRef.value) return
      const selection = selectionRef.value

      selectRef.value.height = selection.offsetHeight
      if (expanded.value && emptyText.value !== false) {
        popper.value?.updatePopper?.()
      }
    }


() => {
    resetInputWidth()
    calculatePopperSize()
    popper.value?.updatePopper?.()
    if (props.multiple) {
      return resetInputHeight()
    }
  }


() => {
    const select = selectionRef.value
    if (select) {
      states.selectWidth = select.getBoundingClientRect().width
    }
  }


(option: Option, idx: number, byClick = true) => {
    if (props.multiple) {
      let selectedOptions = (props.modelValue as any[]).slice()

      const index = getValueIndex(selectedOptions, getValueKey(option))
      if (index > -1) {
        selectedOptions = [
          ...selectedOptions.slice(0, index),
          ...selectedOptions.slice(index + 1),
        ]
        states.cachedOptions.splice(index, 1)
        removeNewOption(option)
      } else if (
        props.multipleLimit <= 0 ||
        selectedOptions.length < props.multipleLimit
      ) {
        selectedOptions = [...selectedOptions, getValueKey(option)]
        states.cachedOptions.push(option)
        selectNewOption(option)
        updateHoveringIndex(idx)
      }
      update(selectedOptions)
      if (option.created) {
        states.query = ''
        handleQueryChange('')
        states.inputLength = 20
      }
      if (props.filterable && !props.reserveKeyword) {
        inputRef.value.focus?.()
        onUpdateInputValue('')
      }
      if (props.filterable) {
        states.calculatedWidth =
          calculatorRef.value.getBoundingClientRect().width
      }
      resetInputHeight()
      setSoftFocus()
    } else {
      selectedIndex.value = idx
      states.selectedLabel = option.label
      update(getValueKey(option))
      expanded.value = false
      states.isComposing = false
      states.isSilentBlur = byClick
      selectNewOption(option)
      if (!option.created) {
        clearAllNewOption()
      }
      updateHoveringIndex(idx)
    }
  }


(event: MouseEvent, tag: Option) => {
    const index = (props.modelValue as Array<any>).indexOf(tag.value)

    if (index > -1 && !selectDisabled.value) {
      const value = [
        ...(props.modelValue as Array<unknown>).slice(0, index),
        ...(props.modelValue as Array<unknown>).slice(index + 1),
      ]
      states.cachedOptions.splice(index, 1)
      update(value)
      emit('remove-tag', tag.value)
      states.softFocus = true
      removeNewOption(tag)
      return nextTick(focusAndUpdatePopup)
    }
    event.stopPropagation()
  }


(event: FocusEvent) => {
    const focused = states.isComposing
    states.isComposing = true
    if (!states.softFocus) {
      // If already in the focus state, shouldn't trigger event
      if (!focused) emit('focus', event)
    } else {
      states.softFocus = false
    }
  }


() => {
    states.softFocus = false

    // reset input value when blurred
    // https://github.com/ElemeFE/element/pull/10822
    return nextTick(() => {
      inputRef.value?.blur?.()
      if (calculatorRef.value) {
        states.calculatedWidth =
          calculatorRef.value.getBoundingClientRect().width
      }
      if (states.isSilentBlur) {
        states.isSilentBlur = false
      } else {
        if (states.isComposing) {
          emit('blur')
        }
      }
      states.isComposing = false
    })
  }


() => {
      inputRef.value?.blur?.()
      if (calculatorRef.value) {
        states.calculatedWidth =
          calculatorRef.value.getBoundingClientRect().width
      }
      if (states.isSilentBlur) {
        states.isSilentBlur = false
      } else {
        if (states.isComposing) {
          emit('blur')
        }
      }
      states.isComposing = false
    }


() => {
    if (states.displayInputValue.length > 0) {
      onUpdateInputValue('')
    } else {
      expanded.value = false
    }
  }


(e: KeyboardEvent) => {
    if (states.displayInputValue.length === 0) {
      e.preventDefault()
      const selected = (props.modelValue as Array<any>).slice()
      selected.pop()
      removeNewOption(states.cachedOptions.pop())
      update(selected)
    }
  }


() => {
    let emptyValue: string | any[]
    if (isArray(props.modelValue)) {
      emptyValue = []
    } else {
      emptyValue = ''
    }

    states.softFocus = true
    if (props.multiple) {
      states.cachedOptions = []
    } else {
      states.selectedLabel = ''
    }
    expanded.value = false
    update(emptyValue)
    emit('clear')
    clearAllNewOption()
    return nextTick(focusAndUpdatePopup)
  }


(val: string) => {
    states.displayInputValue = val
    states.inputValue = val
  }


(
    direction: 'forward' | 'backward',
    hoveringIndex: number = undefined
  ) => {
    const options = filteredOptions.value
    if (
      !['forward', 'backward'].includes(direction) ||
      selectDisabled.value ||
      options.length <= 0 ||
      optionsAllDisabled.value
    ) {
      return
    }
    if (!expanded.value) {
      return toggleMenu()
    }
    if (hoveringIndex === undefined) {
      hoveringIndex = states.hoveringIndex
    }
    let newIndex = -1
    if (direction === 'forward') {
      newIndex = hoveringIndex + 1
      if (newIndex >= options.length) {
        // return to the first option
        newIndex = 0
      }
    } else if (direction === 'backward') {
      newIndex = hoveringIndex - 1
      if (newIndex < 0) {
        // navigate to the last one
        newIndex = options.length - 1
      }
    }
    const option = options[newIndex]
    if (option.disabled || option.type === 'Group') {
      // prevent dispatching multiple nextTick callbacks.
      return onKeyboardNavigate(direction, newIndex)
    } else {
      updateHoveringIndex(newIndex)
      scrollToItem(newIndex)
    }
  }


() => {
    if (!expanded.value) {
      return toggleMenu()
    } else if (
      ~states.hoveringIndex &&
      filteredOptions.value[states.hoveringIndex]
    ) {
      onSelect(
        filteredOptions.value[states.hoveringIndex],
        states.hoveringIndex,
        false
      )
    }
  }


(idx: number) => {
    states.hoveringIndex = idx
  }


() => {
    states.hoveringIndex = -1
  }


() => {
    const _input = inputRef.value
    if (_input) {
      _input.focus?.()
    }
  }


(event) => {
    const value = event.target.value
    onUpdateInputValue(value)
    if (states.displayInputValue.length > 0 && !expanded.value) {
      expanded.value = true
    }

    states.calculatedWidth = calculatorRef.value.getBoundingClientRect().width
    if (props.multiple) {
      resetInputHeight()
    }
    if (props.remote) {
      debouncedOnInputChange()
    } else {
      return onInputChange()
    }
  }


() => {
    expanded.value = false
    return handleBlur()
  }


() => {
    states.inputValue = states.displayInputValue
    return nextTick(() => {
      if (~indexRef.value) {
        updateHoveringIndex(indexRef.value)
        scrollToItem(states.hoveringIndex)
      }
    })
  }


() => {
      if (~indexRef.value) {
        updateHoveringIndex(indexRef.value)
        scrollToItem(states.hoveringIndex)
      }
    }


(index: number) => {
    menuRef.value.scrollToItem(index)
  }


() => {
    resetHoveringIndex()
    if (props.multiple) {
      if ((props.modelValue as Array<any>).length > 0) {
        let initHovering = false
        states.cachedOptions.length = 0
        states.previousValue = props.modelValue.toString()
        ;(props.modelValue as Array<any>).map((selected) => {
          const itemIndex = filteredOptions.value.findIndex(
            (option) => getValueKey(option) === selected
          )
          if (~itemIndex) {
            states.cachedOptions.push(
              filteredOptions.value[itemIndex] as Option
            )
            if (!initHovering) {
              updateHoveringIndex(itemIndex)
            }
            initHovering = true
          }
        })
      } else {
        states.cachedOptions = []
        states.previousValue = ''
      }
    } else {
      if (hasModelValue.value) {
        states.previousValue = props.modelValue
        const options = filteredOptions.value
        const selectedItemIndex = options.findIndex(
          (option) => getValueKey(option) === props.modelValue
        )
        if (~selectedItemIndex) {
          states.selectedLabel = options[selectedItemIndex].label
          updateHoveringIndex(selectedItemIndex)
        } else {
          states.selectedLabel = `${props.modelValue}`
        }
      } else {
        states.selectedLabel = ''
        states.previousValue = ''
      }
    }
    calculatePopperSize()
  }


(selected) => {
          const itemIndex = filteredOptions.value.findIndex(
            (option) => getValueKey(option) === selected
          )
          if (~itemIndex) {
            states.cachedOptions.push(
              filteredOptions.value[itemIndex] as Option
            )
            if (!initHovering) {
              updateHoveringIndex(itemIndex)
            }
            initHovering = true
          }
        }


(option) => getValueKey(option) === selected


(option) => getValueKey(option) === props.modelValue


(val) => {
    emit('visible-change', val)
    if (val) {
      popper.value.update?.()
      // the purpose of this function is to differ the blur event trigger mechanism
    } else {
      states.displayInputValue = ''
      createNewOption('')
    }
  }


() => props.modelValue


(val, oldVal) => {
      if (!val || val.toString() !== states.previousValue) {
        initStates()
      }
      if (!isEqual(val, oldVal)) {
        elFormItem?.validate?.('change').catch((err) => debugWarn(err))
      }
    }


(err) => debugWarn(err)


() => props.options


() => {
      const input = inputRef.value
      // filter or remote-search scenarios are not initialized
      if (!input || (input && document.activeElement !== input)) {
        initStates()
      }
    }


() => {
    return nextTick(menuRef.value.resetScrollTop)
  }


() => {
    initStates()
    addResizeListener(selectRef.value, handleResize)
  }


() => {
    removeResizeListener(selectRef.value, handleResize)
  }


@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    MyCalendarRoutingModule,
    NgbModalModule,
    FlatpickrModule.forRoot(),
    CalendarModule.forRoot({
      provide: DateAdapter,
      useFactory: adapterFactory
    })
  ],
  declarations: [MyCalendarComponent],
  exports: [MyCalendarComponent]
})
export class MyCalendarModule {}


export class Footer extends Component {
    render() {
        return (

                            A silly game written by Jeff Clement

        );
    }
}


render() {
        return (

                            A silly game written by Jeff Clement

        );
    }


export type Card = {
    id: CardId;
    title: string;
    awards: number;
    value: number;
    happiness: number;
    buy?: {
        cost: number;
    },
    flip?: {
        id: CardId;
        cost: number;
    }
    recycle?: {
        id: CardId;
        cost: number
    }
}


n => n + 1


@Component({
    selector: 'pagination-widget',
    templateUrl: './pagination-widget.component.html',
    styleUrls: ['./pagination-widget.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class PaginationWidgetComponent {
    private numberOfPages: number;
    public iterator: number[];
    public currentPage: number;

    @HostBinding('class.hidden') get shouldHide() {
        return this.numberOfPages < 2;
    }

    @Output() pageChanged = new EventEmitter<number>();

    @Input() disabled = true;
    @Input() set pagination(value: PaginationResponse<any>) {
        if (value) {
            this.numberOfPages = value.last_page > 10 ? 10 : value.last_page;
            if (this.numberOfPages > 1) {
                this.iterator = Array.from(Array(this.numberOfPages).keys()).map(n => n + 1);
                this.currentPage = value.current_page;
            }
        }
    }

    constructor(private router: Router) {}

    public selectPage(page: number) {
        if (this.currentPage !== page) {
            this.currentPage = page;
            this.pageChanged.next(page);
            this.router.navigate([], {queryParams: {page}, replaceUrl: true});
        }
    }

    public nextPage() {
        const newPage = this.currentPage + 1;
        this.selectPage(newPage <= this.numberOfPages ? newPage : this.currentPage);
    }

    public prevPage() {
        const newPage = this.currentPage - 1;
        this.selectPage(newPage >= 1 ? newPage : this.currentPage);
    }
}


public selectPage(page: number) {
        if (this.currentPage !== page) {
            this.currentPage = page;
            this.pageChanged.next(page);
            this.router.navigate([], {queryParams: {page}, replaceUrl: true});
        }
    }


public nextPage() {
        const newPage = this.currentPage + 1;
        this.selectPage(newPage <= this.numberOfPages ? newPage : this.currentPage);
    }


public prevPage() {
        const newPage = this.currentPage - 1;
        this.selectPage(newPage >= 1 ? newPage : this.currentPage);
    }


@NgModule({
  declarations: [
    AppComponent,
    AframeVrComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA]
})
export class AppModule { }


export function isPrimitive(variable: VariableValue): variable is Primative {
  return (
    !Array.isArray(variable) ||
    (variable[0] !== null && typeof variable[0] !== "object")
  );
}


function isValidType(type: string): boolean {
  return type
    .split("|")
    .map((s) => s.trim())
    .every((part) => DATA_TYPES.includes(part));
}


function parseValue(value: VariableValue): VariableValue {
  if (typeof value !== "string") {
    return value;
  }

  if (value === "null") {
    return null;
  }

  if (/^(true|false)$/i.test(value)) {
    return value === "true";
  }

  const number = parseFloat(value);
  if (!Number.isNaN(number) && number.toString().length === value.length) {
    return number;
  }

  return value;
}


function matchParen(s: string, count = 0): string {
  const match = s.match(/\(|\)/);
  if (!match || typeof match.index === "undefined") {
    return s;
  }

  const i = match.index + 1;
  if (match[0] === ")") {
    if (count === 1) {
      return s.substring(0, i);
    }

    return s.substring(0, i) + matchParen(s.substring(i), count - 1);
  }

  return s.substring(0, i) + matchParen(s.substring(i), count + 1);
}


function parseMap(mapValue: string): ValuedVariable[] {
  let remaining = mapValue.substring(1, mapValue.length - 1);
  const values: ValuedVariable[] = [];
  while (remaining.length) {
    const i = remaining.indexOf(": ");
    if (i === -1) {
      log.error(
        "Unable to hack a css variable correctly since no valid key/value split was found."
      );
      log.error("Original Map Value: ", mapValue);
      log.error("Remaining string: ", remaining);
      process.exit(1);
    }

    const name = remaining.substring(0, i);
    remaining = remaining.substring(i + 2);
    let j =
      name === "font-family"
        ? remaining.search(/, [-a-z]+: /)
        : remaining.indexOf(",");
    if (j === -1) {
      j = remaining.length;
    }

    const remainingString = remaining.substring(0, j);
    let value: VariableValue = remainingString;
    if (remainingString.startsWith("(")) {
      const mapString = matchParen(remaining);
      j = mapString.length;
      value = parseMap(mapString);
    } else if (remainingString.includes("(")) {
      const matched = matchParen(remaining);
      j = matched.length;
      value = matched;
    }

    value = parseValue(value);
    remaining = remaining.substring(j + 1).trim();
    values.push({ name, value });
  }

  return values;
}


export function getCompiledValue(variable: VariableItem): ValuedVariable {
  const {
    file: { path },
    context: { name, value },
    type,
  } = variable;

  const prefix = `$${name}: `;
  const data = `@import '${path}';
@error '${prefix}#{${value}}'`;

  try {
    renderSync({
      data,
      outputStyle: "expanded",
      includePaths: [tempStylesDir],
    });
    throw new Error("Should never happen");
  } catch (e) {
    const { message } = e as Error;
    if (/Undefined variable |File to import not found/.test(message)) {
      log.error(`Unable to hackily generate the value for "${name}"`);
      log.error();
      log.error(message);
      process.exit(1);
    }

    let value: VariableValue = message.substring(prefix.length);
    switch (type) {
      case "List": {
        const parsed = value
          .split(/\s|,/)
          .map((part) => parseValue(part)) as SimplePrimative[];

        value = parsed;
        break;
      }
      case "Map":
        value = parseMap(value);
        break;
      default:
        // sanity check for typos since sassdoc doesn't have any validation for this
        if (!isValidType(type || "")) {
          log.error(
            `${name} variable has an invalid @type declaration: "${type}"`
          );
          log.error();
          process.exit(1);
        }
        value = parseValue(value);
    }

    return {
      name,
      value,
    };
  }
}


(s) => s.trim()


(part) => DATA_TYPES.includes(part)


(part) => parseValue(part)


export interface ValuedVariable {
  name: string;
  value: VariableValue;
}


export type VariableValue =
  | SimplePrimative
  | SimplePrimative[]
  | ValuedVariable
  | ValuedVariable[];


export type GetUserDataEntity = {
  id: string
  name: string
  githubId: number
  avatarUrl: string
  login: string
}


/**
 * The extended `Array#forEach` method that accepts a single value as an argument.
 *
 * @param values   - A value or values to iterate over.
 * @param iteratee - An iteratee function.
 */
export declare function forEach<T>(values: T | T[], iteratee: (value: T, index: number, array: T[]) => void): void;


(info) => `${info.timestamp} ${info.level}: ${info.message}`


class WinstonLogger implements LoggerInterface {
  private readonly logger: any;
  private readonly format: any;

  constructor() {
    this.format = winston.format.combine(
      winston.format.colorize(),
      winston.format.timestamp(),
      winston.format.align(),
      winston.format.printf(
        (info) => `${info.timestamp} ${info.level}: ${info.message}`
      )
    );

    this.logger = winston.createLogger({
      level: process.env.ENV_STAGE === "prod" ? "error" : "info",
      transports: [
        new winston.transports.Console({
          format: this.format,
        }),
      ],
    });
  }
  logRequest(message: string) {
    this.logger.info(message);
  }

  logError(message: string) {
    this.logger.error(message);
  }
}


interface LoggerInterface {
  logRequest: (message: string) => void;
  logError: (message: string) => void;
}


logRequest(message: string) {
    this.logger.info(message);
  }


logError(message: string) {
    this.logger.error(message);
  }


(props: CodeCopyButtonProps) => <CodeCopyButton margin


(props) => (
  <Box
    as={LivePreview}


(props) => <LiveError className


() => (
  <Box
    position="absolute"


(props: CodeBlockProps) => {
  const { className = '', live = true, manual = false, render = false, children, ...rest } = props;
  const [editorCode, setEditorCode] = useState(children.trim());
  const language = (className && (className.replace(/language-/, '') as Language)) || 'jsx';
  const { onCopy, hasCopied } = useClipboard(editorCode);
  const { pathname } = useRouter();

  // We have to do some manual work here to avoid naming conflict between components
  let imports = {};

  // Fix SearchProvider and Pagination import clashes
  if (pathname.startsWith('/components')) {
    imports = { Pagination: ReactComponents.Pagination };
  } else if (pathname.startsWith('/hooks')) {
    imports = { SearchProvider: ReactHooks.SearchProvider };
  } else if (pathname.startsWith('/search-ui')) {
    imports = { SearchProvider: ReactSearchUI.SearchProvider };
  }

  const liveProviderProps = {
    theme: codeThemes.dark,
    language,
    code: editorCode,
    scope: {
      ...ReactComponents,
      ...ReactHooks,
      ...ReactSearchUI,
      ...imports,
      mdx,
    },
    noInline: manual,
    ...rest,
  };

  const handleCodeChange = (newCode: string) => setEditorCode(newCode.trim());

  if (language === 'jsx' && live === true) {
    return (
      <SearchProvider>
        <LiveProvider {...liveProviderProps}>
          <Box position="relative">
            <EditableNotice />
            <LiveCodePreview />
            <LiveCodeError />
            <Box position="relative">
              <CopyButton onClick={onCopy} theme="dark">
                {hasCopied ? 'Copied!' : 'Copy'}
              </CopyButton>
              {/* @ts-ignore padding works but isn't in types?! */}
              <LiveEditor onChange={handleCodeChange} style={liveEditorStyle} padding={20} className="rounded-b-md" />
            </Box>
          </Box>
        </LiveProvider>
      </SearchProvider>


(newCode: string) => setEditorCode(newCode.trim())


interface CodeBlockProps {
  children: string;
  className?: string;
  live?: boolean;
  manual?: boolean;
  render?: boolean;
}


(account) => {
            this.account = account;
        }


(message) => {
            this.principal.identity().then((account) => {
                this.account = account;
            });
        }


(account) => {
                this.account = account;
            }


@Component({
    selector: 'equoid-kitchensink',
    templateUrl: './kitchensink.component.html',
    styleUrls: [
        'kitchensink.scss'
    ]

})
export class KitchensinkComponent implements OnInit {
    account: Account;

    constructor(
        private principal: Principal,
        private loginService: LoginService,
        private eventManager: JhiEventManager
    ) {
    }

    ngOnInit() {
        this.principal.identity().then((account) => {
            this.account = account;
        });
        this.registerAuthenticationSuccess();
    }

    registerAuthenticationSuccess() {
        this.eventManager.subscribe('authenticationSuccess', (message) => {
            this.principal.identity().then((account) => {
                this.account = account;
            });
        });
    }

    isAuthenticated() {
        return this.principal.isAuthenticated();
    }

    login() {
        this.loginService.login();
    }
}


ngOnInit() {
        this.principal.identity().then((account) => {
            this.account = account;
        });
        this.registerAuthenticationSuccess();
    }


registerAuthenticationSuccess() {
        this.eventManager.subscribe('authenticationSuccess', (message) => {
            this.principal.identity().then((account) => {
                this.account = account;
            });
        });
    }


isAuthenticated() {
        return this.principal.isAuthenticated();
    }


login() {
        this.loginService.login();
    }


type vkernElement = svgCoreAttributesElement<SVGElement> & {

};


@Injectable()
export class CalendarService {

    constructor(private http: Http) { }

}


(request: Request, paramType: RequestParams): object => {
    switch (paramType) {
        case RequestParams.BODY:
            return request.getBody();
        case RequestParams.QUERY:
            return request.getQueryParams();
        default:
            return null;
    }
}


(
    Klass: new() => ValidationClass, paramType: RequestParams, options: RequestValidationOptions,
): MethodDecorator => {
    const validatorOptions: ValidatorOptions = options.allowUnknownFields
        ? { whitelist: false, forbidNonWhitelisted: false }
        : { whitelist: true, forbidNonWhitelisted: true };

    return (target, key, descriptor: PropertyDescriptor): any => {
        const originalMethod = descriptor.value;

        descriptor.value = async function (request: Request, ...args: any[]): Promise<any> {
            const klass = new Klass();
            const validationObject = getValidationObject(request, paramType);
            Object.keys(validationObject).forEach((prop: string) => {
                // @ts-ignore
                klass[prop] = validationObject[prop];
            });
            const validationResult = await klass.validate(validatorOptions);
            if (validationResult.length > 0) {
                throw new ValidationError({ validationErrors: validationResult });
            }

            return originalMethod.call(this, request, ...args);
        };
    };
}


(target, key, descriptor: PropertyDescriptor): any => {
        const originalMethod = descriptor.value;

        descriptor.value = async function (request: Request, ...args: any[]): Promise<any> {
            const klass = new Klass();
            const validationObject = getValidationObject(request, paramType);
            Object.keys(validationObject).forEach((prop: string) => {
                // @ts-ignore
                klass[prop] = validationObject[prop];
            });
            const validationResult = await klass.validate(validatorOptions);
            if (validationResult.length > 0) {
                throw new ValidationError({ validationErrors: validationResult });
            }

            return originalMethod.call(this, request, ...args);
        };
    }


(prop: string) => {
                // @ts-ignore
                klass[prop] = validationObject[prop];
            }


(paramType: RequestParams) => (
    klass: new() => ValidationClass, options: RequestValidationOptions = {},
): MethodDecorator => RequestValidation(klass, paramType, options)


(
    klass: new() => ValidationClass, options: RequestValidationOptions = {},
): MethodDecorator => RequestValidation(klass, paramType, options)


export interface RequestValidationOptions {
    allowUnknownFields?: boolean;
}


export interface CommandContainingBuilder {
    addCommandToBuilder(command: Command): void;

    addCommand(command?: Command): CommandBuilder<CommandContainingBuilder>;
}


user => user?.name?.first


user => user?.name?.last


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'myApp';

  users = [
    {
      id: 1, name: { first: 'Ben', last: 'Lesh' }
    },
    {
      id: 2, name: { first: 'Jay', last: 'Phelps' }
    }
  ];

  users$ = from(this.users);

  firstName$ = this.users$.pipe(
    map(user => user?.name?.first)
  );

  lastName$ = this.users$.pipe(
    map(user => user?.name?.last)
  );
}


() => {
  afterEach(() => {
    delete (window as any).config;
    jest.resetAllMocks();
  });

  it('creates snapshot', () => {
    (window as any).config = {
      motd: 'this is a sample',
    };

    const result = render(<BannerMOTD />);
    expect(result.asFragment()).toMatchSnapshot();
  });

  describe('Render', () => {
    it('renders component', () => {
      (window as any).config = {
        motd: 'this is a sample',
      };

      const { getByRole, getByText, getByTestId } = render(<BannerMOTD />);

      const alert = getByRole('alert');
      expect(alert).toBeInTheDocument();
      expect(alert).toHaveClass('infoAlert alert-info');
      expect(getByTestId('closeBannerMOTD')).toBeInTheDocument();
      expect(getByText('this is a sample')).toBeInTheDocument();
    });

    it('renders component with specific severity type', () => {
      (window as any).config = {
        motd: 'this is a sample',
        motdSeverity: 'error',
      };

      const { getByRole } = render(<BannerMOTD />);

      const alert = getByRole('alert');
      expect(alert).toHaveClass('dangerAlert alert-danger');
    });

    it('closes alert', () => {
      (window as any).config = {
        motd: 'this is a sample',
      };

      const { getByRole, getByTestId, container } = render(<BannerMOTD />);

      const alert = getByRole('alert');
      expect(alert).toBeInTheDocument();

      const btn = getByTestId('closeBannerMOTD');
      fireEvent.click(btn);

      waitFor(() => {
        expect(container).toBeEmptyDOMElement();
      });
    });

    describe('does not render component', () => {
      it('when motd is undefined', () => {
        const { container } = render(<BannerMOTD />);
        expect(container).toBeEmptyDOMElement();
      });

      it('when motd is a empty string', () => {
        (window as any).config = {
          motd: '',
        };

        const { container } = render(<BannerMOTD />);
        expect(container).toBeEmptyDOMElement();
      });

      it('when motd is a {{ .motd }}', () => {
        // This is important for dev
        (window as any).config = {
          motd: '{{ .motd }}',
        };

        const { container } = render(<BannerMOTD />);
        expect(container).toBeEmptyDOMElement();
      });
    });
  });
}


() => {
    delete (window as any).config;
    jest.resetAllMocks();
  }


() => {
    (window as any).config = {
      motd: 'this is a sample',
    };

    const result = render(<BannerMOTD />);
    expect(result.asFragment()).toMatchSnapshot();
  }


() => {
    it('renders component', () => {
      (window as any).config = {
        motd: 'this is a sample',
      };

      const { getByRole, getByText, getByTestId } = render(<BannerMOTD />);

      const alert = getByRole('alert');
      expect(alert).toBeInTheDocument();
      expect(alert).toHaveClass('infoAlert alert-info');
      expect(getByTestId('closeBannerMOTD')).toBeInTheDocument();
      expect(getByText('this is a sample')).toBeInTheDocument();
    });

    it('renders component with specific severity type', () => {
      (window as any).config = {
        motd: 'this is a sample',
        motdSeverity: 'error',
      };

      const { getByRole } = render(<BannerMOTD />);

      const alert = getByRole('alert');
      expect(alert).toHaveClass('dangerAlert alert-danger');
    });

    it('closes alert', () => {
      (window as any).config = {
        motd: 'this is a sample',
      };

      const { getByRole, getByTestId, container } = render(<BannerMOTD />);

      const alert = getByRole('alert');
      expect(alert).toBeInTheDocument();

      const btn = getByTestId('closeBannerMOTD');
      fireEvent.click(btn);

      waitFor(() => {
        expect(container).toBeEmptyDOMElement();
      });
    });

    describe('does not render component', () => {
      it('when motd is undefined', () => {
        const { container } = render(<BannerMOTD />);
        expect(container).toBeEmptyDOMElement();
      });

      it('when motd is a empty string', () => {
        (window as any).config = {
          motd: '',
        };

        const { container } = render(<BannerMOTD />);
        expect(container).toBeEmptyDOMElement();
      });

      it('when motd is a {{ .motd }}', () => {
        // This is important for dev
        (window as any).config = {
          motd: '{{ .motd }}',
        };

        const { container } = render(<BannerMOTD />);
        expect(container).toBeEmptyDOMElement();
      });
    });
  }


() => {
      (window as any).config = {
        motd: 'this is a sample',
      };

      const { getByRole, getByText, getByTestId } = render(<BannerMOTD />);

      const alert = getByRole('alert');
      expect(alert).toBeInTheDocument();
      expect(alert).toHaveClass('infoAlert alert-info');
      expect(getByTestId('closeBannerMOTD')).toBeInTheDocument();
      expect(getByText('this is a sample')).toBeInTheDocument();
    }


() => {
      (window as any).config = {
        motd: 'this is a sample',
        motdSeverity: 'error',
      };

      const { getByRole } = render(<BannerMOTD />);

      const alert = getByRole('alert');
      expect(alert).toHaveClass('dangerAlert alert-danger');
    }


() => {
      (window as any).config = {
        motd: 'this is a sample',
      };

      const { getByRole, getByTestId, container } = render(<BannerMOTD />);

      const alert = getByRole('alert');
      expect(alert).toBeInTheDocument();

      const btn = getByTestId('closeBannerMOTD');
      fireEvent.click(btn);

      waitFor(() => {
        expect(container).toBeEmptyDOMElement();
      });
    }


() => {
        expect(container).toBeEmptyDOMElement();
      }


() => {
      it('when motd is undefined', () => {
        const { container } = render(<BannerMOTD />);
        expect(container).toBeEmptyDOMElement();
      });

      it('when motd is a empty string', () => {
        (window as any).config = {
          motd: '',
        };

        const { container } = render(<BannerMOTD />);
        expect(container).toBeEmptyDOMElement();
      });

      it('when motd is a {{ .motd }}', () => {
        // This is important for dev
        (window as any).config = {
          motd: '{{ .motd }}',
        };

        const { container } = render(<BannerMOTD />);
        expect(container).toBeEmptyDOMElement();
      });
    }


() => {
        const { container } = render(<BannerMOTD />);
        expect(container).toBeEmptyDOMElement();
      }


() => {
        (window as any).config = {
          motd: '',
        };

        const { container } = render(<BannerMOTD />);
        expect(container).toBeEmptyDOMElement();
      }


() => {
        // This is important for dev
        (window as any).config = {
          motd: '{{ .motd }}',
        };

        const { container } = render(<BannerMOTD />);
        expect(container).toBeEmptyDOMElement();
      }


(res)=>{

        this.laptopData=res;
        // console.log(this.laptopData);
        // this.image=res['buffer'];

        for(var i=0;i<this.laptopData.length;i++)
        {
          // console.log(this.laptopData[i]);
          this.p=this.laptopData[i].ext;
          let title=this.laptopData[i].title;
          let price=this.laptopData[i].price;
          let id=this.laptopData[i]._id;
          let category=this.laptopData[i].category;
          let image=this.laptopData[i].imageName;
          console.log()
          this.service.getImage(this.laptopData[i].imageName,this.laptopData[i].ext).subscribe((res)=>{
            this.gif=res;
            // console.log(this.gif);
            // console.log('data:image/'+this.p+';base64,'+this.gif.buffer.image);
            this.image_data_final.push('data:image/'+this.p+';base64,'+this.gif.buffer.image);
            let ct=0;
            for(let j=0;j<this.cart.length;j++){
              if(this.cart[j].id==id){
                this.finalData.push({
                  'item':title,
                  'price':price,
                  'category':category,
                  'id':id,
                  'image':'data:image/'+this.p+';base64,'+this.gif.buffer.image,
                  'counter':this.cart[j].counter
                });
                ct=1;
                break;
              }

            }
            if(ct==0){
              this.finalData.push({
                'item':title,
                'price':price,
                'category':category,
                'id':id,
                'image':'data:image/'+this.p+';base64,'+this.gif.buffer.image,
                'counter':0
              });
            }

          });
        }
        console.log(this.laptopData);
        console.log(this.image_data_final);
        console.log(this.finalData);
        // this.attach();
      }


(res)=>{
            this.gif=res;
            // console.log(this.gif);
            // console.log('data:image/'+this.p+';base64,'+this.gif.buffer.image);
            this.image_data_final.push('data:image/'+this.p+';base64,'+this.gif.buffer.image);
            let ct=0;
            for(let j=0;j<this.cart.length;j++){
              if(this.cart[j].id==id){
                this.finalData.push({
                  'item':title,
                  'price':price,
                  'category':category,
                  'id':id,
                  'image':'data:image/'+this.p+';base64,'+this.gif.buffer.image,
                  'counter':this.cart[j].counter
                });
                ct=1;
                break;
              }

            }
            if(ct==0){
              this.finalData.push({
                'item':title,
                'price':price,
                'category':category,
                'id':id,
                'image':'data:image/'+this.p+';base64,'+this.gif.buffer.image,
                'counter':0
              });
            }

          }


(res)=>{
            this.cart=res;
            console.log(res);
            let ct=0;

      }


(res)=>console.log(res)


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


@Component({
  selector: 'app-laptop',
  templateUrl: './laptop.component.html',
  styleUrls: ['./laptop.component.css']
})
export class LaptopComponent implements OnInit {
loading=true;
  constructor(private service:NikhilService,private route:Router) {
    // if(!localStorage.getItem('token'))
    // {
    //   this.route.navigate(['/login']);
    // }else{
      this.cart1();
      this.loading=false;
      this.service.getlaptop("laptop").subscribe((res)=>{

        this.laptopData=res;
        // console.log(this.laptopData);
        // this.image=res['buffer'];

        for(var i=0;i<this.laptopData.length;i++)
        {
          // console.log(this.laptopData[i]);
          this.p=this.laptopData[i].ext;
          let title=this.laptopData[i].title;
          let price=this.laptopData[i].price;
          let id=this.laptopData[i]._id;
          let category=this.laptopData[i].category;
          let image=this.laptopData[i].imageName;
          console.log()
          this.service.getImage(this.laptopData[i].imageName,this.laptopData[i].ext).subscribe((res)=>{
            this.gif=res;
            // console.log(this.gif);
            // console.log('data:image/'+this.p+';base64,'+this.gif.buffer.image);
            this.image_data_final.push('data:image/'+this.p+';base64,'+this.gif.buffer.image);
            let ct=0;
            for(let j=0;j<this.cart.length;j++){
              if(this.cart[j].id==id){
                this.finalData.push({
                  'item':title,
                  'price':price,
                  'category':category,
                  'id':id,
                  'image':'data:image/'+this.p+';base64,'+this.gif.buffer.image,
                  'counter':this.cart[j].counter
                });
                ct=1;
                break;
              }

            }
            if(ct==0){
              this.finalData.push({
                'item':title,
                'price':price,
                'category':category,
                'id':id,
                'image':'data:image/'+this.p+';base64,'+this.gif.buffer.image,
                'counter':0
              });
            }

          });
        }
        console.log(this.laptopData);
        console.log(this.image_data_final);
        console.log(this.finalData);
        // this.attach();
      });

    // }
   }
  laptopData:any;
  cart:any;
  finalData:any=[];
p:any;
image_data_final:any=[];
gif:any=[];

    ngOnInit() {

  //     this.service.getlaptop("laptop").subscribe((res)=>{
  //       this.laptopData=res;
  //       console.log(res);

  // this.service.findCartItem(localStorage.getItem('email')).subscribe((res)=>{
  //   this.cart=res;
  //   console.log(res);
  //   let ct=0;
  //   for(let i=0;i<this.laptopData.length;i++)
  //     {
  //       for(let j=0;j<this.cart.length;j++)
  //       {
  //         if(this.cart[j].id==this.laptopData[i]._id){
  //       this.finalData.push({
  //         'item':this.laptopData[i].title,
  //         'price':this.laptopData[i].price,
  //         'category':this.laptopData[i].category,
  //         'image':this.laptopData[i].imageName,
  //         'id':this.laptopData[i]._id,
  //         'counter':this.cart[j].counter
  //       })
  //       ct=1;
  //       break;
  //     }
  //   }
  //   if(ct==0){
  //     this.finalData.push({
  //       'item':this.laptopData[i].title,
  //       'price':this.laptopData[i].price,
  //       'category':this.laptopData[i].category,
  //       'image':this.laptopData[i].imageUrl,
  //       'id':this.laptopData[i]._id,
  //       'counter':0

  //     });
  //   }else{
  //     ct=0;
  //   }
  //     }
  // });
  // console.log(this.finalData);
  //     });
    }
    cart1(){
      this.service.findCartItem(localStorage.getItem('email')).subscribe((res)=>{
            this.cart=res;
            console.log(res);
            let ct=0;

      });

    }

    counting(data:any)
  {
    if(!localStorage.getItem('token'))
    {
      this.route.navigate(['/login']);
  // this.toastr.errorToastr("please login first ",'Warning ',{position:'top-center'});
  alert("please login frst")

    }else{
console.log(data);
data.counter++;
let a=data.price;
let b=data.item;
let c=data.counter;
let d=data.category;
let total=a*c;

let f=localStorage.getItem('email');
    this.service.cartItem(a,b,c,d,data.id,f,total).subscribe((res)=>console.log(res));
  }
alert("product added into cart")

}
  revCounting(data1:any)
  {

if(data1.counter!=0)
{    data1.counter--;
  let a=data1.price;
let b=data1.item;
let c=data1.counter;
let d=data1.category;
let total=a*c;

let f=localStorage.getItem('email');
    this.service.cartItem(a,b,c,d,data1.id,f,total).subscribe((res)=>console.log(res));
  // console.log(data1);
  }
  else{

    // this.toastr.errorToastr("you cant add item in  negative quantity",'oops',{position:'top-center'});
    alert("you can't add item in negative quantity")
}
if(data1.counter<1)
    {
     this.service.deleteCartItem(data1.id).subscribe((res)=>{
       console.log(res);
        });
  }
}
  }


ngOnInit() {

  //     this.service.getlaptop("laptop").subscribe((res)=>{
  //       this.laptopData=res;
  //       console.log(res);

  // this.service.findCartItem(localStorage.getItem('email')).subscribe((res)=>{
  //   this.cart=res;
  //   console.log(res);
  //   let ct=0;
  //   for(let i=0;i<this.laptopData.length;i++)
  //     {
  //       for(let j=0;j<this.cart.length;j++)
  //       {
  //         if(this.cart[j].id==this.laptopData[i]._id){
  //       this.finalData.push({
  //         'item':this.laptopData[i].title,
  //         'price':this.laptopData[i].price,
  //         'category':this.laptopData[i].category,
  //         'image':this.laptopData[i].imageName,
  //         'id':this.laptopData[i]._id,
  //         'counter':this.cart[j].counter
  //       })
  //       ct=1;
  //       break;
  //     }
  //   }
  //   if(ct==0){
  //     this.finalData.push({
  //       'item':this.laptopData[i].title,
  //       'price':this.laptopData[i].price,
  //       'category':this.laptopData[i].category,
  //       'image':this.laptopData[i].imageUrl,
  //       'id':this.laptopData[i]._id,
  //       'counter':0

  //     });
  //   }else{
  //     ct=0;
  //   }
  //     }
  // });
  // console.log(this.finalData);
  //     });
    }


cart1(){
      this.service.findCartItem(localStorage.getItem('email')).subscribe((res)=>{
            this.cart=res;
            console.log(res);
            let ct=0;

      });

    }


counting(data:any)
  {
    if(!localStorage.getItem('token'))
    {
      this.route.navigate(['/login']);
  // this.toastr.errorToastr("please login first ",'Warning ',{position:'top-center'});
  alert("please login frst")

    }else{
console.log(data);
data.counter++;
let a=data.price;
let b=data.item;
let c=data.counter;
let d=data.category;
let total=a*c;

let f=localStorage.getItem('email');
    this.service.cartItem(a,b,c,d,data.id,f,total).subscribe((res)=>console.log(res));
  }
alert("product added into cart")

}


revCounting(data1:any)
  {

if(data1.counter!=0)
{    data1.counter--;
  let a=data1.price;
let b=data1.item;
let c=data1.counter;
let d=data1.category;
let total=a*c;

let f=localStorage.getItem('email');
    this.service.cartItem(a,b,c,d,data1.id,f,total).subscribe((res)=>console.log(res));
  // console.log(data1);
  }
  else{

    // this.toastr.errorToastr("you cant add item in  negative quantity",'oops',{position:'top-center'});
    alert("you can't add item in negative quantity")
}
if(data1.counter<1)
    {
     this.service.deleteCartItem(data1.id).subscribe((res)=>{
       console.log(res);
        });
  }
}


() =>
        Promise.resolve({
            token: {
                id: 'test_id',
            },
        })


export interface InputDataInterface {
  [index: number]: { modified: boolean, value: number }
}


export function moduleFromPort(document, range): string {
    let text = document.getText(new vscode.Range(new vscode.Position(0,0), range.end))
    let depthParathesis = 0;
    let i = 0;

    for (i = text.length; i>0; i--) {
        if (text[i] == ')')
            depthParathesis++;
        else if (text[i] == '(')
            depthParathesis--;

        if (depthParathesis == -1) {
            let match_param = text.slice(0, i).match(/(\w+)\s*#\s*$/);
            let match_simple = text.slice(0, i).match(/(\w+)\s+(\w+)\s*$/);
            if (match_param)
                return match_param[1]
            else if (match_simple)
                return match_simple[1]
        }
    }
}


function findPortLocation(symbol: vscode.SymbolInformation, port:string): Thenable<vscode.Location> {
    return vscode.workspace.openTextDocument(symbol.location.uri).then( doc => {

        for (let i = symbol.location.range.start.line; i<doc.lineCount; i++) {
            let line = doc.lineAt(i).text;
            if (line.match("\\bword\\b".replace('word', port))) {
                return new vscode.Location(symbol.location.uri, new vscode.Position(i, line.indexOf(port)));
            }
        }
    });
}


function clean(arr: Array<any>, deleteValue): Array<any> {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == deleteValue) {
        arr.splice(i, 1);
        i--;
      }
    }
    return arr;
}


async (resolve, reject) => {
            let range = document.getWordRangeAtPosition(position);
            let line = document.lineAt(position.line).text;
            let word = document.getText(range);

            if (!range) {
                reject();
            }

            // Check for port
            else if (line.match(this.regex_port.replace('word', word))) {
                let container = moduleFromPort(document, range)

                resolve(Promise.resolve(this.workspaceSymProvider.provideWorkspaceSymbols(container, token, true).then( res => {
                    return Promise.all( res.map(x => findPortLocation(x, word)));
                }).then( arrWithUndefined => {
                    return clean(arrWithUndefined, undefined)
                })));
            }

            else {
                // Lookup all symbols in the current document
                await this.docSymProvider.provideDocumentSymbols(document).then(symbols => {
                    symbols.forEach(x => {
                        if(x.name === word) {
                            resolve(x.location);
                        }
                    });
                });

                await this.workspaceSymProvider.provideWorkspaceSymbols(word, token, true).then( res => {
                    if (res.length == 0) {
                        reject();
                    }
                    resolve(res.map( x => x.location ));
                });
            }
        }


res => {
                    return Promise.all( res.map(x => findPortLocation(x, word)));
                }


x => findPortLocation(x, word)


arrWithUndefined => {
                    return clean(arrWithUndefined, undefined)
                }


symbols => {
                    symbols.forEach(x => {
                        if(x.name === word) {
                            resolve(x.location);
                        }
                    });
                }


x => {
                        if(x.name === word) {
                            resolve(x.location);
                        }
                    }


res => {
                    if (res.length == 0) {
                        reject();
                    }
                    resolve(res.map( x => x.location ));
                }


x => x.location


doc => {

        for (let i = symbol.location.range.start.line; i<doc.lineCount; i++) {
            let line = doc.lineAt(i).text;
            if (line.match("\\bword\\b".replace('word', port))) {
                return new vscode.Location(symbol.location.uri, new vscode.Position(i, line.indexOf(port)));
            }
        }
    }


export class SystemVerilogDefinitionProvider implements vscode.DefinitionProvider {

    private workspaceSymProvider : SystemVerilogWorkspaceSymbolProvider;
    private docSymProvider       : SystemVerilogDocumentSymbolProvider;

    // Strings used in regex'es
    // private regex_module = '$\\s*word\\s*(';
    private regex_port = '\\.word\\s*\\(';

    constructor(workspaceSymProvider: SystemVerilogWorkspaceSymbolProvider, docSymProvider : SystemVerilogDocumentSymbolProvider) {
        this.workspaceSymProvider = workspaceSymProvider;
        this.docSymProvider = docSymProvider;
    };

    public provideDefinition(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise<vscode.Definition> {
        return new Promise ( async (resolve, reject) => {
            let range = document.getWordRangeAtPosition(position);
            let line = document.lineAt(position.line).text;
            let word = document.getText(range);

            if (!range) {
                reject();
            }

            // Check for port
            else if (line.match(this.regex_port.replace('word', word))) {
                let container = moduleFromPort(document, range)

                resolve(Promise.resolve(this.workspaceSymProvider.provideWorkspaceSymbols(container, token, true).then( res => {
                    return Promise.all( res.map(x => findPortLocation(x, word)));
                }).then( arrWithUndefined => {
                    return clean(arrWithUndefined, undefined)
                })));
            }

            else {
                // Lookup all symbols in the current document
                await this.docSymProvider.provideDocumentSymbols(document).then(symbols => {
                    symbols.forEach(x => {
                        if(x.name === word) {
                            resolve(x.location);
                        }
                    });
                });

                await this.workspaceSymProvider.provideWorkspaceSymbols(word, token, true).then( res => {
                    if (res.length == 0) {
                        reject();
                    }
                    resolve(res.map( x => x.location ));
                });
            }
        });
    }
}


public provideDefinition(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): Promise<vscode.Definition> {
        return new Promise ( async (resolve, reject) => {
            let range = document.getWordRangeAtPosition(position);
            let line = document.lineAt(position.line).text;
            let word = document.getText(range);

            if (!range) {
                reject();
            }

            // Check for port
            else if (line.match(this.regex_port.replace('word', word))) {
                let container = moduleFromPort(document, range)

                resolve(Promise.resolve(this.workspaceSymProvider.provideWorkspaceSymbols(container, token, true).then( res => {
                    return Promise.all( res.map(x => findPortLocation(x, word)));
                }).then( arrWithUndefined => {
                    return clean(arrWithUndefined, undefined)
                })));
            }

            else {
                // Lookup all symbols in the current document
                await this.docSymProvider.provideDocumentSymbols(document).then(symbols => {
                    symbols.forEach(x => {
                        if(x.name === word) {
                            resolve(x.location);
                        }
                    });
                });

                await this.workspaceSymProvider.provideWorkspaceSymbols(word, token, true).then( res => {
                    if (res.length == 0) {
                        reject();
                    }
                    resolve(res.map( x => x.location ));
                });
            }
        });
    }


user => user.subscriptions


type => Playlist


playlist => playlist.subscriptions


@Entity('subscription')
export class Subscription extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({
    type: 'number',
    name: 'userId',
  })
  @ManyToOne(type => User, user => user.subscriptions)
  user: User;

  @Column({
    type: 'number',
    name: 'playlistId',
  })
  @ManyToOne(type => Playlist, playlist => playlist.subscriptions)
  playlist: Playlist;

  constructor(user: User, playlist: Playlist) {
    super();
    this.user = user;
    this.playlist = playlist;
  }
}


res => {
        console.log('dung');
        this.router.navigate(['/dm'])
      }


err => {
        console.log(err, value);
        document.getElementById('result').innerHTML = "tài khoản hoặc mật khẩu không chính xác"

      }


res => {
      this.router.navigate(['/dm'])
    }


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

  loginform: FormGroup
  constructor(
    public authService: AuthService,
    private router: Router,
    private fb: FormBuilder
  ) {
    this.createForm()
  }

  ngOnInit() {

  }
  createForm() {
    this.loginform = this.fb.group({
      email: ['', Validators.required],
      password: ['', Validators.required]
    })
  }
  tryLogin(value) {
    this.authService.doLogin(value).then(
      res => {
        console.log('dung');
        this.router.navigate(['/dm'])
      }, err => {
        console.log(err, value);
        document.getElementById('result').innerHTML = "tài khoản hoặc mật khẩu không chính xác"

      }
    )
  }
  tryGoogleLogin() {
    this.authService.doGoogleLogin().then(res => {
      this.router.navigate(['/dm'])
    })
  }
}


ngOnInit() {

  }


createForm() {
    this.loginform = this.fb.group({
      email: ['', Validators.required],
      password: ['', Validators.required]
    })
  }


tryLogin(value) {
    this.authService.doLogin(value).then(
      res => {
        console.log('dung');
        this.router.navigate(['/dm'])
      }, err => {
        console.log(err, value);
        document.getElementById('result').innerHTML = "tài khoản hoặc mật khẩu không chính xác"

      }
    )
  }


tryGoogleLogin() {
    this.authService.doGoogleLogin().then(res => {
      this.router.navigate(['/dm'])
    })
  }


interface SuperAgentRequest extends Request {
        agent(agent?: https.Agent): this;

        cookies: string;
        method: string;
        url: string;
    }


interface SuperAgentStatic extends SuperAgent<SuperAgentRequest> {
        (url: string): SuperAgentRequest;
        // tslint:disable-next-line:unified-signatures
        (method: string, url: string): SuperAgentRequest;

        agent(): this & Request;
        serialize: { [type: string]: Serializer };
        parse: { [type: string]: Parser };
    }


interface SuperAgent<Req extends SuperAgentRequest> extends stream.Stream {
        jar: cookiejar.CookieJar;
        attachCookies(req: Req): void;
        checkout(url: string, callback?: CallbackHandler): Req;
        connect(url: string, callback?: CallbackHandler): Req;
        copy(url: string, callback?: CallbackHandler): Req;
        del(url: string, callback?: CallbackHandler): Req;
        delete(url: string, callback?: CallbackHandler): Req;
        get(url: string, callback?: CallbackHandler): Req;
        head(url: string, callback?: CallbackHandler): Req;
        lock(url: string, callback?: CallbackHandler): Req;
        merge(url: string, callback?: CallbackHandler): Req;
        mkactivity(url: string, callback?: CallbackHandler): Req;
        mkcol(url: string, callback?: CallbackHandler): Req;
        move(url: string, callback?: CallbackHandler): Req;
        notify(url: string, callback?: CallbackHandler): Req;
        options(url: string, callback?: CallbackHandler): Req;
        patch(url: string, callback?: CallbackHandler): Req;
        post(url: string, callback?: CallbackHandler): Req;
        propfind(url: string, callback?: CallbackHandler): Req;
        proppatch(url: string, callback?: CallbackHandler): Req;
        purge(url: string, callback?: CallbackHandler): Req;
        put(url: string, callback?: CallbackHandler): Req;
        report(url: string, callback?: CallbackHandler): Req;
        saveCookies(res: Response): void;
        search(url: string, callback?: CallbackHandler): Req;
        subscribe(url: string, callback?: CallbackHandler): Req;
        trace(url: string, callback?: CallbackHandler): Req;
        unlock(url: string, callback?: CallbackHandler): Req;
        unsubscribe(url: string, callback?: CallbackHandler): Req;
    }


interface ResponseError extends Error {
        status: number;
        text: string;
        method: string;
        path: string;
    }


interface Response extends NodeJS.ReadableStream {
        accepted: boolean;
        badRequest: boolean;
        body: any;
        charset: string;
        clientError: boolean;
        error: ResponseError;
        files: any;
        forbidden: boolean;
        get(header: string): string;
        get(header: 'Set-Cookie'): string[];
        header: any;
        info: boolean;
        links: object;
        noContent: boolean;
        notAcceptable: boolean;
        notFound: boolean;
        ok: boolean;
        redirect: boolean;
        serverError: boolean;
        status: number;
        statusType: number;
        text: string;
        type: string;
        unauthorized: boolean;
        xhr: XMLHttpRequest;
    }


interface Request extends Promise<Response> {
        abort(): void;
        accept(type: string): this;
        attach(field: string, file: MultipartValueSingle, options?: string | { filename?: string; contentType?: string }): this;
        auth(user: string, pass: string, options?: { type: 'basic' | 'auto' }): this;
        auth(token: string, options: { type: 'bearer' }): this;
        buffer(val?: boolean): this;
        ca(cert: Buffer): this;
        cert(cert: Buffer | string): this;
        clearTimeout(): this;
        end(callback?: CallbackHandler): this;
        field(name: string, val: MultipartValue): this;
        field(fields: { [fieldName: string]: MultipartValue }): this;
        get(field: string): string;
        key(cert: Buffer | string): this;
        ok(callback: (res: Response) => boolean): this;
        on(name: 'error', handler: (err: any) => void): this;
        on(name: 'progress', handler: (event: ProgressEvent) => void): this;
        on(name: string, handler: (event: any) => void): this;
        parse(parser: Parser): this;
        part(): this;
        pfx(cert: Buffer | string | { pfx: Buffer, passphrase: string }): this;
        pipe(stream: NodeJS.WritableStream, options?: object): stream.Writable;
        query(val: object | string): this;
        redirects(n: number): this;
        responseType(type: string): this;
        retry(count?: number, callback?: CallbackHandler): this;
        send(data?: string | object): this;
        serialize(serializer: Serializer): this;
        set(field: object): this;
        set(field: string, val: string): this;
        set(field: 'Cookie', val: string[]): this;
        timeout(ms: number | { deadline?: number, response?: number }): this;
        type(val: string): this;
        unset(field: string): this;
        use(fn: Plugin): this;
        withCredentials(): this;
        write(data: string | Buffer, encoding?: string): this;
    }


interface ProgressEvent {
        direction: 'download' | 'upload';
        loaded: number;
        percent?: number;
        total?: number;
    }


type CallbackHandler = (err: any, res: request.Response) => void;


type Serializer = (obj: any) => string;


type BrowserParser = (str: string) => any;


type NodeParser = (res: request.Response, callback: (err: Error | null, body: any) => void) => void;


type Parser = BrowserParser | NodeParser;


type MultipartValueSingle = Blob | Buffer | fs.ReadStream | string | boolean | number;


type MultipartValue = MultipartValueSingle | MultipartValueSingle[];


type Plugin = (req: SuperAgentRequest) => void;


@Controller()
export class MessageController {
  @Post('youtube/messages/pin')
  pinMessage(@Body() body, @Response() resp) {
    this.messageService.pinMessage(body.id);

    return resp.json({ success: true });
  }

  constructor(private messageService: MessageService) {}
}


@Post('youtube/messages/pin')
  pinMessage(@Body() body, @Response() resp) {
    this.messageService.pinMessage(body.id);

    return resp.json({ success: true });
  }


export default class PistonArmCollision extends Solid {
    public constructor(
        name = 'minecraft:piston_arm_collision', // It's actually supposed to be "pistonArmCollision", but that's dumb
        id: BlockIdsType = BlockIdsType.PistonArmCollision
    ) {
        super({
            name,
            id,
            hardness: 1.5
        });
    }
}


export function isBlank(toTest: String): boolean {
  if (toTest === null || toTest === undefined) {
    return true;
  } else {
    toTest = toTest.trim();
    return toTest === '';
  }
}


/**
 * Random String Generator (simplified version)
 *
 * Info:      http://stackoverflow.com/a/27872144/383904
 * Use:       randomString(length);
 * Default:   return a random alpha-numeric string
 */
export function randomString(len): string {
  let str = '',
    i = 0;
  for (; i++ < len; ) {
    let rand = Math.floor(Math.random() * 62);
    const charCode = (rand += rand > 9 ? (rand < 36 ? 55 : 61) : 48);
    str += String.fromCharCode(charCode);
  }
  return str;
}