text:
/* eslint-disable @typescript-eslint/no-explicit-any */

export type WorkspacesFactoryFunction = (glue: any, config?: any) => Promise<void>;
declare const WorkspacesFactory: WorkspacesFactoryFunction;
export default WorkspacesFactory;

/**
 * @docmenuorder 1
 * @docName Workspaces
 * @intro
 * The Workspaces API offers advanced window management functionalities. Using Workspaces, users are able to arrange multiple applications
 * within the same visual window (called *Frame*). This arrangement can be performed programmatically or by dragging and dropping applications within the Frame.
 * Users can also save Workspace Layouts and restore them within the same Frame or even in different Frames.
 *
 * The Glue42 Workspaces enable the users to compose a custom arrangement of applications by treating each application
 * as an individual building block that can be added, removed, moved or resized within a Workspace.
 * The Frame can hold multiple Workspaces (as tabs) and can also be maximized, minimized or resized.
 *
 * The Workspaces API is accessible through the `glue.workspaces` object.
 */
export namespace Glue42Workspaces {

    /** An object describing a workspace layout. */
    export interface WorkspaceLayout {
        /** An unique string name and identifier of the layout */
        name: string;

        /** The type of the workspace element. */
        type: "Workspace";

        /** The components of the workspace layout. This collection can contain only one element and it must be a workspace component. */
        components: Array<WorkspaceComponent>;

        /** An object containing various layout metadata. */
        metadata?: any;
    }

    /** An object describing a workspace definition in a workspace layout. */
    export interface WorkspaceComponent {
        /** The type of the workspace element. */
        type: "Workspace";

        state: {
            /** An array of all the workspace's children. */
            children: Array<RowLayoutItem | ColumnLayoutItem | GroupLayoutItem | WindowLayoutItem>;

            /** An object containing various element settings. */
            config: any;

            /** An object containing the context of the workspace layout */
            context: any;
        };
    }

    /** An object describing a row definition in a workspace layout. */
    export interface RowLayoutItem {
        /** The type of the workspace element. */
        type: "row";

        /** An array of all the row's children. */
        children: Array<RowLayoutItem | ColumnLayoutItem | GroupLayoutItem | WindowLayoutItem>;

        /** An object containing various element settings. */
        config: any;
    }

    /** An object describing a column definition in a workspace layout. */
    export interface ColumnLayoutItem {
        /** The type of the workspace element. */
        type: "column";

        /** An array of all the column's children. */
        children: Array<RowLayoutItem | ColumnLayoutItem | GroupLayoutItem | WindowLayoutItem>;

        /** An object containing various element settings. */
        config: any;
    }

    /** An object describing a group definition in a workspace layout. */
    export interface GroupLayoutItem {
        /** The type of the workspace element. */
        type: "group";

        /** An array of all the group's children which can only of type window. */
        children: WindowLayoutItem[];

        /** An object containing various element settings. */
        config: any;
    }

    /** An object describing a window definition in a workspace layout. */
    export interface WindowLayoutItem {
        /** The type of the workspace element. */
        type: "window";
        /** A configuration object for the window layout */
        config: {
            /** The name of the application as defined in Glue Desktop */
            appName: string;
            /** The url of the window, in case it is not a defined as an application. */
            url?: string;
            /** The title of the window */
            title?: string;
        };
    }

    /** A function which when called unsubscribes the user from further notifications. */
    export type Unsubscribe = () => void;

    /** An object containing all the possible settings when restoring a workspace from a layout. */
    export interface RestoreWorkspaceConfig {
        /** An object which will be set as the window context of all windows inside this workspace. */
        context?: object;

        /** The title of the new workspace. */
        title?: string;

        /** A string id of an existing frame. If provided, this workspace will be opened in that specific frame */
        frameId?: string;

        /** A setting used to declare that the workspace must be in a new frame and also provide options for that new frame */
        newFrame?: NewFrameConfig | boolean;

        loadingStrategy?: LoadingStrategy;
        /** Used for replacing the specified workspace instead of creating a new one */
        reuseWorkspaceId?: string;
    }

    /** An object containing the bounds of a frame */
    export interface FrameBounds {
        top?: number;
        left?: number;
        width?: number;
        height?: number;
    }

    /** An object describing the possible settings when defining a new frame. */
    export interface NewFrameConfig {
        /** An object describing the possible settings when defining a new frame. */
        bounds?: FrameBounds;
    }

    /** An object defining the resize parameters of a frame. */
    export interface ResizeConfig {
        /** The targeted width value */
        width?: number;

        /** The targeted height value */
        height?: number;

        /** Toggles whether or not the provided width and height values should be treated as absolute or relative to the current values. */
        relative?: boolean;
    }

    /** An object defining the position parameters of a frame. */
    export interface MoveConfig {
        /** The targeted top value */
        top?: number;

        /** The targeted left value */
        left?: number;

        /** Toggles whether or not the provided top and left values should be treated as absolute or relative to the current values. */
        relative?: boolean;
    }

    /** An object containing settings applied when creating a new workspace. */
    export interface WorkspaceCreateConfig {
        /** A boolean which defines whether or not the workspace should also be saved as a layout when created. */
        saveLayout?: boolean;
    }

    /** The loading strategy used to open new workspaces */
    export type LoadingStrategy = "direct" | "delayed" | "lazy";

    /** An object which represent a workspace element. This is an element can be a box or a workspace window. */
    export type WorkspaceElement = WorkspaceBox | WorkspaceWindow;

    /** An object which represent a workspace box. This is an element which contains other elements, called children. */
    export type WorkspaceBox = Row | Column | Group;

    /** The possible window states for a workspaces frame. */
    export type FrameState = "maximized" | "minimized" | "normal";

    /** An object describing the options of the builder. */
    export interface BuilderConfig {
        /** A string defining the type of the builder. */
        type: "workspace" | "row" | "column" | "group";

        /** An object describing various options when creating a builder. */
        definition?: WorkspaceDefinition | BoxDefinition;
    }

    /** Workspace-specific options. */
    export interface WorkspaceConfig {
        /** A title of the workspace. */
        title?: string;

        /** Position of the workspace in relation to it's siblings in the frame. */
        position?: number;

        /** States whether or not the workspace should have focus when opened. */
        isFocused?: boolean;

        /** Provides the opportunity to open a workspace with no tab header */
        noTabHeader?: boolean;

        /** Used for replacing the specified workspace instead of creating a new one */
        reuseWorkspaceId?: string;

        loadStrategy?: LoadingStrategy;
    }

    /** An object describing the possible options when defining a new workspace */
    export interface WorkspaceDefinition {
        /** An array of all the workspace's children which will also be opened. */
        children?: Array<WorkspaceWindowDefinition | BoxDefinition>;

        /** An object which will be set as the window context of all windows inside this workspace. */
        context?: any;

        /** Workspace-specific options. */
        config?: WorkspaceConfig;

        /** Options regarding the frame where this workspace will be opened in. */
        frame?: {
            /** A string id of an existing frame. If provided, this workspace will be opened in that specific frame */
            reuseFrameId?: string;

            /** A setting used to declare that the workspace must be in a new frame and also provide options for that new frame */
            newFrame?: NewFrameConfig | boolean;
        };
    }

    /** An object describing the possible options when opening a box inside a workspace. */
    export interface BoxDefinition {
        /** The type of the workspace element. */
        type?: "column" | "row" | "group";

        /** An array of all the box's children which will also be opened. */
        children?: Array<WorkspaceWindowDefinition | BoxDefinition>;

        config?: any;
    }

    /** An object describing the possible options when opening a window inside a workspace. */
    export interface WorkspaceWindowDefinition {
        /** The type of the workspace element. */
        type?: "window";

        /** The name of the application as defined, which will be opened. */
        appName?: string;

        /** The window id of an existing standalone window, which will be dragged into the workspace. */
        windowId?: string;

        /** An object which will be passed to the newly created window. This object is then accessible via the Windows API */
        context?: any;
    }

    /** An object describing the basic details of a frame */
    export interface FrameSummary {
        /** An unique string identifier of the frame */
        id: string;
    }

    /** An object describing the basic details of a workspace */
    export interface WorkspaceSummary {
        /** An unique string identifier of the workspace */
        id: string;

        /** The string id of the frame containing this workspace */
        frameId: string;

        /** The position of this workspace regarding it's siblings */
        positionIndex: number;

        /** The title of the workspace */
        title: string;

        /** The name of the originating layout of the current workspace if any */
        layoutName: string | undefined;
    }

    /** An object describing the basic details of a workspace window */
    export interface WorkspaceWindowSummary {
        /** An unique string identifier of the window */
        id: string | undefined;

        /** An unique string identifier of the workspace element that hosts the window */
        elementId: string;

        /** The type of the workspace element */
        type: "window";

        /** The string id of the frame containing this window */
        frameId: string;

        /** The application name of the window if it was registered as an application */
        appName: string;

        /** The string id of the workspace containing this window */
        workspaceId: string;

        /** The position of this window regarding it's siblings */
        positionIndex: number;

        /** A flag showing whether or not the window is maximized within it's box */
        isMaximized: boolean;

        /** A flag showing whether or not the window's content is loaded */
        isLoaded: boolean;

        /** A flag showing whether or not the window has focus */
        focused: boolean;

        /** The title of the window */
        title: string;
    }

    /** An object describing a workspace layout without the underlying structure */
    export interface WorkspaceLayoutSummary {
        /** An unique string name and identifier of the layout */
        name: string;
    }

    /** An object describing a frame */
    export interface Frame extends FrameSummary {
        /**
         * Retrieves the current bounds of the frame.
         */
        getBounds(): Promise<FrameBounds>;

        /**
         * Changes the size of this frame.
         * @param config An object defining the resize parameters.
         */
        resize(config: ResizeConfig): Promise<void>;

        /**
         * Changes the position of this frame.
         * @param config An object defining the position parameters.
         */
        move(config: MoveConfig): Promise<void>;

        /**
         * Focuses this frame.
         */
        focus(): Promise<void>;

        /**
         * Returns the current state of the frame.
         * Not available in Glue42 Core
         */
        state(): Promise<FrameState>;

        /**
         * Minimizes this frame.
         * Not available in Glue42 Core
         */
        minimize(): Promise<void>;

        /**
         * Minimizes this frame.
         * Not available in Glue42 Core
         */
        minimize(): Promise<void>;

        /**
         * Maximizes this frame.
         * Not available in Glue42 Core
         */
        maximize(): Promise<void>;

        /**
         * Restores this frame.
         * Not available in Glue42 Core
         */
        restore(): Promise<void>;

        /**
         * Closes this frame.
         */
        close(): Promise<void>;

        /**
         * Returns an object detailing the current state of this frame.
         */
        snapshot(): Promise<FrameSnapshot>;

        /**
         * Returns a collection of all workspaces present in this frame.
         */
        workspaces(): Promise<Workspace[]>;

        /**
         * Opens a new workspace in this frame by restoring a previously saved workspace layout.
         * @param name The name of a saved workspace layout, which will be restored.
         * @param options An optional object containing various workspace restore options.
         */
        restoreWorkspace(name: string, options?: RestoreWorkspaceConfig): Promise<Workspace>;

        /**
         * Opens a new workspace in this frame based on the provided definition.
         * @param definition An object describing the shape and options of the workspace.
         * @param saveConfig An object used to set various create options.
         */
        createWorkspace(definition: WorkspaceDefinition, config?: WorkspaceCreateConfig): Promise<Workspace>;

        /**
         * Notifies when this frame is closed.
         * @param callback Callback function to handle the event.
         */
        onClosed(callback: (closed: { frameId: string }) => void): Promise<Unsubscribe>;

        /**
         * Notifies when this frame is maximized.
         * This event is not supported in Glue42 Core.
         * @param callback Callback function to handle the event.
         */
        onMaximized(callback: () => void): Promise<Unsubscribe>;

        /**
         * Notifies when this frame is closed.
         * This event is not supported in Glue42 Core.
         * @param callback Callback function to handle the event.
         */
        onMinimized(callback: () => void): Promise<Unsubscribe>;

        /**
         * Notifies when this frame is closed.
         * This event is not supported in Glue42 Core.
         * @param callback Callback function to handle the event.
         */
        onNormal(callback: () => void): Promise<Unsubscribe>;

        /**
         * Notifies when a new workspace was opened in this frame and returns an unsubscribe function.
         * @param callback Callback function to handle the event. Receives the added workspace as a parameter.
         */
        onWorkspaceOpened(callback: (workspace: Workspace) => void): Promise<Unsubscribe>;

        /**
         * Notifies when a workspace is selected in this frame and returns an unsubscribe function.
         * @param callback Callback function to handle the event. Receives the selected workspace as a parameter.
         */
        onWorkspaceSelected(callback: (workspace: Workspace) => void): Promise<Unsubscribe>;

        /**
         * Notifies when a workspace present in this frame was closed and returns an unsubscribe function.
         * @param callback Callback function to handle the event. Receives an object with the closed workspace id and frame id as a parameter.
         */
        onWorkspaceClosed(callback: (closed: { frameId: string; workspaceId: string }) => void): Promise<Unsubscribe>;

        /**
         * Notifies when a new window was added to a workspace part of this frame and returns an unsubscribe function.
         * An added window means that the window has a place in the workspace (it is a valid workspace element), but does not guarantee that the contents of the window are loaded.
         * @param callback Callback function to handle the event. Receives the added window as a parameter.
         */
        onWindowAdded(callback: (window: WorkspaceWindow) => void): Promise<Unsubscribe>;

        /**
         * Notifies when a window was removed from a workspace part of this frame and returns an unsubscribe function.
         * @param callback Callback function to handle the event. Receives an object containing the ids of the removed window, and the respective workspace and frame as a parameter.
         */
        onWindowRemoved(callback: (removed: { windowId?: string; workspaceId: string; frameId: string }) => void): Promise<Unsubscribe>;

        /**
         * Notifies when a window's content was loaded in a workspace part of this frame and returns an unsubscribe function.
         * A loaded window is a window, which was added to a workspace, it's contents were loaded and is present in the windows collection.
         * @param callback Callback function to handle the event. Receives the loaded window as a parameter.
         */
        onWindowLoaded(callback: (window: WorkspaceWindow) => void): Promise<Unsubscribe>;
    }

    /** An object describing a workspace */
    export interface Workspace extends WorkspaceSummary {

        /** A collection containing the immediate children of this workspace */
        children: WorkspaceElement[];

        /** An object representing the frame containing this workspace */
        frame: Frame;

        /**
         * Gives focus to this workspace.
         */
        focus(): Promise<void>;

        /**
         * Closes this workspace and all of it's children.
         */
        close(): Promise<void>;

        /**
         * Returns a snapshot object describing the full current state of this workspace.
         */
        snapshot(): Promise<WorkspaceSnapshot>;

        /**
         * Sets a new title for this workspace.
         * @param title The new title value.
         */
        setTitle(title: string): Promise<void>;

        /**
         * Gets the context for this workspace.
         */
        getContext(): Promise<any>;

        /**
         * Sets the context for this workspace. This operation will completely overwrite the existing context.
         * @param data The new context value.
         */
        setContext(data: any): Promise<void>;

        /**
         * Updated the context for this workspace. This operation will merge the existing context with the provided value.
         * @param data The context value to update.
         */
        updateContext(data: any): Promise<void>;

        /**
         * Notifies when the context for this workspace was updated.
         * @param callback Callback function to handle the event.
         */
        onContextUpdated(callback: (data: any) => void): Promise<Unsubscribe>;

        /**
         * Updates this workspace reference to reflect the current state of the workspace.
         */
        refreshReference(): Promise<void>;

        /**
         * Saves the current workspace structure as a layout. In Glue42 Core this will throw an error if the name matches the name of a read-only layout.
         * @param name A string representing the name (also ID) of the new workspace layout.
         */
        saveLayout(name: string, config?: { saveContext?: boolean }): Promise<void>;

        /**
         * Returns the first box in this workspace, which satisfies the provided predicate.
         * @param predicate A filtering function (predicate) called for each box present in this workspace.
         */
        getBox(predicate: (box: WorkspaceBox) => boolean): WorkspaceBox;

        /**
         * Returns all boxes in this workspace, which satisfy the provided predicate. If no predicate was provided, will return all boxes.
         * @param predicate A filtering function (predicate) called for each box present in this workspace.
         */
        getAllBoxes(predicate?: (box: WorkspaceBox) => boolean): WorkspaceBox[];

        /**
         * Returns the first row in this workspace, which satisfies the provided predicate.
         * @param predicate A filtering function (predicate) called for each row present in this workspace.
         */
        getRow(predicate: (row: Row) => boolean): Row;

        /**
         * Returns all rows in this workspace, which satisfy the provided predicate. If no predicate was provided, will return all rows.
         * @param predicate A filtering function (predicate) called for each row present in this workspace.
         */
        getAllRows(predicate?: (row: Row) => boolean): Row[];

        /**
         * Returns the first column in this workspace, which satisfies the provided predicate.
         * @param predicate A filtering function (predicate) called for each column present in this workspace.
         */
        getColumn(predicate: (column: Column) => boolean): Column;

        /**
         * Returns all columns in this workspace, which satisfy the provided predicate. If no predicate was provided, will return all column.
         * @param predicate A filtering function (predicate) called for each column present in this workspace.
         */
        getAllColumns(predicate?: (columns: Column) => boolean): Column[];

        /**
         * Returns the first group in this workspace, which satisfies the provided predicate.
         * @param predicate A filtering function (predicate) called for each group present in this workspace.
         */
        getGroup(predicate: (group: Group) => boolean): Group;

        /**
         * Returns all groups in this workspace, which satisfy the provided predicate. If no predicate was provided, will return all groups.
         * @param predicate A filtering function (predicate) called for each group present in this workspace.
         */
        getAllGroups(predicate?: (group: Group) => boolean): Group[];

        /**
         * Returns the first window in this workspace, which satisfies the provided predicate.
         * @param predicate A filtering function (predicate) called for each window present in this workspace.
         */
        getWindow(predicate: (window: WorkspaceWindow) => boolean): WorkspaceWindow;

        /**
         * Returns all windows in this workspace, which satisfy the provided predicate. If no predicate was provided, will return all windows.
         * @param predicate A filtering function (predicate) called for each window present in this workspace.
         */
        getAllWindows(predicate?: (window: WorkspaceWindow) => boolean): WorkspaceWindow[];

        /**
         * Adds a new row to this workspace.
         * @param definition An object describing the available row settings.
         */
        addRow(definition?: BoxDefinition): Promise<Row>;

        /**
         * Adds a new column to this workspace.
         * @param definition An object describing the available column settings.
         */
        addColumn(definition?: BoxDefinition): Promise<Column>;

        /**
         * Adds a new group to this workspace.
         * @param definition An object describing the available group settings.
         */
        addGroup(definition?: BoxDefinition): Promise<Group>;

        /**
         * Adds a new window to this workspace.
         * @param definition An object describing the available window settings.
         */
        addWindow(definition: WorkspaceWindowDefinition): Promise<WorkspaceWindow>;

        /**
         * Removes the first element of this workspace which satisfies the predicate.
         * @param predicate A filtering function (predicate) called for each element in this workspace.
         */
        remove(predicate: (child: WorkspaceElement) => boolean): Promise<void>;

        /**
         * Removes the first immediate child of this workspaces which satisfies the predicate.
         * @param predicate A filtering function (predicate) called for immediate child of this workspace.
         */
        removeChild(predicate: (child: WorkspaceElement) => boolean): Promise<void>;

        /**
         * Transforms this workspace into a workspace with one immediate child of type row and all existing elements are inserted as a child to that row.
         */
        bundleToRow(): Promise<void>;

        /**
         * Transforms this workspace into a workspace with one immediate child of type column and all existing elements are inserted as a child to that row.
         */
        bundleToColumn(): Promise<void>;

        /**
         * Notifies when this workspace is closed.
         * @param callback Callback function to handle the event.
         */
        onClosed(callback: () => void): Promise<Unsubscribe>;

        /**
         * Notifies when a new window was added to this workspace and returns an unsubscribe function.
         * An added window means that the window has a place in the workspace (it is a valid workspace element), but does not guarantee that the contents of the window are loaded.
         * @param callback Callback function to handle the event. Receives the added window as a parameter.
         */
        onWindowAdded(callback: (window: WorkspaceWindow) => void): Promise<Unsubscribe>;

        /**
         * Notifies when a window was removed from this workspace and returns an unsubscribe function.
         * Not supported in Glue42 Core
         * @param callback Callback function to handle the event. Receives an object containing the ids of the removed window, and the respective workspace and frame as a parameter.
         */
        onWindowRemoved(callback: (removed: { windowId?: string; workspaceId: string; frameId: string }) => void): Promise<Unsubscribe>;

        /**
         * Notifies when a window's content was loaded in this workspace and returns an unsubscribe function.
         * A loaded window is a window, which was added to a workspace, it's contents were loaded and is present in the windows collection.
         * @param callback Callback function to handle the event. Receives the loaded window as a parameter.
         */
        onWindowLoaded(callback: (window: WorkspaceWindow) => void): Promise<Unsubscribe>;
    }

    /** An object containing the summary of a workspace box */
    export interface BoxSummary {

        /** An unique string identifier of this box */
        id: string;

        /** The unique string identifier of the frame containing this box */
        frameId: string;

        /** The unique string identifier of the workspace containing this box */
        workspaceId: string;

        /** An number representing the positing of this box relative to it's siblings */
        positionIndex: number;
    }

    /** An object describing a workspace box */
    export interface Box extends BoxSummary {

        /** A collection containing the immediate children of this box */
        children: WorkspaceElement[];

        /** An object representing this box's parent */
        parent: Workspace | WorkspaceBox;

        /** An object representing the frame containing this box */
        frame: Frame;

        /** An object representing the workspace containing this box */
        workspace: Workspace;

        /**
         * Opens a new window inside this box and loads it's content.
         * @param definition An object describing the requested window.
         */
        addWindow(definition: WorkspaceWindowDefinition): Promise<WorkspaceWindow>;

        /**
         * Adds a new group box to this box.
         * @param definition An object describing the type of the requested builder, alongside other settings.
         */
        addGroup(definition?: BoxDefinition | BoxBuilder): Promise<Group>;

        /**
         * Adds a new column box to this box.
         * @param definition An object describing the type of the requested builder, alongside other settings.
         */
        addColumn(definition?: BoxDefinition | BoxBuilder): Promise<Column>;

        /**
         * Adds a new row box to this box.
         * @param definition An object describing the type of the requested builder, alongside other settings.
         */
        addRow(definition?: BoxDefinition | BoxBuilder): Promise<Row>;

        /**
         * Removes the first immediate child of this box which satisfies the predicate.
         * @param predicate A filtering function (predicate) called for immediate child of this box.
         */
        removeChild(predicate: (child: WorkspaceElement) => boolean): Promise<void>;

        /**
         * Maximizes this box relative to it's parent box.
         */
        maximize(): Promise<void>;

        /**
         * Restores this box, if previously maximized.
         */
        restore(): Promise<void>;

        /**
         * Closes this box all of it's children.
         */
        close(): Promise<void>;
    }

    /** An object describing a row type workspace box */
    export interface Row extends Box {
        type: "row";
    }

    /** An object describing a column type workspace box */
    export interface Column extends Box {
        type: "column";
    }

    /** An object describing a group type workspace box */
    export interface Group extends Box {
        type: "group";
    }

    /** An object describing a window part of an existing workspace */
    export interface WorkspaceWindow extends WorkspaceWindowSummary {

        /** An object representing the workspace, which contains this window */
        workspace: Workspace;

        /** An object representing the frame, which contains this window */
        frame: Frame;

        /** An object representing the parent box, which contains this window */
        parent: Workspace | WorkspaceBox;

        /**
         * Forces a window, which was added to the workspace to load it's contents.
         */
        forceLoad(): Promise<void>;

        /**
         * Gives focus to the window.
         */
        focus(): Promise<void>;

        /**
         * Closes the workspace window.
         */
        close(): Promise<void>;

        /**
         * Sets a new title to the workspace window.
         * @param title The new title for the window.
         */
        setTitle(title: string): Promise<void>;

        /**
         * Maximizes the workspace window relative to it's parent box.
         */
        maximize(): Promise<void>;

        /**
         * Restores a previously maximized workspace window.
         */
        restore(): Promise<void>;

        /**
         * Removes a workspace window from the workspace and turns it into a standalone window.
         */
        eject(): Promise<any>;

        /**
         * Returns the underlying GDWindow (Enterprise) or WebWindow (Core) of the workspace window.
         */
        getGdWindow(): any;

        /**
         * Moves the workspace window to a new box. In Glue42 Core this box must be part of the same frame.
         * @param box An object describing the new box of the window.
         */
        moveTo(box: WorkspaceBox): Promise<void>;

        /**
         * Notifies when this window was removed from the workspace.
         * @param callback Callback function to handle the event.
         */
        onRemoved(callback: () => void): Promise<Unsubscribe>;
    }

    /** An object describing a builder user to create workspaces */
    export interface WorkspaceBuilder {
        /**
         * Adds a new row to the calling workspace. Returns the new row.
         * @param config An object describing the type of the requested builder, alongside other settings.
         */
        addRow(definition?: BoxDefinition): BoxBuilder;

        /**
         * Adds a new column to the calling workspace. Returns the new column.
         * @param config An object describing the type of the requested builder, alongside other settings.
         */
        addColumn(definition?: BoxDefinition): BoxBuilder;

        /**
         * Adds a new group to the calling workspace. Returns the new group.
         * @param config An object describing the type of the requested builder, alongside other settings.
         */
        addGroup(definition?: BoxDefinition): BoxBuilder;

        /**
         * Adds a new window to the calling workspace. Returns the calling workspace.
         * @param config An object describing the requested window.
         */
        addWindow(definition: WorkspaceWindowDefinition): WorkspaceBuilder;

        /**
         * Creates a new workspace using the builder as a blueprint for structure and contents.
         * @param config An object containing workspace creating options.
         */
        create(config?: WorkspaceCreateConfig): Promise<Workspace>;
    }

    /** An object describing a builder used to create workspace boxes */
    export interface BoxBuilder {
        /**
         * Adds a new row to the calling box. Returns the new row.
         * @param config An object describing the type of the requested builder, alongside other settings.
         */
        addRow(definition?: BoxDefinition): BoxBuilder;

        /**
         * Adds a new column to the calling box. Returns the new column.
         * @param config An object describing the type of the requested builder, alongside other settings.
         */
        addColumn(definition?: BoxDefinition): BoxBuilder;

        /**
         * Adds a new group to the calling box. Returns the new group.
         * @param config An object describing the type of the requested builder, alongside other settings.
         */
        addGroup(definition?: BoxDefinition): BoxBuilder;

        /**
         * Adds a new window to the calling box. Returns the immediate parent box of the window.
         * @param config An object describing the requested window.
         */
        addWindow(definition: WorkspaceWindowDefinition): BoxBuilder;

        /**
         * Returns the JSON object which describes the full structure of the box.
         */
        serialize(): BoxDefinition;
    }

    /** A configuration object used to save a current workspace as a layout */
    export interface WorkspaceLayoutSaveConfig {
        /**
         * A string used as name (doubles as id) of the layout, which is later used when restoring it.
         */
        name: string;

        /**
         * A string representing the id of the workspace whose structure should be saved into a layout.
         */
        workspaceId: string;

        /** Toggles whether or not the current workspace context should be saved in the layout */
        saveContext?: boolean;
    }

    /** An object describing the complete state of a frame at the time when the object was created */
    export interface FrameSnapshot {
        /**
         * A string identifier unique to each frame
         */
        id: string;
    }

    /** An object describing the complete state of a workspace at the time when the object was created */
    export interface WorkspaceSnapshot {
        /**
         * A string identifier unique to each workspace
         */
        id: string;
    }

    /** An API enabling basic CRUD workspaces actions */
    export interface WorkspaceLayoutsAPI {
        /**
         * Returns a collection of summarized layouts data. This data contains all the standard data excluding the actual structure of the layout.
         * This is helpful in cases where a simple query of existing layouts is needed without the complexity of transmitting the full layouts structure.
         */
        getSummaries(): Promise<WorkspaceLayoutSummary[]>;

        /**
         * Deletes a previously saved layout. In Glue42 Core delete will fail with an error in trying to delete a read-only layout, this is a layout defined in the glue.layouts.json file.
         * @param name The name of the layout to delete.
         */
        delete(name: string): Promise<void>;

        /**
         * Returns all layouts which satisfy the predicate. This collection of all saved layouts includes the layouts structure. If no predicate is provided, it returns all saved layouts.
         * @param predicate A filtering function (predicate) called for each saved layout.
         */
        export(predicate?: (layout: WorkspaceLayout) => boolean): Promise<WorkspaceLayout[]>;

        /**
         * Saves the provided layouts into Glue42. In Glue42 Core this will fail with an error if a provided layout's name matches a read-only layout.
         * @param layouts A collection of layouts to add to Glue42.
         */
        import(layouts: WorkspaceLayout[], mode?: "replace" | "merge"): Promise<void>;

        /**
         * Saves an existing, open workspace as a layout.
         * @param config An object describing the name of the layout and the id of the workspace, whose structure will be saved.
         */
        save(config: WorkspaceLayoutSaveConfig): Promise<WorkspaceLayout>;

        /**
         * Notifies when a layouts has been saved. This event is fired when a new layout has been saved and an existing layout has been updated.
         * @param callback Callback function to handle the event. Receives the saved layout as a parameter.
         */
        onSaved(callback: (layout: WorkspaceLayout) => void): Promise<Unsubscribe>;

        /**
         * Notifies when a layouts has been removed.
         * @param callback Callback function to handle the event. Receives the removed layout as a parameter.
         */
        onRemoved(callback: (layout: WorkspaceLayout) => void): Promise<Unsubscribe>;
    }

    /**
     * @docmenuorder 1
     */
    export interface API {
        /**
         * Checks whether or not the calling window is currently present inside of a workspace
         */
        inWorkspace(): Promise<boolean>;

        /**
         * Gets either a workspace or a box builder depending on the provided type inside the config object.
         * This builder is used to dynamically construct a workspace runtime.
         * @param config An object describing the type of the requested builder, alongside other settings.
         */
        getBuilder(config: BuilderConfig): WorkspaceBuilder | BoxBuilder;

        /**
         * Returns the frame instance of the calling window. Throws an error if the calling window is not part of a workspace.
         */
        getMyFrame(): Promise<Frame>;

        /**
         * Returns the first frame instance which satisfies the provided predicate or undefined, if non do.
         * @param predicate A filtering function (predicate) called for each open frame.
         */
        getFrame(predicate: (frame: Frame) => boolean): Promise<Frame>;

        /**
         * Returns all frames which satisfy the provided predicate. If no predicate is provided, will return all frames.
         * @param predicate A filtering function (predicate) called for each open frame.
         */
        getAllFrames(predicate?: (frame: Frame) => boolean): Promise<Frame[]>;

        /**
         * Returns an collection of objects, where each object contains basic information about an open workspace.
         * This function was designed for easy and quick listing of existing workspaces without adding the complexity of transmitting the entire structure of each workspace.
         */
        getAllWorkspacesSummaries(): Promise<WorkspaceSummary[]>;

        /**
         * Returns the instance of the workspace where the calling window is located.
         * Throws an error if the calling window is not not part of any workspace.
         */
        getMyWorkspace(): Promise<Workspace>;

        /**
         * Returns the first workspace instance which satisfies the provided predicate or undefined, if non do.
         * @param predicate A filtering function (predicate) called for each open workspace.
         */
        getWorkspace(predicate: (workspace: Workspace) => boolean): Promise<Workspace>;

        /**
         * Returns all workspaces which satisfy the provided predicate. If no predicate is provided, will return all workspaces.
         * @param predicate A filtering function (predicate) called for each open workspace.
         */
        getAllWorkspaces(predicate?: (workspace: Workspace) => boolean): Promise<Workspace[]>;

        /**
         * Returns the workspace window instance of the first window, which is part of a workspace and satisfies the provided predicate.
         * This function will search recursively in all open workspaces.
         * @param predicate A filtering function (predicate) called for each window in each open workspace.
         */
        getWindow(predicate: (workspaceWindow: WorkspaceWindow) => boolean): Promise<WorkspaceWindow>;

        /**
         * Returns the instance of the first box, which satisfies the provided predicate.
         * This function will search recursively in all open workspaces.
         * @param predicate A filtering function (predicate) called for each box in each open workspace.
         */
        getBox(predicate: (box: WorkspaceBox) => boolean): Promise<WorkspaceBox>;

        /**
         * Opens a new workspace by restoring a previously saved workspace layout.
         * @param name The name of a saved workspace layout, which will be restored.
         * @param options An optional object containing various workspace restore options.
         */
        restoreWorkspace(name: string, options?: RestoreWorkspaceConfig): Promise<Workspace>;

        /**
         * Opens a new workspace based on the provided definition.
         * @param definition An object describing the shape and options of the workspace.
         * @param saveConfig An object used to set various create options.
         */
        createWorkspace(definition: WorkspaceDefinition, saveConfig?: WorkspaceCreateConfig): Promise<Workspace>;

        /**
         * An API which gives full read, write and delete access to the workspaces layouts.
         */
        layouts: WorkspaceLayoutsAPI;

        /**
         * Notifies when a new frame was opened and returns an unsubscribe function.
         * @param callback Callback function to handle the event. Receives the added frame as a parameter.
         */
        onFrameOpened(callback: (frame: Frame) => void): Promise<Unsubscribe>;

        /**
         * Notifies when a new frame was closed and returns an unsubscribe function.
         * @param callback Callback function to handle the event. Receives an object containing the id of the closed frame as a parameter.
         */
        onFrameClosed(callback: (closed: { frameId: string }) => void): Promise<Unsubscribe>;

        /**
         * Notifies when a new workspace was opened in any of the opened frames and returns an unsubscribe function.
         * @param callback Callback function to handle the event. Receives the added workspace as a parameter.
         */
        onWorkspaceOpened(callback: (workspace: Workspace) => void): Promise<Unsubscribe>;

        /**
         * Notifies when a workspace present in any of the opened frames was closed and returns an unsubscribe function.
         * @param callback Callback function to handle the event. Receives an object with the closed workspace id and frame id as a parameter.
         */
        onWorkspaceClosed(callback: (closed: { frameId: string; workspaceId: string }) => void): Promise<Unsubscribe>;

        /**
         * Notifies when a new window was added to any workspace in any frame and returns an unsubscribe function.
         * An added window means that the window has a place in a workspace (it is a valid workspace element), but does not guarantee that the contents of the window are loaded.
         * @param callback Callback function to handle the event. Receives the added window as a parameter.
         */
        onWindowAdded(callback: (workspaceWindow: WorkspaceWindow) => void): Promise<Unsubscribe>;

        /**
         * Notifies when a window's content was loaded in any workspace in any frame and returns an unsubscribe function.
         * A loaded window is a window, which was added to a workspace, it's contents were loaded and it is present in the windows collection.
         * @param callback Callback function to handle the event. Receives the loaded window as a parameter.
         */
        onWindowLoaded(callback: (workspaceWindow: WorkspaceWindow) => void): Promise<Unsubscribe>;

        /**
         * Notifies when a window was removed from any workspace and any frame and returns an unsubscribe function.
         * @param callback Callback function to handle the event. Receives an object containing the ids of the removed window, and the respective workspace and frame as a parameter.
         */
        onWindowRemoved(callback: (removed: { windowId?: string; workspaceId: string; frameId: string }) => void): Promise<Unsubscribe>;

    }
}


text:
import React, { Component } from 'react';
import injectSheet, { jss } from 'react-jss';

import Button from './button';
import Title from './Title';
import Footer from './Footer';
import Viewer from './viewer';
import { PDFJS } from './pdfjs/pdfjs-viewer';
import ProgressBar from './progress-bar';
import styles from './styles';
import './css/style.css';

// const DEFAULT_URL = '../../web/compressed.tracemonkey-pldi-09.pdf';
const DEFAULT_SCALE_DELTA = 1.1;
const MIN_SCALE = 0.25;
const MAX_SCALE = 10.0;
const DEFAULT_SCALE_VALUE = 'auto';

const style = {
  pdfviewerBody: {
    background: 'url(' + require('./css/images/document_bg.png') + ')',
    color: '#fff',
    fontFamily: 'sans-serif',
    fontSize: 10,
    height: '100%',
    width: '100%',
    overflow: 'hidden',
    paddingBottom: '5rem'
  }
}

let sheet;
class App extends Component {

  constructor(props) {
    super(props);

    this.state = {
      pageNumber: 1,
      pdfPageCount: 0,
      title: 'sample-title.pdf',
      pdf: null,
      loadingProgress: 0,
      percent: 0
    }

    this.initializePDFJS();

    this._pdfLoadingTask = null;
    this._pdfDocument = null;
    this._pdfViewer = null;
    this._pdfHistory = null;
    this._pdfLinkService = null;
  }

  initializePDFJS() {
    PDFJS.useOnlyCssZoom = true;
    PDFJS.disableTextLayer = true;
    PDFJS.maxImageSize = -1;//4096 * 4096;
    // @todo implement
    // PDFJS.workerSrc = '../../build/dist/build/pdf.worker.js';
    // PDFJS.cMapUrl = '../../build/dist/cmaps/';
    // PDFJS.cMapPacked = true;
  }

  /**
   * handle pdf loading progress
   * @param {object} progressData
   */
  loadingProgressHandler = (progressData) => {
    let percent = progressData.loaded / progressData.total;
    this.progress(percent);
    this.setState({ loadingProgress: percent });
    console.log(progressData.loaded / progressData.total);
  }

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

  onPageUp = () => {
    let pageNumber = this.state.pageNumber + 1;
    this.setState({ pageNumber });
    this._pdfViewer.currentPageNumber = pageNumber;
  }

  onPageDown = () => {
    let pageNumber = this.state.pageNumber - 1;
    this.setState({ pageNumber });
    this._pdfViewer.currentPageNumber = pageNumber;
  }

  onZoomIn = (ticks) => {
    var newScale = this._pdfViewer.currentScale;
    do {
      newScale = (newScale * DEFAULT_SCALE_DELTA).toFixed(2);
      newScale = Math.ceil(newScale * 10) / 10;
      newScale = Math.min(MAX_SCALE, newScale);
    } while (--ticks && newScale < MAX_SCALE);
    this._pdfViewer.currentScaleValue = newScale;

  }

  onZoomOut = (ticks) => {
    var newScale = this._pdfViewer.currentScale;
    do {
      newScale = (newScale / DEFAULT_SCALE_DELTA).toFixed(2);
      newScale = Math.floor(newScale * 10) / 10;
      newScale = Math.max(MIN_SCALE, newScale);
    } while (--ticks && newScale > MIN_SCALE);
    this._pdfViewer.currentScaleValue = newScale;

  }

  setTitle = (title) => {
    this.setState({ title });
  }

  pageCount = () => {
    return this.state.pdfPageCount;
  }

  get page() {
    if (this._pdfViewer) {
      return this._pdfViewer.currentPageNumber;
    }
  }

  set page(page) { }

  componentWillUnmount() {
    console.log('pdfviewer unmounted');
    jss.removeStyleSheet(sheet)
    this.close();
  }

  componentDidMount() {

    sheet = jss.createStyleSheet(styles, { named: false }).attach()
    // document.html.classList.toggle('html', true)
    document.body.classList.toggle('body', true)

    console.log('pdfview application loaded');

    let linkService = new PDFJS.PDFLinkService();
    this._pdfLinkService = linkService;

    let container = this._viewer.viewerContainer;
    console.log(container);

    let pdfViewer = new PDFJS.PDFViewer({
      container: container,
      linkService: linkService
    });

    this._pdfViewer = pdfViewer;

    linkService.setViewer(pdfViewer);

    this._pdfHistory = new PDFJS.PDFHistory({
      linkService: linkService
    });

    linkService.setHistory(this._pdfHistory);

    container.addEventListener('pagesinit', () => {
      // We can use pdfViewer now, e.g. let's change default scale.
      pdfViewer.currentScaleValue = DEFAULT_SCALE_VALUE;
    });

    container.addEventListener('pagechange', (evt) => {
      let pageNumber = evt.pageNumber;
      this.setState({ pageNumber });;
    }, true);

    this.animationStarted().then(() => {
      console.log('ready to open the pdf');
      if (this.props.url) this.openPDF();
    });
  }
  setTitleUsingUrl = (url) => {
    this._url = url;
    var title = PDFJS.getFilenameFromUrl(url) || url;
    try {
      title = decodeURIComponent(title);
    } catch (e) {
      // decodeURIComponent may throw URIError,
      // fall back to using the unprocessed url in that case
    }
    this.setTitle(title);
  }

  setTitleUsingMetadata = (pdfDocument) => {

    pdfDocument.getMetadata().then((data) => {
      var info = data.info, metadata = data.metadata;
      this.documentInfo = info;
      this.metadata = metadata;

      // Provides some basic debug information
      console.log('PDF ' + pdfDocument.fingerprint + ' [' +
        info.PDFFormatVersion + ' ' + (info.Producer || '-').trim() +
        ' / ' + (info.Creator || '-').trim() + ']' +
        ' (PDF.js: ' + (PDFJS.version || '-') +
        (!PDFJS.disableWebGL ? ' [WebGL]' : '') + ')');

      var pdfTitle;
      if (metadata && metadata.has('dc:title')) {
        var title = metadata.get('dc:title');
        // Ghostscript sometimes returns 'Untitled', so prevent setting the
        // title to 'Untitled.
        if (title !== 'Untitled') {
          pdfTitle = title;
        }
      }

      if (!pdfTitle && info && info['Title']) {
        pdfTitle = info['Title'];
      }

      if (pdfTitle) {
        this.setTitle(pdfTitle + ' - ' + document.title);
      }
    });

  }

  /**
   * opens the pdf in the url prop
   */
  openPDF() {

    if (this._pdfLoadingTask) {
      // We need to destroy already opened document
      return this.close().then(() => {
        // ... and repeat the open() call.
        return this.openPDF();
      });
    }

    if (typeof this.props.url === 'string') {
      this.setTitleUsingUrl(this.props.url);
    }

    let loadingTask = PDFJS.getDocument(this.props.url);
    this._pdfLoadingTask = loadingTask;

    loadingTask.onProgress = this.loadingProgressHandler;

    return loadingTask.promise.then((pdfDocument) => {
      // Document loaded, specifying document for the viewer.
      this._pdfDocument = pdfDocument;

      this.setState({
        pdf: pdfDocument,
        pdfPageCount: pdfDocument.numPages
      });

      // this.pdfPageCount = pdfDocument
      this._pdfViewer.setDocument(pdfDocument);
      this._pdfLinkService.setDocument(pdfDocument);
      this._pdfHistory.initialize(pdfDocument.fingerprint);

      this.setTitleUsingMetadata(pdfDocument);
    });
  }

  progress = (level) => {
    var percent = Math.round(level * 100);
    // Updating the bar if value increases.
    if (percent > this.state.percent || isNaN(percent)) {
      this.setState({ percent });
    }
  }

  set loadingBar(x) { }

  close = () => {

    console.log('closing pdfjs');

    // var errorWrapper = document.getElementById('errorWrapper');
    // errorWrapper.setAttribute('hidden', 'true');

    if (!this._pdfLoadingTask) {
      return Promise.resolve();
    }

    var promise = this._pdfLoadingTask.destroy();
    this._pdfLoadingTask = null;

    if (this._pdfDocument) {
      this._pdfDocument = null;

      this._pdfViewer.setDocument(null);
      this._pdfLinkService.setDocument(null, null);
    }

    return promise;

  }

  animationStarted() {
    return new Promise((resolve) => {
      window.requestAnimationFrame(resolve);
    })
  }

  render() {
    return (
      <div id="pdfViewer" className="pdf-viewer" style={style.pdfviewerBody}>
        <Title title={this.state.title} />
        <ProgressBar percent={this.state.percent} ref={(c) => this._progressBar = c} />
        <Viewer ref={(c) => this._viewer = c} />
        <Footer>

          <Button
            className="pageDown"
            onClick={this.onPageDown}
            title="Previous Page"
            id="previous"
            disabled={this.state.pageNumber === 1}
            ></Button>

          <Button
            className="pageUp"
            onClick={this.onPageUp}
            title="Next Page"
            id="next"
            disabled={this.state.pageNumber === this.state.pdfPageCount}
            ></Button>

          <input
            type="number"
            id="pageNumber"
            className="toolbarField pageNumber"
            value={this.state.pageNumber}
            onChange={this.onPageNumberChange}
            size="4"
            min="1"
            ></input>

          <Button
            className="close"
            onClick={this.props.onClose}
            title="Close"
            id="close"
            ></Button>

          <Button className="zoomOut" onClick={this.onZoomOut} title="Zoom Out" id="zoomOut"></Button>
          <Button className="zoomIn" onClick={this.onZoomIn} title="Zoom In" id="zoomIn"></Button>

        </Footer>
      </div>
    );
  }
}

App.propTypes = {
  url: React.PropTypes.any.isRequired,
  onClose: React.PropTypes.func
}

export default App;

redpajama_set_name: RedPajamaGithub


text:
REnv is a tool for running commands with a set of environment variables.
It can be used to quickly switch the value of environment variables which is particularly useful for some devops tools.

Environment variable values are stored in .env files at a well known location:

1. Windows: %APPDATA%\renv\envs\
2. Linux/Unix: $HOME/.config/renv/envs/

## Installation

1. install rust from https://www.rust-lang.org/
2. ensure you have installed your platform's matching compiler toolchain (gcc, mingw or msvc)
2. run ```cargo install renv```

## Platforms

REnv supports windows, linux and unix.

## Commands
REnv supports the following commands:

###edit
Start $EDITOR to modify the contents of the named .env file

###exec
Run a command with the environment variables loaded from the named .env file
Add a "--" before any arguments that might contain hyphens and confuse renv's argument parsing.

###install
Copy a given .env file to the location calculated from the given environment name

###list
List installed environment .env files by environment name

###new
Create a blank installed environment .env file and stsart $EDITOR to edit the contents

###remove
Delete the installed environment .env file

###show
Print the contents of the named environment .env file to the console

## Examples

```
cat > prod.env <<EOF
RENV=prod
AWS_ACCESS_KEY_ID=foo
AWS_SECRET_ACCESS_KEY=bar
EOF

renv install prod prod.env

renv exec prod -- aws s3 ls
```


text:
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import {CustomElement} from 'chrome://resources/js/custom_element.js';
import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js';

import {TabGroupVisualData} from './tab_strip.mojom-webui.js';
import {TabsApiProxy, TabsApiProxyImpl} from './tabs_api_proxy.js';

export class TabGroupElement extends CustomElement {
  static get template() {
    return `{__html_template__}`;
  }

  private tabsApi_: TabsApiProxy;
  private chip_: HTMLElement;
  private isValidDragOverTarget_: boolean;

  constructor() {
    super();

    this.tabsApi_ = TabsApiProxyImpl.getInstance();

    this.chip_ = this.$('#chip') as HTMLElement;
    this.chip_.addEventListener('click', () => this.onClickChip_());
    this.chip_.addEventListener(
        'keydown', e => this.onKeydownChip_(/** @type {!KeyboardEvent} */ (e)));

    /**
     * Flag indicating if this element can accept dragover events. This flag
     * is updated by TabListElement while animating.
     */
    this.isValidDragOverTarget_ = true;
  }

  get isValidDragOverTarget(): boolean {
    return !this.hasAttribute('dragging_') && this.isValidDragOverTarget_;
  }

  set isValidDragOverTarget(isValid: boolean) {
    this.isValidDragOverTarget_ = isValid;
  }

  getDragImage(): HTMLElement {
    return this.$('#dragImage') as HTMLElement;
  }

  getDragImageCenter(): HTMLElement {
    // Since the drag handle is #dragHandle, the drag image should be
    // centered relatively to it.
    return this.$('#dragHandle') as HTMLElement;
  }

  private onClickChip_() {
    if (!this.dataset.groupId) {
      return;
    }

    const boundingBox = this.$('#chip')!.getBoundingClientRect();
    this.tabsApi_.showEditDialogForGroup(
        this.dataset.groupId, boundingBox.left, boundingBox.top,
        boundingBox.width, boundingBox.height);
  }

  private onKeydownChip_(event: KeyboardEvent) {
    if (event.key === 'Enter' || event.key === ' ') {
      this.onClickChip_();
    }
  }

  setDragging(enabled: boolean) {
    // Since the draggable target is the #chip, if the #chip moves and is no
    // longer under the pointer while the dragstart event is happening, the drag
    // will get canceled. This is unfortunately the behavior of the native drag
    // and drop API. The workaround is to have two different attributes: one
    // to get the drag image and start the drag event while keeping #chip in
    // place, and another to update the placeholder to take the place of where
    // the #chip would be.
    this.toggleAttribute('getting-drag-image_', enabled);
    requestAnimationFrame(() => {
      this.toggleAttribute('dragging', enabled);
    });
  }

  setDraggedOut(isDraggedOut: boolean) {
    this.toggleAttribute('dragged-out_', isDraggedOut);
  }

  isDraggedOut(): boolean {
    return this.hasAttribute('dragged-out_');
  }

  setTouchPressed(isTouchPressed: boolean) {
    this.toggleAttribute('touch_pressed_', isTouchPressed);
  }

  updateVisuals(visualData: TabGroupVisualData) {
    (this.$('#title') as HTMLElement).innerText = visualData.title;
    this.style.setProperty('--tabstrip-tab-group-color-rgb', visualData.color);
    this.style.setProperty(
        '--tabstrip-tab-group-text-color-rgb', visualData.textColor);

    // Content strings are empty for the label and are instead replaced by
    // the aria-describedby attribute on the chip.
    if (visualData.title) {
      this.chip_.setAttribute(
          'aria-label',
          loadTimeData.getStringF('namedGroupLabel', visualData.title, ''));
    } else {
      this.chip_.setAttribute(
          'aria-label', loadTimeData.getStringF('unnamedGroupLabel', ''));
    }
  }
}

declare global {
  interface HTMLElementTagNameMap {
    'tabstrip-tab-group': TabGroupElement;
  }
}

customElements.define('tabstrip-tab-group', TabGroupElement);

export function isTabGroupElement(element: Element): boolean {
  return element.tagName === 'TABSTRIP-TAB-GROUP';
}

export function isDragHandle(element: Element): boolean {
  return element.id === 'dragHandle';
}


text:
var Constants = require('./Constants');

function SmlBuffer(value){

	if(value===undefined) {
		this.buffer = Buffer.alloc(Constants.MAX_BUFFER_SIZE);
	} else {
		this.buffer=value;
	}
	this.offset=0;
    this.lastReadValueType=null;
}

SmlBuffer.prototype.getBuffer = function getBuffer(){
	return this.buffer;
};

SmlBuffer.prototype.getOffset = function getOffset(){
	return this.offset;
};

SmlBuffer.prototype.setOffset = function setOffset(value){
	this.offset = value;
};

SmlBuffer.prototype.getLength = function getLength(){
	return this.buffer.length;
};

SmlBuffer.prototype.toString = function toString(){
	if (!Buffer.isBuffer(this.buffer)) return this.buffer;
	return this.buffer.toString('hex');
};

SmlBuffer.prototype.finalize = function finalize(startOffset){
    if (!startOffset) startOffset=0;
    this.buffer=this.buffer.slice(startOffset, this.offset);
};

// ########################## OctetString #########################################################

SmlBuffer.prototype.writeOctetString = function writeOctetString(value){
	/*var bits = Math.ceil(Math.log(value.length)/Math.log(2));
	var bytes = Math.ceil(bits/4);
	var hexLength = (value.length+bytes).toString(16).length % 2 === 0 ? (value.length+bytes).toString(16) : "0"+(value.length+bytes).toString(16);
	var length = new Buffer(hexLength, 'hex');

	for(var i=0; i<bytes; i++){
		if(bytes-(i+1) > 0){
			byte = 0x80 | ((length.readUInt8(Math.floor(i/2)) & 0xF0)>>4);
		} else {
			byte = 0x00 | (length.readUInt8(Math.floor(i/2)) & 0x0F);
		}
		this.buffer.writeUInt8(byte, this.offset);
		this.offset+=1;
	}*/
    this.writeTLField(0x0, value.length); // SEQUENZ

    if (Buffer.isBuffer(value)) {
        value.copy(this.buffer, this.offset);
        this.offset+=value.length;
    }
    else {
        for(var j=0; j<value.length; j++){
    		this.buffer.writeUInt8(value.charCodeAt(j), this.offset);
    		this.offset++;
    	}
    }
};

SmlBuffer.prototype.readOctetString = function readOctetString(){
	var tlField = this.readTLField();

	var type = tlField.type;
	var length = tlField.length;

	// OPTIONAL
	if(type === 0x00 && length===0x01){
		return undefined;
	} else {
		if(type !== 0x08 && type !== 0x00){
			throw new Error("Unknown TL-Field 0x"+tlField.type.toString(16)+tlField.length.toString(16)+" for OctetString [Offset: "+this.offset+"]!");
		} else {
            this.lastReadValueType=type;
            var result = this.buffer.slice(this.offset, this.offset+tlField.length-1);
			this.offset+=tlField.length-1;
			return result;
		}
	}
};

// ############################ read #############################################

SmlBuffer.prototype.readUInt8 = function readUInt8(){
	var result = this.buffer.readUInt8(this.offset);
	this.offset++;
    this.lastReadValueType = Constants.UINT8;
	return result;
};

SmlBuffer.prototype.readInt8 = function readInt8(){
	var result = this.buffer.readInt8(this.offset);
	this.offset++;
    this.lastReadValueType = Constants.INT8;
	return result;
};

SmlBuffer.prototype.readUInt16 = function readUInt16(){
	var result = this.buffer.readUInt16BE(this.offset);
	this.offset+=2;
    this.lastReadValueType = Constants.UINT16;
	return result;
};

SmlBuffer.prototype.readInt16 = function readInt16(){
	var result = this.buffer.readInt16BE(this.offset);
	this.offset+=2;
    this.lastReadValueType = Constants.INT16;
	return result;
};

SmlBuffer.prototype.readUInt32 = function readUInt32(){
	var result = this.buffer.readUInt32BE(this.offset);
	this.offset+=4;
    this.lastReadValueType = Constants.UINT32;
	return result;
};

SmlBuffer.prototype.readInt32 = function readInt32(){
	var result = this.buffer.readInt32BE(this.offset);
	this.offset+=4;
    this.lastReadValueType = Constants.INT32;
	return result;
};

SmlBuffer.prototype.readUInt64 = function readUInt64(){
	//var result = (this.buffer.readUInt32BE(this.offset+4)<<8) & this.buffer.readUIntBE(this.offset);
	/*var result = this.buffer.readDoubleBE(this.offset);
	this.offset+=8;
    this.lastReadValueType = Constants.UINT64;
	return result;*/
    var Int64 = require('int64-buffer');
    var int64 = new Int64.Uint64BE(this.buffer, this.offset);
    this.offset+=8;
    this.lastReadValueType = Constants.UINT64;
    if (int64.toNumber().toString(10)==int64.toString(10)) {
        return int64.toNumber();
    }
    else {
        return int64.toString(10);
    }
};

SmlBuffer.prototype.readInt64 = function readInt64(){
	var Int64 = require('int64-buffer');
	var int64 = new Int64.Int64BE(this.buffer, this.offset);
	this.offset+=8;
    this.lastReadValueType = Constants.INT64;
    if (int64.toNumber().toString(10)==int64.toString(10)) {
        return int64.toNumber();
    }
    else {
        return int64.toString(10);
    }
};

// ################################ write ########################################

SmlBuffer.prototype.writeInt8 = function writeInt8(value){
	this.buffer.writeInt8(value, this.offset);
	this.offset+=1;
};

SmlBuffer.prototype.writeUInt8 = function writeUInt8(value){
	this.buffer.writeUInt8(value, this.offset);
	this.offset+=1;
};

SmlBuffer.prototype.writeInt16 = function writeInt16(value){
	this.buffer.writeInt16BE(value, this.offset);
	this.offset+=2;
};

SmlBuffer.prototype.writeUInt16 = function writeUInt16(value){
	this.buffer.writeUInt16BE(value, this.offset);
	this.offset+=2;
};

SmlBuffer.prototype.writeInt32 = function writeInt32(value){
	this.buffer.writeInt32BE(value, this.offset);
	this.offset+=4;
};

SmlBuffer.prototype.writeUInt32 = function writeUInt32(value){
	this.buffer.writeUInt32BE(value, this.offset);
	this.offset+=4;
};

SmlBuffer.prototype.writeInt64 = function writeInt64(value){
	//this.buffer.writeDoubleBE(value, this.offset);
    var Int64 = require('int64-buffer');
    if (typeof value == "string") int64 = new Int64.Int64BE(value,10);
      else int64 = new Int64.Int64BE(value);
    int64.toBuffer().copy(this.buffer,this.offset);
	this.offset+=8;
};

SmlBuffer.prototype.writeUInt64 = function writeUInt64(value){
	//this.buffer.writeDoubleBE(value, this.offset);
    var Int64 = require('int64-buffer');
    var int64;
    if (typeof value == "string") int64 = new Int64.Uint64BE(value,10);
      else int64 = new Int64.Uint64BE(value);
    int64.toBuffer().copy(this.buffer,this.offset);
	this.offset+=8;
};

// #########################################################################

SmlBuffer.prototype.readTLField = function readTLField(){
	var length = 0;
	var counter = 0;
    var type;
    var readMore = false;
    do {
        var tlField = this.buffer.readUInt8(this.offset);
		this.offset++;

        readMore = (tlField >> 7 === 1) ? true : false;
        if (type === undefined) {
			type = ((tlField & 0x7F) >> 4);
		}
		length = ((length<<4) + (tlField & 0x0F));
        if ((tlField & 0x7F) >> 4 === 0 && readMore) { // We have an OctetString and want to return "left length" istead of full length
            counter++;
        }
	} while (readMore);

    length-=counter;
	return {type: type, length: length};
};

// ToDo: Multibyte tl fields
SmlBuffer.prototype.writeTLField = function writeTLField(value, length){
    if (! length) {
        // we directly write out the value because not allowed to be bigger then 1 bytes
        if (value > 0xFF) {
            throw new Error("writeTLField without length only allowed for 1 byte values");
        }
        this.buffer.writeUInt8(value, this.offset);
    	this.offset++;
    }
    else {
        if (value > 0x7) {
            throw new Error("writeTLField with type >0x7 is not allowed");
        }
        // value if the "type" and length is the length
        var bytes = Math.ceil(Math.log(length)/Math.log(2) / 4);
		if (value === 0x0) {
		    length += bytes;
        }

		var lengthVals = [];
        do {
            lengthVals.push(length - ((length >> 4) << 4));
            length = length >> 4;
        } while (length > 0);

        var baseValue = value << 4;
        while (lengthVals.length) {
            var currentLength = lengthVals.pop();
            var writeValue = 0;
            if (lengthVals.length) writeValue = 0x80; // set highest bit because length still > 15
            writeValue = writeValue | baseValue | currentLength;
            this.buffer.writeUInt8(writeValue, this.offset);
        	this.offset++;
            baseValue = 0;
        }
    }
};

SmlBuffer.prototype.readUnsigned = function readUnsigned(){
	var tlField = this.readTLField();
	var type = tlField.type;
	var length = tlField.length;

	// Optional
	if(type===0x00 && length === 0x01){
        this.lastReadValueType = Constants.OPTIONAL;
        return undefined;
	} else {
		if(type!=Constants.UNSIGNED && type!==0x00){
			throw new Error("Wrong TL-Field (" + type.toString(16) + ") for Unsigned!");
		} else {
			if(length == 0x02){
                this.lastReadValueType = Constants.UINT8;
				return this.readUInt8();
			} else if(length == 0x03){
                this.lastReadValueType = Constants.UINT16;
				return this.readUInt16();
			} else if(length == 0x04){
				// Just for EMH impelementation and short Timestamps because of misconfigured/unreachable NTP Server
                this.lastReadValueType = Constants.UINT32;
                var result = this.buffer.readUIntBE(this.offset,3);
                this.offset+=3;
                return result;
			} else if(length == 0x05){
                this.lastReadValueType = Constants.UINT32;
				return this.readUInt32();
			} else if(length == 0x09){
                this.lastReadValueType = Constants.UINT64;
				return this.readUInt64();
			}
		}
	}
};

SmlBuffer.prototype.writeUnsigned = function writeUnsigned(value, tlField){
	if(tlField==Constants.UINT8){
		this.writeTLField(Constants.UINT8);
		this.writeUInt8(value);
	} else if(tlField==Constants.UINT16){
		this.writeTLField(Constants.UINT16);
		this.writeUInt16(value);
	} else if(tlField==Constants.UINT32){
		this.writeTLField(Constants.UINT32);
		this.writeUInt32(value);
	} else if(tlField==Constants.UINT64){
		this.writeTLField(Constants.UINT64);
		this.writeUInt64(value);
	} else if (valueType==Constants.OPTIONAL){
        this.writeUInt8(0x01);
    }
};

SmlBuffer.prototype.readInteger = function readInteger(){
	var tlField = this.readTLField();
	var type = tlField.type;
	var length = tlField.length;

	if(type===0x00 && length === 0x01){
		return undefined;
	} else {
		if(type != Constants.INTEGER && type !== 0x00){
			throw new Error("Wrong TL-Field for Integer!");
		} else {
			if(length == 0x02){
                this.lastReadValueType = Constants.INT8;
				return this.readInt8();
			} else if(length == 0x03){
                this.lastReadValueType = Constants.INT16;
				return this.readInt16();
            } else if(length == 0x04){
                this.lastReadValueType = Constants.INT32;
                var result = this.buffer.readIntBE(this.offset,3);
                this.offset+=3;
                return result;
			} else if(length == 0x05){
                this.lastReadValueType = Constants.INT32;
				return this.readInt32();
            } else if(length == 0x06){
                this.lastReadValueType = Constants.INT64;
				var result = this.buffer.readIntBE(this.offset,5);
                this.offset+=5;
                return result;
			} else if(length == 0x09){
                this.lastReadValueType = Constants.INT64;
				return this.readInt64();
			}
		}
	}
};

SmlBuffer.prototype.writeInteger = function writeInteger(value, tlField){
	if(tlField==Constants.INT8){
		this.writeTLField(Constants.INT8);
		this.writeInt8(value);
	} else if(tlField==Constants.INT16){
		this.writeTLField(Constants.INT16);
		this.writeInt16(value);
	} else if(tlField==Constants.INT32){
		this.writeTLField(Constants.INT32);
		this.writeInt32(value);
	} else if(tlField==Constants.INT64){
		this.writeTLField(Constants.INT64);
		this.writeInt64(value);
	} else if (valueType==Constants.OPTIONAL){
        this.writeUInt8(0x01);
    }
};

SmlBuffer.prototype.readSmlValue = function readSmlValue(){

	if((this.buffer.readUInt8(this.offset)>>4)===0x00 || (this.buffer.readUInt8(this.offset)>>4)===0x08){
		return this.readOctetString();
	} else if((this.buffer.readUInt8(this.offset)>>4)==0x04){
		return this.readSmlBoolean();
	} else if((this.buffer.readUInt8(this.offset)>>4)==0x05){
		return this.readInteger();
	} else if((this.buffer.readUInt8(this.offset)>>4)==0x06){
		return this.readUnsigned();
	} else {
		throw new Error("Wrong TL-Field 0x"+this.buffer.readUInt8(this.offset).toString(16)+" for SmlValue!");
	}
};

SmlBuffer.prototype.writeSmlValue = function writeSmlValue(value, valueType){
	if(valueType==Constants.BOOLEAN){
		this.writeSmlBoolean(value);
	} else if(valueType==Constants.OCTET_STRING){
		this.writeOctetString(value);
	} else if(valueType==Constants.UINT8){
		this.writeUnsigned(value, valueType);
	} else if(valueType==Constants.UINT16){
		this.writeUnsigned(value, valueType);
	} else if(valueType==Constants.UINT32){
		this.writeUnsigned(value, valueType);
	} else if(valueType==Constants.UINT64){
		this.writeUnsigned(value, valueType);
	} else if(valueType==Constants.INT8){
		this.writeInteger(value, valueType);
	} else if(valueType==Constants.INT16){
		this.writeInteger(value, valueType);
	} else if(valueType==Constants.INT32){
		this.writeInteger(value, valueType);
	} else if(valueType==Constants.INT64){
		this.writeInteger(value, valueType);
	} else if (valueType==Constants.OPTIONAL){
        this.writeUInt8(0x01);
    }
};

SmlBuffer.prototype.readSmlBoolean = function readSmlBoolean(){
	var tlField = this.readTLField();
	var type = tlField.type;
	var length = tlField.length;

	if(type === 0x00 && length === 0x01){
		// OPTIONAL
		return undefined;
	} else {
		if(type != Constants.BOOLEAN || length != 0x02){
			throw new Error("Wrong TL-Field for Boolean!");
		} else {
			if(this.readUInt8()===0x00){
                this.lastReadValueType = Constants.BOOLEAN;
				return false;
			} else {
                this.lastReadValueType = Constants.BOOLEAN;
				return true;
			}
		}
	}
};

SmlBuffer.prototype.writeSmlBoolean = function writeSmlBoolean(value){

	if(value === undefined){
		// Optional
		this.writeUInt8(Constants.OPTIONAL);
	} else {
		this.writeTLField(0x42);
		if(value === true){
			this.writeUInt8(0x01);
		} else {
			this.writeUInt8(0x00);
		}
	}
};

SmlBuffer.prototype.readChoice = function readChoice(){
	var tlField = this.readTLField();

	var type = tlField.type;
	var length = tlField.length;

	if (type === 0x00 && length === 0x01) {
		// OPTIONAL
		return undefined;
	} else if (tlField.type == 0x06 && tlField.length == 0x05) {
		// workaround Holley DTZ541
		// if SML_ListEntry valTime (SML_Time) is given there are missing bytes:
		// 0x72: indicate a list for SML_Time with 2 entries
		// 0x62 0x01: indicate secIndex
		// 0x65 + 4 bytes seconds
		// instead, the DTZ541 starts with the last line: 0x65 + 4 bytes secIndex
		//
		// reset the previously read tl-field to be able
		// to re-read the TLField 0x65 to get the secIndex value
		this.setOffset(this.offset - 1);
		// this workaround will return choice 0x01 and sets the offset back to
		return 0x01;
	} else if (tlField.type != 0x07 && tlField.length != 0x02) {
		throw new Error("Wrong TL-Field 0x" + type.toString(16) + length.toString(16) + " for Choice!");
	} else {
		return this.readUnsigned();
	}
};

SmlBuffer.prototype.writeChoice = function writeChoice(value, tlField){
	this.writeTLField(0x72);
	if([Constants.UINT8, Constants.UINT16, Constants.UINT32, Constants.UINT64].indexOf(tlField) > -1){
		this.writeUnsigned(value, tlField);
	} else {
		throw new Error("Unknown Choice-Element!");
	}
};

module.exports = SmlBuffer;


text:
/*
 *    This program is free software; you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation; either version 2 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program; if not, write to the Free Software
 *    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

/*
 *    SimpleCLI.java
 *    Copyright (C) 1999 University of Waikato, Hamilton, New Zealand
 *
 */

package weka.gui;

import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

/**
 * Creates a very simple command line for invoking the main method of
 * classes. System.out and System.err are redirected to an output area.
 * Features a simple command history -- use up and down arrows to move
 * through previous commmands. This gui uses only AWT (i.e. no Swing).
 *
 * @author Len Trigg (trigg@cs.waikato.ac.nz)
 * @author FracPete (fracpete at waikato dot ac dot nz)
 * @version $Revision: 7059 $
 */
public class SimpleCLI
  extends Frame {

  /** for serialization */
  static final long serialVersionUID = -50661410800566036L;

  /**
   * Constructor
   *
   * @throws Exception if an error occurs
   */
  public SimpleCLI() throws Exception {
    setTitle(Messages.getInstance().getString("SimpleCL_SetTitle_Text"));
    setLayout(new BorderLayout());
    add(new SimpleCLIPanel());
    pack();
    setSize(600, 500);
    setVisible(true);
  }

  /**
   * Method to start up the simple cli
   *
   * @param args array of command line arguments. Not used.
   */
  public static void main(String[] args) {

    try {
      final SimpleCLI frame = new SimpleCLI();
      frame.addWindowListener(new WindowAdapter() {
	public void windowClosing(WindowEvent param1) {
	  System.err.println(Messages.getInstance().getString("SimpleCL_Main_Error_Text"));
	  frame.dispose();
	}
      });
      frame.setVisible(true);
    } catch (Exception e) {
      System.out.println(Thread.currentThread().getStackTrace()[1].getClassName() +e.getMessage());
      System.exit(0);
    }
  }
}


text:
package org.fusesource.scalate.camel

import _root_.org.junit.runner.RunWith
import _root_.org.scalatest.junit.JUnitRunner
import _root_.org.scalatest.FunSuite
import _root_.org.apache.camel.builder.RouteBuilder
import _root_.org.apache.camel._
import _root_.org.apache.camel.impl.DefaultCamelContext

/**
 * @version $Revision : 1.1 $
 */
@RunWith(classOf[JUnitRunner])
class CamelScalateEndpointTest extends FunSuite {
  val uriPrefix = "scalate:org/fusesource/scalate/camel/"

  scenario(uriPrefix + "constant.ssp", "James", "<hello>James</hello>")
  scenario(uriPrefix + "example.ssp", "James", "<hello>James</hello>")

  /**
   * Processes the route builder using the given callback function which processes a producer template on the constructed
   * camel context
   */
  def withRouteBuilder(routeBuilder: RouteBuilder)(useTemplate: (ProducerTemplate) => Unit): Unit = {
    val context = new DefaultCamelContext()
    context.setTracing(true)
    context.addRoutes(routeBuilder)
    try {
      context.start()

      val template = context.createProducerTemplate()
      Thread.sleep(2000)
      useTemplate(template)
    } finally {
      context.stop()
    }
  }

  def scenario(uri: String, body: Any, expectedResult: String): Unit = {
    test("routing to endpoint " + uri) {
      val startUri = "direct:start"
      val headerValue = "someHeaderValue"

      val routeBuilder = new RouteBuilder() {
        def configure(): Unit = {
          from(startUri).to(uri)
        }
      }
      withRouteBuilder(routeBuilder) {
        template =>
          val response = template.request(startUri, new Processor() {
            def process(exchange: Exchange): Unit = {
              val in = exchange.getIn
              in.setBody(body)
              in.setHeader("cheese", headerValue)

              println("sending body: " + exchange.getIn.getBody)
            }
          })

          val out = response.getOut
          assume(out != null, "out was null when sending to uri: " + uri + " body: " + body)

          val actualBody = out.getBody(classOf[String])
          assume(actualBody != null, "Null body should not be returned when sending to: " + uri + " with out message: " + out)

          assertResult(expectedResult) {
            actualBody.trim()
          }
          assertResult(headerValue) {
            out.getHeader("cheese", classOf[String])
          }
      }
    }
  }

}


text:
import sys
import os

import numpy as np
import scipy.sparse as sp
import scipy.sparse.linalg as spla

from .. import N, solve, ones, flatten_sparse_matrix, diag_add, dot

import pytest

this_dir = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(this_dir, os.pardir))

DTYPES = ['f8', np.complex128]

@pytest.mark.parametrize('dtype', DTYPES)
def test_solve_identity_ones(dtype):
    b = np.ones(N, dtype=dtype)
    mat = sp.eye(N, format='csr', dtype=dtype)
    obs = solve(mat, b)
    exp = spla.spsolve(mat, b)
    assert np.allclose(exp, obs)

@pytest.mark.parametrize('dtype', DTYPES)
def test_solve_identity_range(dtype):
    b = np.arange(N, dtype=dtype)
    mat = sp.eye(N, format='csr', dtype=dtype)
    obs = solve(mat, b)
    exp = spla.spsolve(mat, b)
    assert np.allclose(exp, obs)

@pytest.mark.parametrize('dtype', DTYPES)
def test_solve_ones_ones(dtype):
    b = np.ones(N, dtype=dtype)
    mat = ones(dtype=dtype) + 9*sp.eye(N, format='csr', dtype=dtype)
    obs = solve(mat, b)
    exp = spla.spsolve(mat, b)
    assert np.allclose(exp, obs)

@pytest.mark.parametrize('dtype', DTYPES)
def test_solve_ones_range(dtype):
    b = np.arange(N, dtype=dtype)
    mat = ones(dtype=dtype) + 9*sp.eye(N, format='csr', dtype=dtype)
    obs = solve(mat, b)
    exp = spla.spsolve(mat, b)
    assert np.allclose(exp, obs)

@pytest.mark.parametrize('dtype', DTYPES)
def test_solve_range_range(dtype):
    b = np.arange(N, dtype=dtype)
    mat = ones(dtype=dtype) + sp.diags([b], offsets=[0], shape=(N, N),
                                              format='csr', dtype=dtype)
    obs = solve(mat, b)
    exp = spla.spsolve(mat, b)
    assert np.allclose(exp, obs)

@pytest.mark.parametrize('dtype', DTYPES)
def test_diag_add(dtype):
    mat = ones(dtype=dtype)
    res = mat + 9*sp.eye(N, format='csr', dtype=dtype)
    exp = flatten_sparse_matrix(res)
    obs = diag_add(mat, 9.0)
    assert np.allclose(exp, obs)

@pytest.mark.parametrize('dtype', DTYPES)
def test_dot(dtype):
    x = np.arange(N, dtype=dtype)
    mat = ones(dtype=dtype) + 9*sp.eye(N, format='csr', dtype=dtype)
    exp = mat.dot(x)
    obs = dot(mat, x)
    assert np.allclose(exp, obs)


text:
require 'spec_helper'

describe Projects::GraphsController do
  let(:project) { create(:project, :repository) }
  let(:user)    { create(:user) }

  before do
    sign_in(user)
    project.add_maintainer(user)
  end

  describe 'GET languages' do
    it "redirects_to action charts" do
      get(:commits, params: { namespace_id: project.namespace.path, project_id: project.path, id: 'master' })

      expect(response).to redirect_to action: :charts
    end
  end

  describe 'GET commits' do
    it "redirects_to action charts" do
      get(:commits, params: { namespace_id: project.namespace.path, project_id: project.path, id: 'master' })

      expect(response).to redirect_to action: :charts
    end
  end

  describe 'charts' do
    context 'with an anonymous user' do
      let(:project) { create(:project, :repository, :public) }

      before do
        sign_out(user)
      end

      it 'renders charts with 200 status code' do
        get(:charts, params: { namespace_id: project.namespace.path, project_id: project.path, id: 'master' })

        expect(response).to have_gitlab_http_status(:ok)
        expect(response).to render_template(:charts)
      end
    end

    context 'when languages were previously detected' do
      let(:project) { create(:project, :repository, detected_repository_languages: true) }
      let!(:repository_language) { create(:repository_language, project: project) }

      it 'sets the languages properly' do
        get(:charts, params: { namespace_id: project.namespace.path, project_id: project.path, id: 'master' })

        expect(assigns[:languages]).to eq(
          [value: repository_language.share,
           label: repository_language.name,
           color: repository_language.color,
           highlight: repository_language.color])
      end
    end
  end
end


text:
require 'mime/types'
require 'resync/xml'

module Resync
  # Base class for ResourceSync-specific elements describing a
  # resource or link.
  #
  # @!attribute [rw] modified_time
  #   @return [Time] the date and time when the referenced resource was last modified.
  # @!attribute [rw] length
  #   @return [Integer] the content length of the referenced resource.
  # @!attribute [rw] mime_type
  #   @return [MIME::Type] the media type of the referenced resource.
  # @!attribute [rw] encoding
  #   @return [String] the content encoding (if any) applied to the data in the
  #     referenced resource (e.g. for compression)
  # @!attribute [rw] hashes
  #   @return [Hash<String, String>] fixity information for the referenced
  #     resource, as a map from hash algorithm tokens (e.g. +md5+, +sha-256+)
  #     to hex-encoded digest values.
  # @!attribute [rw] path
  #   @return [String] for +ResourceDumpManifests+ and +ChangeDumpManifests+,
  #     the path to the referenced resource within the dump ZIP file.
  class Descriptor
    include ::XML::Mapping

    # ------------------------------------------------------------
    # Attributes

    time_node :modified_time, '@modified', default_value: nil
    numeric_node :length, '@length', default_value: nil
    mime_type_node :mime_type, '@type', default_value: nil
    text_node :encoding, '@encoding', default_value: nil
    hash_codes_node :hashes, '@hash', default_value: nil
    text_node :path, '@path', default_value: nil

    # ------------------------------------------------------------
    # Initializer

    # Creates a new +Descriptor+ instance with the specified fields.
    #
    # @param modified_time [Time] The date and time when the referenced resource was last modified.
    # @param length [Integer] The content length of the referenced resource.
    # @param mime_type [MIME::Type] The media type of the referenced resource.
    # @param encoding [String] Any content encoding (if any) applied to the data in the
    #   referenced resource (e.g. for compression)
    # @param hashes [Hash<String, String>] Fixity information for the referenced
    #   resource, as a map from hash algorithm tokens (e.g. +md5+, +sha-256+)
    #   to hex-encoded digest values.
    # @param path [String] For +ResourceDumpManifests+ and +ChangeDumpManifests+,
    #   the path to the referenced resource within the dump ZIP file.
    def initialize( # rubocop:disable Metrics/ParameterLists
        modified_time: nil,
        length: nil,
        mime_type: nil,
        encoding: nil,
        hashes: nil,
        path: nil
    )
      self.modified_time = modified_time
      self.length = length
      self.mime_type = mime_type
      self.encoding = encoding
      self.hashes = hashes
      self.path = path
    end

    # ------------------------------------------------------------
    # Custom setters

    def modified_time=(value)
      @modified_time = time_or_nil(value)
    end

    def length=(value)
      @length = natural_number_or_nil(value)
    end

    def mime_type=(value)
      @mime_type = mime_type_or_nil(value)
    end

    def hashes=(value)
      @hashes = Descriptor.hash_of_hashcodes(value)
    end

    # ------------------------------------------------------------
    # Public methods

    # Gets the hash value for the specified algorithm.
    #
    # @param algorithm [String] The token (e.g. +md5+, +sha-256+) for the hash algorithm.
    # @return [String] The hex-encoded digest value.
    def hash(algorithm)
      hashes[algorithm]
    end

    # ------------------------------
    # Conversions

    def self.hash_of_hashcodes(hashes)
      return {} unless hashes
      return hashes if hashes.is_a?(Hash)
      hashes.split(/[[:space:]]+/).map { |hash| hash.split(':') }.to_h
    end

    # ------------------------------------------------------------
    # Private methods

    private

    # ------------------------------
    # Parameter validators

    def time_or_nil(time)
      raise ArgumentError, "time #{time} is not a Time" if time && !time.is_a?(Time)
      time
    end

    def natural_number_or_nil(value)
      raise ArgumentError, "value #{value} must be a non-negative integer" if value && (!value.is_a?(Integer) || value < 0)
      value
    end

    def mime_type_or_nil(mime_type)
      return nil unless mime_type
      return mime_type if mime_type.is_a?(MIME::Type)

      mt = MIME::Types[mime_type].first
      return mt if mt

      MIME::Type.new(mime_type)
    end

  end
end


text:
namespace StudentSystem.WebApi.Infrastructure.Mapping
{
	public interface IMapFrom<TModel>
	{
	}
}


text:
/**
*** \file BileObj.h
*** \brief Defines the main data structures used by BILE
***
*** The top-level BILE "object" is the \b Publication. A Publication consists
*** of a number of \b Sections.  Each Section can contain a number of \b Stories
*** as well as subsections, and each Section can have a number of \b Indexes
*** that can be used to generate index pages of Stories sorted in a particular
*** order (for example, a blog Publication might sort the Stories in order of
*** decreasing date, or a glossary Publication in alphabetical order) An Index
*** defined at the Publication level includes all Stories in the Publication,
*** whereas an Index defined in a Section only indexes the Stories in that
*** Section, and not any of its subsections.
***
*** In addition to Indexes, a Publication can have one or more sets of \b Tags
*** that allow Stories to be grouped according in one or more general
*** categories.
**/
#ifndef BILEOBJ_H
#define BILEOBJ_H
#include <stdio.h>
#include "Dict.h"
#include "List.h"
#include "Vars.h"

/** Identifies the type of a particular BILE data structure */
typedef enum {
	/** Publication */
	BILE_PUB,
	/** Section */
	BILE_SECTION,
	/** Story */
	BILE_STORY,
	/** Index */
	BILE_INDEX,
	/** Tag collection */
	BILE_TAGS
} BileObjType;

/** Generic object type */
typedef struct tag_object {
	BileObjType type;
	Vars        *variables;
} BileObject;

/** Section data structure */
typedef struct tag_section {
	BileObjType             type;
	Vars                    *variables;
	struct      tag_section *parent;
	char                    *dir;
	List                    *sections;
	List                    *indexes;
	List                    *stories;
} Section;

/** Publication data structure */
typedef struct tag_publication {
	BileObjType type;
	Vars        *variables;
	char        *inputDirectory;
	char        *outputDirectory;
	char        *templateDirectory;
	bool        forceMode;
	bool        verboseMode;
	char        *scriptFileName;
	FILE        *scriptFile;
	Dict        *templateCache;
	Section     *root;
	List        *tagList;
} Publication;

/** Tags data structure */
typedef struct tag_tags {
	BileObjType type;
	Vars        *variables;
	char        *name;
	Dict        *tags;
} Tags;

/** Story data structure */
typedef struct tag_story {
	BileObjType type;
	Vars        *variables;
	Section     *parent;
	char        *inputPath;
	Dict        *tags;
} Story;

/** Index data structure */
typedef struct tag_index {
	BileObjType type;
	Vars        *variables;
	Section     *parent;
	char        *name;
	List        *stories;
} Index;

#endif /* BILEOBJ_H */


text:
#ifndef __BWK_MENU_MODE_DEFINED__
#define __BWK_MENU_MODE_DEFINED__

#include <vector>

#include "BwkMode.hpp"
#include "BwkSlots.hpp"

class BwkPlayer;

/**
 * The Main Menu, where the user can change graphics settings, start new games, or
 * enter passwords to return to their save states.
 */
class BwkMenuMode : public BwkMode
{
private:
    static BwkMenuMode * _instance;     // Singleton instance.
public:
    static BwkMenuMode * instance();

private:
     BwkMenuMode();
public:
    BwkMode * update();
    void draw();

public:
	void buttonDown(Gosu::Button);
	void buttonUp(Gosu::Button);

private:
	BwkMode * _queuedReturn;
	Gosu::Image * _bg;			// The background image to scroll
	double _bgScrollHorz;		// Background scroll offset, horizontal
	double _bgScrollVert;		// Background scroll offset, vertical
	int _currentOption;			// The index of the current selected option
	std::vector<BwkSlots::Bwk_Data_Img_Slot> _mainOptions;
	std::vector<BwkSlots::Bwk_Data_Img_Slot> _gfxOptions;
	std::vector<BwkSlots::Bwk_Data_Img_Slot> _soundOptions;
	std::vector<BwkSlots::Bwk_Data_Img_Slot> * _curOptions;
	BwkPlayer * _bwock;
};

/**
 *  Instance Accessor
 *
 *  @return Singleton instance
 */
inline BwkMenuMode * BwkMenuMode::instance()
{
    if( _instance == NULL ) {
        _instance = new BwkMenuMode;
    }
    return _instance;
}

#endif //  __BWK_MENU_MODE_DEFINED__


text:
import numpy as np

from bokeh.document import Document
from bokeh.models import ColumnDataSource, DataRange1d, Plot, LinearAxis, Grid
from bokeh.models.glyphs import Rect
from bokeh.plotting import show

N = 9
x = np.linspace(-2, 2, N)
y = x**2
w = x/15.0 + 0.3
h = y/20.0 + 0.3

source = ColumnDataSource(dict(x=x, y=y, w=w, h=h))

xdr = DataRange1d(sources=[source.columns("x")])
ydr = DataRange1d(sources=[source.columns("y")])

plot = Plot(
    title=None, x_range=xdr, y_range=ydr, plot_width=300, plot_height=300,
    h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None)

glyph = Rect(x="x", y="y", width="w", height="h", angle=-0.7, fill_color="#CAB2D6")
plot.add_glyph(source, glyph)

xaxis = LinearAxis()
plot.add_layout(xaxis, 'below')

yaxis = LinearAxis()
plot.add_layout(yaxis, 'left')

plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

doc = Document()
doc.add(plot)

show(plot)


text: The messages sent to this node **must** originate from an _http input_ node