text stringlengths 9 39.2M | dir stringlengths 26 295 | lang stringclasses 185
values | created_date timestamp[us] | updated_date timestamp[us] | repo_name stringlengths 1 97 | repo_full_name stringlengths 7 106 | star int64 1k 183k | len_tokens int64 1 13.8M |
|---|---|---|---|---|---|---|---|---|
```xml
import { CMDL } from "./cmdl.js";
import { InputStream } from "./stream.js";
import { ResourceSystem } from "./resource.js";
import { assert, assertExists } from "../util.js";
// CHAR (DKCR)
export interface CHAR {
name: string;
cmdl: CMDL;
}
function parseDKCR(stream: InputStream, resourceSystem: ResourceSystem, assetID: string): CHAR | null {
stream.skip(21);
const name = stream.readString();
const cinfID = stream.readAssetID();
const cprmID = stream.readAssetID();
stream.skip(4);
const type = stream.readString();
assert(type === 'SkinnedModel' || type === 'FrozenModel');
const cmdlID = stream.readAssetID();
const cskrID = stream.readAssetID();
const cmdl = assertExists(resourceSystem.loadAssetByID<CMDL>(cmdlID, 'CMDL'));
return { name, cmdl };
}
function parseMP3(stream: InputStream, resource: ResourceSystem, assetID: string): CHAR | null {
const name = stream.readString();
const cmdlID = stream.readAssetID();
const cmdl = assertExists(resource.loadAssetByID<CMDL>(cmdlID, 'CMDL'));
return { name, cmdl };
}
export function parse(stream: InputStream, resourceSystem: ResourceSystem, assetID: string): CHAR | null {
const magic = stream.readUint16();
if (magic === 0x59BE)
return parseDKCR(stream, resourceSystem, assetID);
else
return parseMP3(stream, resourceSystem, assetID);
}
``` | /content/code_sandbox/src/MetroidPrime/char.ts | xml | 2016-10-06T21:43:45 | 2024-08-16T17:03:52 | noclip.website | magcius/noclip.website | 3,206 | 356 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="uicolor_MyGrayColor">#aaaaaa</color>
</resources>
``` | /content/code_sandbox/tests/Mono.Android-Tests/Resources/values/colors.xml | xml | 2016-03-30T15:37:14 | 2024-08-16T19:22:13 | android | dotnet/android | 1,905 | 38 |
```xml
import { LogContexts, LogLevels, createLogger } from 'bs-logger'
import { backportTsJestDebugEnvVar } from './backports'
const original = process.env.TS_JEST_LOG
const buildOptions = () => ({
context: {
[LogContexts.package]: 'ts-jest',
[LogContexts.logLevel]: LogLevels.trace,
version: require('../../package.json').version,
},
targets: process.env.TS_JEST_LOG || undefined,
})
export let rootLogger = createLogger(buildOptions())
backportTsJestDebugEnvVar(rootLogger)
// re-create the logger if the env var has been backported
if (original !== process.env.TS_JEST_LOG) {
rootLogger = createLogger(buildOptions())
}
``` | /content/code_sandbox/src/utils/logger.ts | xml | 2016-08-30T13:47:17 | 2024-08-16T15:05:40 | ts-jest | kulshekhar/ts-jest | 6,902 | 165 |
```xml
<BindableObject xmlns="path_to_url" xmlns:x="path_to_url" xmlns:system="clr-namespace:System;assembly=mscorlib.dll" x:Class="Xamarin.Forms.Xaml.UnitTests.DuplicateXArgumentsElements">
<BindableObject.BindingContext>
<system:Uri>
<x:Arguments>path_to_url
<x:Arguments>path_to_url
</system:Uri>
</BindableObject.BindingContext>
</BindableObject>
``` | /content/code_sandbox/Xamarin.Forms.Xaml.UnitTests/DuplicateXArgumentsElements.xaml | xml | 2016-03-18T15:52:03 | 2024-08-16T16:25:43 | Xamarin.Forms | xamarin/Xamarin.Forms | 5,637 | 97 |
```xml
import { Message } from '@lumino/messaging';
import { Widget } from '@lumino/widgets';
import { Dialog, showDialog } from './dialog';
const INPUT_DIALOG_CLASS = 'jp-Input-Dialog';
const INPUT_BOOLEAN_DIALOG_CLASS = 'jp-Input-Boolean-Dialog';
/**
* Namespace for input dialogs
*/
export namespace InputDialog {
/**
* Common constructor options for input dialogs
*/
export interface IOptions extends IBaseOptions {
/**
* The top level text for the dialog. Defaults to an empty string.
*/
title: Dialog.Header;
/**
* The host element for the dialog. Defaults to `document.body`.
*/
host?: HTMLElement;
/**
* An optional renderer for dialog items. Defaults to a shared
* default renderer.
*/
renderer?: Dialog.IRenderer;
/**
* Label for ok button.
*/
okLabel?: string;
/**
* Label for cancel button.
*/
cancelLabel?: string;
/**
* The checkbox to display in the footer. Defaults no checkbox.
*/
checkbox?: Partial<Dialog.ICheckbox> | null;
/**
* The index of the default button. Defaults to the last button.
*/
defaultButton?: number;
}
/**
* Constructor options for boolean input dialogs
*/
export interface IBooleanOptions extends IOptions {
/**
* Default value
*/
value?: boolean;
}
/**
* Create and show a input dialog for a boolean.
*
* @param options - The dialog setup options.
*
* @returns A promise that resolves with whether the dialog was accepted
*/
export function getBoolean(
options: IBooleanOptions
): Promise<Dialog.IResult<boolean>> {
return showDialog({
...options,
body: new InputBooleanDialog(options),
buttons: [
Dialog.cancelButton({ label: options.cancelLabel }),
Dialog.okButton({ label: options.okLabel })
],
focusNodeSelector: 'input'
});
}
/**
* Constructor options for number input dialogs
*/
export interface INumberOptions extends IOptions {
/**
* Default value
*/
value?: number;
}
/**
* Create and show a input dialog for a number.
*
* @param options - The dialog setup options.
*
* @returns A promise that resolves with whether the dialog was accepted
*/
export function getNumber(
options: INumberOptions
): Promise<Dialog.IResult<number>> {
return showDialog({
...options,
body: new InputNumberDialog(options),
buttons: [
Dialog.cancelButton({ label: options.cancelLabel }),
Dialog.okButton({ label: options.okLabel })
],
focusNodeSelector: 'input'
});
}
/**
* Constructor options for item selection input dialogs
*/
export interface IItemOptions extends IOptions {
/**
* List of choices
*/
items: Array<string>;
/**
* Default choice
*
* If the list is editable a string with a default value can be provided
* otherwise the index of the default choice should be given.
*/
current?: number | string;
/**
* Is the item editable?
*/
editable?: boolean;
/**
* Placeholder text for editable input
*/
placeholder?: string;
}
/**
* Create and show a input dialog for a choice.
*
* @param options - The dialog setup options.
*
* @returns A promise that resolves with whether the dialog was accepted
*/
export function getItem(
options: IItemOptions
): Promise<Dialog.IResult<string>> {
return showDialog({
...options,
body: new InputItemsDialog(options),
buttons: [
Dialog.cancelButton({ label: options.cancelLabel }),
Dialog.okButton({ label: options.okLabel })
],
focusNodeSelector: options.editable ? 'input' : 'select'
});
}
/**
* Constructor options for item selection input dialogs
*/
export interface IMultipleItemsOptions extends IOptions {
/**
* List of choices
*/
items: Array<string>;
/**
* Default choices
*/
defaults?: string[];
}
/**
* Create and show a input dialog for a choice.
*
* @param options - The dialog setup options.
*
* @returns A promise that resolves with whether the dialog was accepted
*/
export function getMultipleItems(
options: IMultipleItemsOptions
): Promise<Dialog.IResult<string[]>> {
return showDialog({
...options,
body: new InputMultipleItemsDialog(options),
buttons: [
Dialog.cancelButton({ label: options.cancelLabel }),
Dialog.okButton({ label: options.okLabel })
]
});
}
/**
* Constructor options for text input dialogs
*/
export interface ITextOptions extends IOptions {
/**
* Default input text
*/
text?: string;
/**
* Placeholder text
*/
placeholder?: string;
/**
* Selection range
*
* Number of characters to pre-select when dialog opens.
* Default is to select the whole input text if present.
*/
selectionRange?: number;
/**
* Pattern used by the browser to validate the input value.
*/
pattern?: string;
/**
* Whether the input is required (has to be non-empty).
*/
required?: boolean;
}
/**
* Create and show a input dialog for a text.
*
* @param options - The dialog setup options.
*
* @returns A promise that resolves with whether the dialog was accepted
*/
export function getText(
options: ITextOptions
): Promise<Dialog.IResult<string>> {
return showDialog({
...options,
body: new InputTextDialog(options),
buttons: [
Dialog.cancelButton({ label: options.cancelLabel }),
Dialog.okButton({ label: options.okLabel })
],
focusNodeSelector: 'input'
});
}
/**
* Create and show a input dialog for a password.
*
* @param options - The dialog setup options.
*
* @returns A promise that resolves with whether the dialog was accepted
*/
export function getPassword(
options: Omit<ITextOptions, 'selectionRange'>
): Promise<Dialog.IResult<string>> {
return showDialog({
...options,
body: new InputPasswordDialog(options),
buttons: [
Dialog.cancelButton({ label: options.cancelLabel }),
Dialog.okButton({ label: options.okLabel })
],
focusNodeSelector: 'input'
});
}
}
/**
* Constructor options for base input dialog body.
*/
interface IBaseOptions {
/**
* Label of the requested input
*/
label?: string;
/**
* Additional prefix string preceding the input (e.g. ).
*/
prefix?: string;
/**
* Additional suffix string following the input (e.g. $).
*/
suffix?: string;
}
/**
* Base widget for input dialog body
*/
class InputDialogBase<T> extends Widget implements Dialog.IBodyWidget<T> {
/**
* InputDialog constructor
*
* @param label Input field label
*/
constructor(options: IBaseOptions) {
super();
this.addClass(INPUT_DIALOG_CLASS);
this._input = document.createElement('input');
this._input.classList.add('jp-mod-styled');
this._input.id = 'jp-dialog-input-id';
if (options.label !== undefined) {
const labelElement = document.createElement('label');
labelElement.textContent = options.label;
labelElement.htmlFor = this._input.id;
// Initialize the node
this.node.appendChild(labelElement);
}
const wrapper = document.createElement('div');
wrapper.className = 'jp-InputDialog-inputWrapper';
if (options.prefix) {
const prefix = document.createElement('span');
prefix.className = 'jp-InputDialog-inputPrefix';
prefix.textContent = options.prefix;
// Both US WDS (path_to_url
// and UK DS (path_to_url recommend
// hiding prefixes and suffixes from screen readers.
prefix.ariaHidden = 'true';
wrapper.appendChild(prefix);
}
wrapper.appendChild(this._input);
if (options.suffix) {
const suffix = document.createElement('span');
suffix.className = 'jp-InputDialog-inputSuffix';
suffix.textContent = options.suffix;
suffix.ariaHidden = 'true';
wrapper.appendChild(suffix);
}
this.node.appendChild(wrapper);
}
/** Input HTML node */
protected _input: HTMLInputElement;
}
/**
* Widget body for input boolean dialog
*/
class InputBooleanDialog extends InputDialogBase<boolean> {
/**
* InputBooleanDialog constructor
*
* @param options Constructor options
*/
constructor(options: InputDialog.IBooleanOptions) {
super(options);
this.addClass(INPUT_BOOLEAN_DIALOG_CLASS);
this._input.type = 'checkbox';
this._input.checked = options.value ? true : false;
}
/**
* Get the text specified by the user
*/
getValue(): boolean {
return this._input.checked;
}
}
/**
* Widget body for input number dialog
*/
class InputNumberDialog extends InputDialogBase<number> {
/**
* InputNumberDialog constructor
*
* @param options Constructor options
*/
constructor(options: InputDialog.INumberOptions) {
super(options);
this._input.type = 'number';
this._input.value = options.value ? options.value.toString() : '0';
}
/**
* Get the number specified by the user.
*/
getValue(): number {
if (this._input.value) {
return Number(this._input.value);
} else {
return Number.NaN;
}
}
}
/**
* Base widget body for input text/password/email dialog
*/
class InputDialogTextBase extends InputDialogBase<string> {
/**
* InputDialogTextBase constructor
*
* @param options Constructor options
*/
constructor(options: Omit<InputDialog.ITextOptions, 'selectionRange'>) {
super(options);
this._input.value = options.text ? options.text : '';
if (options.placeholder) {
this._input.placeholder = options.placeholder;
}
if (options.pattern) {
this._input.pattern = options.pattern;
}
if (options.required) {
this._input.required = options.required;
}
}
/**
* Get the text specified by the user
*/
getValue(): string {
return this._input.value;
}
}
/**
* Widget body for input text dialog
*/
class InputTextDialog extends InputDialogTextBase {
/**
* InputTextDialog constructor
*
* @param options Constructor options
*/
constructor(options: InputDialog.ITextOptions) {
super(options);
this._input.type = 'text';
this._initialSelectionRange = Math.min(
this._input.value.length,
Math.max(0, options.selectionRange ?? this._input.value.length)
);
}
/**
* A message handler invoked on an `'after-attach'` message.
*/
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
if (this._initialSelectionRange > 0 && this._input.value) {
this._input.setSelectionRange(0, this._initialSelectionRange);
}
}
private _initialSelectionRange: number;
}
/**
* Widget body for input password dialog
*/
class InputPasswordDialog extends InputDialogTextBase {
/**
* InputPasswordDialog constructor
*
* @param options Constructor options
*/
constructor(options: InputDialog.ITextOptions) {
super(options);
this._input.type = 'password';
}
/**
* A message handler invoked on an `'after-attach'` message.
*/
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
if (this._input.value) {
this._input.select();
}
}
}
/**
* Widget body for input list dialog
*/
class InputItemsDialog extends InputDialogBase<string> {
/**
* InputItemsDialog constructor
*
* @param options Constructor options
*/
constructor(options: InputDialog.IItemOptions) {
super(options);
this._editable = options.editable || false;
let current = options.current || 0;
let defaultIndex: number;
if (typeof current === 'number') {
defaultIndex = Math.max(0, Math.min(current, options.items.length - 1));
current = '';
}
this._list = document.createElement('select');
options.items.forEach((item, index) => {
const option = document.createElement('option');
if (index === defaultIndex) {
option.selected = true;
current = item;
}
option.value = item;
option.textContent = item;
this._list.appendChild(option);
});
if (options.editable) {
/* Use of list and datalist */
const data = document.createElement('datalist');
data.id = 'input-dialog-items';
data.appendChild(this._list);
this._input.type = 'list';
this._input.value = current;
this._input.setAttribute('list', data.id);
if (options.placeholder) {
this._input.placeholder = options.placeholder;
}
this.node.appendChild(data);
} else {
/* Use select directly */
this._input.parentElement!.replaceChild(this._list, this._input);
}
}
/**
* Get the user choice
*/
getValue(): string {
if (this._editable) {
return this._input.value;
} else {
return this._list.value;
}
}
private _list: HTMLSelectElement;
private _editable: boolean;
}
/**
* Widget body for input list dialog
*/
class InputMultipleItemsDialog extends InputDialogBase<string> {
/**
* InputMultipleItemsDialog constructor
*
* @param options Constructor options
*/
constructor(options: InputDialog.IMultipleItemsOptions) {
super(options);
let defaults = options.defaults || [];
this._list = document.createElement('select');
this._list.setAttribute('multiple', '');
options.items.forEach(item => {
const option = document.createElement('option');
option.value = item;
option.textContent = item;
this._list.appendChild(option);
});
// use the select
this._input.remove();
this.node.appendChild(this._list);
// select the current ones
const htmlOptions = this._list.options;
for (let i: number = 0; i < htmlOptions.length; i++) {
const option = htmlOptions[i];
if (defaults.includes(option.value)) {
option.selected = true;
} else {
option.selected = false;
}
}
}
/**
* Get the user choices
*/
getValue(): string[] {
let result = [];
for (let opt of this._list.options) {
if (opt.selected && !opt.classList.contains('hidden')) {
result.push(opt.value || opt.text);
}
}
return result;
}
private _list: HTMLSelectElement;
}
``` | /content/code_sandbox/packages/apputils/src/inputdialog.ts | xml | 2016-06-03T20:09:17 | 2024-08-16T19:12:44 | jupyterlab | jupyterlab/jupyterlab | 14,019 | 3,262 |
```xml
import { map, distinctUntilChanged, OperatorFunction } from "rxjs";
/**
* An observable operator that reduces an emitted collection to a single object,
* returning a default if all items are ignored.
* @param reduce The reduce function to apply to the filtered collection. The
* first argument is the accumulator, and the second is the current item. The
* return value is the new accumulator.
* @param defaultValue The default value to return if the collection is empty. The
* default value is also the initial value of the accumulator.
*/
export function reduceCollection<Item, Accumulator>(
reduce: (acc: Accumulator, value: Item) => Accumulator,
defaultValue: Accumulator,
): OperatorFunction<Item[], Accumulator> {
return map((values: Item[]) => {
const reduced = (values ?? []).reduce(reduce, structuredClone(defaultValue));
return reduced;
});
}
/**
* An observable operator that emits distinct values by checking that all
* values in the previous entry match the next entry. This method emits
* when a key is added and does not when a key is removed.
* @remarks This method checks objects. It does not check items in arrays.
*/
export function distinctIfShallowMatch<Item>(): OperatorFunction<Item, Item> {
return distinctUntilChanged((previous, current) => {
let isDistinct = true;
for (const key in current) {
isDistinct &&= previous[key] === current[key];
}
return isDistinct;
});
}
``` | /content/code_sandbox/libs/common/src/tools/rx.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 320 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<!--
~ All Rights Reserved.
-->
<TextView
xmlns:android="path_to_url"
android:id="@android:id/text1"
android:layout_width="match_parent"
android:layout_height="?attr/dropdownListPreferredItemHeight"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:ellipsize="marquee"
android:gravity="center_vertical"
android:singleLine="true"
style="?android:attr/spinnerItemStyle" />
``` | /content/code_sandbox/app/src/main/res/layout/simple_spinner_item.xml | xml | 2016-02-01T13:44:19 | 2024-08-15T05:23:34 | Douya | zhanghai/Douya | 4,549 | 124 |
```xml
<test>
<query>SELECT count() FROM hits_100m_single WHERE NOT ignore(substring(URL, 10, 20))</query>
<query>SELECT count() FROM hits_100m_single WHERE NOT ignore(substring(PageCharset, 1, 2))</query>
</test>
``` | /content/code_sandbox/tests/performance/slices_hits.xml | xml | 2016-06-02T08:28:18 | 2024-08-16T18:39:33 | ClickHouse | ClickHouse/ClickHouse | 36,234 | 66 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~
~ path_to_url
~
~ Unless required by applicable law or agreed to in writing, software
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<databases>
<database>db</database>
</databases>
``` | /content/code_sandbox/test/e2e/operation/showprocesslist/src/test/resources/env/scenario/cluster_jdbc_proxy/data/actual/databases.xml | xml | 2016-01-18T12:49:26 | 2024-08-16T15:48:11 | shardingsphere | apache/shardingsphere | 19,707 | 101 |
```xml
/*
* LoggingMiddleware
*
* Logging strategy for Redux, specific to Oni
*/
import { Store } from "redux"
import * as Log from "oni-core-logging"
export const createLoggingMiddleware = (storeName: string) => (store: Store<any>) => (
next: any,
) => (action: any): any => {
Log.verbose("[REDUX - " + storeName + "][ACTION] " + action.type)
const result = next(action)
return result
}
``` | /content/code_sandbox/browser/src/Redux/LoggingMiddleware.ts | xml | 2016-11-16T14:42:55 | 2024-08-14T11:48:05 | oni | onivim/oni | 11,355 | 107 |
```xml
'use strict';
import * as fse from "fs-extra";
import * as path from "path";
import { CancellationToken, CodeAction, CodeActionContext, CodeActionKind, CodeActionProvider, CodeActionProviderMetadata, Command, commands, Diagnostic, DiagnosticRelatedInformation, ExtensionContext, ProviderResult, Range, Selection, TextDocument, Uri } from "vscode";
import { Commands } from "../commands";
import { upgradeGradle } from "../standardLanguageClientUtils";
const UPGRADE_GRADLE_WRAPPER_TITLE = "Upgrade Gradle Wrapper";
const WRAPPER_PROPERTIES_DESCRIPTOR = "gradle/wrapper/gradle-wrapper.properties";
const GRADLE_PROBLEM_ID = 0x00080000;
const GRADLE_INVALID_TYPE_CODE_ID = GRADLE_PROBLEM_ID + 1;
export class GradleCodeActionProvider implements CodeActionProvider<CodeAction> {
public provideCodeActions(document: TextDocument, range: Range | Selection, context: CodeActionContext, token: CancellationToken): ProviderResult<(CodeAction | Command)[]> {
if (context?.diagnostics?.length && context.diagnostics[0].source === "Java") {
return this.provideGradleCodeActions(document, context.diagnostics);
}
return [];
}
async provideGradleCodeActions(document: TextDocument, diagnostics: readonly Diagnostic[]): Promise<CodeAction[]> {
const codeActions = [];
for (const diagnostic of diagnostics) {
if (diagnostic.message?.startsWith("The build file has been changed")) {
const reloadProjectAction = new CodeAction("Reload project", CodeActionKind.QuickFix);
reloadProjectAction.command = {
title: "Reload Project",
command: Commands.CONFIGURATION_UPDATE,
arguments: [document.uri],
};
codeActions.push(reloadProjectAction);
continue;
}
const documentUri = document.uri.toString();
if (documentUri.endsWith(WRAPPER_PROPERTIES_DESCRIPTOR) && diagnostic.code === GRADLE_INVALID_TYPE_CODE_ID.toString()) {
const projectPath = path.resolve(Uri.parse(documentUri).fsPath, "..", "..", "..").normalize();
if (await fse.pathExists(projectPath)) {
const projectUri = Uri.file(projectPath).toString();
const upgradeWrapperCommand: Command = {
title: UPGRADE_GRADLE_WRAPPER_TITLE,
command: Commands.UPGRADE_GRADLE_WRAPPER_CMD,
arguments: [projectUri]
};
const codeAction = new CodeAction(UPGRADE_GRADLE_WRAPPER_TITLE, CodeActionKind.QuickFix.append("gradle"));
codeAction.command = upgradeWrapperCommand;
codeActions.push(codeAction);
}
}
}
return codeActions;
}
}
export const gradleCodeActionMetadata: CodeActionProviderMetadata = {
providedCodeActionKinds: [
CodeActionKind.QuickFix.append("gradle")
]
};
``` | /content/code_sandbox/src/gradle/gradleCodeActionProvider.ts | xml | 2016-08-12T15:02:43 | 2024-08-15T03:36:05 | vscode-java | redhat-developer/vscode-java | 2,064 | 608 |
```xml
import { iconSize, QrCodeIcon, spacing } from '@expo/styleguide-native';
import { NavigationProp, useNavigation } from '@react-navigation/native';
import { Divider, Row, Text, useExpoTheme } from 'expo-dev-client-components';
import * as React from 'react';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { ModalStackRoutes } from '../../navigation/Navigation.types';
import {
alertWithCameraPermissionInstructions,
requestCameraPermissionsAsync,
} from '../../utils/PermissionUtils';
export function DevelopmentServersOpenQR() {
const theme = useExpoTheme();
const navigation = useNavigation<NavigationProp<ModalStackRoutes>>();
const handleQRPressAsync = async () => {
if (await requestCameraPermissionsAsync()) {
navigation.navigate('QRCode');
} else {
await alertWithCameraPermissionInstructions();
}
};
return (
<>
<Divider style={{ height: 1 }} />
<TouchableOpacity onPress={handleQRPressAsync}>
<Row padding="medium" align="center">
<QrCodeIcon
size={iconSize.small}
style={{ marginRight: spacing[2] }}
color={theme.icon.default}
/>
<Text type="InterRegular">Scan QR code</Text>
</Row>
</TouchableOpacity>
</>
);
}
``` | /content/code_sandbox/apps/expo-go/src/screens/HomeScreen/DevelopmentServersOpenQR.tsx | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 282 |
```xml
/*
*
* This source code is licensed under the MIT license which is detailed in the LICENSE.txt file.
*/
import { QWidget } from "@nodegui/nodegui";
import { Block } from "./Block.js";
/**
* A frame around a Block.
*
* Every block inside a terminal is held within a a `BlockFrame`. The visual
* appearance of the `BlockFrame` can vary from invisible to a full frame
* with title bar and surrounding visible frame.
*/
export interface BlockFrame {
getBlock(): Block;
setBlock(block: Block): void;
getWidget(): QWidget;
setViewportTop(relativeTopPx: number): void;
getTag(): number;
}
``` | /content/code_sandbox/main/src/terminal/BlockFrame.ts | xml | 2016-03-04T12:39:59 | 2024-08-16T18:44:37 | extraterm | sedwards2009/extraterm | 2,501 | 142 |
```xml
import Fuse from 'fuse.js';
import { Choices } from './choices';
import { Choice } from './choice';
import { ClassNames } from './class-names';
import { PositionOptionsType } from './position-options-type';
import { Types } from './types';
/**
* Choices options interface
*
* **Terminology**
*
* - **Choice:** A choice is a value a user can select. A choice would be equivalent to the `<option></option>` element within a select input.
* - **Group:** A group is a collection of choices. A group should be seen as equivalent to a `<optgroup></optgroup>` element within a select input.
* - **Item:** An item is an inputted value **_(text input)_** or a selected choice **_(select element)_**. In the context of a select element, an item is equivelent to a selected option element: `<option value="Hello" selected></option>` whereas in the context of a text input an item is equivelant to `<input type="text" value="Hello">`
*/
export interface Options {
/**
* Optionally suppress console errors and warnings.
*
* **Input types affected:** text, select-single, select-multiple
*
* @default false
*/
silent: boolean;
/**
* Add pre-selected items (see terminology) to text input.
*
* **Input types affected:** text
*
* @example
* ```
* ['value 1', 'value 2', 'value 3']
* ```
*
* @example
* ```
* [{
* value: 'Value 1',
* label: 'Label 1',
* id: 1
* },
* {
* value: 'Value 2',
* label: 'Label 2',
* id: 2,
* customProperties: {
* random: 'I am a custom property'
* }
* }]
* ```
*
* @default []
*/
items: string[] | Choice[];
/**
* Add choices (see terminology) to select input.
*
* **Input types affected:** select-one, select-multiple
*
* @example
* ```
* [{
* value: 'Option 1',
* label: 'Option 1',
* selected: true,
* disabled: false,
* },
* {
* value: 'Option 2',
* label: 'Option 2',
* selected: false,
* disabled: true,
* customProperties: {
* description: 'Custom description about Option 2',
* random: 'Another random custom property'
* },
* }]
* ```
*
* @default []
*/
choices: Choice[];
/**
* The amount of choices to be rendered within the dropdown list `("-1" indicates no limit)`. This is useful if you have a lot of choices where it is easier for a user to use the search area to find a choice.
*
* **Input types affected:** select-one, select-multiple
*
* @default -1
*/
renderChoiceLimit: number;
/**
* The amount of items a user can input/select `("-1" indicates no limit)`.
*
* **Input types affected:** text, select-multiple
*
* @default -1
*/
maxItemCount: number;
/**
* Whether a user can add items.
*
* **Input types affected:** text
*
* @default true
*/
addItems: boolean;
/**
* A filter that will need to pass for a user to successfully add an item.
*
* **Input types affected:** text
*
* @default null
*/
addItemFilter: string | RegExp | Types.FilterFunction | null;
/**
* The text that is shown when a user has inputted a new item but has not pressed the enter key. To access the current input value, pass a function with a `value` argument (see the **default config** [path_to_url#setup] for an example), otherwise pass a string.
*
* **Input types affected:** text
*
* @default
* ```
* (value) => `Press Enter to add <b>"${value}"</b>`;
* ```
*/
addItemText: string | Types.NoticeStringFunction;
/**
* Whether a user can remove items.
*
* **Input types affected:** text, select-multiple
*
* @default true
*/
removeItems: boolean;
/**
* Whether each item should have a remove button.
*
* **Input types affected:** text, select-one, select-multiple
*
* @default false
*/
removeItemButton: boolean;
/**
* Whether a user can edit items. An item's value can be edited by pressing the backspace.
*
* **Input types affected:** text
*
* @default false
*/
editItems: boolean;
/**
* Whether HTML should be rendered in all Choices elements.
* If `false`, all elements (placeholder, items, etc.) will be treated as plain text.
* If `true`, this can be used to perform XSS scripting attacks if you load choices from a remote source.
*
* **Deprecation Warning:** This will default to `false` in a future release.
*
* **Input types affected:** text, select-one, select-multiple
*
* @default true
*/
allowHTML: boolean;
/**
* Whether each inputted/chosen item should be unique.
*
* **Input types affected:** text, select-multiple
*
* @default true
*/
duplicateItemsAllowed: boolean;
/**
* What divides each value. The default delimiter separates each value with a comma: `"Value 1, Value 2, Value 3"`.
*
* **Input types affected:** text
*
* @default ','
*/
delimiter: string;
/**
* Whether a user can paste into the input.
*
* **Input types affected:** text, select-multiple
*
* @default true
*/
paste: boolean;
/**
* Whether a search area should be shown.
*
* @note Multiple select boxes will always show search areas.
*
* **Input types affected:** select-one
*
* @default true
*/
searchEnabled: boolean;
/**
* Whether choices should be filtered by input or not. If `false`, the search event will still emit, but choices will not be filtered.
*
* **Input types affected:** select-one
*
* @default true
*/
searchChoices: boolean;
/**
* The minimum length a search value should be before choices are searched.
*
* **Input types affected:** select-one, select-multiple
*
* @default 1
*/
searchFloor: number;
/**
* The maximum amount of search results to show.
*
* **Input types affected:** select-one, select-multiple
*
* @default 4
*/
searchResultLimit: number;
/**
* Specify which fields should be used when a user is searching. If you have added custom properties to your choices, you can add these values thus: `['label', 'value', 'customProperties.example']`.
*
* Input types affected:select-one, select-multiple
*
* @default ['label', 'value']
*/
searchFields: string[];
/**
* Whether the dropdown should appear above `(top)` or below `(bottom)` the input. By default, if there is not enough space within the window the dropdown will appear above the input, otherwise below it.
*
* **Input types affected:** select-one, select-multiple
*
* @default 'auto'
*/
position: PositionOptionsType;
/**
* Whether the scroll position should reset after adding an item.
*
* **Input types affected:** select-multiple
*
* @default true
*/
resetScrollPosition: boolean;
/**
* Whether choices and groups should be sorted. If false, choices/groups will appear in the order they were given.
*
* **Input types affected:** select-one, select-multiple
*
* @default true
*/
shouldSort: boolean;
/**
* Whether items should be sorted. If false, items will appear in the order they were selected.
*
* **Input types affected:** text, select-multiple
*
* @default false
*/
shouldSortItems: boolean;
/**
* The function that will sort choices and items before they are displayed (unless a user is searching). By default choices and items are sorted by alphabetical order.
*
* **Input types affected:** select-one, select-multiple
*
* @example
* ```
* // Sorting via length of label from largest to smallest
* const example = new Choices(element, {
* sorter: function(a, b) {
* return b.label.length - a.label.length;
* },
* };
* ```
*
* @default sortByAlpha
*/
sorter: (current: Choice, next: Choice) => number;
/**
* Whether the input should show a placeholder. Used in conjunction with `placeholderValue`. If `placeholder` is set to true and no value is passed to `placeholderValue`, the passed input's placeholder attribute will be used as the placeholder value.
*
* **Input types affected:** text, select-multiple
*
* @note For single select boxes, the recommended way of adding a placeholder is as follows:
* ```
* <select>
* <option placeholder>This is a placeholder</option>
* <option>...</option>
* <option>...</option>
* <option>...</option>
* </select>
* ```
*
* @default true
*/
placeholder: boolean;
/**
* The value of the inputs placeholder.
*
* **Input types affected:** text, select-multiple
*
* @default null
*/
placeholderValue: string | null;
/**
* The value of the search inputs placeholder.
*
* **Input types affected:** select-one
*
* @default null
*/
searchPlaceholderValue: string | null;
/**
* Prepend a value to each item added/selected.
*
* **Input types affected:** text, select-one, select-multiple
*
* @default null
*/
prependValue: string | null;
/**
* Append a value to each item added/selected.
*
* **Input types affected:** text, select-one, select-multiple
*
* @default null
*/
appendValue: string | null;
/**
* Whether selected choices should be removed from the list. By default choices are removed when they are selected in multiple select box. To always render choices pass `always`.
*
* **Input types affected:** select-one, select-multiple
*
* @default 'auto';
*/
renderSelectedChoices: 'auto' | 'always';
/**
* The text that is shown whilst choices are being populated via AJAX.
*
* **Input types affected:** select-one, select-multiple
*
* @default 'Loading...'
*/
loadingText: string;
/**
* The text that is shown when a user's search has returned no results. Optionally pass a function returning a string.
*
* **Input types affected:** select-one, select-multiple
*
* @default 'No results found'
*/
noResultsText: string | Types.StringFunction;
/**
* The text that is shown when a user has selected all possible choices. Optionally pass a function returning a string.
*
* **Input types affected:** select-multiple
*
* @default 'No choices to choose from'
*/
noChoicesText: string | Types.StringFunction;
/**
* The text that is shown when a user hovers over a selectable choice.
*
* **Input types affected:** select-multiple, select-one
*
* @default 'Press to select'
*/
itemSelectText: string;
/**
* The text that is shown when a user has focus on the input but has already reached the **max item count** [path_to_url#maxitemcount]. To access the max item count, pass a function with a `maxItemCount` argument (see the **default config** [path_to_url#setup] for an example), otherwise pass a string.
*
* **Input types affected:** text
*
* @default
* ```
* (maxItemCount) => `Only ${maxItemCount} values can be added.`;
* ```
*/
maxItemText: string | Types.NoticeLimitFunction;
/**
* If no duplicates are allowed, and the value already exists in the array.
*
* @default 'Only unique values can be added'
*/
uniqueItemText: string | Types.NoticeStringFunction;
/**
* The text that is shown when addItemFilter is passed and it returns false
*
* **Input types affected:** text
*
* @default 'Only values matching specific conditions can be added'
*/
customAddItemText: string | Types.NoticeStringFunction;
/**
* Compare choice and value in appropriate way (e.g. deep equality for objects). To compare choice and value, pass a function with a `valueComparer` argument (see the [default config](path_to_url#setup) for an example).
*
* **Input types affected:** select-one, select-multiple
*
* @default
* ```
* (choice, item) => choice === item;
* ```
*/
valueComparer: Types.ValueCompareFunction;
/**
* Classes added to HTML generated by By default classnames follow the BEM notation.
*
* **Input types affected:** text, select-one, select-multiple
*/
classNames: ClassNames;
/**
* Choices uses the great Fuse library for searching. You can find more options here: path_to_url
*/
fuseOptions: Fuse.IFuseOptions<Choices>;
/**
* ID of the connected label to improve a11y. If set, aria-labelledby will be added.
*/
labelId: string;
/**
* Function to run once Choices initialises.
*
* **Input types affected:** text, select-one, select-multiple
*
* @note For each callback, this refers to the current instance of This can be useful if you need access to methods `(this.disable())` or the config object `(this.config)`.
*
* @default null
*/
callbackOnInit: ((this: Choices) => void) | null;
/**
* Function to run on template creation. Through this callback it is possible to provide custom templates for the various components of Choices (see terminology). For Choices to work with custom templates, it is important you maintain the various data attributes defined here [path_to_url#L1993-L2067].
*
* **Input types affected:** text, select-one, select-multiple
*
* @note For each callback, this refers to the current instance of This can be useful if you need access to methods `(this.disable())` or the config object `(this.config)`.
*
* @example
* ```
* const example = new Choices(element, {
* callbackOnCreateTemplates: function (template) {
* var classNames = this.config.classNames;
* return {
* item: (data) => {
* return template(`
* <div class="${classNames.item} ${data.highlighted ? classNames.highlightedState : classNames.itemSelectable}" data-item data-id="${data.id}" data-value="${data.value}" ${data.active ? 'aria-selected="true"' : ''} ${data.disabled ? 'aria-disabled="true"' : ''}>
* <span>★</span> ${data.label}
* </div>
* `);
* },
* choice: (data) => {
* return template(`
* <div class="${classNames.item} ${classNames.itemChoice} ${data.disabled ? classNames.itemDisabled : classNames.itemSelectable}" data-select-text="${this.config.itemSelectText}" data-choice ${data.disabled ? 'data-choice-disabled aria-disabled="true"' : 'data-choice-selectable'} data-id="${data.id}" data-value="${data.value}" ${data.groupId > 0 ? 'role="treeitem"' : 'role="option"'}>
* <span>★</span> ${data.label}
* </div>
* `);
* },
* };
* }
* });
* ```
*
* @default null
*/
callbackOnCreateTemplates: ((template: Types.StrToEl) => void) | null;
}
//# sourceMappingURL=options.d.ts.map
``` | /content/code_sandbox/public/types/src/scripts/interfaces/options.d.ts | xml | 2016-03-15T14:02:08 | 2024-08-15T07:08:50 | Choices | Choices-js/Choices | 6,092 | 3,745 |
```xml
import React from 'react';
import { styled, typography } from 'storybook/internal/theming';
import type { Call } from '@storybook/instrumenter';
import { MethodCall, Node } from './MethodCall';
const StyledWrapper = styled.div(({ theme }) => ({
backgroundColor: theme.background.content,
padding: '20px',
boxShadow: `0 0 0 1px ${theme.appBorderColor}`,
color: theme.color.defaultText,
fontFamily: typography.fonts.mono,
fontSize: typography.size.s1,
}));
export default {
title: 'MethodCall',
component: MethodCall,
decorators: [
(Story: any) => (
<StyledWrapper>
<Story />
</StyledWrapper>
),
],
parameters: {
layout: 'fullscreen',
},
};
export const Args = () => (
<div style={{ display: 'inline-flex', flexDirection: 'column', gap: 10 }}>
<Node value={null} />
<Node value={undefined} />
<Node value="Hello world" />
<Node value="path_to_url" />
<Node value="012345678901234567890123456789012345678901234567890123456789" />
{}
<Node value={true} />
<Node value={false} />
<Node value={12345} />
<Node value={['foo', 1, { hello: 'world' }]} />
<Node value={[...Array(23)].map((_, i) => i)} />
<Node value={{ hello: 'world' }} />
<Node value={{ hello: 'world', arr: [1, 2, 3], more: true }} />
<Node value={{ hello: 'world', arr: [1, 2, 3], more: true }} showObjectInspector />
<Node
value={{
hello: 'world',
arr: [1, 2, 3],
more: true,
regex: /regex/,
class: class DummyClass {},
fn: () => 123,
asyncFn: async () => 'hello',
}}
showObjectInspector
/>
<Node value={{ __class__: { name: 'FooBar' } }} />
<Node value={{ __function__: { name: 'goFaster' } }} />
<Node value={{ __function__: { name: '' } }} />
<Node value={{ __element__: { localName: 'hr' } }} />
<Node value={{ __element__: { localName: 'foo', prefix: 'x' } }} />
<Node value={{ __element__: { localName: 'div', id: 'foo' } }} />
<Node value={{ __element__: { localName: 'span', classNames: ['foo', 'bar'] } }} />
<Node value={{ __element__: { localName: 'button', innerText: 'Click me' } }} />
<Node
value={{ __date__: { value: new Date(Date.UTC(2012, 11, 20, 0, 0, 0)).toISOString() } }}
/>
<Node value={{ __date__: { value: new Date(1600000000000).toISOString() } }} />
<Node value={{ __date__: { value: new Date(1600000000123).toISOString() } }} />
<Node value={{ __error__: { name: 'EvalError', message: '' } }} />
<Node value={{ __error__: { name: 'SyntaxError', message: "Can't do that" } }} />
<Node
value={{
__error__: { name: 'TypeError', message: "Cannot read property 'foo' of undefined" },
}}
/>
<Node
value={{
__error__: { name: 'ReferenceError', message: 'Invalid left-hand side in assignment' },
}}
/>
<Node
value={{
__error__: {
name: 'Error',
message:
"XMLHttpRequest cannot load path_to_url No 'Access-Control-Allow-Origin' header is present on the requested resource.",
},
}}
/>
<Node value={{ __regexp__: { flags: 'i', source: 'hello' } }} />
<Node value={{ __regexp__: { flags: '', source: 'src(.*)\\.js$' } }} />
<Node value={{ __symbol__: { description: '' } }} />
<Node value={{ __symbol__: { description: 'Hello world' } }} />
</div>
);
const calls: Call[] = [
{
cursor: 0,
id: '1',
ancestors: [],
path: ['screen'],
method: 'getByText',
storyId: 'kind--story',
args: ['Click'],
interceptable: false,
retain: false,
},
{
cursor: 1,
id: '2',
ancestors: [],
path: ['userEvent'],
method: 'click',
storyId: 'kind--story',
args: [{ __callId__: '1' }],
interceptable: true,
retain: false,
},
{
cursor: 2,
id: '3',
ancestors: [],
path: [],
method: 'expect',
storyId: 'kind--story',
args: [true],
interceptable: true,
retain: false,
},
{
cursor: 3,
id: '4',
ancestors: [],
path: [{ __callId__: '3' }, 'not'],
method: 'toBe',
storyId: 'kind--story',
args: [false],
interceptable: true,
retain: false,
},
{
cursor: 4,
id: '5',
ancestors: [],
path: ['jest'],
method: 'fn',
storyId: 'kind--story',
args: [{ __function__: { name: 'actionHandler' } }],
interceptable: false,
retain: false,
},
{
cursor: 5,
id: '6',
ancestors: [],
path: [],
method: 'expect',
storyId: 'kind--story',
args: [{ __callId__: '5' }],
interceptable: false,
retain: false,
},
{
cursor: 6,
id: '7',
ancestors: [],
path: ['expect'],
method: 'stringMatching',
storyId: 'kind--story',
args: [{ __regexp__: { flags: 'i', source: 'hello' } }],
interceptable: false,
retain: false,
},
{
cursor: 7,
id: '8',
ancestors: [],
path: [{ __callId__: '6' }, 'not'],
method: 'toHaveBeenCalledWith',
storyId: 'kind--story',
args: [
{ __callId__: '7' },
[
{ __error__: { name: 'Error', message: "Cannot read property 'foo' of undefined" } },
{ __symbol__: { description: 'Hello world' } },
],
],
interceptable: false,
retain: false,
},
{
cursor: 8,
id: '9',
ancestors: [],
path: [],
method: 'step',
storyId: 'kind--story',
args: ['Custom step label', { __function__: { name: '' } }],
interceptable: true,
retain: false,
},
];
const callsById = calls.reduce((acc, call) => {
acc.set(call.id, call);
return acc;
}, new Map<Call['id'], Call>());
export const Step = () => <MethodCall call={callsById.get('9')} callsById={callsById} />;
export const Simple = () => <MethodCall call={callsById.get('1')} callsById={callsById} />;
export const Nested = () => <MethodCall call={callsById.get('2')} callsById={callsById} />;
export const Chained = () => <MethodCall call={callsById.get('4')} callsById={callsById} />;
export const Complex = () => <MethodCall call={callsById.get('8')} callsById={callsById} />;
``` | /content/code_sandbox/code/addons/interactions/src/components/MethodCall.stories.tsx | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 1,774 |
```xml
import * as path from "path";
import * as fs from "fs";
import * as glob from "glob";
import * as semver from "semver";
import { Node } from "../../common/node/node";
import { ChildProcess } from "../../common/node/childProcess";
import { ErrorHelper } from "../../common/error/errorHelper";
import { InternalErrorCode } from "../../common/error/internalErrorCode";
import { ProjectVersionHelper } from "../../common/projectVersionHelper";
import { getFileNameWithoutExtension } from "../../common/utils";
import customRequire from "../../common/customRequire";
import { PlatformType } from "../launchArgs";
import { AppLauncher } from "../appLauncher";
export interface ConfigurationData {
fullProductName: string;
configurationFolder: string;
}
export interface IOSBuildLocationData {
executable: string;
configurationFolder: string;
}
export class PlistBuddy {
private static readonly plistBuddyExecutable = "/usr/libexec/PlistBuddy";
private static readonly SCHEME_IN_PRODUCTS_FOLDER_PATH_VERSION = "0.59.0";
private static readonly NEW_RN_IOS_CLI_LOCATION_VERSION = "0.60.0";
private static readonly RN69_FUND_XCODE_PROJECT_LOCATION_VERSION = "0.69.0";
private static readonly RN_VERSION_CLI_PLATFORM_APPLE = "0.74.0";
private readonly TARGET_BUILD_DIR_SEARCH_KEY = "TARGET_BUILD_DIR";
private readonly FULL_PRODUCT_NAME_SEARCH_KEY = "FULL_PRODUCT_NAME";
private nodeChildProcess: ChildProcess;
constructor({ nodeChildProcess = new Node.ChildProcess() } = {}) {
this.nodeChildProcess = nodeChildProcess;
}
public async getBundleId(
platformProjectRoot: string,
projectRoot: string,
platform: PlatformType.iOS | PlatformType.macOS,
simulator: boolean = true,
configuration: string = "Debug",
productName?: string,
scheme?: string,
): Promise<string> {
const iOSBuildLocationData = await this.getExecutableAndConfigurationFolder(
platformProjectRoot,
projectRoot,
platform,
simulator,
configuration,
productName,
scheme,
);
const infoPlistPath = path.join(
iOSBuildLocationData.configurationFolder,
iOSBuildLocationData.executable,
platform === PlatformType.iOS ? "Info.plist" : path.join("Contents", "Info.plist"),
);
return await this.invokePlistBuddy("Print:CFBundleIdentifier", infoPlistPath);
}
public async getExecutableAndConfigurationFolder(
platformProjectRoot: string,
projectRoot: string,
platform: PlatformType.iOS | PlatformType.macOS,
simulator: boolean = true,
configuration: string = "Debug",
productName?: string,
scheme?: string,
): Promise<IOSBuildLocationData> {
const rnVersions = await ProjectVersionHelper.getReactNativeVersions(projectRoot);
let productsFolder;
if (
semver.gte(
rnVersions.reactNativeVersion,
PlistBuddy.SCHEME_IN_PRODUCTS_FOLDER_PATH_VERSION,
) ||
ProjectVersionHelper.isCanaryVersion(rnVersions.reactNativeVersion)
) {
if (!scheme) {
// If no scheme were provided via runOptions.scheme or via runArguments then try to get scheme using the way RN CLI does.
scheme = this.getInferredScheme(
platformProjectRoot,
projectRoot,
rnVersions.reactNativeVersion,
);
if (platform === PlatformType.macOS) {
scheme = `${scheme}-macOS`;
}
}
productsFolder = path.join(platformProjectRoot, "build", scheme, "Build", "Products");
} else {
productsFolder = path.join(platformProjectRoot, "build", "Build", "Products");
}
const sdkType =
platform === PlatformType.iOS ? this.getSdkType(simulator, scheme) : undefined;
let configurationFolder = path.join(
productsFolder,
`${configuration}${sdkType ? `-${sdkType}` : ""}`,
);
let executable = "";
if (productName) {
executable = `${productName}.app`;
if (!fs.existsSync(path.join(configurationFolder, executable))) {
const configurationData = this.getConfigurationData(
projectRoot,
rnVersions.reactNativeVersion,
platformProjectRoot,
configuration,
scheme,
configurationFolder,
sdkType,
);
configurationFolder = configurationData.configurationFolder;
}
} else {
const executableList = this.findExecutable(configurationFolder);
if (!executableList.length) {
const configurationData_1 = this.getConfigurationData(
projectRoot,
rnVersions.reactNativeVersion,
platformProjectRoot,
configuration,
scheme,
configurationFolder,
sdkType,
);
configurationFolder = configurationData_1.configurationFolder;
executableList.push(configurationData_1.fullProductName);
} else if (executableList.length > 1) {
throw ErrorHelper.getInternalError(
InternalErrorCode.IOSFoundMoreThanOneExecutablesCleanupBuildFolder,
configurationFolder,
);
}
executable = `${executableList[0]}`;
}
return {
executable,
configurationFolder,
};
}
public async setPlistProperty(
plistFile: string,
property: string,
value: string,
): Promise<void> {
// Attempt to set the value, and if it fails due to the key not existing attempt to create the key
try {
await this.invokePlistBuddy(`Set ${property} ${value}`, plistFile);
} catch (e) {
await this.invokePlistBuddy(`Add ${property} string ${value}`, plistFile);
}
}
public async setPlistBooleanProperty(
plistFile: string,
property: string,
value: boolean,
): Promise<void> {
// Attempt to set the value, and if it fails due to the key not existing attempt to create the key
try {
await this.invokePlistBuddy(`Set ${property} ${String(value)}`, plistFile);
} catch (e) {
await this.invokePlistBuddy(`Add ${property} bool ${String(value)}`, plistFile);
}
}
public async deletePlistProperty(plistFile: string, property: string): Promise<void> {
try {
await this.invokePlistBuddy(`Delete ${property}`, plistFile);
} catch (err) {
if (!err.toString().toLowerCase().includes("does not exist")) {
throw err;
}
}
}
public readPlistProperty(plistFile: string, property: string): Promise<string> {
return this.invokePlistBuddy(`Print ${property}`, plistFile);
}
public getBuildPathAndProductName(
platformProjectRoot: string,
projectWorkspaceConfigName: string,
configuration: string,
scheme: string,
sdkType?: string,
): ConfigurationData {
const xcodebuildParams = ["-workspace", projectWorkspaceConfigName, "-scheme", scheme];
if (sdkType) {
xcodebuildParams.push("-sdk", sdkType);
}
xcodebuildParams.push("-configuration", configuration, "-showBuildSettings");
const buildSettings = this.nodeChildProcess.execFileSync("xcodebuild", xcodebuildParams, {
encoding: "utf8",
cwd: platformProjectRoot,
});
const targetBuildDir = this.fetchParameterFromBuildSettings(
<string>buildSettings,
this.TARGET_BUILD_DIR_SEARCH_KEY,
);
const fullProductName = this.fetchParameterFromBuildSettings(
<string>buildSettings,
this.FULL_PRODUCT_NAME_SEARCH_KEY,
);
if (!targetBuildDir) {
throw new Error("Failed to get the target build directory.");
}
if (!fullProductName) {
throw new Error("Failed to get full product name.");
}
return {
fullProductName,
configurationFolder: targetBuildDir,
};
}
public getInferredScheme(
platformProjectRoot: string,
projectRoot: string,
rnVersion: string,
): string {
const projectWorkspaceConfigName = this.getProjectWorkspaceConfigName(
platformProjectRoot,
projectRoot,
rnVersion,
);
return getFileNameWithoutExtension(projectWorkspaceConfigName);
}
public getSdkType(simulator: boolean, scheme?: string): string {
const sdkSuffix = simulator ? "simulator" : "os";
const deviceType =
(scheme?.toLowerCase().indexOf("tvos") ?? -1) > -1 ? "appletv" : "iphone";
return `${deviceType}${sdkSuffix}`;
}
public getProjectWorkspaceConfigName(
platformProjectRoot: string,
projectRoot: string,
rnVersion: string,
): string {
// Portion of code was taken from path_to_url
// and modified a little bit
/**
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
*/
const iOSCliPlatform = semver.gte(rnVersion, PlistBuddy.RN_VERSION_CLI_PLATFORM_APPLE)
? "cli-platform-apple"
: "cli-platform-ios";
const iOSCliFolderName =
semver.gte(rnVersion, PlistBuddy.NEW_RN_IOS_CLI_LOCATION_VERSION) ||
ProjectVersionHelper.isCanaryVersion(rnVersion)
? iOSCliPlatform
: "cli";
const findXcodeProjectLocation = `node_modules/@react-native-community/${iOSCliFolderName}/build/${
semver.gte(rnVersion, PlistBuddy.RN69_FUND_XCODE_PROJECT_LOCATION_VERSION)
? "config/findXcodeProject"
: "commands/runIOS/findXcodeProject"
}`;
const findXcodeProject = customRequire(
path.join(
AppLauncher.getNodeModulesRootByProjectPath(projectRoot),
findXcodeProjectLocation,
),
).default;
const xcodeProject = findXcodeProject(fs.readdirSync(platformProjectRoot));
if (!xcodeProject) {
throw new Error(
`Could not find Xcode project files in "${platformProjectRoot}" folder`,
);
}
return xcodeProject.name;
}
public getConfigurationData(
projectRoot: string,
reactNativeVersion: string,
platformProjectRoot: string,
configuration: string,
scheme: string | undefined,
oldConfigurationFolder: string,
sdkType?: string,
): ConfigurationData {
if (!scheme) {
throw ErrorHelper.getInternalError(
InternalErrorCode.IOSCouldNotFoundExecutableInFolder,
oldConfigurationFolder,
);
}
const projectWorkspaceConfigName = this.getProjectWorkspaceConfigName(
platformProjectRoot,
projectRoot,
reactNativeVersion,
);
return this.getBuildPathAndProductName(
platformProjectRoot,
projectWorkspaceConfigName,
configuration,
scheme,
sdkType,
);
}
/**
* @param {string} buildSettings
* @param {string} parameterName
* @returns {string | null}
*/
public fetchParameterFromBuildSettings(
buildSettings: string,
parameterName: string,
): string | null {
const targetBuildMatch = new RegExp(`${parameterName} = (.+)$`, "m").exec(buildSettings);
return targetBuildMatch && targetBuildMatch[1] ? targetBuildMatch[1].trim() : null;
}
private findExecutable(folder: string): string[] {
return glob.sync("*.app", {
cwd: folder,
});
}
private async invokePlistBuddy(command: string, plistFile: string): Promise<string> {
const res = await this.nodeChildProcess.exec(
`${PlistBuddy.plistBuddyExecutable} -c '${command}' '${plistFile}'`,
);
const outcome = await res.outcome;
return outcome.toString().trim();
}
}
``` | /content/code_sandbox/src/extension/ios/plistBuddy.ts | xml | 2016-01-20T21:10:07 | 2024-08-16T15:29:52 | vscode-react-native | microsoft/vscode-react-native | 2,617 | 2,549 |
```xml
import { IndexMetadata } from "../../metadata/IndexMetadata"
import { TableIndexOptions } from "../options/TableIndexOptions"
/**
* Database's table index stored in this class.
*/
export class TableIndex {
readonly "@instanceof" = Symbol.for("TableIndex")
// your_sha256_hash---------
// Public Properties
// your_sha256_hash---------
/**
* Index name.
*/
name?: string
/**
* Columns included in this index.
*/
columnNames: string[] = []
/**
* Indicates if this index is unique.
*/
isUnique: boolean
/**
* The SPATIAL modifier indexes the entire column and does not allow indexed columns to contain NULL values.
* Works only in MySQL.
*/
isSpatial: boolean
/**
* Create the index using the CONCURRENTLY modifier
* Works only in postgres.
*/
isConcurrent: boolean
/**
* The FULLTEXT modifier indexes the entire column and does not allow prefixing.
* Works only in MySQL.
*/
isFulltext: boolean
/**
* NULL_FILTERED indexes are particularly useful for indexing sparse columns, where most rows contain a NULL value.
* In these cases, the NULL_FILTERED index can be considerably smaller and more efficient to maintain than
* a normal index that includes NULL values.
*
* Works only in Spanner.
*/
isNullFiltered: boolean
/**
* Fulltext parser.
* Works only in MySQL.
*/
parser?: string
/**
* Index filter condition.
*/
where: string
// your_sha256_hash---------
// Constructor
// your_sha256_hash---------
constructor(options: TableIndexOptions) {
this.name = options.name
this.columnNames = options.columnNames
this.isUnique = !!options.isUnique
this.isSpatial = !!options.isSpatial
this.isConcurrent = !!options.isConcurrent
this.isFulltext = !!options.isFulltext
this.isNullFiltered = !!options.isNullFiltered
this.parser = options.parser
this.where = options.where ? options.where : ""
}
// your_sha256_hash---------
// Public Methods
// your_sha256_hash---------
/**
* Creates a new copy of this index with exactly same properties.
*/
clone(): TableIndex {
return new TableIndex(<TableIndexOptions>{
name: this.name,
columnNames: [...this.columnNames],
isUnique: this.isUnique,
isSpatial: this.isSpatial,
isConcurrent: this.isConcurrent,
isFulltext: this.isFulltext,
isNullFiltered: this.isNullFiltered,
parser: this.parser,
where: this.where,
})
}
// your_sha256_hash---------
// Static Methods
// your_sha256_hash---------
/**
* Creates index from the index metadata object.
*/
static create(indexMetadata: IndexMetadata): TableIndex {
return new TableIndex(<TableIndexOptions>{
name: indexMetadata.name,
columnNames: indexMetadata.columns.map(
(column) => column.databaseName,
),
isUnique: indexMetadata.isUnique,
isSpatial: indexMetadata.isSpatial,
isConcurrent: indexMetadata.isConcurrent,
isFulltext: indexMetadata.isFulltext,
isNullFiltered: indexMetadata.isNullFiltered,
parser: indexMetadata.parser,
where: indexMetadata.where,
})
}
}
``` | /content/code_sandbox/src/schema-builder/table/TableIndex.ts | xml | 2016-02-29T07:41:14 | 2024-08-16T18:28:52 | typeorm | typeorm/typeorm | 33,875 | 740 |
```xml
/**
* @packageDocumentation
* @module documentsearch-extension
*/
import {
ILabShell,
JupyterFrontEnd,
JupyterFrontEndPlugin
} from '@jupyterlab/application';
import { ICommandPalette, MainAreaWidget } from '@jupyterlab/apputils';
import {
ISearchKeyBindings,
ISearchProviderRegistry,
SearchDocumentModel,
SearchDocumentView,
SearchProviderRegistry
} from '@jupyterlab/documentsearch';
import { ISettingRegistry } from '@jupyterlab/settingregistry';
import { ITranslator } from '@jupyterlab/translation';
import { CommandRegistry } from '@lumino/commands';
import { Widget } from '@lumino/widgets';
/**
* Class added to widgets that can be searched (have a search provider).
*/
const SEARCHABLE_CLASS = 'jp-mod-searchable';
/**
* Class added to widgets with open search view (not necessarily focused).
*/
const SEARCH_ACTIVE_CLASS = 'jp-mod-search-active';
namespace CommandIDs {
/**
* Start search in a document
*/
export const search = 'documentsearch:start';
/**
* Start search and replace in a document
*/
export const searchAndReplace = 'documentsearch:startWithReplace';
/**
* Find next search match
*/
export const findNext = 'documentsearch:highlightNext';
/**
* Find previous search match
*/
export const findPrevious = 'documentsearch:highlightPrevious';
/**
* End search in a document
*/
export const end = 'documentsearch:end';
/**
* Toggle search in selection
*/
export const toggleSearchInSelection =
'documentsearch:toggleSearchInSelection';
}
/**
* When automatic selection search filter logic should be active.
*
* - `multiple-selected`: when multiple lines/cells are selected
* - `any-selected`: when any number of characters/cells are selected
* - `never`: never
*/
type AutoSearchInSelection = 'never' | 'multiple-selected' | 'any-selected';
const labShellWidgetListener: JupyterFrontEndPlugin<void> = {
id: '@jupyterlab/documentsearch-extension:labShellWidgetListener',
description: 'Active search on valid document',
requires: [ILabShell, ISearchProviderRegistry],
autoStart: true,
activate: (
app: JupyterFrontEnd,
labShell: ILabShell,
registry: ISearchProviderRegistry
) => {
// If a given widget is searchable, apply the searchable class.
// If it's not searchable, remove the class.
const transformWidgetSearchability = (widget: Widget | null) => {
if (!widget) {
return;
}
if (registry.hasProvider(widget)) {
widget.addClass(SEARCHABLE_CLASS);
} else {
widget.removeClass(SEARCHABLE_CLASS);
}
};
// Update searchability of the active widget when the registry
// changes, in case a provider for the current widget was added
// or removed
registry.changed.connect(() =>
transformWidgetSearchability(labShell.activeWidget)
);
// Apply the searchable class only to the active widget if it is actually
// searchable. Remove the searchable class from a widget when it's
// no longer active.
labShell.activeChanged.connect((_, args) => {
const oldWidget = args.oldValue;
if (oldWidget) {
oldWidget.removeClass(SEARCHABLE_CLASS);
}
transformWidgetSearchability(args.newValue);
});
}
};
type KeyBindingsCache = Record<
'next' | 'previous' | 'toggleSearchInSelection',
CommandRegistry.IKeyBinding | undefined
>;
/**
* Exposes the current keybindings to search box view.
*/
class SearchKeyBindings implements ISearchKeyBindings {
constructor(private _commandRegistry: CommandRegistry) {
this._cache = this._buildCache();
this._commandRegistry.keyBindingChanged.connect(this._rebuildCache, this);
}
get next() {
return this._cache.next;
}
get previous() {
return this._cache.previous;
}
get toggleSearchInSelection() {
return this._cache.toggleSearchInSelection;
}
private _rebuildCache() {
this._cache = this._buildCache();
}
private _buildCache(): KeyBindingsCache {
const next = this._commandRegistry.keyBindings.find(
binding => binding.command === CommandIDs.findNext
);
const previous = this._commandRegistry.keyBindings.find(
binding => binding.command === CommandIDs.findPrevious
);
const toggleSearchInSelection = this._commandRegistry.keyBindings.find(
binding => binding.command === CommandIDs.toggleSearchInSelection
);
return {
next,
previous,
toggleSearchInSelection
};
}
dispose() {
this._commandRegistry.keyBindingChanged.disconnect(
this._rebuildCache,
this
);
}
private _cache: KeyBindingsCache;
}
/**
* Initialization data for the document-search extension.
*/
const extension: JupyterFrontEndPlugin<ISearchProviderRegistry> = {
id: '@jupyterlab/documentsearch-extension:plugin',
description: 'Provides the document search registry.',
provides: ISearchProviderRegistry,
requires: [ITranslator],
optional: [ICommandPalette, ISettingRegistry],
autoStart: true,
activate: (
app: JupyterFrontEnd,
translator: ITranslator,
palette: ICommandPalette,
settingRegistry: ISettingRegistry | null
) => {
const trans = translator.load('jupyterlab');
let searchDebounceTime = 500;
let autoSearchInSelection: AutoSearchInSelection = 'never';
// Create registry
const registry: SearchProviderRegistry = new SearchProviderRegistry(
translator
);
const searchViews = new Map<string, SearchDocumentView>();
if (settingRegistry) {
const loadSettings = settingRegistry.load(extension.id);
const updateSettings = (settings: ISettingRegistry.ISettings): void => {
searchDebounceTime = settings.get('searchDebounceTime')
.composite as number;
autoSearchInSelection = settings.get('autoSearchInSelection')
.composite as AutoSearchInSelection;
};
Promise.all([loadSettings, app.restored])
.then(([settings]) => {
updateSettings(settings);
settings.changed.connect(settings => {
updateSettings(settings);
});
})
.catch((reason: Error) => {
console.error(reason.message);
});
}
const isEnabled = () => {
const widget = app.shell.currentWidget;
if (!widget) {
return false;
}
return registry.hasProvider(widget);
};
const getSearchWidget = (widget: Widget | null) => {
if (!widget) {
return;
}
const widgetId = widget.id;
let searchView = searchViews.get(widgetId);
if (!searchView) {
const searchProvider = registry.getProvider(widget);
if (!searchProvider) {
return;
}
const searchModel = new SearchDocumentModel(
searchProvider,
searchDebounceTime
);
const keyBingingsInfo = new SearchKeyBindings(app.commands);
const newView = new SearchDocumentView(
searchModel,
translator,
keyBingingsInfo
);
searchViews.set(widgetId, newView);
// find next, previous and end are now enabled
[
CommandIDs.findNext,
CommandIDs.findPrevious,
CommandIDs.end,
CommandIDs.toggleSearchInSelection
].forEach(id => {
app.commands.notifyCommandChanged(id);
});
/**
* Activate the target widget when the search panel is closing
*/
newView.closed.connect(() => {
if (!widget.isDisposed) {
widget.activate();
widget.removeClass(SEARCH_ACTIVE_CLASS);
}
});
/**
* Remove from mapping when the search view is disposed.
*/
newView.disposed.connect(() => {
if (!widget.isDisposed) {
widget.activate();
widget.removeClass(SEARCH_ACTIVE_CLASS);
}
searchViews.delete(widgetId);
// find next, previous and end are now disabled
[
CommandIDs.findNext,
CommandIDs.findPrevious,
CommandIDs.end,
CommandIDs.toggleSearchInSelection
].forEach(id => {
app.commands.notifyCommandChanged(id);
});
});
/**
* Dispose resources when the widget is disposed.
*/
widget.disposed.connect(() => {
newView.dispose();
searchModel.dispose();
searchProvider.dispose();
keyBingingsInfo.dispose();
});
searchView = newView;
}
if (!searchView.isAttached) {
Widget.attach(searchView, widget.node);
widget.addClass(SEARCH_ACTIVE_CLASS);
if (widget instanceof MainAreaWidget) {
// Offset the position of the search widget to not cover the toolbar nor the content header.
// TODO this does not update once the search widget is displayed.
searchView.node.style.top = `${
widget.toolbar.node.getBoundingClientRect().height +
widget.contentHeader.node.getBoundingClientRect().height
}px`;
}
if (searchView.model.searchExpression) {
searchView.model.refresh();
}
}
return searchView;
};
app.commands.addCommand(CommandIDs.search, {
label: trans.__('Find'),
isEnabled: isEnabled,
execute: async args => {
const searchWidget = getSearchWidget(app.shell.currentWidget);
if (searchWidget) {
const searchText = args['searchText'] as string;
if (searchText) {
searchWidget.setSearchText(searchText);
} else {
searchWidget.setSearchText(
searchWidget.model.suggestedInitialQuery
);
}
const selectionState = searchWidget.model.selectionState;
let enableSelectionMode = false;
switch (autoSearchInSelection) {
case 'multiple-selected':
enableSelectionMode = selectionState === 'multiple';
break;
case 'any-selected':
enableSelectionMode =
selectionState === 'multiple' || selectionState === 'single';
break;
case 'never':
// no-op
break;
}
if (enableSelectionMode) {
await searchWidget.model.setFilter('selection', true);
}
searchWidget.focusSearchInput();
}
}
});
app.commands.addCommand(CommandIDs.searchAndReplace, {
label: trans.__('Find and Replace'),
isEnabled: isEnabled,
execute: args => {
const searchWidget = getSearchWidget(app.shell.currentWidget);
if (searchWidget) {
const searchText = args['searchText'] as string;
if (searchText) {
searchWidget.setSearchText(searchText);
} else {
searchWidget.setSearchText(
searchWidget.model.suggestedInitialQuery
);
}
const replaceText = args['replaceText'] as string;
if (replaceText) {
searchWidget.setReplaceText(replaceText);
}
searchWidget.showReplace();
searchWidget.focusSearchInput();
}
}
});
app.commands.addCommand(CommandIDs.findNext, {
label: trans.__('Find Next'),
isEnabled: () =>
!!app.shell.currentWidget &&
searchViews.has(app.shell.currentWidget.id),
execute: async () => {
const currentWidget = app.shell.currentWidget;
if (!currentWidget) {
return;
}
await searchViews.get(currentWidget.id)?.model.highlightNext();
}
});
app.commands.addCommand(CommandIDs.findPrevious, {
label: trans.__('Find Previous'),
isEnabled: () =>
!!app.shell.currentWidget &&
searchViews.has(app.shell.currentWidget.id),
execute: async () => {
const currentWidget = app.shell.currentWidget;
if (!currentWidget) {
return;
}
await searchViews.get(currentWidget.id)?.model.highlightPrevious();
}
});
app.commands.addCommand(CommandIDs.end, {
label: trans.__('End Search'),
isEnabled: () =>
!!app.shell.currentWidget &&
searchViews.has(app.shell.currentWidget.id),
execute: async () => {
const currentWidget = app.shell.currentWidget;
if (!currentWidget) {
return;
}
searchViews.get(currentWidget.id)?.close();
}
});
app.commands.addCommand(CommandIDs.toggleSearchInSelection, {
label: trans.__('Search in Selection'),
isEnabled: () =>
!!app.shell.currentWidget &&
searchViews.has(app.shell.currentWidget.id) &&
'selection' in
searchViews.get(app.shell.currentWidget.id)!.model.filtersDefinition,
execute: async () => {
const currentWidget = app.shell.currentWidget;
if (!currentWidget) {
return;
}
const model = searchViews.get(currentWidget.id)?.model;
if (!model) {
return;
}
const currentValue = model.filters['selection'];
return model.setFilter('selection', !currentValue);
}
});
app.shell.currentChanged?.connect(() => {
Object.values(CommandIDs).forEach(cmd => {
app.commands.notifyCommandChanged(cmd);
});
});
// Add the command to the palette.
if (palette) {
[
CommandIDs.search,
CommandIDs.findNext,
CommandIDs.findPrevious,
CommandIDs.end,
CommandIDs.toggleSearchInSelection
].forEach(command => {
palette.addItem({
command,
category: trans.__('Main Area')
});
});
}
// Provide the registry to the system.
return registry;
}
};
export default [extension, labShellWidgetListener];
``` | /content/code_sandbox/packages/documentsearch-extension/src/index.ts | xml | 2016-06-03T20:09:17 | 2024-08-16T19:12:44 | jupyterlab | jupyterlab/jupyterlab | 14,019 | 2,894 |
```xml
import * as semver from "semver";
import * as nls from "vscode-nls";
import { MobilePlatformDeps, TargetType } from "../generalPlatform";
import { IAndroidRunOptions, PlatformType } from "../launchArgs";
import { Package } from "../../common/node/package";
import { OutputVerifier, PatternToFailure } from "../../common/outputVerifier";
import { TelemetryHelper } from "../../common/telemetryHelper";
import { CommandExecutor } from "../../common/commandExecutor";
import { InternalErrorCode } from "../../common/error/internalErrorCode";
import { ErrorHelper } from "../../common/error/errorHelper";
import { notNullOrUndefined } from "../../common/utils";
import { PromiseUtil } from "../../common/node/promise";
import { GeneralMobilePlatform } from "../generalMobilePlatform";
import { ProjectVersionHelper } from "../../common/projectVersionHelper";
import { LogCatMonitorManager } from "./logCatMonitorManager";
import { AndroidTarget, AndroidTargetManager } from "./androidTargetManager";
import { AdbHelper, AndroidAPILevel } from "./adb";
import { LogCatMonitor } from "./logCatMonitor";
import { PackageNameResolver } from "./packageNameResolver";
nls.config({
messageFormat: nls.MessageFormat.bundle,
bundleFormat: nls.BundleFormat.standalone,
})();
const localize = nls.loadMessageBundle();
/**
* Android specific platform implementation for debugging RN applications.
*/
export class AndroidPlatform extends GeneralMobilePlatform {
// We should add the common Android build/run errors we find to this list
private static RUN_ANDROID_FAILURE_PATTERNS: PatternToFailure[] = [
{
pattern: "Failed to install on any devices",
errorCode: InternalErrorCode.AndroidCouldNotInstallTheAppOnAnyAvailibleDevice,
},
{
pattern: "com.android.ddmlib.ShellCommandUnresponsiveException",
errorCode: InternalErrorCode.AndroidShellCommandTimedOut,
},
{
pattern: "Android project not found",
errorCode: InternalErrorCode.AndroidProjectNotFound,
},
{
pattern: "error: more than one device/emulator",
errorCode: InternalErrorCode.AndroidMoreThanOneDeviceOrEmulator,
},
{
pattern: /^Error: Activity class {.*} does not exist\.$/m,
errorCode: InternalErrorCode.AndroidFailedToLaunchTheSpecifiedActivity,
},
];
private static RUN_ANDROID_SUCCESS_PATTERNS: string[] = [
"BUILD SUCCESSFUL",
"Starting the app",
"Starting: Intent",
];
private packageName: string;
private adbHelper: AdbHelper;
private logCatMonitor: LogCatMonitor | null = null;
private needsToLaunchApps: boolean = false;
protected targetManager: AndroidTargetManager;
protected target?: AndroidTarget;
// We set remoteExtension = null so that if there is an instance of androidPlatform that wants to have it's custom remoteExtension it can. This is specifically useful for tests.
constructor(protected runOptions: IAndroidRunOptions, platformDeps: MobilePlatformDeps = {}) {
super(runOptions, platformDeps);
this.adbHelper = new AdbHelper(
this.runOptions.projectRoot,
runOptions.nodeModulesRoot,
this.logger,
);
this.targetManager = new AndroidTargetManager(this.adbHelper);
}
public showDevMenu(deviceId?: string): Promise<void> {
return this.adbHelper.showDevMenu(deviceId);
}
public reloadApp(deviceId?: string): Promise<void> {
return this.adbHelper.reloadApp(deviceId);
}
public async getTarget(): Promise<AndroidTarget> {
if (!this.target) {
const onlineTargets = await this.adbHelper.getOnlineTargets();
const target = await this.getTargetFromRunArgs();
if (target) {
this.target = target;
} else {
const onlineTargetsBySpecifiedType = onlineTargets.filter(target => {
switch (this.runOptions.target) {
case TargetType.Simulator:
return target.isVirtualTarget;
case TargetType.Device:
return !target.isVirtualTarget;
case undefined:
case "":
return true;
default:
return target.id === this.runOptions.target;
}
});
if (onlineTargetsBySpecifiedType.length) {
this.target = AndroidTarget.fromInterface(onlineTargetsBySpecifiedType[0]);
} else if (onlineTargets.length) {
this.logger.warning(
localize(
"ThereIsNoOnlineTargetWithSpecifiedTargetType",
"There is no any online target with specified target type '{0}'. Continue with any online target.",
this.runOptions.target,
),
);
this.target = AndroidTarget.fromInterface(onlineTargets[0]);
} else {
throw ErrorHelper.getInternalError(
InternalErrorCode.AndroidThereIsNoAnyOnlineDebuggableTarget,
);
}
}
}
return this.target;
}
public async runApp(shouldLaunchInAllDevices: boolean = false): Promise<void> {
let extProps: any = {
platform: {
value: PlatformType.Android,
isPii: false,
},
};
if (this.runOptions.isDirect) {
extProps.isDirect = {
value: true,
isPii: false,
};
this.projectObserver?.updateRNAndroidHermesProjectState(true);
}
extProps = TelemetryHelper.addPlatformPropertiesToTelemetryProperties(
this.runOptions,
this.runOptions.reactNativeVersions,
extProps,
);
await TelemetryHelper.generate("AndroidPlatform.runApp", extProps, async () => {
const env = GeneralMobilePlatform.getEnvArgument(
process.env,
this.runOptions.env,
this.runOptions.envFile,
);
if (
!semver.valid(
this.runOptions.reactNativeVersions.reactNativeVersion,
) /* Custom RN implementations should support this flag*/ ||
semver.gte(
this.runOptions.reactNativeVersions.reactNativeVersion,
AndroidPlatform.NO_PACKAGER_VERSION,
) ||
ProjectVersionHelper.isCanaryVersion(
this.runOptions.reactNativeVersions.reactNativeVersion,
)
) {
this.runArguments.push("--no-packager");
}
const mainActivity = GeneralMobilePlatform.getOptFromRunArgs(
this.runArguments,
"--main-activity",
);
if (mainActivity) {
this.adbHelper.setLaunchActivity(mainActivity);
} else if (notNullOrUndefined(this.runOptions.debugLaunchActivity)) {
this.runArguments.push("--main-activity", this.runOptions.debugLaunchActivity);
this.adbHelper.setLaunchActivity(this.runOptions.debugLaunchActivity);
}
const runAndroidSpawn = new CommandExecutor(
this.runOptions.nodeModulesRoot,
this.projectPath,
this.logger,
).spawnReactCommand("run-android", this.runArguments, { env });
const output = new OutputVerifier(
() => Promise.resolve(AndroidPlatform.RUN_ANDROID_SUCCESS_PATTERNS),
() => Promise.resolve(AndroidPlatform.RUN_ANDROID_FAILURE_PATTERNS),
PlatformType.Android,
).process(runAndroidSpawn);
let devicesIdsForLaunch: string[] = [];
const onlineTargetsIds = (await this.adbHelper.getOnlineTargets()).map(
target => target.id,
);
let targetId: string | undefined;
try {
try {
await output;
} finally {
targetId = await this.getTargetIdForRunApp(onlineTargetsIds);
this.packageName = await this.getPackageName();
devicesIdsForLaunch = [targetId];
}
} catch (error) {
if (!targetId) {
targetId = await this.getTargetIdForRunApp(onlineTargetsIds);
}
if (
error.message ===
ErrorHelper.getInternalError(
InternalErrorCode.AndroidMoreThanOneDeviceOrEmulator,
).message &&
onlineTargetsIds.length >= 1 &&
targetId
) {
/* If it failed due to multiple devices, we'll apply this workaround to make it work anyways */
this.needsToLaunchApps = true;
devicesIdsForLaunch = shouldLaunchInAllDevices ? onlineTargetsIds : [targetId];
} else {
throw error;
}
}
await PromiseUtil.forEach(devicesIdsForLaunch, deviceId =>
this.launchAppWithADBReverseAndLogCat(deviceId),
);
});
}
public async enableJSDebuggingMode(): Promise<void> {
return this.adbHelper.switchDebugMode(
this.runOptions.projectRoot,
this.packageName,
true,
(await this.getTarget()).id,
this.getAppIdSuffixFromRunArgumentsIfExists(),
);
}
public async disableJSDebuggingMode(): Promise<void> {
return this.adbHelper.switchDebugMode(
this.runOptions.projectRoot,
this.packageName,
false,
(await this.getTarget()).id,
this.getAppIdSuffixFromRunArgumentsIfExists(),
);
}
public prewarmBundleCache(): Promise<void> {
return this.packager.prewarmBundleCache(PlatformType.Android);
}
public getRunArguments(): string[] {
let runArguments: string[] = [];
if (this.runOptions.runArguments && this.runOptions.runArguments.length > 0) {
runArguments = this.runOptions.runArguments;
} else {
if (this.runOptions.variant) {
runArguments.push("--variant", this.runOptions.variant);
}
if (this.runOptions.target) {
if (
this.runOptions.target !== TargetType.Device &&
this.runOptions.target !== TargetType.Simulator
) {
runArguments.push("--deviceId", this.runOptions.target);
}
}
}
return runArguments;
}
public dispose(): void {
if (this.logCatMonitor) {
LogCatMonitorManager.delMonitor(this.logCatMonitor.deviceId);
this.logCatMonitor = null;
}
}
public async getTargetFromRunArgs(): Promise<AndroidTarget | undefined> {
if (this.runOptions.runArguments && this.runOptions.runArguments.length) {
const deviceId = GeneralMobilePlatform.getOptFromRunArgs(
this.runOptions.runArguments,
"--deviceId",
);
if (deviceId) {
return new AndroidTarget(true, this.adbHelper.isVirtualTarget(deviceId), deviceId);
}
}
return undefined;
}
private async getTargetIdForRunApp(onlineTargetsIds: string[]): Promise<string> {
let deviceId: string | undefined;
if (this.runOptions.runArguments && this.runOptions.runArguments.length) {
deviceId = GeneralMobilePlatform.getOptFromRunArgs(
this.runOptions.runArguments,
"--deviceId",
);
}
return deviceId
? deviceId
: this.runOptions.target &&
this.runOptions.target !== TargetType.Simulator &&
this.runOptions.target !== TargetType.Device &&
onlineTargetsIds.find(id => id === this.runOptions.target)
? this.runOptions.target
: (await this.getTarget()).id;
}
private getAppIdSuffixFromRunArgumentsIfExists(): string | undefined {
const appIdSuffixIndex = this.runArguments.indexOf("--appIdSuffix");
if (appIdSuffixIndex > -1) {
return this.runArguments[appIdSuffixIndex + 1];
}
return undefined;
}
private async launchAppWithADBReverseAndLogCat(deviceId: string): Promise<void> {
await this.configureADBReverseWhenApplicable(deviceId);
if (this.needsToLaunchApps) {
await this.adbHelper.launchApp(this.runOptions.projectRoot, this.packageName, deviceId);
}
return this.startMonitoringLogCat(deviceId, this.runOptions.logCatArguments);
}
private async configureADBReverseWhenApplicable(deviceId: string): Promise<void> {
// For other emulators and devices we try to enable adb reverse
const apiVersion = await this.adbHelper.apiVersion(deviceId);
if (apiVersion >= AndroidAPILevel.LOLLIPOP) {
// If we support adb reverse
try {
void this.adbHelper.reverseAdb(deviceId, Number(this.runOptions.packagerPort));
} catch (error) {
// "adb reverse" command could work incorrectly with remote devices, then skip the error and try to go on
if (
this.adbHelper.isRemoteTarget(deviceId) &&
error.message.includes(AndroidPlatform.RUN_ANDROID_FAILURE_PATTERNS[3].pattern)
) {
this.logger.warning(error.message);
} else {
throw error;
}
}
} else {
this.logger.warning(
localize(
"DeviceSupportsOnlyAPILevel",
"Device {0} supports only API Level {1}. \n Level {2} is needed to support port forwarding via adb reverse. \n For debugging to work you'll need <Shake or press menu button> for the dev menu, \n go into <Dev Settings> and configure <Debug Server host & port for Device> to be \n an IP address of your computer that the Device can reach. More info at: \n path_to_url#debugging-react-native-apps",
deviceId,
apiVersion,
AndroidAPILevel.LOLLIPOP,
),
);
}
}
private async getPackageName(): Promise<string> {
const appName = await new Package(this.runOptions.projectRoot).name();
return new PackageNameResolver(appName).resolvePackageName(this.runOptions.projectRoot);
}
private startMonitoringLogCat(deviceId: string, logCatArguments: string[]): void {
LogCatMonitorManager.delMonitor(deviceId); // Stop previous logcat monitor if it's running
// this.logCatMonitor can be mutated, so we store it locally too
this.logCatMonitor = new LogCatMonitor(deviceId, this.adbHelper, logCatArguments);
LogCatMonitorManager.addMonitor(this.logCatMonitor);
this.logCatMonitor
.start() // The LogCat will continue running forever, so we don't wait for it
.catch(error => {
this.logger.warning(error);
this.logger.warning(
localize("ErrorWhileMonitoringLogCat", "Error while monitoring LogCat"),
);
}); // The LogCatMonitor failing won't stop the debugging experience
}
}
``` | /content/code_sandbox/src/extension/android/androidPlatform.ts | xml | 2016-01-20T21:10:07 | 2024-08-16T15:29:52 | vscode-react-native | microsoft/vscode-react-native | 2,617 | 3,023 |
```xml
import React, { useState } from 'react';
// erxes
// local
import ModalTrigger from '../../../common/ModalTrigger';
import Icon from '../../../common/Icon';
import { ParticipantItemWrapper } from '../../styles';
import FormGroup from '../../../common/form/Group';
import FormControl from '../../../common/form/Control';
import Button from '../../../common/Button';
import Uploader from '../../../common/Uploader';
type Props = {
chat?: any;
editChat: (_id: string, name?: any[], featuredImage?: string) => void;
};
const GroupChat = (props: Props) => {
const { chat, editChat } = props;
const [name, setName] = useState(chat.name || '');
const [featuredImage, setFeaturedImage] = useState(chat.featuredImage || []);
const handleSubmit = (callback) => {
editChat(chat._id, name, featuredImage);
callback();
};
const changeName = (p) => {
return (
<>
<h3>Change Name</h3>
<FormGroup>
<FormControl
placeholder="Title"
type="text"
name="name"
onChange={(e: any) => setName(e.target.value)}
defaultValue={name}
/>
</FormGroup>
<br />
<Button
style={{ float: 'right' }}
onClick={() => handleSubmit(p.closeModal)}
>
Add
</Button>
<Button
btnStyle="simple"
style={{ float: 'right', marginRight: '10px' }}
onClick={p.closeModal}
>
Cancel
</Button>
</>
);
};
const changeImage = (p) => {
return (
<>
<h3>Change Name</h3>
<Uploader
defaultFileList={featuredImage}
onChange={setFeaturedImage}
btnText="Cover Image"
btnIcon="image"
single={true}
btnIconSize={30}
/>
<br />
<Button
style={{ float: 'right' }}
onClick={() => handleSubmit(p.closeModal)}
>
Add
</Button>
<Button
btnStyle="simple"
style={{ float: 'right', marginRight: '10px' }}
onClick={p.closeModal}
>
Cancel
</Button>
</>
);
};
return (
<>
<ModalTrigger
title="Add people"
trigger={
<ParticipantItemWrapper>
<a href="#">
<Icon
icon="edit"
size={13}
color="black"
style={{ margin: '0 0.6em' }}
/>
Change group chat name
</a>
</ParticipantItemWrapper>
}
content={(p) => changeName(p)}
isAnimate={true}
hideHeader={true}
/>
<ModalTrigger
title="Add people"
trigger={
<ParticipantItemWrapper>
<a href="#">
<Icon
icon="edit"
size={13}
color="black"
style={{ margin: '0 0.6em' }}
/>
Change group chat image
</a>
</ParticipantItemWrapper>
}
content={(p) => changeImage(p)}
isAnimate={true}
hideHeader={true}
/>
</>
);
};
export default GroupChat;
``` | /content/code_sandbox/exm/modules/exmFeed/components/chat/GroupChatAction.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 718 |
```xml
import type { ViewStyle } from 'react-native';
import { splitStyles } from '../splitStyles';
describe('splitStyles', () => {
const styles: Readonly<ViewStyle> = Object.freeze({
backgroundColor: 'red',
marginTop: 1,
marginBottom: 2,
marginLeft: 3,
padding: 4,
borderTopLeftRadius: 5,
borderTopRightRadius: 6,
right: 4,
});
it('splits margins, paddings, and border radiuses correctly', () => {
const marginPredicate = (style: string) => style.startsWith('margin');
const paddingPredicate = (style: string) => style.startsWith('padding');
const borderRadiusPredicate = (style: string) =>
style.startsWith('border') && style.endsWith('Radius');
const [filteredStyles, marginStyles, paddingStyles, borderRadiusStyles] =
splitStyles(
styles,
marginPredicate,
paddingPredicate,
borderRadiusPredicate
);
expect(keysLength(filteredStyles)).toBeGreaterThan(0);
expect(keysLength(filteredStyles)).toBeLessThan(keysLength(styles));
for (const style in filteredStyles) {
expect(marginPredicate(style)).toBeFalsy();
expect(paddingPredicate(style)).toBeFalsy();
expect(borderRadiusPredicate(style)).toBeFalsy();
}
expect(keysLength(marginStyles)).toBeGreaterThan(0);
for (const style in marginStyles) {
expect(marginPredicate(style)).toBeTruthy();
}
expect(keysLength(paddingStyles)).toBeGreaterThan(0);
for (const style in paddingStyles) {
expect(paddingPredicate(style)).toBeTruthy();
}
expect(keysLength(borderRadiusStyles)).toBeGreaterThan(0);
for (const style in borderRadiusStyles) {
expect(borderRadiusPredicate(style)).toBeTruthy();
}
});
it('filtered styles is an empty object if all styles matched some predicate', () => {
const styles = {
margin: 5,
padding: 6,
};
const [filteredStyles] = splitStyles(
styles,
(style) => style.startsWith('margin'),
(style) => style.startsWith('padding')
);
expect(keysLength(filteredStyles)).toBe(0);
});
it('processes predicates in order', () => {
const [, marginStyles, marginStyles2, marginStyles3] = splitStyles(
styles,
(style) => style.startsWith('margin'),
(style) => style.startsWith('margin'),
(style) => style.startsWith('margin')
);
expect(keysLength(marginStyles)).toBeGreaterThan(0);
expect(keysLength(marginStyles2)).toBe(0);
expect(keysLength(marginStyles3)).toBe(0);
});
});
function keysLength(object: object): number {
return Object.keys(object).length;
}
``` | /content/code_sandbox/src/utils/__tests__/splitStyles.test.ts | xml | 2016-10-19T05:56:53 | 2024-08-16T08:48:04 | react-native-paper | callstack/react-native-paper | 12,646 | 584 |
```xml
import { createContext } from 'react';
import { Context } from './types';
export const context = createContext<Context<any> | null>(null);
``` | /content/code_sandbox/packages/uniforms/src/context.ts | xml | 2016-05-10T13:08:50 | 2024-08-13T11:27:18 | uniforms | vazco/uniforms | 1,934 | 31 |
```xml
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
EventEmitter,
Input,
OnDestroy,
OnInit,
Output,
ViewChild
} from '@angular/core';
import { TranslateService } from '@ngx-translate/core';
import { Store } from '@ngxs/store';
import { Application } from 'app/model/application.model';
import { Pipeline } from 'app/model/pipeline.model';
import { Project } from 'app/model/project.model';
import { WNode, Workflow } from 'app/model/workflow.model';
import { WorkflowNodeRun } from 'app/model/workflow.run.model';
import { ApplicationWorkflowService } from 'app/service/application/application.workflow.service';
import { PipelineService } from 'app/service/pipeline/pipeline.service';
import { VariableService } from 'app/service/variable/variable.service';
import { AutoUnsubscribe } from 'app/shared/decorator/autoUnsubscribe';
import { ParameterEvent } from 'app/shared/parameter/parameter.event.model';
import { ToastService } from 'app/shared/toast/ToastService';
import { PreferencesState } from 'app/store/preferences.state';
import { ProjectState } from 'app/store/project.state';
import { UpdateWorkflow } from 'app/store/workflow.action';
import { WorkflowState } from 'app/store/workflow.state';
import cloneDeep from 'lodash-es/cloneDeep';
import { Subscription } from 'rxjs';
import { finalize, first } from 'rxjs/operators';
declare let CodeMirror: any;
@Component({
selector: 'app-workflow-node-input',
templateUrl: './wizard.input.html',
styleUrls: ['./wizard.input.scss'],
changeDetection: ChangeDetectionStrategy.OnPush
})
@AutoUnsubscribe()
export class WorkflowWizardNodeInputComponent implements OnInit, OnDestroy {
@Input() workflow: Workflow;
@Input() readonly = true;
@Output() inputChange = new EventEmitter<boolean>();
@ViewChild('textareaCodeMirror') codemirror: any;
project: Project;
editMode: boolean;
noderun: WorkflowNodeRun;
editableNode: WNode;
nodeSub: Subscription;
suggest: string[] = [];
payloadString: string;
branches: string[] = [];
invalidJSON = false;
loadingBranches = false;
codeMirrorConfig: any;
pipParamsReady = false;
currentPipeline: Pipeline;
remotes: string[] = [];
tags: string[] = [];
loading: boolean;
themeSubscription: Subscription;
constructor(
private _store: Store,
private _variableService: VariableService,
private _appWorkflowService: ApplicationWorkflowService,
private _translate: TranslateService,
private _toast: ToastService,
private _cd: ChangeDetectorRef,
private _pipelineService: PipelineService
) {
this.project = this._store.selectSnapshot(ProjectState.projectSnapshot);
this.editMode = this._store.selectSnapshot(WorkflowState).editMode;
}
ngOnDestroy(): void { } // Should be set to use @AutoUnsubscribe with AOT
ngOnInit(): void {
this.noderun = this._store.selectSnapshot(WorkflowState).workflowNodeRun;
this.nodeSub = this._store.select(WorkflowState.getSelectedNode()).subscribe(n => {
this.editableNode = cloneDeep(n);
if (this.editableNode) {
this.init();
} else if (this.noderun) {
this.payloadString = JSON.stringify(this.noderun.payload, undefined, 4);
}
this._cd.markForCheck();
});
this.codeMirrorConfig = {
matchBrackets: true,
autoCloseBrackets: true,
mode: 'application/json',
lineWrapping: true,
autoRefresh: true,
readOnly: this.readonly
};
this.themeSubscription = this._store.select(PreferencesState.theme)
.pipe(finalize(() => this._cd.markForCheck()))
.subscribe(t => {
this.codeMirrorConfig.theme = t === 'night' ? 'darcula' : 'default';
if (this.codemirror && this.codemirror.instance) {
this.codemirror.instance.setOption('theme', this.codeMirrorConfig.theme);
}
});
}
init(): void {
if (!this.editableNode.context.default_payload) {
this.editableNode.context.default_payload = {};
}
this.suggest = [];
this._variableService.getContextVariable(this.project.key, this.editableNode.context.pipeline_id)
.subscribe((suggest) => this.suggest = suggest);
// TODO delete .repository_fullname condition and update handler to get history branches of node_run (issue: #1815)
let app = Workflow.getApplication(this.workflow, this.editableNode);
if (this.editableNode.context && app && app.repository_fullname) {
this.loadingBranches = true;
this.refreshVCSInfos(app);
}
this.payloadString = JSON.stringify(this.editableNode.context.default_payload, undefined, 4);
let pipeline = Workflow.getPipeline(this.workflow, this.editableNode);
if (pipeline) {
this._pipelineService.getPipeline(this.project.key, pipeline.name)
.pipe(first()).subscribe(p => {
this.currentPipeline = p;
this.pipParamsReady = true;
this.editableNode.context.default_pipeline_parameters =
cloneDeep(Pipeline.mergeAndKeepOld(p.parameters, this.editableNode.context.default_pipeline_parameters));
try {
this.editableNode.context.default_payload = JSON.parse(this.payloadString);
this.invalidJSON = false;
} catch (e) {
this.invalidJSON = true;
}
if (!this.editableNode.context.default_payload) {
this.editableNode.context.default_payload = {};
}
this._cd.markForCheck();
});
}
}
pushEvent(): void {
this.inputChange.emit(true);
}
parameterEvent(event: ParameterEvent) {
this.pushEvent();
}
changeCodeMirror(eventRoot: any, sendEvent: boolean): void {
if (eventRoot.type !== 'click' && eventRoot.type !== 'change') {
this.updateValue(eventRoot);
}
if (!this.codemirror || !this.codemirror.instance) {
return;
}
if (eventRoot.type === 'click') {
this.showHint(this.codemirror.instance, null);
}
this.codemirror.instance.on('keyup', (cm, event) => {
if (!cm.state.completionActive && event.keyCode !== 32) {
this.showHint(cm, event);
}
});
}
refreshVCSInfos(app: Application, remote?: string) {
this._appWorkflowService.getVCSInfos(this.project.key, app.name, remote)
.pipe(finalize(() => {
this.loadingBranches = false;
this._cd.markForCheck();
}))
.subscribe((vcsInfos) => {
if (vcsInfos.branches) {
this.branches = vcsInfos.branches.map((br) => '"' + br.display_id + '"');
}
if (vcsInfos.remotes) {
this.remotes = vcsInfos.remotes.map((rem) => '"' + rem.fullname + '"');
}
if (vcsInfos.tags) {
this.tags = vcsInfos.tags.map((tag) => '"' + tag.tag + '"');
}
});
}
updateValue(payload): void {
if (this.noderun) {
return;
}
let newPayload: {};
if (!payload) {
return;
}
let previousPayload = JSON.stringify(cloneDeep(this.editableNode.context.default_payload), undefined, 4);
try {
newPayload = JSON.parse(payload);
this.invalidJSON = false;
} catch (e) {
this.invalidJSON = true;
return;
}
this.payloadString = JSON.stringify(newPayload, undefined, 4);
this.editableNode.context.default_payload = JSON.parse(this.payloadString);
if (previousPayload !== payload) {
this.pushEvent();
}
}
showHint(cm, event) {
CodeMirror.showHint(this.codemirror.instance, CodeMirror.hint.payload, {
completeSingle: true,
closeCharacters: / /,
payloadCompletionList: {
branches: this.branches,
repositories: this.remotes,
tags: this.tags,
},
specialChars: ''
});
}
updateWorkflow(): void {
this.loading = true;
let clonedWorkflow = cloneDeep(this.workflow);
let n: WNode;
if (this.editMode) {
n = Workflow.getNodeByRef(this.editableNode.ref, clonedWorkflow);
} else {
n = Workflow.getNodeByID(this.editableNode.id, clonedWorkflow);
}
n.context.default_payload = this.editableNode.context.default_payload;
n.context.default_pipeline_parameters = this.editableNode.context.default_pipeline_parameters;
if (n.context.default_pipeline_parameters) {
n.context.default_pipeline_parameters.forEach(p => {
p.value = p.value.toString();
});
}
this._store.dispatch(new UpdateWorkflow({
projectKey: this.workflow.project_key,
workflowName: this.workflow.name,
changes: clonedWorkflow
})).pipe(finalize(() => {
this.loading = false;
this._cd.markForCheck();
}))
.subscribe(() => {
this.inputChange.emit(false);
if (this.editMode) {
this._toast.info('', this._translate.instant('workflow_ascode_updated'));
} else {
this._toast.success('', this._translate.instant('workflow_updated'));
}
});
}
}
``` | /content/code_sandbox/ui/src/app/shared/workflow/wizard/input/wizard.input.component.ts | xml | 2016-10-11T08:28:23 | 2024-08-16T01:55:31 | cds | ovh/cds | 4,535 | 2,036 |
```xml
import { writeFile } from 'fs';
import { escapeJsStr, indent } from './util';
export interface Test {
name: string;
code: string;
defaultRequestId: string | null;
}
export interface TestSuite {
name: string;
suites: TestSuite[];
tests?: Test[];
}
export const generate = (suites: TestSuite[]) => {
const lines = [
'const { expect } = chai;',
'',
'// Clear active request before test starts (will be set inside test)',
'beforeEach(() => insomnia.clearActiveRequest());',
'',
];
for (const s of suites || []) {
lines.push(...generateSuiteLines(0, s));
}
return lines.join('\n');
};
export const generateToFile = async (
filepath: string,
suites: TestSuite[],
) => {
return new Promise<void>((resolve, reject) => {
const js = generate(suites);
return writeFile(filepath, js, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
};
const generateSuiteLines = (
n: number,
suite?: TestSuite | null,
) => {
if (!suite) {
return [];
}
const lines: string[] = [];
lines.push(indent(n, `describe('${escapeJsStr(suite.name)}', () => {`));
const suites = suite.suites || [];
for (let i = 0; i < suites.length; i++) {
if (i !== 0) {
lines.push('');
}
lines.push(...generateSuiteLines(n + 1, suites[i]));
}
const tests = suite.tests || [];
for (let i = 0; i < tests.length; i++) {
// Add blank like if
// - it's the first test
// - we've outputted suites above
if (suites.length > 0 || i !== 0) {
lines.push('');
}
lines.push(...generateTestLines(n + 1, tests[i]));
}
lines.push(indent(n, '});'));
return lines;
};
const generateTestLines = (num: number, test?: Test | null) => {
if (!test) {
return [];
}
const lines: string[] = [];
// Define test it() block (all test cases are async by default)
lines.push(indent(num, `it('${escapeJsStr(test.name)}', async () => {`));
// Add helper variables that are necessary
const { defaultRequestId } = test;
if (typeof defaultRequestId === 'string') {
lines.push(indent(num, '// Set active request on global insomnia object'));
lines.push(
indent(num, `insomnia.setActiveRequestId('${defaultRequestId}');`),
);
}
// Add user-defined test source
test.code && lines.push(indent(num + 1, test.code));
// Close the it() block
lines.push(indent(num, '});'));
return lines;
};
``` | /content/code_sandbox/packages/insomnia-testing/src/generate/generate.ts | xml | 2016-04-23T03:54:26 | 2024-08-16T16:50:44 | insomnia | Kong/insomnia | 34,054 | 647 |
```xml
<!--
Description: entry author url relative to Content-Location header, ignoring sibling base, and resolving absolute path.
-->
<feed xmlns="path_to_url" xml:base="path_to_url">
<entry>
<author>
<name xml:base="path_to_url">Name</name>
<uri>/relative/link</uri>
</author>
</entry>
</feed>
``` | /content/code_sandbox/testdata/parser/atom/feed_entry_author_uri_base.xml | xml | 2016-01-23T02:44:34 | 2024-08-16T15:16:03 | gofeed | mmcdole/gofeed | 2,547 | 83 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
<file source-language="en" target-language="ru" datatype="plaintext" original="teams.en.xlf">
<body>
<trans-unit id="A_4Fc7c" resname="teams.project_access">
<source>teams.project_access</source>
<target> </target>
</trans-unit>
<trans-unit id="QchGnbx" resname="teams.customer_access">
<source>teams.customer_access</source>
<target> </target>
</trans-unit>
<trans-unit id=".yIcFDx" resname="team.visibility_global">
<source>team.visibility_global</source>
<target> , .</target>
</trans-unit>
<trans-unit id="hlIIRjb" resname="team.visibility_restricted">
<source>team.visibility_restricted</source>
<target> .</target>
</trans-unit>
<trans-unit id="sx7AVYH" resname="team.project_visibility_inherited">
<source>team.project_visibility_inherited</source>
<target> , .</target>
</trans-unit>
<trans-unit id="FC4DW27" resname="team.activity_visibility_inherited">
<source>team.activity_visibility_inherited</source>
<target> , / .</target>
</trans-unit>
<trans-unit id="cZEIdcu" resname="team.create_default">
<source>team.create_default</source>
<target> </target>
</trans-unit>
<trans-unit id="6g81kYY" approved="no" resname="team.member">
<source>team.member</source>
<target state="translated"></target>
</trans-unit>
</body>
</file>
</xliff>
``` | /content/code_sandbox/translations/teams.ru.xlf | xml | 2016-10-20T17:06:34 | 2024-08-16T18:27:30 | kimai | kimai/kimai | 3,084 | 441 |
```xml
export default function(number: number, index: number): [string, string] {
return [
['xusto agora', 'daqu a un pouco'],
['hai %s segundos', 'en %s segundos'],
['hai 1 minuto', 'nun minuto'],
['hai %s minutos', 'en %s minutos'],
['hai 1 hora', 'nunha hora'],
['hai %s horas', 'en %s horas'],
['hai 1 da', 'nun da'],
['hai %s das', 'en %s das'],
['hai 1 semana', 'nunha semana'],
['hai %s semanas', 'en %s semanas'],
['hai 1 mes', 'nun mes'],
['hai %s meses', 'en %s meses'],
['hai 1 ano', 'nun ano'],
['hai %s anos', 'en %s anos'],
][index] as [string, string];
}
``` | /content/code_sandbox/src/lang/gl.ts | xml | 2016-06-23T02:06:23 | 2024-08-16T02:07:26 | timeago.js | hustcc/timeago.js | 5,267 | 206 |
```xml
import { extend } from '../core/util';
import { getDepthFunc } from '../core/util/gl';
import Browser from '../core/Browser';
import Point from '../geo/Point';
import ImageGLRenderable from '../renderer/layer/ImageGLRenderable';
import CanvasRenderer from '../renderer/layer/CanvasRenderer';
import { ResourceCache } from '../renderer/layer/CanvasRenderer';
import Extent from '../geo/Extent';
import Layer, { LayerOptionsType } from './Layer';
import { PointExtent } from '../geo';
/**
*
*
* @english
* @property options - ImageLayer's options
* @property options.crossOrigin=null - image's corssOrigin
* @property options.renderer=gl - ImageLayer's renderer, canvas or gl. gl tiles requires image CORS that canvas doesn't. canvas tiles can't pitch.
* @property options.alphaTest=0 - only for gl renderer, pixels alpha <= alphaTest will be discarded
* @property options.depthMask=true - only for gl renderer, whether to write into depth buffer
* @property options.depthFunc=String - only for gl renderer, depth function, available values: never,<, =, <=, >, !=, >=, always
* @memberOf ImageLayer
* @instance
*/
const options: ImageLayerOptionsType = {
renderer: Browser.webgl ? 'gl' : 'canvas',
crossOrigin: null,
alphaTest: false,
depthMask: true,
depthFunc: '<='
};
const TEMP_POINT = new Point(0, 0);
/**
* images layer,
*
* @english
* @classdesc
* A layer used to display images, you can specify each image's geographic extent and opacity
* @category layer
* @extends Layer
* @param id - tile layer's id
* @param images=null - images
* @param options=null - options defined in [ImageLayer]{@link ImageLayer#options}
* @example
* new ImageLayer("images", [{
url : 'path_to_url
extent: [xmin, ymin, xmax, ymax],
opacity : 1
}])
*/
class ImageLayer extends Layer {
//@internal
_images: Array<ImageItem>;
//@internal
_imageData: Array<ImageDataItem>;
constructor(id: string, images?: ImageLayerOptionsType | Array<ImageItem>, options?: ImageLayerOptionsType) {
if (images && !Array.isArray(images) && !(images as ImageItem).url) {
options = images;
images = null;
}
super(id, options);
this._images = images as Array<ImageItem>;
}
onAdd() {
this._prepareImages(this._images);
}
/**
*
*
* @english
* Set images and redraw
* @param images - new images
* @return this
*/
setImages(images: Array<ImageItem>) {
this._images = images;
this._prepareImages(images);
return this;
}
/**
*
*
* @english
* Get images
* @return
*/
getImages(): Array<ImageItem> {
return this._images;
}
//@internal
_prepareImages(images: Array<ImageItem>) {
images = images || [];
if (!Array.isArray(images)) {
images = [images];
}
const map = this.getMap();
const glRes = map.getGLRes();
this._imageData = images.map(img => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore /src/geo/Extent.js -> ts
const extent = new Extent(img.extent);
return extend({}, img, {
extent: extent,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore /src/geo/Extent.js -> ts out
extent2d: extent.convertTo(c => map.coordToPointAtRes(c, glRes))
});
});
this._images = images;
const renderer = this.getRenderer();
if (renderer) {
renderer.refreshImages();
}
}
getRenderer() {
return super.getRenderer() as ImageLayerCanvasRenderer;
}
}
ImageLayer.mergeOptions(options);
const EMPTY_ARRAY = [];
export class ImageLayerCanvasRenderer extends CanvasRenderer {
//@internal
_imageLoaded: boolean
isDrawable() {
if (this.getMap().getPitch()) {
if (console) {
console.warn('ImageLayer with canvas renderer can\'t be pitched, use gl renderer (\'renderer\' : \'gl\') instead.');
}
return false;
}
return true;
}
checkResources() {
if (this._imageLoaded) {
return EMPTY_ARRAY;
}
const layer = this.layer;
let urls = layer._imageData.map(img => [img.url, null, null]);
if (this.resources) {
const unloaded = [];
const resources = new ResourceCache();
urls.forEach(url => {
if (this.resources.isResourceLoaded(url)) {
const img = this.resources.getImage(url);
resources.addResource(url, img);
} else {
unloaded.push(url);
}
});
this.resources.forEach((url, res) => {
if (!resources.isResourceLoaded(url)) {
this.retireImage(res.image);
}
});
this.resources = resources;
urls = unloaded;
}
this._imageLoaded = true;
return urls;
}
retireImage(image: LayerImageType) {
const img = image as ImageBitmap;
if (img.close) {
img.close();
}
}
refreshImages() {
this._imageLoaded = false;
this.setToRedraw();
}
draw(timestamp?: number, context?: any) {
if (!this.isDrawable()) {
return;
}
this.prepareCanvas();
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._painted = false;
this._drawImages(timestamp, context);
this.completeRender();
}
//@internal
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_drawImages(timestamp?: number, context?: any) {
const imgData = this.layer._imageData;
const map = this.getMap();
const mapExtent = map.get2DExtentAtRes(map.getGLRes());
if (imgData && imgData.length) {
for (let i = 0; i < imgData.length; i++) {
const extent = imgData[i].extent2d;
const image = this.resources && this.resources.getImage(imgData[i].url);
if (image && mapExtent.intersects(extent)) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
this._painted = true;
this._drawImage(image, extent, imgData[i].opacity || 1);
}
}
}
}
//@internal
_drawImage(image: LayerImageType, extent: PointExtent, opacity: number) {
let globalAlpha = 0;
const ctx = this.context;
if (opacity < 1) {
globalAlpha = ctx.globalAlpha;
ctx.globalAlpha = opacity;
}
const map = this.getMap();
const nw = TEMP_POINT.set(extent.xmin, extent.ymax);
const point = map._pointAtResToContainerPoint(nw, map.getGLRes());
let x = point.x, y = point.y;
const bearing = map.getBearing();
if (bearing) {
ctx.save();
ctx.translate(x, y);
if (bearing) {
ctx.rotate(-bearing * Math.PI / 180);
}
x = y = 0;
}
const scale = map.getGLScale();
ctx.drawImage(image, x, y, extent.getWidth() / scale, extent.getHeight() / scale);
if (bearing) {
ctx.restore();
}
if (globalAlpha) {
ctx.globalAlpha = globalAlpha;
}
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
drawOnInteracting(event?: any, timestamp?: number, context?: any) {
this.draw();
}
}
export class ImageLayerGLRenderer extends ImageGLRenderable(ImageLayerCanvasRenderer) {
drawOnInteracting(event: any, timestamp: number, context: any) {
this.draw(timestamp, context);
}
//@internal
_prepareGLContext() {
const gl = this.gl;
if (gl) {
gl.disable(gl.STENCIL_TEST);
gl.disable(gl.POLYGON_OFFSET_FILL);
gl.enable(gl.DEPTH_TEST);
gl.enable(gl.BLEND);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
gl.depthFunc(getDepthFunc(this.layer.options['depthFunc']));
const depthMask = !!this.layer.options['depthMask'];
gl.depthMask(depthMask);
}
}
//@internal
_drawImages(timestamp?: number, parentContext?: any) {
const gl = this.gl;
if (parentContext && parentContext.renderTarget) {
const fbo = parentContext.renderTarget.fbo;
if (fbo) {
const framebuffer = parentContext.renderTarget.getFramebuffer(fbo);
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
}
}
this._prepareGLContext();
super._drawImages();
if (parentContext && parentContext.renderTarget) {
const fbo = parentContext.renderTarget.fbo;
if (fbo) {
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
}
}
}
//override to set to always drawable
isDrawable() {
return true;
}
//@internal
_drawImage(image: LayerImageType, extent: PointExtent, opacity: number) {
this.drawGLImage(image, extent.xmin, extent.ymax, extent.getWidth(), extent.getHeight(), 1, opacity);
}
createContext() {
this.createGLContext();
}
resizeCanvas(canvasSize) {
if (!this.canvas) {
return;
}
super.resizeCanvas(canvasSize);
this.resizeGLCanvas();
}
clearCanvas() {
if (!this.canvas) {
return;
}
super.clearCanvas();
this.clearGLCanvas();
}
retireImage(image: LayerImageType) {
const img = image as ImageBitmap;
if (img.close) {
img.close();
}
this.disposeImage(image);
}
onRemove() {
this.removeGLCanvas();
super.onRemove();
}
}
ImageLayer.registerRenderer('canvas', ImageLayerCanvasRenderer);
ImageLayer.registerRenderer('gl', ImageLayerGLRenderer);
export default ImageLayer;
export type ImageItem = {
url: string,
extent: Extent | [number, number, number, number],
opacity?: number
}
export type ImageDataItem = ImageItem & {
extent2d: PointExtent;
}
export type LayerImageType = HTMLImageElement | ImageBitmap;
enum depthFuncEnum {
'never', '<', '=', '<=', ' >', '!=', '>=', 'always'
}
export type ImageLayerOptionsType = LayerOptionsType & {
crossOrigin?: string,
renderer?: 'canvas' | 'gl' | 'dom',
alphaTest?: boolean,
depthMask?: boolean,
depthFunc?: keyof typeof depthFuncEnum
}
``` | /content/code_sandbox/src/layer/ImageLayer.ts | xml | 2016-02-03T02:41:32 | 2024-08-15T16:51:49 | maptalks.js | maptalks/maptalks.js | 4,272 | 2,448 |
```xml
//
//
// path_to_url
//
// Unless required by applicable law or agreed to in writing, software
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { provideHttpClientTesting } from '@angular/common/http/testing';
import { MaterialModule } from 'src/app/material.module';
import { BackendService } from 'src/app/shared/services/backend.service';
import ContactComponent from './contact.component';
describe('ContactComponent', () => {
let component: ContactComponent;
let fixture: ComponentFixture<ContactComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ContactComponent],
imports: [MaterialModule],
providers: [
BackendService,
provideHttpClient(),
provideHttpClientTesting(),
],
}).compileComponents();
fixture = TestBed.createComponent(ContactComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
``` | /content/code_sandbox/console-webapp/src/app/settings/contact/contact.component.spec.ts | xml | 2016-02-29T20:16:48 | 2024-08-15T19:49:29 | nomulus | google/nomulus | 1,685 | 217 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="path_to_url" xmlns:xsi="path_to_url" xsi:schemaLocation="path_to_url path_to_url">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.vladsch.flexmark</groupId>
<artifactId>flexmark-java</artifactId>
<version>0.64.8</version>
</parent>
<artifactId>flexmark-ext-gfm-tasklist</artifactId>
<name>flexmark-java extension for generating GitHub style task list items</name>
<description>flexmark-java extension to convert bullet list items that start with [ ] to a TaskListItem node</description>
<dependencies>
<dependency>
<groupId>com.vladsch.flexmark</groupId>
<artifactId>flexmark-util</artifactId>
</dependency>
<dependency>
<groupId>com.vladsch.flexmark</groupId>
<artifactId>flexmark</artifactId>
</dependency>
<dependency>
<groupId>com.vladsch.flexmark</groupId>
<artifactId>flexmark-test-util</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.vladsch.flexmark</groupId>
<artifactId>flexmark-core-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
``` | /content/code_sandbox/flexmark-ext-gfm-tasklist/pom.xml | xml | 2016-01-23T15:29:29 | 2024-08-15T04:04:18 | flexmark-java | vsch/flexmark-java | 2,239 | 327 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<issues format="6" by="lint 8.4.0-alpha06" type="baseline" client="gradle" dependencies="false" name="AGP (8.4.0-alpha06)" variant="all" version="8.4.0-alpha06">
<issue
id="RetrofitUsage"
message="This annotation requires an `@Body` parameter."
errorLine1=" @POST("image")"
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="src/debug/kotlin/catchup/app/ui/bugreport/BugReportApi.kt"
line="43"
column="3"/>
</issue>
<issue
id="VectorRaster"
message="Limit vector icons sizes to 200200 to keep icon drawing fast; see path_to_url#when for more"
errorLine1=" android:height="213dp""
errorLine2=" ~~~~~">
<location
file="src/main/res/drawable/no_connection.xml"
line="18"
column="21"/>
</issue>
<issue
id="Untranslatable"
message="The resource string "app_name" is marked as translatable="false", but is translated to "de" (German) here"
errorLine1=" <string name="app_name" translatable="false">CatchUp</string>"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/values-de/strings.xml"
line="18"
column="27"/>
</issue>
<issue
id="Untranslatable"
message="The resource string "app_name" is marked as translatable="false", but is translated to "fr" (French) here"
errorLine1=" <string name="app_name" translatable="false">CatchUp</string>"
errorLine2=" ~~~~~~~~~~~~~~~~~~~~">
<location
file="src/main/res/values-fr/strings.xml"
line="18"
column="27"/>
</issue>
<issue
id="AutoboxingStateCreation"
message="Prefer `mutableFloatStateOf` instead of `mutableStateOf`"
errorLine1=" val offsetState = mutableStateOf(0f)"
errorLine2=" ~~~~~~~~~~~~~~">
<location
file="src/main/kotlin/catchup/app/ui/activity/FlickToDismiss.kt"
line="90"
column="21"/>
</issue>
<issue
id="HardcodedText"
message="Hardcoded string "Your GitHub username", should use `@string` resource"
errorLine1=" android:hint="Your GitHub username""
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/debug/res/layout/bugreport_view.xml"
line="32"
column="7"/>
</issue>
<issue
id="HardcodedText"
message="Hardcoded string "What's the problem?", should use `@string` resource"
errorLine1=" android:hint="What's the problem?""
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/debug/res/layout/bugreport_view.xml"
line="42"
column="7"/>
</issue>
<issue
id="HardcodedText"
message="Hardcoded string "Additional details", should use `@string` resource"
errorLine1=" android:hint="Additional details""
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/debug/res/layout/bugreport_view.xml"
line="53"
column="7"/>
</issue>
<issue
id="HardcodedText"
message="Hardcoded string "Include screenshot?", should use `@string` resource"
errorLine1=" android:text="Include screenshot?""
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/debug/res/layout/bugreport_view.xml"
line="63"
column="7"/>
</issue>
<issue
id="HardcodedText"
message="Hardcoded string "Include logs?", should use `@string` resource"
errorLine1=" android:text="Include logs?""
errorLine2=" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~">
<location
file="src/debug/res/layout/bugreport_view.xml"
line="73"
column="7"/>
</issue>
</issues>
``` | /content/code_sandbox/app-scaffold/lint-baseline.xml | xml | 2016-04-25T09:33:27 | 2024-08-16T02:22:21 | CatchUp | ZacSweers/CatchUp | 1,958 | 1,068 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<IsPackable>false</IsPackable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.Core" Version="3.7.200.18" />
<PackageReference Include="AWSSDK.S3" Version="3.7.201.16" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
<PackageReference Include="Moq" Version="4.16.1" />
<PackageReference Include="MSTest.TestAdapter" Version="2.2.8" />
<PackageReference Include="MSTest.TestFramework" Version="2.2.8" />
<PackageReference Include="coverlet.collector" Version="3.1.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\S3_Basics\S3_BasicsScenario.csproj" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/dotnetv3/S3/S3_BasicsScenarioTests/S3_BasicsScenarioTests.csproj | xml | 2016-08-18T19:06:57 | 2024-08-16T18:59:44 | aws-doc-sdk-examples | awsdocs/aws-doc-sdk-examples | 9,298 | 358 |
```xml
import { useCallback, useEffect, useState } from 'react';
import _debounce from '@proton/utils/debounce';
export const useDebouncedValue = <T extends string | number>(valueIn: T, time: number): T => {
const [valueOut, setValueOut] = useState(valueIn);
const debounce = useCallback(
_debounce((value) => setValueOut(value), time, { leading: true }),
[time]
);
useEffect(() => debounce(valueIn), [valueIn]);
useEffect(() => () => debounce.cancel(), []);
return valueOut;
};
``` | /content/code_sandbox/packages/pass/hooks/useDebouncedValue.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 125 |
```xml
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Version>3.5.2</Version>
<AssemblyVersion>3.5.2.0</AssemblyVersion>
<FileVersion>3.5.2.0</FileVersion>
<Description>Facilitates testing of workflows built on Workflow-Core</Description>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="3.1.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="3.1.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="3.1.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\WorkflowCore.DSL\WorkflowCore.DSL.csproj" />
<ProjectReference Include="..\..\src\WorkflowCore\WorkflowCore.csproj" />
</ItemGroup>
</Project>
``` | /content/code_sandbox/src/WorkflowCore.Testing/WorkflowCore.Testing.csproj | xml | 2016-11-15T23:32:24 | 2024-08-16T06:12:22 | workflow-core | danielgerlag/workflow-core | 5,247 | 215 |
```xml
import { ArrowRight } from "lucide-react"
import { ICategory } from "@/types/product.types"
import { Button } from "@/components/ui/button"
const SubCategory = ({
subCats,
name,
chooseCat,
_id,
}: ICategory & {
subCats: ICategory[]
chooseCat: (string: string) => void
}) => {
return (
<div className="">
<div className="text-sm leading-none font-semibold pb-1">{name}</div>
{subCats.length > 0 && (
<div className="pb-1 text-sm text-slate-500">
{subCats.map((e) => (
<div
key={e._id}
className="font-medium hover:text-primary cursor-pointer"
onClick={() => chooseCat(e._id)}
>
{e.name}
</div>
))}
</div>
)}
<Button
variant={"link"}
className="h-auto p-0 font-semibold"
onClick={() => chooseCat(_id)}
>
<ArrowRight className="h-4 w-4 ml-1" />
</Button>
</div>
)
}
export default SubCategory
``` | /content/code_sandbox/pos/modules/products/components/SubCategory.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 263 |
```xml
import { getLogger } from '@jitsi/logger';
const logger = getLogger(__filename);
/**
* Discovers component versions in a conference.
*/
export default class ComponentsVersions {
versions: {[key: string]: string};
conference: any;
/**
* Creates new instance of <tt>ComponentsVersions</tt> which will be discovering
* the versions of conferencing system components in given
* <tt>JitsiConference</tt>.
* @param conference <tt>JitsiConference</tt> instance which will be used to
* listen for focus presence updates.
* @constructor
*/
constructor(conference) {
this.versions = {};
this.conference = conference;
this.conference.addCommandListener('versions', this._processVersions.bind(this));
}
/**
* Processes versions information from presence.
*
* @param {*} versions - The versions element.
* @param {*} mucJid - MUC JID for the sender.
* @returns {void}
*/
_processVersions(versions, _, mucJid) {
if (!this.conference.isFocus(mucJid)) {
logger.warn(
`Received versions not from the focus user: ${versions}`,
mucJid);
return;
}
versions.children.forEach(component => {
const name = component.attributes.name;
const version = component.value;
if (this.versions[name] !== version) {
this.versions[name] = version;
logger.info(`Got ${name} version: ${version}`);
}
});
}
/**
* Obtains the version of conferencing system component.
* @param componentName the name of the component for which we want to obtain
* the version.
* @returns {String} which describes the version of the component identified by
* given <tt>componentName</tt> or <tt>undefined</tt> if not found.
*/
getComponentVersion(componentName) {
return this.versions[componentName];
}
}
``` | /content/code_sandbox/modules/version/ComponentsVersions.ts | xml | 2016-01-27T22:44:09 | 2024-08-16T02:51:56 | lib-jitsi-meet | jitsi/lib-jitsi-meet | 1,328 | 435 |
```xml
<?xml version="1.0"?>
<response status="success">
<result>
<devices>
<entry name="target1">
<serial>target1</serial>
<connected>yes</connected>
<multi-vsys>yes</multi-vsys>
<vsys>
<entry name="vsys1"/>
<entry name="vsys2"/>
</vsys>
</entry>
<entry name="target2">
<serial>target2</serial>
<connected>yes</connected>
<multi-vsys>no</multi-vsys>
<vsys>
<entry name="vsys1"/>
</vsys>
</entry>
</devices>
</result>
</response>
``` | /content/code_sandbox/Packs/PAN-OS/Integrations/Panorama/test_data/devices_list.xml | xml | 2016-06-06T12:17:02 | 2024-08-16T11:52:59 | content | demisto/content | 1,108 | 163 |
```xml
import Joi from "joi";
import { AppOptions } from "coral-server/app";
import { validate } from "coral-server/app/request/body";
import { RequestLimiter } from "coral-server/app/request/limiter";
import { decodeJWT, extractTokenFromRequest } from "coral-server/services/jwt";
import {
redeem,
verifyInviteTokenString,
} from "coral-server/services/users/auth/invite";
import { RequestHandler, TenantCoralRequest } from "coral-server/types/express";
export type InviteCheckOptions = Pick<
AppOptions,
"mongo" | "signingConfig" | "redis" | "config"
>;
export const inviteCheckHandler = ({
redis,
signingConfig,
mongo,
config,
}: InviteCheckOptions): RequestHandler<TenantCoralRequest> => {
const ipLimiter = new RequestLimiter({
redis,
ttl: "10m",
max: 10,
prefix: "ip",
config,
});
const subLimiter = new RequestLimiter({
redis,
ttl: "5m",
max: 10,
prefix: "sub",
config,
});
return async (req, res, next) => {
try {
// Rate limit based on the IP address and user agent.
await ipLimiter.test(req, req.ip);
const { tenant, now } = req.coral;
// Grab the token from the request.
const tokenString = extractTokenFromRequest(req, true);
if (!tokenString) {
return res.sendStatus(400);
}
// Decode the token so we can rate limit based on the user's ID.
const { sub } = decodeJWT(tokenString);
if (sub) {
await subLimiter.test(req, sub);
}
// Verify the token.
await verifyInviteTokenString(
mongo,
tenant,
signingConfig,
tokenString,
now
);
return res.sendStatus(204);
} catch (err) {
return next(err);
}
};
};
export interface InviteBody {
username: string;
password: string;
}
export const InviteBodySchema = Joi.object().keys({
username: Joi.string().trim(),
password: Joi.string(),
});
export type InviteOptions = Pick<
AppOptions,
"mongo" | "signingConfig" | "redis" | "config"
>;
export const inviteHandler = ({
redis,
mongo,
signingConfig,
config,
}: InviteOptions): RequestHandler<TenantCoralRequest> => {
const ipLimiter = new RequestLimiter({
redis,
ttl: "10m",
max: 10,
prefix: "ip",
config,
});
const subLimiter = new RequestLimiter({
redis,
ttl: "5m",
max: 10,
prefix: "sub",
config,
});
return async (req, res, next) => {
try {
// Rate limit based on the IP address and user agent.
await ipLimiter.test(req, req.ip);
const { tenant, now } = req.coral;
// Grab the token from the request.
const tokenString = extractTokenFromRequest(req, true);
if (!tokenString) {
return res.sendStatus(400);
}
// Decode the token so we can rate limit based on the user's ID.
const { sub } = decodeJWT(tokenString);
if (sub) {
await subLimiter.test(req, sub);
}
// Get the fields from the body. Validate will throw an error if the body
// does not conform to the specification.
const { username, password }: InviteBody = validate(
InviteBodySchema,
req.body
);
// Redeem the invite to create the new user.
await redeem(
mongo,
tenant,
signingConfig,
tokenString,
{ username, password },
now
);
return res.sendStatus(204);
} catch (err) {
return next(err);
}
};
};
``` | /content/code_sandbox/server/src/core/server/app/handlers/api/account/invite.ts | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 875 |
```xml
#import "RNPermissionHandlerBluetooth.h"
#import <CoreBluetooth/CoreBluetooth.h>
@interface RNPermissionHandlerBluetooth() <CBPeripheralManagerDelegate>
@property (nonatomic, strong) CBPeripheralManager* manager;
@property (nonatomic, strong) void (^resolve)(RNPermissionStatus status);
@property (nonatomic, strong) void (^reject)(NSError *error);
@end
@implementation RNPermissionHandlerBluetooth
+ (NSArray<NSString *> * _Nonnull)usageDescriptionKeys {
return @[
@"NSBluetoothAlwaysUsageDescription",
@"NSBluetoothPeripheralUsageDescription",
];
}
+ (NSString * _Nonnull)handlerUniqueId {
return @"ios.permission.BLUETOOTH";
}
- (void)checkWithResolver:(void (^ _Nonnull)(RNPermissionStatus))resolve
rejecter:(void (__unused ^ _Nonnull)(NSError * _Nonnull))reject {
#if TARGET_OS_SIMULATOR
return resolve(RNPermissionStatusNotAvailable);
#else
if (@available(iOS 13.1, *)) {
switch ([CBManager authorization]) {
case CBManagerAuthorizationNotDetermined:
return resolve(RNPermissionStatusNotDetermined);
case CBManagerAuthorizationRestricted:
return resolve(RNPermissionStatusRestricted);
case CBManagerAuthorizationDenied:
return resolve(RNPermissionStatusDenied);
case CBManagerAuthorizationAllowedAlways:
return resolve(RNPermissionStatusAuthorized);
}
} else {
switch ([CBPeripheralManager authorizationStatus]) {
case CBPeripheralManagerAuthorizationStatusNotDetermined:
return resolve(RNPermissionStatusNotDetermined);
case CBPeripheralManagerAuthorizationStatusRestricted:
return resolve(RNPermissionStatusRestricted);
case CBPeripheralManagerAuthorizationStatusDenied:
return resolve(RNPermissionStatusDenied);
case CBPeripheralManagerAuthorizationStatusAuthorized:
return resolve(RNPermissionStatusAuthorized);
}
}
#endif
}
- (void)requestWithResolver:(void (^ _Nonnull)(RNPermissionStatus))resolve
rejecter:(void (^ _Nonnull)(NSError * _Nonnull))reject {
#if TARGET_OS_SIMULATOR
return resolve(RNPermissionStatusNotAvailable);
#else
_resolve = resolve;
_reject = reject;
_manager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil options:@{
CBPeripheralManagerOptionShowPowerAlertKey: @false,
}];
#endif
}
- (void)peripheralManagerDidUpdateState:(nonnull CBPeripheralManager *)peripheral {
switch (peripheral.state) {
case CBManagerStatePoweredOff:
case CBManagerStateResetting:
case CBManagerStateUnsupported:
return _resolve(RNPermissionStatusNotAvailable);
case CBManagerStateUnknown:
return _resolve(RNPermissionStatusNotDetermined);
case CBManagerStateUnauthorized:
return _resolve(RNPermissionStatusDenied);
case CBManagerStatePoweredOn:
return [self checkWithResolver:_resolve rejecter:_reject];
}
}
@end
``` | /content/code_sandbox/ios/Bluetooth/RNPermissionHandlerBluetooth.mm | xml | 2016-03-24T16:33:42 | 2024-08-15T16:56:05 | react-native-permissions | zoontek/react-native-permissions | 4,008 | 604 |
```xml
import { ShapeComponent as SC } from '../../runtime';
import { Color } from './color';
export type TriangleOptions = Record<string, any>;
/**
*
*/
export const Triangle: SC<TriangleOptions> = (options, context) => {
return Color(
{ colorAttribute: 'fill', symbol: 'triangle', ...options },
context,
);
};
Triangle.props = {
defaultMarker: 'triangle',
...Color.props,
};
``` | /content/code_sandbox/src/shape/point/triangle.ts | xml | 2016-05-26T09:21:04 | 2024-08-15T16:11:17 | G2 | antvis/G2 | 12,060 | 94 |
```xml
import { array, object, SchemaOf, string } from 'yup';
import { Values } from './types';
export function validation(): SchemaOf<Values> {
return array(
object({
name: string().required('Name is required'),
value: string().default(''),
})
);
}
``` | /content/code_sandbox/app/react/docker/containers/CreateView/LabelsTab/validation.ts | xml | 2016-05-19T20:15:28 | 2024-08-16T19:15:14 | portainer | portainer/portainer | 30,083 | 66 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions
xmlns="path_to_url"
xmlns:flowable="path_to_url"
targetNamespace="OneTaskCategory">
<process id="oneTaskProcess" name="The One Task Process">
<documentation>One task process description</documentation>
<startEvent id="theStart" />
<sequenceFlow id="flow1" sourceRef="theStart" targetRef="processTask" />
<userTask id="processTask" name="Process task" flowable:candidateGroups="sales">
<documentation>Process task description</documentation>
</userTask>
<sequenceFlow id="flow2" sourceRef="processTask" targetRef="processTask2" />
<userTask id="processTask2" name="Process task 2" flowable:candidateGroups="sales">
<documentation>Process task description</documentation>
</userTask>
<sequenceFlow id="flow3" sourceRef="processTask2" targetRef="theEnd" />
<endEvent id="theEnd" />
</process>
</definitions>
``` | /content/code_sandbox/modules/flowable-rest/src/test/resources/org/flowable/rest/service/api/history/HistoricTaskInstanceQueryResourceTest.testQueryTaskInstancesWithCandidateGroup.bpmn20.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 245 |
```xml
export = require("@xarc/webpack");
``` | /content/code_sandbox/packages/xarc-app-dev/src/config/webpack/index.ts | xml | 2016-09-06T19:02:39 | 2024-08-11T11:43:11 | electrode | electrode-io/electrode | 2,103 | 10 |
```xml
import type { PreparedStory } from '@storybook/core/types';
export interface View<TStorybookRoot> {
// Get ready to render a story, returning the element to render to
prepareForStory(story: PreparedStory<any>): TStorybookRoot;
prepareForDocs(): TStorybookRoot;
showErrorDisplay(err: { message?: string; stack?: string }): void;
showNoPreview(): void;
showPreparingStory(options?: { immediate: boolean }): void;
showPreparingDocs(options?: { immediate: boolean }): void;
showMain(): void;
showDocs(): void;
showStory(): void;
showStoryDuringRender(): void;
}
``` | /content/code_sandbox/code/core/src/preview-api/modules/preview-web/View.ts | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 140 |
```xml
/** @jsxRuntime automatic */
/** @jsxImportSource @fluentui/react-jsx-runtime */
import { assertSlots } from '@fluentui/react-utilities';
import type { SwitchState, SwitchSlots } from './Switch.types';
/**
* Render a Switch component by passing the state defined props to the appropriate slots.
*/
export const renderSwitch_unstable = (state: SwitchState) => {
assertSlots<SwitchSlots>(state);
const { labelPosition } = state;
return (
<state.root>
<state.input />
{labelPosition !== 'after' && state.label && <state.label />}
<state.indicator />
{labelPosition === 'after' && state.label && <state.label />}
</state.root>
);
};
``` | /content/code_sandbox/packages/react-components/react-switch/library/src/components/Switch/renderSwitch.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 159 |
```xml
import * as React from 'react';
import type { Meta } from '@storybook/react';
import { Button, CompoundButton, MenuButton, SplitButton, ToggleButton } from '@fluentui/react-button';
import type {
ButtonState,
CompoundButtonState,
MenuButtonState,
SplitButtonState,
ToggleButtonState,
} from '@fluentui/react-button';
import { FluentProvider, FluentProviderCustomStyleHooks } from '@fluentui/react-provider';
import { makeStyles, mergeClasses, shorthands } from '@griffel/react';
export default {
title: 'FluentProvider CustomStyleHooks',
component: FluentProvider,
} satisfies Meta<typeof FluentProvider>;
export const Default = () => <FluentProvider>Hello, world</FluentProvider>;
const useCustomStyles = makeStyles({
button: {
backgroundColor: 'red',
color: 'white',
...shorthands.borderWidth('4px'),
...shorthands.borderColor('crimson'),
...shorthands.borderRadius('0'),
},
});
export const ButtonCustomStyles = () => {
const styles = useCustomStyles();
const customStyleHooks: FluentProviderCustomStyleHooks = {
useButtonStyles_unstable: (state: unknown) => {
const componentState = state as ButtonState;
componentState.root.className = mergeClasses(componentState.root.className, styles.button);
},
};
return (
<FluentProvider customStyleHooks_unstable={customStyleHooks}>
<Button>Hello, world</Button>
</FluentProvider>
);
};
ButtonCustomStyles.storyName = 'Button';
export const CompoundButtonCustomStyles = () => {
const styles = useCustomStyles();
const customStyleHooks: FluentProviderCustomStyleHooks = {
useCompoundButtonStyles_unstable: (state: unknown) => {
const componentState = state as CompoundButtonState;
componentState.root.className = mergeClasses(componentState.root.className, styles.button);
},
};
return (
<FluentProvider customStyleHooks_unstable={customStyleHooks}>
<CompoundButton secondaryContent={'Another hello'}>Hello, world</CompoundButton>
</FluentProvider>
);
};
CompoundButtonCustomStyles.storyName = 'CompoundButton';
export const MenuButtonCustomStyles = () => {
const styles = useCustomStyles();
const customStyleHooks: FluentProviderCustomStyleHooks = {
useMenuButtonStyles_unstable: (state: unknown) => {
const componentState = state as MenuButtonState;
componentState.root.className = mergeClasses(componentState.root.className, styles.button);
},
};
return (
<FluentProvider customStyleHooks_unstable={customStyleHooks}>
<MenuButton>Hello, world</MenuButton>
</FluentProvider>
);
};
MenuButtonCustomStyles.storyName = 'MenuButton';
export const SplitButtonCustomStyles = () => {
const styles = useCustomStyles();
const customStyleHooks: FluentProviderCustomStyleHooks = {
useSplitButtonStyles_unstable: (state: unknown) => {
const componentState = state as SplitButtonState;
if (componentState.menuButton) {
componentState.menuButton.className = mergeClasses(componentState.menuButton.className, styles.button);
}
if (componentState.primaryActionButton) {
componentState.primaryActionButton.className = mergeClasses(
componentState.primaryActionButton.className,
styles.button,
);
}
},
};
return (
<FluentProvider customStyleHooks_unstable={customStyleHooks}>
<SplitButton>Hello, world</SplitButton>
</FluentProvider>
);
};
SplitButtonCustomStyles.storyName = 'SplitButton';
export const ToggleButtonCustomStyles = () => {
const styles = useCustomStyles();
const customStyleHooks: FluentProviderCustomStyleHooks = {
useToggleButtonStyles_unstable: (state: unknown) => {
const componentState = state as ToggleButtonState;
componentState.root.className = mergeClasses(componentState.root.className, styles.button);
},
};
return (
<FluentProvider customStyleHooks_unstable={customStyleHooks}>
<ToggleButton>Hello, world</ToggleButton>
</FluentProvider>
);
};
ToggleButtonCustomStyles.storyName = 'ToggleButton';
``` | /content/code_sandbox/apps/vr-tests-react-components/src/stories/CustomStyleHooks.stories.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 889 |
```xml
import { CameraType } from '@antv/g';
import { Renderer as WebGLRenderer } from '@antv/g-webgl';
import { Plugin as ThreeDPlugin, DirectionalLight } from '@antv/g-plugin-3d';
import { Plugin as ControlPlugin } from '@antv/g-plugin-control';
import { Runtime, corelib, extend } from '@antv/g2';
import { threedlib } from '@antv/g2-extension-3d';
// Create a WebGL renderer.
const renderer = new WebGLRenderer();
renderer.registerPlugin(new ThreeDPlugin());
renderer.registerPlugin(new ControlPlugin());
// Customize our own Chart with threedlib.
const Chart = extend(Runtime, { ...corelib(), ...threedlib() });
const chart = new Chart({
container: 'container',
renderer,
depth: 400, // Define the depth of chart.
});
chart
.point3D()
.data({
type: 'fetch',
value:
'path_to_url
})
.encode('x', 'Horsepower')
.encode('y', 'Miles_per_Gallon')
.encode('z', 'Weight_in_lbs')
.encode('color', 'Origin')
.encode('shape', 'cube')
.coordinate({ type: 'cartesian3D' })
.scale('x', { nice: true })
.scale('y', { nice: true })
.scale('z', { nice: true })
.legend(false)
.axis('x', { gridLineWidth: 2 })
.axis('y', { gridLineWidth: 2, titleBillboardRotation: -Math.PI / 2 })
.axis('z', { gridLineWidth: 2 });
chart.render().then(() => {
const { canvas } = chart.getContext();
const camera = canvas.getCamera();
// Use perspective projection mode.
camera.setPerspective(0.1, 5000, 45, 640 / 480);
camera.setType(CameraType.ORBITING);
// Add a directional light into scene.
const light = new DirectionalLight({
style: {
intensity: 3,
fill: 'white',
direction: [-1, 0, 1],
},
});
canvas.appendChild(light);
});
``` | /content/code_sandbox/site/examples/threed/scatter/demo/perspective-projection.ts | xml | 2016-05-26T09:21:04 | 2024-08-15T16:11:17 | G2 | antvis/G2 | 12,060 | 485 |
```xml
/**
*/
import type { User } from '@nextcloud/cypress'
import { nameVersion, openVersionsPanel, uploadThreeVersions, doesNotHaveAction, setupTestSharedFileFromUser } from './filesVersionsUtils'
import { getRowForFile } from '../files/FilesUtils'
describe('Versions naming', () => {
let randomFileName = ''
let user: User
before(() => {
randomFileName = Math.random().toString(36).replace(/[^a-z]+/g, '').substring(0, 10) + '.txt'
cy.createRandomUser()
.then((_user) => {
user = _user
uploadThreeVersions(user, randomFileName)
cy.login(user)
cy.visit('/apps/files')
openVersionsPanel(randomFileName)
})
})
it('Names the versions', () => {
nameVersion(2, 'v1')
cy.get('#tab-version_vue').within(() => {
cy.get('[data-files-versions-version]').eq(2).contains('v1')
cy.get('[data-files-versions-version]').eq(2).contains('Initial version').should('not.exist')
})
nameVersion(1, 'v2')
cy.get('#tab-version_vue').within(() => {
cy.get('[data-files-versions-version]').eq(1).contains('v2')
})
nameVersion(0, 'v3')
cy.get('#tab-version_vue').within(() => {
cy.get('[data-files-versions-version]').eq(0).contains('v3 (Current version)')
})
})
context('Name versions of shared file', () => {
context('with edit permission', () => {
before(() => {
setupTestSharedFileFromUser(user, randomFileName, { update: true })
openVersionsPanel(randomFileName)
})
it('Names the versions', () => {
nameVersion(2, 'v1 - shared')
cy.get('#tab-version_vue').within(() => {
cy.get('[data-files-versions-version]').eq(2).contains('v1 - shared')
cy.get('[data-files-versions-version]').eq(2).contains('Initial version').should('not.exist')
})
nameVersion(1, 'v2 - shared')
cy.get('#tab-version_vue').within(() => {
cy.get('[data-files-versions-version]').eq(1).contains('v2 - shared')
})
nameVersion(0, 'v3 - shared')
cy.get('#tab-version_vue').within(() => {
cy.get('[data-files-versions-version]').eq(0).contains('v3 - shared (Current version)')
})
})
})
context('without edit permission', () => {
it('Does not show action', () => {
setupTestSharedFileFromUser(user, randomFileName, { update: false })
openVersionsPanel(randomFileName)
cy.get('[data-files-versions-version]').eq(0).find('.action-item__menutoggle').should('not.exist')
cy.get('[data-files-versions-version]').eq(0).get('[data-cy-version-action="label"]').should('not.exist')
doesNotHaveAction(1, 'label')
doesNotHaveAction(2, 'label')
})
it('Does not work without update permission through direct API access', () => {
let hostname: string
let fileId: string|undefined
let versionId: string|undefined
setupTestSharedFileFromUser(user, randomFileName, { update: false })
.then(recipient => {
openVersionsPanel(randomFileName)
cy.url().then(url => { hostname = new URL(url).hostname })
getRowForFile(randomFileName).invoke('attr', 'data-cy-files-list-row-fileid').then(_fileId => { fileId = _fileId })
cy.get('[data-files-versions-version]').eq(1).invoke('attr', 'data-files-versions-version').then(_versionId => { versionId = _versionId })
cy.then(() => {
cy.logout()
cy.request({
method: 'PROPPATCH',
auth: { user: recipient.userId, pass: recipient.password },
headers: {
cookie: '',
},
body: `<?xml version="1.0"?>
<d:propertyupdate xmlns:d="DAV:"
xmlns:oc="path_to_url"
xmlns:nc="path_to_url"
xmlns:ocs="path_to_url">
<d:set>
<d:prop>
<nc:version-label>not authorized labeling</nc:version-label>
</d:prop>
</d:set>
</d:propertyupdate>`,
url: `path_to_url{hostname}/remote.php/dav/versions/${recipient.userId}/versions/${fileId}/${versionId}`,
failOnStatusCode: false,
})
.then(({ status }) => {
expect(status).to.equal(403)
})
})
})
})
})
})
})
``` | /content/code_sandbox/cypress/e2e/files_versions/version_naming.cy.ts | xml | 2016-06-02T07:44:14 | 2024-08-16T18:23:54 | server | nextcloud/server | 26,415 | 1,115 |
```xml
import { type FC, useEffect, useState } from 'react';
import { Card } from '@proton/atoms/Card';
import { type ModalProps, ModalTwoContent, ModalTwoHeader } from '@proton/components/components';
import { PassModal } from '@proton/pass/components/Layout/Modal/PassModal';
import { useSessionLockPinSubmitEffect } from '@proton/pass/hooks/useSessionLockPinSubmitEffect';
import { PinCodeInput } from './PinCodeInput';
type Props = Omit<ModalProps, 'onSubmit'> & {
title: string;
assistiveText?: string;
loading?: boolean;
onSubmit: (pin: string) => void;
};
export const PinUnlockModal: FC<Props> = ({ title, assistiveText, loading, onSubmit, ...modalProps }) => {
const [value, setValue] = useState<string>('');
useSessionLockPinSubmitEffect(value, { onSubmit });
useEffect(() => {
if (!modalProps.open) setValue('');
}, [modalProps.open]);
return (
<PassModal {...modalProps} size="small">
<ModalTwoHeader title={title} />
<ModalTwoContent className="mb-8">
{assistiveText && (
<Card rounded className="text-sm mb-7">
{assistiveText}
</Card>
)}
<PinCodeInput loading={loading} value={value} onValue={setValue} />
</ModalTwoContent>
</PassModal>
);
};
``` | /content/code_sandbox/packages/pass/components/Lock/PinUnlockModal.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 315 |
```xml
import { IContext, IModels } from '../../connectionResolver';
import { INTEGRATION_KINDS } from '../../constants';
import { sendInboxMessage } from '../../messageBroker';
import { IConversationMessageDocument } from '../../models/definitions/conversationMessages';
import { getPageList } from '../../utils';
interface IKind {
kind: string;
}
interface IDetailParams {
erxesApiId: string;
}
interface IConversationId {
conversationId: string;
}
interface IPageParams {
skip?: number;
limit?: number;
}
interface ICommentsParams extends IConversationId, IPageParams {
isResolved?: boolean;
commentId?: string;
senderId: string;
}
interface IMessagesParams extends IConversationId, IPageParams {
getFirst?: boolean;
}
const buildSelector = async (conversationId: string, model: any) => {
const query = { conversationId: '' };
const conversation = await model.findOne({
erxesApiId: conversationId,
});
if (conversation) {
query.conversationId = conversation._id;
}
return query;
};
const instagramQueries = {
async instagramGetAccounts(_root, { kind }: IKind, { models }: IContext) {
return models.Accounts.find({ kind });
},
async instagramGetIntegrations(_root, { kind }: IKind, { models }: IContext) {
return models.Integrations.find({ kind });
},
async instagramGetIntegrationDetail(
_root,
{ erxesApiId }: IDetailParams,
{ models }: IContext,
) {
return models.Integrations.findOne({ erxesApiId });
},
async instagramGetConfigs(_root, _args, { models }: IContext) {
return models.Configs.find({}).lean();
},
async instagramGetComments(
_root,
args: ICommentsParams,
{ models }: IContext,
) {
const {
conversationId,
isResolved,
commentId,
senderId,
limit = 10,
} = args;
const post = await models.PostConversations.findOne({
erxesApiId: conversationId,
});
const query: {
postId: string;
isResolved?: boolean;
parentId?: string;
senderId?: string;
} = {
postId: post ? post.postId || '' : '',
isResolved: isResolved === true,
};
if (senderId && senderId !== 'undefined') {
const customer = await models.Customers.findOne({ erxesApiId: senderId });
if (customer && customer.userId) {
query.senderId = customer.userId;
}
} else {
query.parentId = commentId !== 'undefined' ? commentId : '';
}
const result = await models.CommentConversation.aggregate([
{
$match: query,
},
{
$lookup: {
from: 'customers_instagrams',
localField: 'senderId',
foreignField: 'userId',
as: 'customer',
},
},
{
$unwind: {
path: '$customer',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'posts_conversations_instagrams',
localField: 'postId',
foreignField: 'postId',
as: 'post',
},
},
{
$unwind: {
path: '$post',
preserveNullAndEmptyArrays: true,
},
},
{
$lookup: {
from: 'comments_instagrams',
localField: 'commentId',
foreignField: 'parentId',
as: 'replies',
},
},
{
$addFields: {
commentCount: { $size: '$replies' },
'customer.avatar': '$customer.profilePic',
'customer._id': '$customer.erxesApiId',
conversationId: '$post.erxesApiId',
},
},
{ $sort: { timestamp: -1 } },
{ $limit: limit },
]);
return result.reverse();
},
async instagramGetCommentCount(_root, args, { models }: IContext) {
const { conversationId, isResolved = false } = args;
const commentCount = await models.CommentConversation.countDocuments({
erxesApiId: conversationId,
});
const comments = await models.CommentConversation.find({
erxesApiId: conversationId,
});
// Extracting comment_ids from the comments array
const comment_ids = comments?.map((item) => item.comment_id);
// Using the extracted comment_ids to search for matching comments
const search = await models.CommentConversation.find({
comment_id: { $in: comment_ids }, // Using $in to find documents with comment_ids in the extracted array
});
if (search.length > 0) {
// Returning the count of matching comments
return {
commentCount: commentCount,
searchCount: search.length,
};
}
// If no matching comments are found, return only the commentCount
return {
commentCount: commentCount,
searchCount: 0,
};
},
async instagramGetPages(_root, args, { models }: IContext) {
const { kind, accountId } = args;
const account = await models.Accounts.getAccount({ _id: accountId });
const accessToken = account.token;
let pages: any[] = [];
try {
pages = await getPageList(models, accessToken, kind);
} catch (e) {
if (!e.message.includes('Application request limit reached')) {
await models.Integrations.updateOne(
{ accountId },
{ $set: { healthStatus: 'account-token', error: `${e.message}` } },
);
}
}
return pages;
},
async instagramConversationDetail(
_root,
{ _id }: { _id: string },
{ models }: IContext,
) {
const conversation = await models.Conversations.findOne({ _id });
if (conversation) {
return conversation;
}
return models.CommentConversation.findOne({ _id });
},
async instagramConversationMessages(
_root,
args: IMessagesParams,
{ models }: IContext,
) {
const { conversationId, limit, skip, getFirst } = args;
const conversation = await models.Conversations.findOne({
erxesApiId: conversationId,
});
let messages: IConversationMessageDocument[] = [];
const query = await buildSelector(conversationId, models.Conversations);
if (conversation) {
if (limit) {
const sort: any = getFirst ? { createdAt: 1 } : { createdAt: -1 };
messages = await models.ConversationMessages.find(query)
.sort(sort)
.skip(skip || 0)
.limit(limit);
return getFirst ? messages : messages.reverse();
}
messages = await models.ConversationMessages.find(query)
.sort({ createdAt: -1 })
.limit(50);
return messages.reverse();
} else {
let comment: any[] = [];
const sort: any = getFirst ? { createdAt: 1 } : { createdAt: -1 };
comment = await models.CommentConversation.find({
erxesApiId: conversationId,
})
.sort(sort)
.skip(skip || 0);
const comment_ids = comment?.map((item) => item.comment_id);
const search = await models.CommentConversationReply.find({
parentId: comment_ids,
})
.sort(sort)
.skip(skip || 0);
if (search.length > 0) {
// Combine the arrays and sort by createdAt in ascending order
return [...comment, ...search].sort((a, b) =>
a.createdAt > b.createdAt ? 1 : -1,
);
} else {
return comment;
}
}
},
/**
* Get all conversation messages count. We will use it in pager
*/
async instagramConversationMessagesCount(
_root,
{ conversationId }: { conversationId: string },
{ models }: IContext,
) {
const selector = await buildSelector(conversationId, models.Conversations);
return models.ConversationMessages.countDocuments(selector);
},
async instagramGetPost(
_root,
{ erxesApiId }: IDetailParams,
{ models }: IContext,
) {
const comment = await models.CommentConversation.findOne({
erxesApiId: erxesApiId,
});
if (comment) {
return await models.PostConversations.findOne({
postId: comment.postId,
});
}
// Return null or some appropriate value when comment is not found
return null;
},
async instagramHasTaggedMessages(
_root,
{ conversationId }: IConversationId,
{ models, subdomain }: IContext,
) {
const commonParams = { isRPC: true, subdomain };
const inboxConversation = await sendInboxMessage({
...commonParams,
action: 'conversations.findOne',
data: { query: { _id: conversationId } },
});
let integration;
if (inboxConversation) {
integration = await sendInboxMessage({
...commonParams,
action: 'integrations.findOne',
data: { _id: inboxConversation.integrationId },
});
}
if (integration && integration.kind !== INTEGRATION_KINDS.MESSENGER) {
return false;
}
const query = await buildSelector(conversationId, models.Conversations);
const messages = await models.ConversationMessages.find({
...query,
customerId: { $exists: true },
createdAt: { $gt: new Date(Date.now() - 24 * 60 * 60 * 1000) },
})
.limit(2)
.lean();
if (messages.length >= 1) {
return false;
}
return true;
},
async instagramPostMessages(
_root,
args: IMessagesParams,
{ models }: IContext,
) {
const { conversationId, limit, skip, getFirst } = args;
let messages: any[] = [];
const query = await buildSelector(conversationId, models.PostConversations);
if (limit) {
const sort: any = getFirst ? { createdAt: 1 } : { createdAt: -1 };
messages = await models.CommentConversation.find(query)
.sort(sort)
.skip(skip || 0)
.limit(limit);
return getFirst ? messages : messages.reverse();
}
messages = await models.CommentConversation.find(query)
.sort({ createdAt: -1 })
.limit(50);
return messages.reverse();
},
};
export default instagramQueries;
``` | /content/code_sandbox/packages/plugin-instagram-api/src/graphql/resolvers/queries.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 2,301 |
```xml
<dict>
<key>LayoutID</key>
<integer>11</integer>
<key>PathMapRef</key>
<array>
<dict>
<key>CodecID</key>
<array>
<integer>287143573</integer>
</array>
<key>Headphone</key>
<dict>
<key>MuteGPIO</key>
<integer>0</integer>
</dict>
<key>Inputs</key>
<array>
<string>LineIn</string>
<string>Mic</string>
</array>
<key>IntSpeaker</key>
<dict>
<key>MuteGPIO</key>
<integer>0</integer>
</dict>
<key>LineIn</key>
<dict>
<key>MuteGPIO</key>
<integer>1342242827</integer>
</dict>
<key>Mic</key>
<dict>
<key>SignalProcessing</key>
<dict>
<key>SoftwareDSP</key>
<dict>
<key>DspFunction0</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>0</integer>
<key>DspFuncName</key>
<string>DspNoiseReduction</string>
<key>DspFuncProcessingIndex</key>
<integer>0</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>2</key>
<integer>0</integer>
<key>3</key>
<integer>0</integer>
<key>4</key>
<integer>0</integer>
</dict>
<key>PatchbayInfo</key>
<dict/>
</dict>
<key>DspFunction1</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>1</integer>
<key>DspFuncName</key>
<string>DspGainStage</string>
<key>DspFuncProcessingIndex</key>
<integer>1</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>2</key>
<integer>1078616770</integer>
<key>3</key>
<integer>1078616770</integer>
</dict>
<key>PatchbayInfo</key>
<dict>
<key>InputPort0</key>
<dict>
<key>PortInstance</key>
<integer>0</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>0</integer>
<key>SourcePortIndex</key>
<integer>0</integer>
</dict>
<key>InputPort1</key>
<dict>
<key>PortInstance</key>
<integer>1</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>0</integer>
<key>SourcePortIndex</key>
<integer>1</integer>
</dict>
</dict>
</dict>
<key>DspFunction2</key>
<dict>
<key>FunctionInfo</key>
<dict>
<key>DspFuncInstance</key>
<integer>2</integer>
<key>DspFuncName</key>
<string>DspEqualization</string>
<key>DspFuncProcessingIndex</key>
<integer>2</integer>
</dict>
<key>ParameterInfo</key>
<dict>
<key>1</key>
<integer>0</integer>
<key>Filter</key>
<array>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>0</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>1</integer>
<key>6</key>
<integer>1118830697</integer>
<key>7</key>
<integer>1060439283</integer>
<key>8</key>
<integer>-1044468775</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>1</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1137063621</integer>
<key>7</key>
<integer>1054939033</integer>
<key>8</key>
<integer>-1086368275</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>4</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>4</integer>
<key>6</key>
<integer>1162269254</integer>
<key>7</key>
<integer>1066566541</integer>
<key>8</key>
<integer>-1056209924</integer>
</dict>
<dict>
<key>2</key>
<integer>2</integer>
<key>3</key>
<integer>15</integer>
<key>4</key>
<integer>0</integer>
<key>5</key>
<integer>6</integer>
<key>6</key>
<integer>1180675529</integer>
<key>7</key>
<integer>1060439283</integer>
<key>8</key>
<integer>-1044381696</integer>
</dict>
</array>
</dict>
<key>PatchbayInfo</key>
<dict>
<key>InputPort0</key>
<dict>
<key>PortInstance</key>
<integer>0</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>1</integer>
<key>SourcePortIndex</key>
<integer>0</integer>
</dict>
<key>InputPort1</key>
<dict>
<key>PortInstance</key>
<integer>1</integer>
<key>PortWidth</key>
<integer>1</integer>
<key>SourceFuncInstance</key>
<integer>1</integer>
<key>SourcePortIndex</key>
<integer>1</integer>
</dict>
</dict>
</dict>
</dict>
</dict>
</dict>
<key>Outputs</key>
<array>
<string>IntSpeaker</string>
<string>Headphone</string>
</array>
<key>PathMapID</key>
<integer>1</integer>
</dict>
</array>
</dict>
``` | /content/code_sandbox/Resources/IDT92HD95/layout11.xml | xml | 2016-03-07T20:45:58 | 2024-08-14T08:57:03 | AppleALC | acidanthera/AppleALC | 3,420 | 1,928 |
```xml
<resources>
<string name="app_name">Visualize</string>
<string name="action_settings">Settings</string>
<!-- - - - - - - - - - - - - - - -
- Used by Preferences -
- - - - - - - - - - - - - - - -->
<!-- Label for the show bass checkbox preference -->
<string name="pref_show_bass_label">Show Bass</string>
<!-- Key name for storing bass in SharedPreferences -->
<string name="pref_show_bass_key" translatable="false">show_bass</string>
<!-- Label for the show mid range checkbox preference -->
<string name="pref_show_mid_range_label">Show Mid Range</string>
<!-- Key name for storing mid range in SharedPreferences -->
<string name="pref_show_mid_range_key" translatable="false">show_mid_range</string>
<!-- Label for the show treble checkbox preference -->
<string name="pref_show_treble_label">Show Treble</string>
<!-- Key name for storing treble in SharedPreferences -->
<string name="pref_show_treble_key" translatable="false">show_treble</string>
<!-- Summary for Checkboxes -->
<string name="pref_show_true">Shown</string>
<string name="pref_show_false">Hidden</string>
<!-- Label for the size preference -->
<string name="pref_size_label">Size Multiplier</string>
<!-- Key name for storing size in SharedPreferences -->
<string name="pref_size_key" translatable="false">size</string>
<!-- Default for size preference -->
<string name="pref_size_default" translatable="false">1</string>
<!-- Label for the color preference -->
<string name="pref_color_label">Shape Color</string>
<!-- Label for red color preference -->
<string name="pref_color_label_red">Red</string>
<!-- Label for blue color preference -->
<string name="pref_color_label_blue">Blue</string>
<!-- Label for green color preference -->
<string name="pref_color_label_green">Green</string>
<!-- Key name for color preference in SharedPreferences -->
<string name="pref_color_key" translatable="false">color</string>
<!-- Value in SharedPreferences for red color option -->
<string name="pref_color_red_value" translatable="false">red</string>
<!-- Value in SharedPreferences for blue color option -->
<string name="pref_color_blue_value" translatable="false">blue</string>
<!-- Value in SharedPreferences for green color option -->
<string name="pref_color_green_value" translatable="false">green</string>
</resources>
``` | /content/code_sandbox/Lesson06-Visualizer-Preferences/T06.09-Solution-EditTextPreference/app/src/main/res/values/strings.xml | xml | 2016-11-02T04:41:25 | 2024-08-12T19:38:05 | ud851-Exercises | udacity/ud851-Exercises | 2,039 | 568 |
```xml
import type { RxCollection, ReplicationPullOptions, ReplicationPushOptions, GraphQLServerUrl, RxGraphQLReplicationQueryBuilderResponseObject, RxGraphQLReplicationClientState, ById } from '../../types/index.d.ts';
import { RxReplicationState } from '../replication/index.ts';
import { SyncOptionsGraphQL } from '../../index.ts';
export declare class RxGraphQLReplicationState<RxDocType, CheckpointType> extends RxReplicationState<RxDocType, CheckpointType> {
readonly url: GraphQLServerUrl;
readonly clientState: RxGraphQLReplicationClientState;
readonly replicationIdentifier: string;
readonly collection: RxCollection<RxDocType>;
readonly deletedField: string;
readonly pull?: ReplicationPullOptions<RxDocType, CheckpointType> | undefined;
readonly push?: ReplicationPushOptions<RxDocType> | undefined;
readonly live?: boolean | undefined;
retryTime?: number | undefined;
autoStart?: boolean | undefined;
readonly customFetch?: WindowOrWorkerGlobalScope["fetch"] | undefined;
constructor(url: GraphQLServerUrl, clientState: RxGraphQLReplicationClientState, replicationIdentifier: string, collection: RxCollection<RxDocType>, deletedField: string, pull?: ReplicationPullOptions<RxDocType, CheckpointType> | undefined, push?: ReplicationPushOptions<RxDocType> | undefined, live?: boolean | undefined, retryTime?: number | undefined, autoStart?: boolean | undefined, customFetch?: WindowOrWorkerGlobalScope["fetch"] | undefined);
setHeaders(headers: ById<string>): void;
setCredentials(credentials: RequestCredentials | undefined): void;
graphQLRequest(queryParams: RxGraphQLReplicationQueryBuilderResponseObject): Promise<any>;
}
export declare function replicateGraphQL<RxDocType, CheckpointType>({ collection, url, headers, credentials, deletedField, waitForLeadership, pull, push, live, fetch: customFetch, retryTime, // in ms
autoStart, replicationIdentifier }: SyncOptionsGraphQL<RxDocType, CheckpointType>): RxGraphQLReplicationState<RxDocType, CheckpointType>;
export * from './helper.ts';
export * from './graphql-schema-from-rx-schema.ts';
export * from './query-builder-from-rx-schema.ts';
export * from './graphql-websocket.ts';
``` | /content/code_sandbox/dist/types/plugins/replication-graphql/index.d.ts | xml | 2016-12-02T19:34:42 | 2024-08-16T15:47:20 | rxdb | pubkey/rxdb | 21,054 | 488 |
```xml
import { makeAPI } from '@statoscope/stats-validator/dist/api';
import { RuleDataInput } from '@statoscope/stats-validator/dist/rule';
import { Prepared } from '@statoscope/webpack-model';
import plugin from '../..';
import statsV4 from '../../../../../test/bundles/v4/simple/stats-prod.json';
import statsV5 from '../../../../../test/bundles/v5/simple/stats-prod.json';
import rule from './';
test('matches', () => {
const pluginInstance = plugin();
const prepared: RuleDataInput<Prepared> = pluginInstance.prepare!([
{ name: 'input.json', data: statsV5 },
{ name: 'reference.json', data: statsV4 },
]);
const api = makeAPI();
rule([{ name: /.+/ }], prepared, api);
expect(api.getStorage()).toMatchSnapshot();
});
test('not matches', () => {
const pluginInstance = plugin();
const prepared: RuleDataInput<Prepared> = pluginInstance.prepare!([
{ name: 'input.json', data: statsV5 },
{ name: 'reference.json', data: statsV4 },
]);
const api = makeAPI();
rule([{ name: /not_exists/ }], prepared, api);
expect(api.getStorage()).toMatchSnapshot();
});
``` | /content/code_sandbox/packages/stats-validator-plugin-webpack/src/rules/diff-deprecated-modules/index.spec.ts | xml | 2016-11-30T14:09:21 | 2024-08-15T18:52:57 | statoscope | statoscope/statoscope | 1,423 | 271 |
```xml
export let dropdown = [function() {
return {
restrict: 'A',
link: link,
scope: {
ref: '=?',
bind: '=?'
}
}
function link(scope, element, attr) {
let dropdown: any = $(element)
dropdown.dropdown({
transition: "vertical flip",
duration: 100,
onChange: onChange,
action: 'hide'
});
if ('ref' in attr){
scope.ref = {
clear: doAction(element, 'clear'),
refresh: doAction(element, 'refresh'),
setSelected: doAction(element, 'set selected'),
getValue: doAction(element, 'get value')
};
}
scope.$watch(function() {
return scope.bind;
}, function(newValue) {
if (newValue) {
let dropdown: any = $(element)
dropdown.dropdown('set selected', newValue);
}
});
function onChange(value /*, text, choice*/){
if (scope.bind){
scope.bind = value;
}
}
}
function doAction(element, action) {
return function(param) {
let dropdown: any = $(element)
dropdown.dropdown(action, param);
}
}
}];
export let dropItem = [function() {
return {
restrict: 'A',
link: link
}
function link(scope, element, attr) {
if (scope.bind === attr.value){
var dropdown: any = $(element).closest('.dropdown');
dropdown.dropdown('set selected', attr.value);
}
if (scope.$last) {
scope.$emit('update:dropdown');
}
}
}];
``` | /content/code_sandbox/src/scripts/directives/dropdown.ts | xml | 2016-06-18T15:04:41 | 2024-08-16T07:12:27 | Electorrent | tympanix/Electorrent | 1,016 | 355 |
```xml
///
///
///
/// path_to_url
///
/// Unless required by applicable law or agreed to in writing, software
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
///
import config from 'config';
import { _logger } from './config/logger';
import { HttpServer } from './api/httpServer';
import { IQueue } from './queue/queue.models';
import { KafkaTemplate } from './queue/kafkaTemplate';
import { PubSubTemplate } from './queue/pubSubTemplate';
import { AwsSqsTemplate } from './queue/awsSqsTemplate';
import { RabbitMqTemplate } from './queue/rabbitmqTemplate';
import { ServiceBusTemplate } from './queue/serviceBusTemplate';
const logger = _logger('main');
logger.info('===CONFIG BEGIN===');
logger.info(JSON.stringify(config, null, 4));
logger.info('===CONFIG END===');
const serviceType: string = config.get('queue_type');
const httpPort = Number(config.get('http_port'));
let queues: IQueue | null;
let httpServer: HttpServer | null;
(async () => {
logger.info('Starting ThingsBoard JavaScript Executor Microservice...');
try {
queues = await createQueue(serviceType);
logger.info(`Starting ${queues.name} template...`);
await queues.init();
logger.info(`${queues.name} template started.`);
httpServer = new HttpServer(httpPort);
} catch (e: any) {
logger.error('Failed to start ThingsBoard JavaScript Executor Microservice: %s', e.message);
logger.error(e.stack);
await exit(-1);
}
})();
async function createQueue(serviceType: string): Promise<IQueue> {
switch (serviceType) {
case 'kafka':
return new KafkaTemplate();
case 'pubsub':
return new PubSubTemplate();
case 'aws-sqs':
return new AwsSqsTemplate();
case 'rabbitmq':
return new RabbitMqTemplate();
case 'service-bus':
return new ServiceBusTemplate();
default:
throw new Error('Unknown service type: ' + serviceType);
}
}
[`SIGINT`, `SIGUSR1`, `SIGUSR2`, `uncaughtException`, `SIGTERM`].forEach((eventType) => {
process.once(eventType, async () => {
logger.info(`${eventType} signal received`);
await exit(0);
})
})
process.on('exit', (code: number) => {
logger.info(`ThingsBoard JavaScript Executor Microservice has been stopped. Exit code: ${code}.`);
});
async function exit(status: number) {
logger.info('Exiting with status: %d ...', status);
try {
if (httpServer) {
const _httpServer = httpServer;
httpServer = null;
await _httpServer.stop();
}
if (queues) {
const _queues = queues;
queues = null;
await _queues.destroy();
}
} catch (e) {
logger.error('Error on exit');
}
process.exit(status);
}
``` | /content/code_sandbox/msa/js-executor/server.ts | xml | 2016-12-01T09:33:30 | 2024-08-16T19:58:25 | thingsboard | thingsboard/thingsboard | 16,820 | 637 |
```xml
import { JWT } from 'google-auth-library'
import { google, sheets_v4 } from 'googleapis'
import { Configuration } from './misc/types'
export function getClient(config: Configuration) {
return new GoogleSheetsApi(config.spreadsheetId, config.privateKey, config.clientEmail)
}
export class GoogleSheetsApi {
private sheets: sheets_v4.Sheets
private spreadsheetId: string
constructor(spreadsheetId: string, privateKey: string, clientEmail: string) {
this.spreadsheetId = spreadsheetId
const jwtClient = new JWT({
email: clientEmail,
key: privateKey.split(String.raw`\n`).join('\n'),
scopes: ['path_to_url
})
this.sheets = google.sheets({ version: 'v4', auth: jwtClient })
}
async getValues(range: string): Promise<sheets_v4.Schema$ValueRange> {
const response = await this.sheets.spreadsheets.values.get({
spreadsheetId: this.spreadsheetId,
range,
})
return response.data
}
async updateValues(range: string, values: any[][]): Promise<sheets_v4.Schema$UpdateValuesResponse> {
const response = await this.sheets.spreadsheets.values.update({
spreadsheetId: this.spreadsheetId,
range,
valueInputOption: 'USER_ENTERED',
requestBody: { values },
})
return response.data
}
async appendValues(range: string, values: any[][]): Promise<sheets_v4.Schema$AppendValuesResponse> {
const response = await this.sheets.spreadsheets.values.append({
spreadsheetId: this.spreadsheetId,
range,
valueInputOption: 'USER_ENTERED',
requestBody: { values },
})
return response.data
}
async clearValues(range: string): Promise<sheets_v4.Schema$ClearValuesResponse> {
const response = await this.sheets.spreadsheets.values.clear({
spreadsheetId: this.spreadsheetId,
range,
})
return response.data
}
async batchUpdate(requests: sheets_v4.Schema$Request[]): Promise<sheets_v4.Schema$BatchUpdateSpreadsheetResponse> {
const response = await this.sheets.spreadsheets.batchUpdate({
spreadsheetId: this.spreadsheetId,
requestBody: { requests },
})
return response.data
}
async getSpreadsheet(fields: string): Promise<sheets_v4.Schema$Spreadsheet> {
const response = await this.sheets.spreadsheets.get({
spreadsheetId: this.spreadsheetId,
fields,
})
return response.data
}
}
``` | /content/code_sandbox/integrations/gsheets/src/client.ts | xml | 2016-11-16T21:57:59 | 2024-08-16T18:45:35 | botpress | botpress/botpress | 12,401 | 564 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="path_to_url"
android:minWidth="@dimen/widget_grid_3"
android:minHeight="@dimen/widget_grid_1"
android:minResizeWidth="@dimen/widget_grid_1"
android:minResizeHeight="@dimen/widget_grid_1"
android:updatePeriodMillis="0"
android:initialLayout="@layout/widget_day_symmetry"
android:previewImage="@drawable/widget_day"
android:resizeMode="horizontal|vertical"
android:configure="wangdaye.com.geometricweather.remoteviews.config.DayWidgetConfigActivity"
android:widgetCategory="home_screen|keyguard" />
``` | /content/code_sandbox/app/src/main/res/xml/widget_day.xml | xml | 2016-02-21T04:39:19 | 2024-08-16T13:35:51 | GeometricWeather | WangDaYeeeeee/GeometricWeather | 2,420 | 150 |
```xml
import * as React from 'react';
export const MenuContext = React.createContext<any>({});
export const MenuContextProvider = MenuContext.Provider;
export const useMenuContext = () => React.useContext(MenuContext);
``` | /content/code_sandbox/packages/fluentui/react-northstar-prototypes/src/prototypes/MenuList/menuContext.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 44 |
```xml
/**
* @file Response data transform interceptor
* @module interceptor/transform
* @author Surmon <path_to_url
*/
import { Request } from 'express'
import { Observable } from 'rxjs'
import { map } from 'rxjs/operators'
import { Injectable, NestInterceptor, CallHandler, ExecutionContext } from '@nestjs/common'
import { HttpResponseSuccess, ResponseStatus } from '@app/interfaces/response.interface'
import { getResponserOptions } from '@app/decorators/responser.decorator'
import * as TEXT from '@app/constants/text.constant'
/**
* @class TransformInterceptor
* @classdesc transform `T` to `HttpResponseSuccess<T>` when controller `Promise` resolved
*/
@Injectable()
export class TransformInterceptor<T> implements NestInterceptor<T, T | HttpResponseSuccess<T>> {
intercept(context: ExecutionContext, next: CallHandler<T>): Observable<T | HttpResponseSuccess<T>> {
const target = context.getHandler()
const { successMessage, transform, paginate } = getResponserOptions(target)
if (!transform) {
return next.handle()
}
const request = context.switchToHttp().getRequest<Request>()
return next.handle().pipe(
map((data: any) => {
return {
status: ResponseStatus.Success,
message: successMessage || TEXT.HTTP_DEFAULT_SUCCESS_TEXT,
params: {
isAuthenticated: request.isAuthenticated(),
isUnauthenticated: request.isUnauthenticated(),
url: request.url,
method: request.method,
routes: request.params,
payload: request.$validatedPayload || {}
},
result: paginate
? {
data: data.documents,
pagination: {
total: data.total,
current_page: data.page,
per_page: data.perPage,
total_page: data.totalPage
}
}
: data
}
})
)
}
}
``` | /content/code_sandbox/src/interceptors/transform.interceptor.ts | xml | 2016-02-13T08:16:02 | 2024-08-12T08:34:20 | nodepress | surmon-china/nodepress | 1,421 | 388 |
```xml
/// <reference path="@ms/odsp.d.ts" />
/// <reference path="@ms/odsp-webpack.d.ts" />
/// <reference path="assertion-error/assertion-error.d.ts" />
/// <reference path="chai/chai.d.ts" />
/// <reference path="es6-collections/es6-collections.d.ts" />
/// <reference path="es6-promise/es6-promise.d.ts" />
/// <reference path="lodash/lodash.d.ts" />
/// <reference path="mocha/mocha.d.ts" />
/// <reference path="node/node.d.ts" />
/// <reference path="react/react.d.ts" />
/// <reference path="react/react-addons-shallow-compare.d.ts" />
/// <reference path="react/react-addons-test-utils.d.ts" />
/// <reference path="react/react-addons-update.d.ts" />
/// <reference path="react/react-dom.d.ts" />
/// <reference path="systemjs/systemjs.d.ts" />
/// <reference path="whatwg-fetch/whatwg-fetch.d.ts" />
/// <reference path="knockout/knockout.d.ts" />
/// <reference path="combokeys/combokeys.d.ts" />
``` | /content/code_sandbox/samples/angular-migration/angular-todo-webpart/typings/tsd.d.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 249 |
```xml
/*
*/
/*
* This code is inspired by
* - react-window path_to_url
* - path_to_url
*/
import { IChangedArgs } from '@jupyterlab/coreutils';
import { IObservableList } from '@jupyterlab/observables';
import { ArrayExt } from '@lumino/algorithm';
import { PromiseDelegate } from '@lumino/coreutils';
import { IDisposable } from '@lumino/disposable';
import { Message, MessageLoop } from '@lumino/messaging';
import { Throttler } from '@lumino/polling';
import { ISignal, Signal } from '@lumino/signaling';
import { PanelLayout, Widget } from '@lumino/widgets';
/**
* For how long after the scroll request should the target position
* be corrected to account for resize of other widgets?
*
* The time is given in milliseconds.
*/
const MAXIMUM_TIME_REMAINING = 100;
/*
* Feature detection
*
* Ref: path_to_url#improving_scrolling_performance_with_passive_listeners
*/
let passiveIfSupported: boolean | { passive: boolean } = false;
try {
// @ts-expect-error unknown signature
window.addEventListener(
'test',
null,
Object.defineProperty({}, 'passive', {
get: function () {
passiveIfSupported = { passive: true };
}
})
);
} catch (err) {
// pass no-op
}
/**
* Windowed list abstract model.
*/
export abstract class WindowedListModel implements WindowedList.IModel {
/**
* Constructor
*
* @param options Constructor options
*/
constructor(options: WindowedList.IModelOptions = {}) {
this._widgetCount = options.itemsList?.length ?? options.count ?? 0;
this._overscanCount = options.overscanCount ?? 1;
this._windowingActive = options.windowingActive ?? true;
this.itemsList = options.itemsList ?? null;
}
/**
* Provide a best guess for the widget size at position index
*
* #### Notes
*
* This function should be very light to compute especially when
* returning the default size.
* The default value should be constant (i.e. two calls with `null` should
* return the same value). But it can change for a given `index`.
*
* @param index Widget position
* @returns Estimated widget size
*/
abstract estimateWidgetSize: (index: number) => number;
/**
* Widget factory for the list items.
*
* Caching the resulting widgets should be done by the callee.
*
* @param index List index
* @returns The widget at the given position
*/
abstract widgetRenderer: (index: number) => Widget;
/**
* The overlap threshold used to decide whether to scroll down to an item
* below the viewport (smart mode). If the item overlap with the viewport
* is greater or equal this threshold the item is considered sufficiently
* visible and will not be scrolled to. The value is the number of pixels
* in overlap if greater than one, or otherwise a fraction of item height.
* By default the item is scrolled to if not full visible in the viewport.
*/
readonly scrollDownThreshold: number = 1;
/**
* The underlap threshold used to decide whether to scroll up to an item
* above the viewport (smart mode). If the item part outside the viewport
* (underlap) is greater than this threshold then the item is considered
* not sufficiently visible and will be scrolled to.
* The value is the number of pixels in underlap if greater than one, or
* otherwise a fraction of the item height.
* By default the item is scrolled to if not full visible in the viewport.
*/
readonly scrollUpThreshold: number = 0;
/**
* Top padding of the the outer window node.
*/
paddingTop: number = 0;
/**
* List widget height
*/
get height(): number {
return this._height;
}
set height(h: number) {
this._height = h;
}
/**
* Test whether the model is disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* Items list to be rendered
*/
get itemsList(): ISimpleObservableList | null {
return this._itemsList;
}
set itemsList(v: ISimpleObservableList | null) {
if (this._itemsList !== v) {
if (this._itemsList) {
this._itemsList.changed.disconnect(this.onListChanged, this);
}
const oldValue = this._itemsList;
this._itemsList = v;
if (this._itemsList) {
this._itemsList.changed.connect(this.onListChanged, this);
} else {
this._widgetCount = 0;
}
this._stateChanged.emit({
name: 'list',
newValue: this._itemsList,
oldValue
});
this._stateChanged.emit({
name: 'count',
newValue: this._itemsList?.length ?? 0,
oldValue: oldValue?.length ?? 0
});
}
}
/**
* Number of widgets to render in addition to those
* visible in the viewport.
*/
get overscanCount(): number {
return this._overscanCount;
}
set overscanCount(newValue: number) {
if (newValue >= 1) {
if (this._overscanCount !== newValue) {
const oldValue = this._overscanCount;
this._overscanCount = newValue;
this._stateChanged.emit({ name: 'overscanCount', newValue, oldValue });
}
} else {
console.error(`Forbidden non-positive overscan count: got ${newValue}`);
}
}
/**
* Viewport scroll offset.
*/
get scrollOffset(): number {
return this._scrollOffset;
}
set scrollOffset(offset: number) {
this._scrollOffset = offset;
}
/**
* Total number of widgets in the list
*/
get widgetCount(): number {
return this._itemsList ? this._itemsList.length : this._widgetCount;
}
set widgetCount(newValue: number) {
if (this.itemsList) {
console.error(
'It is not allow to change the widgets count of a windowed list if a items list is used.'
);
return;
}
if (newValue >= 0) {
if (this._widgetCount !== newValue) {
const oldValue = this._widgetCount;
this._widgetCount = newValue;
this._stateChanged.emit({ name: 'count', newValue, oldValue });
}
} else {
console.error(`Forbidden negative widget count: got ${newValue}`);
}
}
/**
* Whether windowing is active or not.
*
* This is true by default.
*/
get windowingActive(): boolean {
return this._windowingActive;
}
set windowingActive(newValue: boolean) {
if (newValue !== this._windowingActive) {
const oldValue = this._windowingActive;
this._windowingActive = newValue;
this._currentWindow = [-1, -1, -1, -1];
this._lastMeasuredIndex = -1;
this._widgetSizers = [];
this._stateChanged.emit({ name: 'windowingActive', newValue, oldValue });
}
}
/**
* A signal emitted when any model state changes.
*/
get stateChanged(): ISignal<
WindowedListModel,
IChangedArgs<
any,
any,
| 'count'
| 'estimatedWidgetSize'
| 'index'
| 'list'
| 'overscanCount'
| 'windowingActive'
| string
>
> {
return this._stateChanged;
}
/**
* Dispose the model.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
this._isDisposed = true;
Signal.clearData(this);
}
/**
* Get the total list size.
*
* @returns Total estimated size
*/
getEstimatedTotalSize(): number {
let totalSizeOfMeasuredItems = 0;
if (this._lastMeasuredIndex >= this.widgetCount) {
this._lastMeasuredIndex = this.widgetCount - 1;
}
if (this._lastMeasuredIndex >= 0) {
const itemMetadata = this._widgetSizers[this._lastMeasuredIndex];
totalSizeOfMeasuredItems = itemMetadata.offset + itemMetadata.size;
}
let totalSizeOfUnmeasuredItems = 0;
for (let i = this._lastMeasuredIndex + 1; i < this.widgetCount; i++) {
totalSizeOfUnmeasuredItems += this.estimateWidgetSize(i);
}
return totalSizeOfMeasuredItems + totalSizeOfUnmeasuredItems;
}
/**
* Get the scroll offset to display an item in the viewport.
*
* By default, the list will scroll as little as possible to ensure the item is fully visible (`auto`).
* You can control the alignment of the item though by specifying a second alignment parameter.
* Acceptable values are:
*
* auto - Automatically align with the top or bottom minimising the amount scrolled,
* If `alignPreference` is given, follow such preferred alignment.
* If item is smaller than the viewport and fully visible, do not scroll at all.
* smart - If the item is significantly visible, don't scroll at all (regardless of whether it fits in the viewport).
* If the item is less than one viewport away, scroll so that it becomes fully visible (following the `auto` heuristics).
* If the item is more than one viewport away, scroll so that it is centered within the viewport (`center` if smaller than viewport, `top-center` otherwise).
* center - Align the middle of the item with the middle of the viewport (it only works well for items smaller than the viewport).
* top-center - Align the top of the item with the middle of the viewport (works well for items larger than the viewport).
* end - Align the bottom of the item to the bottom of the list.
* start - Align the top of item to the top of the list.
*
* An item is considered significantly visible if:
* - it overlaps with the viewport by the amount specified by `scrollDownThreshold` when below the viewport
* - it exceeds the viewport by the amount less than specified by `scrollUpThreshold` when above the viewport.
*
* @param index Item index
* @param align Where to align the item in the viewport
* @param margin The proportion of viewport to add when aligning with the top/bottom of the list.
* @param precomputed Precomputed values to use when windowing is disabled.
* @param alignPreference Allows to override the alignment of item when the `auto` heuristic decides that the item needs to be scrolled into view.
* @returns The needed scroll offset
*/
getOffsetForIndexAndAlignment(
index: number,
align: WindowedList.ScrollToAlign = 'auto',
margin: number = 0,
precomputed?: {
totalSize: number;
itemMetadata: WindowedList.ItemMetadata;
currentOffset: number;
},
alignPreference?: WindowedList.BaseScrollToAlignment
): number {
const boundedMargin = Math.min(Math.max(0.0, margin), 1.0);
const size = this._height;
const itemMetadata = precomputed
? precomputed.itemMetadata
: this._getItemMetadata(index);
const scrollDownThreshold =
this.scrollDownThreshold <= 1
? itemMetadata.size * this.scrollDownThreshold
: this.scrollDownThreshold;
const scrollUpThreshold =
this.scrollUpThreshold <= 1
? itemMetadata.size * this.scrollUpThreshold
: this.scrollUpThreshold;
// When pre-computed values are not available (we are in windowing mode),
// `getEstimatedTotalSize` is called after ItemMetadata is computed
// to ensure it reflects actual measurements instead of just estimates.
const estimatedTotalSize = precomputed
? precomputed.totalSize
: this.getEstimatedTotalSize();
const topOffset = Math.max(
0,
Math.min(estimatedTotalSize - size, itemMetadata.offset)
);
const bottomOffset = Math.max(
0,
itemMetadata.offset - size + itemMetadata.size
);
// Current offset (+/- padding) is the top edge of the viewport.
const currentOffset = precomputed
? precomputed.currentOffset
: this._scrollOffset;
const viewportPadding = this._windowingActive ? this.paddingTop : 0;
const itemTop = itemMetadata.offset;
const itemBottom = itemMetadata.offset + itemMetadata.size;
const bottomEdge = currentOffset - viewportPadding + size;
const topEdge = currentOffset - viewportPadding;
const crossingBottomEdge = bottomEdge > itemTop && bottomEdge < itemBottom;
const crossingTopEdge = topEdge > itemTop && topEdge < itemBottom;
const isFullyWithinViewport = bottomEdge > itemBottom && topEdge < itemTop;
if (align === 'smart') {
const edgeLessThanOneViewportAway =
currentOffset >= bottomOffset - size &&
currentOffset <= topOffset + size;
const visiblePartBottom = bottomEdge - itemTop;
const hiddenPartTop = topEdge - itemTop;
if (
isFullyWithinViewport ||
(crossingBottomEdge && visiblePartBottom >= scrollDownThreshold) ||
(crossingTopEdge && hiddenPartTop < scrollUpThreshold)
) {
return currentOffset;
} else if (edgeLessThanOneViewportAway) {
// Possibly less than one viewport away, scroll so that it becomes visible (including the margin)
align = 'auto';
} else {
// More than one viewport away, scroll so that it is centered within the list:
// - if the item is smaller than viewport align the middle of the item with the middle of the viewport
// - if the item is larger than viewport align the top of the item with the middle of the viewport
if (itemMetadata.size > size) {
align = 'top-center';
} else {
align = 'center';
}
}
}
if (align === 'auto') {
if (isFullyWithinViewport) {
// No need to change the position, return the current offset.
return currentOffset;
} else if (alignPreference !== undefined) {
align = alignPreference;
} else if (crossingBottomEdge || bottomEdge <= itemBottom) {
align = 'end';
} else {
align = 'start';
}
}
switch (align) {
case 'start':
// Align item top to the top edge.
return Math.max(0, topOffset - boundedMargin * size) + viewportPadding;
case 'end':
// Align item bottom to the bottom edge.
return bottomOffset + boundedMargin * size + viewportPadding;
case 'center':
// Align item centre to the middle of the viewport
return bottomOffset + (topOffset - bottomOffset) / 2;
case 'top-center':
// Align item top to the middle of the viewport
return topOffset - size / 2;
}
}
/**
* Compute the items range to display.
*
* It returns ``null`` if the range does not need to be updated.
*
* @returns The current items range to display
*/
getRangeToRender(): WindowedList.WindowIndex | null {
let newWindowIndex: [number, number, number, number] = [
0,
Math.max(this.widgetCount - 1, -1),
0,
Math.max(this.widgetCount - 1, -1)
];
const previousLastMeasuredIndex = this._lastMeasuredIndex;
if (this.windowingActive) {
newWindowIndex = this._getRangeToRender();
}
const [startIndex, stopIndex] = newWindowIndex;
if (
previousLastMeasuredIndex <= stopIndex ||
this._currentWindow[0] !== startIndex ||
this._currentWindow[1] !== stopIndex
) {
this._currentWindow = newWindowIndex;
return newWindowIndex;
}
return null;
}
/**
* Return the viewport top position and height for range spanning from
* ``startIndex`` to ``stopIndex``.
*
* @param startIndex First item in viewport index
* @param stopIndex Last item in viewport index
* @returns The viewport top position and its height
*/
getSpan(startIndex: number, stopIndex: number): [number, number] {
const startSize = this._getItemMetadata(startIndex);
const top = startSize.offset;
const stopSize = this._getItemMetadata(stopIndex);
const height = stopSize.offset - startSize.offset + stopSize.size;
return [top, height];
}
/**
* WindowedListModel caches offsets and measurements for each index for performance purposes.
* This method clears that cached data for all items after (and including) the specified index.
*
* The list will automatically re-render after the index is reset.
*
* @param index
*/
resetAfterIndex(index: number): void {
const oldValue = this._lastMeasuredIndex;
this._lastMeasuredIndex = Math.min(index, this._lastMeasuredIndex);
if (this._lastMeasuredIndex !== oldValue) {
this._stateChanged.emit({ name: 'index', newValue: index, oldValue });
}
}
/**
* Update item sizes.
*
* This should be called when the real item sizes has been
* measured.
*
* @param sizes New sizes per item index
* @returns Whether some sizes changed or not
*/
setWidgetSize(sizes: { index: number; size: number }[]): boolean {
if (this._currentWindow[0] >= 0) {
let minIndex = Infinity;
for (const item of sizes) {
const key = item.index;
const size = item.size;
if (this._widgetSizers[key].size != size) {
this._widgetSizers[key].size = size;
minIndex = Math.min(minIndex, key);
}
// Always set the flag in case the size estimator provides perfect result
this._widgetSizers[key].measured = true;
}
// If some sizes changed
if (minIndex != Infinity) {
// Invalid follow-up index
this._lastMeasuredIndex = Math.min(this._lastMeasuredIndex, minIndex);
return true;
}
}
return false;
}
/**
* Callback on list changes
*
* @param list List items
* @param changes List change
*/
protected onListChanged(
list: IObservableList<Widget>,
changes: IObservableList.IChangedArgs<Widget>
): void {
switch (changes.type) {
case 'add':
this._widgetSizers.splice(
changes.newIndex,
0,
...new Array(changes.newValues.length).map((_, i) => {
return { offset: 0, size: this.estimateWidgetSize(i) };
})
);
this.resetAfterIndex(changes.newIndex - 1);
break;
case 'move':
ArrayExt.move(this._widgetSizers, changes.oldIndex, changes.newIndex);
this.resetAfterIndex(Math.min(changes.newIndex, changes.oldIndex) - 1);
break;
case 'remove':
this._widgetSizers.splice(changes.oldIndex, changes.oldValues.length);
this.resetAfterIndex(changes.oldIndex - 1);
break;
case 'set':
this.resetAfterIndex(changes.newIndex - 1);
break;
}
}
private _getItemMetadata(index: number): WindowedList.ItemMetadata {
if (index > this._lastMeasuredIndex) {
let offset = 0;
if (this._lastMeasuredIndex >= 0) {
const itemMetadata = this._widgetSizers[this._lastMeasuredIndex];
offset = itemMetadata.offset + itemMetadata.size;
}
for (let i = this._lastMeasuredIndex + 1; i <= index; i++) {
let size = this._widgetSizers[i]?.measured
? this._widgetSizers[i].size
: this.estimateWidgetSize(i);
this._widgetSizers[i] = {
offset,
size,
measured: this._widgetSizers[i]?.measured
};
offset += size;
}
this._lastMeasuredIndex = index;
}
for (let i = 0; i <= this._lastMeasuredIndex; i++) {
const sizer = this._widgetSizers[i];
if (i === 0) {
if (sizer.offset !== 0) {
throw new Error('First offset is not null');
}
} else {
const previous = this._widgetSizers[i - 1];
if (sizer.offset !== previous.offset + previous.size) {
throw new Error(`Sizer ${i} has incorrect offset.`);
}
}
}
return this._widgetSizers[index];
}
private _findNearestItem(offset: number): number {
const lastMeasuredItemOffset =
this._lastMeasuredIndex > 0
? this._widgetSizers[this._lastMeasuredIndex].offset
: 0;
if (lastMeasuredItemOffset >= offset) {
// If we've already measured items within this range just use a binary search as it's faster.
return this._findNearestItemBinarySearch(
this._lastMeasuredIndex,
0,
offset
);
} else {
// If we haven't yet measured this high, fallback to an exponential search with an inner binary search.
// The exponential search avoids pre-computing sizes for the full set of items as a binary search would.
// The overall complexity for this approach is O(log n).
return this._findNearestItemExponentialSearch(
Math.max(0, this._lastMeasuredIndex),
offset
);
}
}
private _findNearestItemBinarySearch(
high: number,
low: number,
offset: number
): number {
while (low <= high) {
const middle = low + Math.floor((high - low) / 2);
const currentOffset = this._getItemMetadata(middle).offset;
if (currentOffset === offset) {
return middle;
} else if (currentOffset < offset) {
low = middle + 1;
} else if (currentOffset > offset) {
high = middle - 1;
}
}
if (low > 0) {
return low - 1;
} else {
return 0;
}
}
private _findNearestItemExponentialSearch(
index: number,
offset: number
): number {
let interval = 1;
while (
index < this.widgetCount &&
this._getItemMetadata(index).offset < offset
) {
index += interval;
interval *= 2;
}
return this._findNearestItemBinarySearch(
Math.min(index, this.widgetCount - 1),
Math.floor(index / 2),
offset
);
}
private _getRangeToRender(): WindowedList.WindowIndex {
const widgetCount = this.widgetCount;
if (widgetCount === 0) {
return [-1, -1, -1, -1];
}
const startIndex = this._getStartIndexForOffset(this._scrollOffset);
const stopIndex = this._getStopIndexForStartIndex(
startIndex,
this._scrollOffset
);
const overscanBackward = Math.max(1, this.overscanCount);
const overscanForward = Math.max(1, this.overscanCount);
return [
Math.max(0, startIndex - overscanBackward),
Math.max(0, Math.min(widgetCount - 1, stopIndex + overscanForward)),
startIndex,
stopIndex
];
}
private _getStartIndexForOffset(offset: number): number {
return this._findNearestItem(offset);
}
private _getStopIndexForStartIndex(
startIndex: number,
scrollOffset: number
): number {
const size = this._height;
const itemMetadata = this._getItemMetadata(startIndex);
const maxOffset = scrollOffset + size;
let offset = itemMetadata.offset + itemMetadata.size;
let stopIndex = startIndex;
while (stopIndex < this.widgetCount - 1 && offset < maxOffset) {
stopIndex++;
offset += this._getItemMetadata(stopIndex).size;
}
return stopIndex;
}
/**
* Default widget size estimation
*
* @deprecated we always use {@link estimateWidgetSize}
*/
protected _estimatedWidgetSize: number = WindowedList.DEFAULT_WIDGET_SIZE;
protected _stateChanged = new Signal<
WindowedListModel,
IChangedArgs<
any,
any,
| 'count'
| 'estimatedWidgetSize'
| 'index'
| 'list'
| 'overscanCount'
| 'windowingActive'
| string
>
>(this);
private _currentWindow: WindowedList.WindowIndex = [-1, -1, -1, -1];
private _height: number = 0;
private _isDisposed = false;
private _itemsList: ISimpleObservableList | null = null;
private _lastMeasuredIndex: number = -1;
private _overscanCount = 1;
private _scrollOffset: number = 0;
private _widgetCount = 0;
private _widgetSizers: WindowedList.ItemMetadata[] = [];
private _windowingActive = true;
}
/**
* Windowed list widget
*/
export class WindowedList<
T extends WindowedList.IModel = WindowedList.IModel,
U = any
> extends Widget {
/**
* Default widget size
*/
static readonly DEFAULT_WIDGET_SIZE = 50;
/**
* Constructor
*
* @param options Constructor options
*/
constructor(options: WindowedList.IOptions<T, U>) {
const renderer = options.renderer ?? WindowedList.defaultRenderer;
const node = document.createElement('div');
node.className = 'jp-WindowedPanel';
const scrollbarElement = node.appendChild(document.createElement('div'));
scrollbarElement.classList.add('jp-WindowedPanel-scrollbar');
const indicator = scrollbarElement.appendChild(
renderer.createScrollbarViewportIndicator
? renderer.createScrollbarViewportIndicator()
: WindowedList.defaultRenderer.createScrollbarViewportIndicator()
);
indicator.classList.add('jp-WindowedPanel-scrollbar-viewportIndicator');
const list = scrollbarElement.appendChild(renderer.createScrollbar());
list.classList.add('jp-WindowedPanel-scrollbar-content');
const outerElement = node.appendChild(renderer.createOuter());
outerElement.classList.add('jp-WindowedPanel-outer');
const innerElement = outerElement.appendChild(
document.createElement('div')
);
innerElement.className = 'jp-WindowedPanel-inner';
const viewport = innerElement.appendChild(renderer.createViewport());
viewport.classList.add('jp-WindowedPanel-viewport');
super({ node });
super.layout = options.layout ?? new WindowedLayout();
this.renderer = renderer;
this._viewportIndicator = indicator;
this._innerElement = innerElement;
this._isScrolling = null;
this._outerElement = outerElement;
this._itemsResizeObserver = null;
this._scrollbarElement = scrollbarElement;
this._scrollToItem = null;
this._scrollRepaint = null;
this._scrollUpdateWasRequested = false;
this._updater = new Throttler(() => this.update(), 50);
this._viewModel = options.model;
this._viewport = viewport;
if (options.scrollbar) {
node.classList.add('jp-mod-virtual-scrollbar');
}
this.viewModel.stateChanged.connect(this.onStateChanged, this);
}
private _viewportIndicator: HTMLElement;
/**
* Whether the parent is hidden or not.
*
* This should be set externally if a container is hidden to
* stop updating the widget size when hidden.
*/
get isParentHidden(): boolean {
return this._isParentHidden;
}
set isParentHidden(v: boolean) {
this._isParentHidden = v;
}
/**
* Widget layout
*/
get layout(): WindowedLayout {
return super.layout as WindowedLayout;
}
/**
* The outer container of the windowed list.
*/
get outerNode(): HTMLElement {
return this._outerElement;
}
/**
* Viewport
*/
get viewportNode(): HTMLElement {
return this._viewport;
}
/**
* Flag to enable virtual scrollbar.
*/
get scrollbar(): boolean {
return this.node.classList.contains('jp-mod-virtual-scrollbar');
}
set scrollbar(enabled: boolean) {
if (enabled) {
this.node.classList.add('jp-mod-virtual-scrollbar');
} else {
this.node.classList.remove('jp-mod-virtual-scrollbar');
}
this._adjustDimensionsForScrollbar();
this.update();
}
/**
* The renderer for this windowed list. Set at instantiation.
*/
protected renderer: WindowedList.IRenderer<U>;
/**
* Windowed list view model
*/
protected get viewModel(): T {
return this._viewModel;
}
/**
* Dispose the windowed list.
*/
dispose(): void {
this._updater.dispose();
super.dispose();
}
/**
* Callback on event.
*
* @param event Event
*/
handleEvent(event: Event): void {
switch (event.type) {
case 'pointerdown':
event.preventDefault();
event.stopPropagation();
this._evtPointerDown(event as PointerEvent);
break;
case 'scroll':
this.onScroll(event);
break;
}
}
/**
* Scroll to the specified offset `scrollTop`.
*
* @param scrollOffset Offset to scroll
*
* @deprecated since v4 This is an internal helper. Prefer calling `scrollToItem`.
*/
scrollTo(scrollOffset: number): void {
if (!this.viewModel.windowingActive) {
this._outerElement.scrollTo({ top: scrollOffset });
return;
}
scrollOffset = Math.max(0, scrollOffset);
if (scrollOffset !== this.viewModel.scrollOffset) {
this.viewModel.scrollOffset = scrollOffset;
this._scrollUpdateWasRequested = true;
this.update();
}
}
/**
* Scroll to the specified item.
*
* By default, the list will scroll as little as possible to ensure the item is fully visible (`auto`).
* You can control the alignment of the item though by specifying a second alignment parameter.
* Acceptable values are:
*
* auto - Automatically align with the top or bottom minimising the amount scrolled,
* If `alignPreference` is given, follow such preferred alignment.
* If item is smaller than the viewport and fully visible, do not scroll at all.
* smart - If the item is significantly visible, don't scroll at all (regardless of whether it fits in the viewport).
* If the item is less than one viewport away, scroll so that it becomes fully visible (following the `auto` heuristics).
* If the item is more than one viewport away, scroll so that it is centered within the viewport (`center` if smaller than viewport, `top-center` otherwise).
* center - Align the middle of the item with the middle of the viewport (it only works well for items smaller than the viewport).
* top-center - Align the top of the item with the middle of the viewport (works well for items larger than the viewport).
* end - Align the bottom of the item to the bottom of the list.
* start - Align the top of item to the top of the list.
*
* @param index Item index to scroll to
* @param align Type of alignment
* @param margin In 'smart' mode the viewport proportion to add
* @param alignPreference Allows to override the alignment of item when the `auto` heuristic decides that the item needs to be scrolled into view.
*/
scrollToItem(
index: number,
align: WindowedList.ScrollToAlign = 'auto',
margin: number = 0.25,
alignPreference?: WindowedList.BaseScrollToAlignment
): Promise<void> {
if (
!this._isScrolling ||
this._scrollToItem === null ||
this._scrollToItem[0] !== index ||
this._scrollToItem[1] !== align
) {
if (this._isScrolling) {
this._isScrolling.reject('Scrolling to a new item is requested.');
}
this._isScrolling = new PromiseDelegate<void>();
// Catch the internal reject, as otherwise this will
// result in an unhandled promise rejection in test.
this._isScrolling.promise.catch(console.debug);
}
this._scrollToItem = [index, align, margin, alignPreference];
this._resetScrollToItem();
let precomputed = undefined;
if (!this.viewModel.windowingActive) {
const item = this._innerElement.querySelector(
`[data-windowed-list-index="${index}"]`
);
if (!item || !(item instanceof HTMLElement)) {
// Note: this can happen when scroll is requested when a cell is getting added
console.debug(`Element with index ${index} not found`);
return Promise.resolve();
}
precomputed = {
totalSize: this._outerElement.scrollHeight,
itemMetadata: {
offset: item.offsetTop,
size: item.clientHeight
},
currentOffset: this._outerElement.scrollTop
};
}
this.scrollTo(
this.viewModel.getOffsetForIndexAndAlignment(
Math.max(0, Math.min(index, this.viewModel.widgetCount - 1)),
align,
margin,
precomputed,
alignPreference
)
);
return this._isScrolling.promise;
}
/**
* A message handler invoked on an `'after-attach'` message.
*/
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
if (this.viewModel.windowingActive) {
this._applyWindowingStyles();
} else {
this._applyNoWindowingStyles();
}
this._addListeners();
this.viewModel.height = this.node.getBoundingClientRect().height;
const viewportStyle = window.getComputedStyle(this._viewport);
this.viewModel.paddingTop = parseFloat(viewportStyle.paddingTop);
this._viewportPaddingTop = this.viewModel.paddingTop;
this._viewportPaddingBottom = parseFloat(viewportStyle.paddingBottom);
this._scrollbarElement.addEventListener('pointerdown', this);
}
/**
* A message handler invoked on an `'before-detach'` message.
*/
protected onBeforeDetach(msg: Message): void {
this._removeListeners();
this._scrollbarElement.removeEventListener('pointerdown', this);
super.onBeforeDetach(msg);
}
/**
* Callback on scroll event
*
* @param event Scroll event
*/
protected onScroll(event: Event): void {
const { clientHeight, scrollHeight, scrollTop } =
event.currentTarget as HTMLDivElement;
// TBC Firefox is emitting two events one with 1px diff then the _real_ scroll
if (
!this._scrollUpdateWasRequested &&
Math.abs(this.viewModel.scrollOffset - scrollTop) > 1
) {
// Test if the scroll event is jumping to the list bottom
// if (Math.abs(scrollHeight - clientHeight - scrollTop) < 1) {
// // FIXME Does not work because it happens in multiple segments in between which the sizing is changing
// // due to widget resizing. A possible fix would be to keep track of the "old" scrollHeight - clientHeight
// // up to some quiet activity.
// this.scrollToItem(this.widgetCount, 'end');
// } else {
const scrollOffset = Math.max(
0,
Math.min(scrollTop, scrollHeight - clientHeight)
);
this.viewModel.scrollOffset = scrollOffset;
this._scrollUpdateWasRequested = false;
this.update();
// }
}
}
/**
* A message handler invoked on an `'resize-request'` message.
*/
protected onResize(msg: Widget.ResizeMessage): void {
const previousHeight = this.viewModel.height;
this.viewModel.height =
msg.height >= 0 ? msg.height : this.node.getBoundingClientRect().height;
if (this.viewModel.height !== previousHeight) {
void this._updater.invoke();
}
super.onResize(msg);
void this._updater.invoke();
}
/**
* Callback on view model change
*
* @param model Windowed list model
* @param changes Change
*/
protected onStateChanged(
model: WindowedList.IModel,
changes: IChangedArgs<number | boolean, number | boolean, string>
): void {
switch (changes.name) {
case 'windowingActive':
this._removeListeners();
if (this.viewModel.windowingActive) {
this._applyWindowingStyles();
this.onScroll({ currentTarget: this.node } as any);
this._addListeners();
// Bail as onScroll will trigger update
return;
} else {
this._applyNoWindowingStyles();
this._addListeners();
}
break;
case 'estimatedWidgetSize':
// This only impact the container height and should not
// impact the elements in the viewport.
this._updateTotalSize();
return;
}
this.update();
}
/**
* A message handler invoked on an `'update-request'` message.
*
* #### Notes
* The default implementation of this handler is a no-op.
*/
protected onUpdateRequest(msg: Message): void {
if (this.viewModel.windowingActive) {
// Throttle update request
if (this._scrollRepaint === null) {
this._needsUpdate = false;
this._scrollRepaint = window.requestAnimationFrame(() => {
this._scrollRepaint = null;
this._update();
if (this._needsUpdate) {
this.update();
}
});
} else {
// Force re rendering if some changes happen during rendering.
this._needsUpdate = true;
}
} else {
this._update();
}
}
/**
* A signal that emits the index when the virtual scrollbar jumps to an item.
*/
protected jumped = new Signal<this, number>(this);
/*
* Hide the native scrollbar if necessary and update dimensions
*/
private _adjustDimensionsForScrollbar() {
const outer = this._outerElement;
const scrollbar = this._scrollbarElement;
if (this.scrollbar) {
// Query DOM
let outerScrollbarWidth = outer.offsetWidth - outer.clientWidth;
// Update DOM
// 1) The native scrollbar is hidden by shifting it out of view.
if (outerScrollbarWidth == 0) {
// If the scrollbar width is zero, one of the following is true:
// - (a) the content is not overflowing
// - (b) the browser uses overlay scrollbars
// In (b) the overlay scrollbars could show up even even if
// occluded by a child element; to prevent this resulting in
// double scrollbar we shift the content by an arbitrary offset.
outerScrollbarWidth = 1000;
outer.style.paddingRight = `${outerScrollbarWidth}px`;
outer.style.boxSizing = 'border-box';
} else {
outer.style.paddingRight = '0';
}
outer.style.width = `calc(100% + ${outerScrollbarWidth}px)`;
// 2) The inner window is shrank to accommodate the virtual scrollbar
this._innerElement.style.marginRight = `${scrollbar.offsetWidth}px`;
} else {
// Reset all styles that may have been touched.
outer.style.width = '100%';
this._innerElement.style.marginRight = '';
outer.style.paddingRight = '0';
outer.style.boxSizing = '';
}
}
/**
* Add listeners for viewport, contents and the virtual scrollbar.
*/
private _addListeners() {
if (this.viewModel.windowingActive) {
if (!this._itemsResizeObserver) {
this._itemsResizeObserver = new ResizeObserver(
this._onItemResize.bind(this)
);
}
for (const widget of this.layout.widgets) {
this._itemsResizeObserver.observe(widget.node);
widget.disposed.connect(
() => this._itemsResizeObserver?.unobserve(widget.node)
);
}
this._outerElement.addEventListener('scroll', this, passiveIfSupported);
this._scrollbarResizeObserver = new ResizeObserver(
this._adjustDimensionsForScrollbar.bind(this)
);
this._scrollbarResizeObserver.observe(this._outerElement);
this._scrollbarResizeObserver.observe(this._scrollbarElement);
} else {
if (!this._areaResizeObserver) {
this._areaResizeObserver = new ResizeObserver(
this._onAreaResize.bind(this)
);
this._areaResizeObserver.observe(this._innerElement);
}
}
}
/**
* Turn off windowing related styles in the viewport.
*/
private _applyNoWindowingStyles() {
this._viewport.style.position = 'relative';
this._viewport.style.top = '0px';
this._innerElement.style.height = '';
}
/**
* Turn on windowing related styles in the viewport.
*/
private _applyWindowingStyles() {
this._viewport.style.position = 'absolute';
}
/**
* Remove listeners for viewport and contents (but not the virtual scrollbar).
*/
private _removeListeners() {
this._outerElement.removeEventListener('scroll', this);
this._areaResizeObserver?.disconnect();
this._areaResizeObserver = null;
this._itemsResizeObserver?.disconnect();
this._itemsResizeObserver = null;
this._scrollbarResizeObserver?.disconnect();
this._scrollbarResizeObserver = null;
}
/**
* Update viewport and DOM state.
*/
private _update(): void {
if (this.isDisposed || !this.layout) {
return;
}
const newWindowIndex = this.viewModel.getRangeToRender();
if (newWindowIndex !== null) {
const [startIndex, stopIndex, firstVisibleIndex, lastVisibleIndex] =
newWindowIndex;
if (this.scrollbar) {
const scrollbarItems = this._renderScrollbar();
const first = scrollbarItems[firstVisibleIndex];
const last = scrollbarItems[lastVisibleIndex];
this._viewportIndicator.style.top = first.offsetTop - 1 + 'px';
this._viewportIndicator.style.height =
last.offsetTop - first.offsetTop + last.offsetHeight + 'px';
}
const toAdd: Widget[] = [];
if (stopIndex >= 0) {
for (let index = startIndex; index <= stopIndex; index++) {
const widget = this.viewModel.widgetRenderer(index);
widget.dataset.windowedListIndex = `${index}`;
toAdd.push(widget);
}
}
const nWidgets = this.layout.widgets.length;
// Remove not needed widgets
for (let itemIdx = nWidgets - 1; itemIdx >= 0; itemIdx--) {
if (!toAdd.includes(this.layout.widgets[itemIdx])) {
this._itemsResizeObserver?.unobserve(
this.layout.widgets[itemIdx].node
);
this.layout.removeWidget(this.layout.widgets[itemIdx]);
}
}
for (let index = 0; index < toAdd.length; index++) {
const item = toAdd[index];
if (this._itemsResizeObserver && !this.layout.widgets.includes(item)) {
this._itemsResizeObserver.observe(item.node);
item.disposed.connect(
() => this._itemsResizeObserver?.unobserve(item.node)
);
}
// The widget may have moved due to drag-and-drop
this.layout.insertWidget(index, item);
}
if (this.viewModel.windowingActive) {
if (stopIndex >= 0) {
// Read this value after creating the cells.
// So their actual sizes are taken into account
this._updateTotalSize();
// Update position of window container
const [top, minHeight] = this.viewModel.getSpan(
startIndex,
stopIndex
);
this._viewport.style.top = `${top}px`;
this._viewport.style.minHeight = `${minHeight}px`;
} else {
// Update inner container height
this._innerElement.style.height = `0px`;
// Update position of viewport node
this._viewport.style.top = `0px`;
this._viewport.style.minHeight = `0px`;
}
// Update scroll
if (this._scrollUpdateWasRequested) {
this._outerElement.scrollTop = this.viewModel.scrollOffset;
this._scrollUpdateWasRequested = false;
}
}
}
let index2 = -1;
for (const w of this._viewport.children) {
const currentIdx = parseInt(
(w as HTMLElement).dataset.windowedListIndex!,
10
);
if (currentIdx < index2) {
throw new Error('Inconsistent dataset index');
} else {
index2 = currentIdx;
}
}
}
/**
* Handle viewport area resize.
*/
private _onAreaResize(_entries: ResizeObserverEntry[]): void {
this._scrollBackToItemOnResize();
}
/**
* Handle viewport content (i.e. items) resize.
*/
private _onItemResize(entries: ResizeObserverEntry[]): void {
this._resetScrollToItem();
if (this.isHidden || this.isParentHidden) {
return;
}
const newSizes: { index: number; size: number }[] = [];
for (let entry of entries) {
// Update size only if item is attached to the DOM
if (entry.target.isConnected) {
// Rely on the data attribute as some nodes may be hidden instead of detach
// to preserve state.
newSizes.push({
index: parseInt(
(entry.target as HTMLElement).dataset.windowedListIndex!,
10
),
size: entry.borderBoxSize[0].blockSize
});
}
}
// If some sizes changed
if (this.viewModel.setWidgetSize(newSizes)) {
this._scrollBackToItemOnResize();
// Update the list
this.update();
}
}
/**
* Scroll to the item which was most recently requested.
*
* This method ensures that the app scrolls to the item even if a resize event
* occurs shortly after the scroll. Consider the following sequence of events:
*
* 1. User is at the nth cell, presses Shift+Enter (run current cell and
* advance to next)
* 2. App scrolls to the next (n+1) cell
* 3. The nth cell finishes running and renders the output, pushing the
* (n+1) cell down out of view
* 4. This triggers the resize observer, which calls this method and scrolls
* the (n+1) cell back into view
*
* On implementation level, this is ensured by scrolling to `this._scrollToItem`
* which is cleared after a short timeout once the scrolling settles
* (see `this._resetScrollToItem()`).
*/
private _scrollBackToItemOnResize() {
if (!this._scrollToItem) {
return;
}
this.scrollToItem(...this._scrollToItem).catch(reason => {
console.log(reason);
});
}
/**
* Clear any outstanding timeout and enqueue scrolling to a new item.
*/
private _resetScrollToItem(): void {
if (this._resetScrollToItemTimeout) {
clearTimeout(this._resetScrollToItemTimeout);
}
if (this._scrollToItem) {
this._resetScrollToItemTimeout = window.setTimeout(() => {
this._scrollToItem = null;
if (this._isScrolling) {
this._isScrolling.resolve();
this._isScrolling = null;
}
}, MAXIMUM_TIME_REMAINING);
}
}
/**
* Render virtual scrollbar.
*/
private _renderScrollbar(): HTMLElement[] {
const { node, renderer, viewModel } = this;
const content = node.querySelector('.jp-WindowedPanel-scrollbar-content')!;
const elements: HTMLElement[] = [];
const getElement = (
item: ReturnType<WindowedList.IRenderer['createScrollbarItem']>,
index: number
) => {
if (item instanceof HTMLElement) {
return item;
} else {
visitedKeys.add(item.key);
const props = { index };
const cachedItem = this._scrollbarItems[item.key];
if (cachedItem && !cachedItem.isDisposed) {
return cachedItem.render(props);
} else {
this._scrollbarItems[item.key] = item;
const element = item.render(props);
return element;
}
}
};
const list = viewModel.itemsList;
const count = list?.length ?? viewModel.widgetCount;
const visitedKeys = new Set<string>();
for (let index = 0; index < count; index += 1) {
const model = list?.get?.(index);
const item = renderer.createScrollbarItem(this, index, model);
const element: HTMLElement = getElement(item, index);
element.classList.add('jp-WindowedPanel-scrollbar-item');
element.dataset.index = `${index}`;
elements.push(element);
}
// dispose of any elements which are no longer in the scrollbar
const keysNotSeen = Object.keys(this._scrollbarItems).filter(
key => !visitedKeys.has(key)
);
for (const key of keysNotSeen) {
this._scrollbarItems[key].dispose();
delete this._scrollbarItems[key];
}
const oldNodes = [...content.childNodes];
if (
oldNodes.length !== elements.length ||
!oldNodes.every((node, index) => elements[index] === node)
) {
content.replaceChildren(...elements);
}
return elements;
}
private _scrollbarItems: Record<
string,
WindowedList.IRenderer.IScrollbarItem
> = {};
/**
* Handle `pointerdown` events on the virtual scrollbar.
*/
private _evtPointerDown(event: PointerEvent): void {
let target = event.target as HTMLElement;
while (target && target.parentElement) {
if (target.hasAttribute('data-index')) {
const index = parseInt(target.getAttribute('data-index')!, 10);
return void (async () => {
await this.scrollToItem(index);
this.jumped.emit(index);
})();
}
target = target.parentElement;
}
}
/**
* Update the total size
*/
private _updateTotalSize(): void {
if (this.viewModel.windowingActive) {
const estimatedTotalHeight = this.viewModel.getEstimatedTotalSize();
const heightWithPadding =
estimatedTotalHeight +
this._viewportPaddingTop +
this._viewportPaddingBottom;
// Update inner container height
this._innerElement.style.height = `${heightWithPadding}px`;
}
}
protected _viewModel: T;
private _viewportPaddingTop: number = 0;
private _viewportPaddingBottom: number = 0;
private _innerElement: HTMLElement;
private _isParentHidden: boolean;
private _isScrolling: PromiseDelegate<void> | null;
private _needsUpdate = false;
private _outerElement: HTMLElement;
private _resetScrollToItemTimeout: number | null;
private _areaResizeObserver: ResizeObserver | null;
private _itemsResizeObserver: ResizeObserver | null;
private _scrollbarElement: HTMLElement;
private _scrollbarResizeObserver: ResizeObserver | null;
private _scrollRepaint: number | null;
private _scrollToItem:
| [
number,
WindowedList.ScrollToAlign,
number,
WindowedList.BaseScrollToAlignment | undefined
]
| null;
private _scrollUpdateWasRequested: boolean;
private _updater: Throttler;
private _viewport: HTMLElement;
}
/**
* Customized layout for windowed list container.
*/
export class WindowedLayout extends PanelLayout {
/**
* Constructor
*/
constructor() {
super({ fitPolicy: 'set-no-constraint' });
}
/**
* Specialized parent type definition
*/
get parent(): WindowedList | null {
return super.parent as WindowedList | null;
}
set parent(value: WindowedList | null) {
super.parent = value;
}
/**
* Attach a widget to the parent's DOM node.
*
* @param index - The current index of the widget in the layout.
*
* @param widget - The widget to attach to the parent.
*
* #### Notes
* This method is called automatically by the panel layout at the
* appropriate time. It should not be called directly by user code.
*
* The default implementation adds the widgets's node to the parent's
* node at the proper location, and sends the appropriate attach
* messages to the widget if the parent is attached to the DOM.
*
* Subclasses may reimplement this method to control how the widget's
* node is added to the parent's node.
*/
protected attachWidget(index: number, widget: Widget): void {
// Look up the next sibling reference node.
let ref = this.parent!.viewportNode.children[index];
// Send a `'before-attach'` message if the parent is attached.
if (this.parent!.isAttached) {
MessageLoop.sendMessage(widget, Widget.Msg.BeforeAttach);
}
// Insert the widget's node before the sibling.
this.parent!.viewportNode.insertBefore(widget.node, ref);
// Send an `'after-attach'` message if the parent is attached.
if (this.parent!.isAttached) {
MessageLoop.sendMessage(widget, Widget.Msg.AfterAttach);
}
}
/**
* Detach a widget from the parent's DOM node.
*
* @param index - The previous index of the widget in the layout.
*
* @param widget - The widget to detach from the parent.
*
* #### Notes
* This method is called automatically by the panel layout at the
* appropriate time. It should not be called directly by user code.
*
* The default implementation removes the widget's node from the
* parent's node, and sends the appropriate detach messages to the
* widget if the parent is attached to the DOM.
*
* Subclasses may reimplement this method to control how the widget's
* node is removed from the parent's node.
*/
protected detachWidget(index: number, widget: Widget): void {
// Send a `'before-detach'` message if the parent is attached.
if (this.parent!.isAttached) {
MessageLoop.sendMessage(widget, Widget.Msg.BeforeDetach);
}
// Remove the widget's node from the parent.
this.parent!.viewportNode.removeChild(widget.node);
// Send an `'after-detach'` message if the parent is attached.
if (this.parent!.isAttached) {
MessageLoop.sendMessage(widget, Widget.Msg.AfterDetach);
}
}
/**
* Move a widget in the parent's DOM node.
*
* @param fromIndex - The previous index of the widget in the layout.
*
* @param toIndex - The current index of the widget in the layout.
*
* @param widget - The widget to move in the parent.
*
* #### Notes
* This method is called automatically by the panel layout at the
* appropriate time. It should not be called directly by user code.
*
* The default implementation moves the widget's node to the proper
* location in the parent's node and sends the appropriate attach and
* detach messages to the widget if the parent is attached to the DOM.
*
* Subclasses may reimplement this method to control how the widget's
* node is moved in the parent's node.
*/
protected moveWidget(
fromIndex: number,
toIndex: number,
widget: Widget
): void {
// Optimize move without de-/attaching as motion appends with parent attached
// Case fromIndex === toIndex, already checked in PanelLayout.insertWidget
// Look up the next sibling reference node.
let ref = this.parent!.viewportNode.children[toIndex];
if (fromIndex < toIndex) {
ref.insertAdjacentElement('afterend', widget.node);
} else {
ref.insertAdjacentElement('beforebegin', widget.node);
}
}
/**
* A message handler invoked on an `'update-request'` message.
*
* #### Notes
* This is a reimplementation of the base class method,
* and is a no-op.
*/
protected onUpdateRequest(msg: Message): void {
// This is a no-op.
}
}
/**
* Windowed list model interface
*/
export interface ISimpleObservableList<T = any> {
get?: (index: number) => T;
length: number;
changed: ISignal<any, IObservableList.IChangedArgs<any>>;
}
/**
* A namespace for windowed list
*/
export namespace WindowedList {
/**
* The default renderer class for windowed lists.
*/
export class Renderer<T = any> implements IRenderer<T> {
/**
* Create the outer, root element of the windowed list.
*/
createOuter(): HTMLElement {
return document.createElement('div');
}
/**
* Create the virtual scrollbar element.
*/
createScrollbar(): HTMLOListElement {
return document.createElement('ol');
}
/**
* Create the virtual scrollbar viewport indicator.
*/
createScrollbarViewportIndicator(): HTMLElement {
return document.createElement('div');
}
/**
* Create an individual item rendered in the scrollbar.
*/
createScrollbarItem(_: WindowedList, index: number): HTMLLIElement {
const li = document.createElement('li');
li.appendChild(document.createTextNode(`${index}`));
return li;
}
/**
* Create the viewport element into which virtualized children are added.
*/
createViewport(): HTMLElement {
return document.createElement('div');
}
}
/**
* The default renderer for windowed lists.
*/
export const defaultRenderer = new Renderer();
/**
* Windowed list model interface
*/
export interface IModel<T = any> extends IDisposable {
/**
* Provide a best guess for the widget size at position index
*
* #### Notes
*
* This function should be very light to compute especially when
* returning the default size.
* The default value should be constant (i.e. two calls with `null` should
* return the same value). But it can change for a given `index`.
*
* @param index Widget position
* @returns Estimated widget size
*/
estimateWidgetSize: (index: number) => number;
/**
* Get the total list size.
*
* @returns Total estimated size
*/
getEstimatedTotalSize(): number;
/**
* Get the scroll offset to display an item in the viewport.
*
* By default, the list will scroll as little as possible to ensure the item is fully visible (`auto`).
* You can control the alignment of the item though by specifying a second alignment parameter.
* Acceptable values are:
*
* auto - Automatically align with the top or bottom minimising the amount scrolled,
* If `alignPreference` is given, follow such preferred alignment.
* If item is smaller than the viewport and fully visible, do not scroll at all.
* smart - If the item is significantly visible, don't scroll at all (regardless of whether it fits in the viewport).
* If the item is less than one viewport away, scroll so that it becomes fully visible (following the `auto` heuristics).
* If the item is more than one viewport away, scroll so that it is centered within the viewport (`center` if smaller than viewport, `top-center` otherwise).
* center - Align the middle of the item with the middle of the viewport (it only works well for items smaller than the viewport).
* top-center - Align the top of the item with the middle of the viewport (works well for items larger than the viewport).
* end - Align the bottom of the item to the bottom of the list.
* start - Align the top of item to the top of the list.
*
* @param index Item index
* @param align Where to align the item in the viewport
* @param margin In 'smart' mode the viewport proportion to add
* @param precomputed Precomputed values to use when windowing is disabled.
* @param alignPreference Allows to override the alignment of item when the `auto` heuristic decides that the item needs to be scrolled into view.
* @returns The needed scroll offset
*/
getOffsetForIndexAndAlignment(
index: number,
align?: ScrollToAlign,
margin?: number,
precomputed?: {
totalSize: number;
itemMetadata: WindowedList.ItemMetadata;
currentOffset: number;
},
alignPreference?: WindowedList.BaseScrollToAlignment
): number;
/**
* Compute the items range to display.
*
* It returns ``null`` if the range does not need to be updated.
*
* @returns The current items range to display
*/
getRangeToRender(): WindowIndex | null;
/**
* Return the viewport top position and height for range spanning from
* ``startIndex`` to ``stopIndex``.
*
* @param start First item in viewport index
* @param stop Last item in viewport index
* @returns The viewport top position and its height
*/
getSpan(start: number, stop: number): [number, number];
/**
* List widget height
*/
height: number;
/**
* Top padding of the the outer window node.
*/
paddingTop?: number;
/**
* Items list to be rendered
*/
itemsList: ISimpleObservableList<T> | null;
/**
* Number of widgets to render in addition to those
* visible in the viewport.
*/
overscanCount: number;
/**
* WindowedListModel caches offsets and measurements for each index for performance purposes.
* This method clears that cached data for all items after (and including) the specified index.
*
* The list will automatically re-render after the index is reset.
*
* @param index
*/
resetAfterIndex(index: number): void;
/**
* Viewport scroll offset.
*/
scrollOffset: number;
/**
* Update item sizes.
*
* This should be called when the real item sizes has been
* measured.
*
* @param sizes New sizes per item index
* @returns Whether some sizes changed or not
*/
setWidgetSize(sizes: { index: number; size: number }[]): boolean;
/**
* A signal emitted when any model state changes.
*/
readonly stateChanged: ISignal<
IModel,
IChangedArgs<
any,
any,
| 'count'
| 'index'
| 'list'
| 'overscanCount'
| 'windowingActive'
| string
>
>;
/**
* Total number of widgets in the list
*/
widgetCount: number;
/**
* Whether windowing is active or not.
*/
windowingActive: boolean;
/**
* Widget factory for the list items.
*
* Caching the resulting widgets should be done by the callee.
*
* @param index List index
* @returns The widget at the given position
*/
widgetRenderer: (index: number) => Widget;
}
/**
* Windowed list model constructor options
*/
export interface IModelOptions {
/**
* Total number of widgets in the list.
*
* #### Notes
* If an observable list is provided this will be ignored.
*/
count?: number;
/**
* Dynamic list of items
*/
itemsList?: IObservableList<any>;
/**
* Number of widgets to render in addition to those
* visible in the viewport.
*/
overscanCount?: number;
/**
* Whether windowing is active or not.
*
* This is true by default.
*/
windowingActive?: boolean;
}
/**
* Windowed list view constructor options
*/
export interface IOptions<
T extends WindowedList.IModel = WindowedList.IModel,
U = any
> {
/**
* Windowed list model to display
*/
model: T;
/**
* Windowed list layout
*/
layout?: WindowedLayout;
/**
* A renderer for the elements of the windowed list.
*/
renderer?: IRenderer<U>;
/**
* Whether the windowed list should display a scrollbar UI.
*/
scrollbar?: boolean;
}
/**
* A windowed list element renderer.
*/
export interface IRenderer<T = any> {
/**
* Create the outer, root element of the windowed list.
*/
createOuter(): HTMLElement;
/**
* Create the virtual scrollbar element.
*/
createScrollbar(): HTMLElement;
/**
* Create the virtual scrollbar viewport indicator.
*/
createScrollbarViewportIndicator?(): HTMLElement;
/**
* Create an individual item rendered in the scrollbar.
*/
createScrollbarItem(
list: WindowedList,
index: number,
item: T | undefined
): HTMLElement | IRenderer.IScrollbarItem;
/**
* Create the viewport element into which virtualized children are added.
*/
createViewport(): HTMLElement;
}
/**
* Renderer statics.
*/
export namespace IRenderer {
/**
* Scrollbar item.
*/
export interface IScrollbarItem extends IDisposable {
/**
* Render the scrollbar item as an HTML element.
*/
render: (props: { index: number }) => HTMLElement;
/**
* Unique item key used for caching.
*/
key: string;
}
}
/**
* Item list metadata
*/
export type ItemMetadata = {
/**
* Item vertical offset in the container
*/
offset: number;
/**
* Item height
*/
size: number;
/**
* Whether the size is an estimation or a measurement.
*/
measured?: boolean;
};
/**
* Basic type of scroll alignment
*/
export type BaseScrollToAlignment = 'center' | 'top-center' | 'start' | 'end';
/**
* Type of scroll alignment including `auto` and `smart`
*/
export type ScrollToAlign = 'auto' | 'smart' | BaseScrollToAlignment;
/**
* Widget range in view port
*/
export type WindowIndex = [number, number, number, number];
}
``` | /content/code_sandbox/packages/ui-components/src/components/windowedlist.ts | xml | 2016-06-03T20:09:17 | 2024-08-16T19:12:44 | jupyterlab | jupyterlab/jupyterlab | 14,019 | 14,690 |
```xml
import { Injectable } from '@angular/core';
import { Session, PublisherProperties, OpenVidu, Publisher, Connection } from 'openvidu-browser';
import { Signal } from '../../models/signal.model';
@Injectable({
providedIn: 'root'
})
export class OpenViduServiceMock {
private OV: OpenVidu = null;
private OVScreen: OpenVidu = null;
private webcamSession: Session = null;
private screenSession: Session = null;
private videoSource = undefined;
private audioSource = undefined;
private screenMediaStream: MediaStream = null;
private webcamMediaStream: MediaStream = null;
constructor() {}
initialize() {}
initSessions() {}
getWebcamSession(): Session {
return null;
}
initializeWebcamSession(): void {}
initializeScreenSession(): void {}
getScreenSession(): Session {
return null;
}
async connectWebcamSession(token: string): Promise<any> {}
disconnectWebcamSession(): void {}
async connectScreenSession(token: string): Promise<any> {}
disconnectScreenSession(): void {}
disconnect() {}
initPublisher(targetElement: string | HTMLElement, properties: PublisherProperties): Publisher {
return null;
}
initPublisherAsync(targetElement: string | HTMLElement, properties: PublisherProperties): Promise<Publisher> {
return null;
}
destroyWebcamPublisher(): void {}
destroyScreenPublisher(): void {}
async publishWebcamPublisher(): Promise<any> {}
unpublishWebcamPublisher(): void {}
async publishScreenPublisher(): Promise<any> {}
unpublishScreenPublisher(): void {}
publishWebcamVideo(active: boolean): void {}
publishWebcamAudio(active: boolean): void {}
publishScreenAudio(active: boolean): void {}
replaceTrack(videoSource: string, audioSource: string, mirror: boolean = true): Promise<any> {
return new Promise((resolve, reject) => {});
}
sendSignal(type: Signal, connection?: Connection, data?: any): void {}
createPublisherProperties(
videoSource: string | MediaStreamTrack | boolean,
audioSource: string | MediaStreamTrack | boolean,
publishVideo: boolean,
publishAudio: boolean,
mirror: boolean
): PublisherProperties {
return {};
}
async replaceScreenTrack() {}
stopAudioTracks(mediaStream: MediaStream) {}
stopVideoTracks(mediaStream: MediaStream) {}
needSendNicknameSignal(): boolean {
return false;
}
isMyOwnConnection(connectionId: string): boolean {
return false;
}
getSessionOfUserConnected(): Session {
return null;
}
private stopScreenTracks() {}
}
``` | /content/code_sandbox/openvidu-components-angular/projects/openvidu-components-angular/src/lib/services/openvidu/openvidu.service.mock.ts | xml | 2016-10-10T13:31:27 | 2024-08-15T12:14:04 | openvidu | OpenVidu/openvidu | 1,859 | 541 |
```xml
import React, { useEffect, useMemo, useRef, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Link, useLocation, useNavigate } from "react-router-dom";
import { Button, Divider, Tooltip } from "antd";
import { useFeatureIsOn } from "@growthbook/growthbook-react";
import CharlesIcon from "assets/icons/charlesIcon.svg?react";
import ModheaderIcon from "assets/icons/modheaderIcon.svg?react";
import { ImportFromCharlesModal } from "../../ImporterComponents/CharlesImporter";
import { ImportRulesModal } from "../../../../../../../modals/ImportRulesModal";
import { AuthConfirmationPopover } from "components/hoc/auth/AuthConfirmationPopover";
import APP_CONSTANTS from "config/constants";
import { SOURCE } from "modules/analytics/events/common/constants";
import { getUserAuthDetails, getAppMode, getUserPersonaSurveyDetails } from "store/selectors";
import PersonaRecommendation from "../PersonaRecommendation";
import { shouldShowRecommendationScreen } from "features/personaSurvey/utils";
import {
trackGettingStartedVideoPlayed,
trackNewRuleButtonClicked,
trackRulesEmptyStateClicked,
} from "modules/analytics/events/common/rules";
import {
trackRulesImportStarted,
trackUploadRulesButtonClicked,
trackCharlesSettingsImportStarted,
} from "modules/analytics/events/features/rules";
import { ImportFromModheaderModal } from "../../ImporterComponents/ModheaderImporter/ImportFromModheaderModal";
import emptyInbox from "./empty-inbox.svg";
import { MdOutlineAddCircleOutline } from "@react-icons/all-files/md/MdOutlineAddCircleOutline";
import { MdOutlineHelpOutline } from "@react-icons/all-files/md/MdOutlineHelpOutline";
import { MdOutlineFileUpload } from "@react-icons/all-files/md/MdOutlineFileUpload";
import { HiOutlineTemplate } from "@react-icons/all-files/hi/HiOutlineTemplate";
import { MdInfoOutline } from "@react-icons/all-files/md/MdInfoOutline";
import { RuleType } from "types";
import RULE_TYPES_CONFIG from "config/constants/sub/rule-types";
import { RuleSelectionListDrawer } from "../../RuleSelectionListDrawer/RuleSelectionListDrawer";
import { trackAskAIClicked } from "features/requestBot";
import { RQButton } from "lib/design-system/components";
import BotIcon from "assets/icons/bot.svg?react";
import { actions } from "store";
import { getCurrentlyActiveWorkspace, getIsWorkspaceMode } from "store/features/teams/selectors";
import { redirectToTeam } from "utils/RedirectionUtils";
import { useIsRedirectFromCreateRulesRoute } from "../../../hooks/useIsRedirectFromCreateRulesRoute";
import "./gettingStarted.scss";
const { PATHS } = APP_CONSTANTS;
export const GettingStarted: React.FC = () => {
const navigate = useNavigate();
const { state } = useLocation();
const dispatch = useDispatch();
const user = useSelector(getUserAuthDetails);
const appMode = useSelector(getAppMode);
const userPersona = useSelector(getUserPersonaSurveyDetails);
const isWorkspaceMode = useSelector(getIsWorkspaceMode);
const currentlyActiveWorkspace = useSelector(getCurrentlyActiveWorkspace);
const gettingStartedVideo = useRef(null);
const [isImportRulesModalActive, setIsImportRulesModalActive] = useState(false);
const [isImportCharlesRulesModalActive, setIsImportCharlesRulesModalActive] = useState(false);
const [isImportModheaderRulesModalActive, setIsImportModheaderRulesModalActive] = useState(false);
const isRedirectFromCreateRulesRoute = useIsRedirectFromCreateRulesRoute();
const [isRulesListDrawerOpen, setIsRulesListDrawerOpen] = useState(isRedirectFromCreateRulesRoute || false);
const onRulesListDrawerClose = () => {
setIsRulesListDrawerOpen(false);
};
const isCharlesImportFeatureFlagOn = useFeatureIsOn("import_rules_from_charles");
const isRecommendationScreenVisible = useMemo(
() => shouldShowRecommendationScreen(userPersona, appMode, state?.src),
[appMode, state?.src, userPersona]
);
const toggleImportRulesModal = () => {
setIsImportRulesModalActive((prev) => !prev);
};
const toggleImportCharlesRulesModal = () => {
setIsImportCharlesRulesModalActive((prev) => !prev);
};
const toggleImportModheaderRulesModal = () => {
setIsImportModheaderRulesModalActive((prev) => !prev);
};
const handleNewRuleClick = (source: string) => {
trackNewRuleButtonClicked(SOURCE.GETTING_STARTED);
trackRulesEmptyStateClicked(source);
setIsRulesListDrawerOpen(true);
};
const handleUploadRulesClick = () => {
setIsImportRulesModalActive(true);
trackRulesImportStarted();
};
useEffect(() => {
if (gettingStartedVideo.current) {
gettingStartedVideo.current.addEventListener("play", () => {
trackGettingStartedVideoPlayed();
});
}
}, []);
if (isRecommendationScreenVisible) {
return <PersonaRecommendation handleUploadRulesClick={handleUploadRulesClick} />;
}
const suggestedRules = [
{
type: RuleType.REDIRECT,
title: "Redirect a request",
icon: RULE_TYPES_CONFIG[RuleType.REDIRECT].ICON,
link: PATHS.RULE_EDITOR.CREATE_RULE.REDIRECT_RULE.ABSOLUTE,
help: "Redirect scripts, APIs, Stylesheets, or any other resource from one environment to another.",
},
{
type: RuleType.RESPONSE,
title: "Override API response",
icon: RULE_TYPES_CONFIG[RuleType.RESPONSE].ICON,
link: PATHS.RULE_EDITOR.CREATE_RULE.RESPONSE_RULE.ABSOLUTE,
help: "Stub API responses to simulate required scenarios effectively.",
},
{
type: RuleType.HEADERS,
title: "Add/Remove header",
icon: RULE_TYPES_CONFIG[RuleType.HEADERS].ICON,
link: PATHS.RULE_EDITOR.CREATE_RULE.HEADERS_RULE.ABSOLUTE,
help: "Modify HTTP headers based conditionally to test frontend or backend behavior.",
},
];
return (
<>
<div className="v2 getting-started-container">
<div className="getting-started-content">
{isWorkspaceMode ? (
<div className="workspace-title-container">
<div className="workspace-title">
<MdInfoOutline />
This is a shared workspace
</div>
<div className="lead">
Rules created here can be accessed by your teammates. To manage your teammates{" "}
<a
href="path_to_url"
className="cursor-pointer"
onClick={(e) => {
e.preventDefault();
redirectToTeam(navigate, currentlyActiveWorkspace.id);
}}
>
click here
</a>
.
</div>
</div>
) : null}
<div className="create-new-rule-container">
<div className="create-new-rule-title">Create new rule</div>
<div className="create-new-rule-content">
<div className="no-rules">
<div className="empty-rules-image-container">
<img width={72} height={72} src={emptyInbox} alt="empty-rules" className="empty-rules" />
<div className="caption">No rules created yet</div>
</div>
<RuleSelectionListDrawer
open={isRulesListDrawerOpen}
onClose={onRulesListDrawerClose}
source={SOURCE.GETTING_STARTED}
onRuleItemClick={() => {
onRulesListDrawerClose();
}}
>
<Button
block
type="primary"
onClick={() => handleNewRuleClick("new_rule")}
className="getting-started-create-rule-btn"
icon={<MdOutlineAddCircleOutline className="anticon" />}
>
New rule
</Button>
</RuleSelectionListDrawer>
</div>
<div className="rule-suggestions">
{suggestedRules.map(({ type, title, icon, link, help }) => {
return (
<Link
to={link}
key={type}
className="suggested-rule-link"
state={{ source: "rules_empty_state" }}
onClick={() => {
trackRulesEmptyStateClicked(type);
}}
>
<span className="icon">{icon()}</span>
<span className="title">{title}</span>
{help ? (
<Tooltip title={help}>
<span className="help-icon">
<MdOutlineHelpOutline />
</span>
</Tooltip>
) : null}
</Link>
);
})}
<RuleSelectionListDrawer
open={isRulesListDrawerOpen}
onClose={onRulesListDrawerClose}
source={SOURCE.GETTING_STARTED}
onRuleItemClick={() => {
onRulesListDrawerClose();
}}
>
<Button type="link" className="link-btn" onClick={() => handleNewRuleClick("view_all_rule_types")}>
View all rule types
</Button>
</RuleSelectionListDrawer>
</div>
</div>
</div>
<Divider className="divider" />
<div className="getting-started-actions">
<AuthConfirmationPopover
title="You need to sign up to upload rules"
callback={handleUploadRulesClick}
source={SOURCE.UPLOAD_RULES}
disabled={window.isChinaUser}
>
<Button
type="link"
className="link-btn"
icon={<MdOutlineFileUpload className="anticon" />}
onClick={() => {
trackRulesEmptyStateClicked("import_json");
trackUploadRulesButtonClicked(SOURCE.GETTING_STARTED);
user?.details?.isLoggedIn && handleUploadRulesClick();
}}
>
Upload rules
</Button>
</AuthConfirmationPopover>
{/* TODO: make desktop only */}
{isCharlesImportFeatureFlagOn ? (
<>
<Button
type="link"
className="link-btn"
icon={<CharlesIcon className="anticon" />}
onClick={() => {
toggleImportCharlesRulesModal();
trackRulesEmptyStateClicked("import_charles");
trackCharlesSettingsImportStarted(SOURCE.GETTING_STARTED);
}}
>
Import from Charles
</Button>
<Button
type="link"
className="link-btn"
icon={<ModheaderIcon className="anticon" />}
onClick={() => {
toggleImportModheaderRulesModal();
trackRulesEmptyStateClicked("import_modheader");
trackCharlesSettingsImportStarted(SOURCE.GETTING_STARTED);
}}
>
Import from ModHeader
</Button>
</>
) : null}
<Button
type="link"
className="link-btn templates-btn"
icon={<HiOutlineTemplate className="anticon" />}
onClick={() => {
trackRulesEmptyStateClicked("templates");
navigate(PATHS.RULES.TEMPLATES.ABSOLUTE);
}}
>
Start with templates
</Button>
</div>
<div className="ask-ai-container">
<div className="title">Ask AI for any help with using Requestly</div>
<div>
<RQButton
block
className="ask-ai-btn"
onClick={() => {
trackAskAIClicked("rules_empty_state");
trackRulesEmptyStateClicked("ai_bot");
dispatch(actions.updateRequestBot({ isActive: true, modelType: "app" }));
}}
>
<div className="ask-ai-btn-content">
<BotIcon />
e.g. How can I insert custom CSS code on a web page?
</div>
</RQButton>
</div>
</div>
</div>
</div>
{isImportCharlesRulesModalActive ? (
<ImportFromCharlesModal
isOpen={isImportCharlesRulesModalActive}
toggle={toggleImportCharlesRulesModal}
triggeredBy={SOURCE.GETTING_STARTED}
/>
) : null}
{isImportModheaderRulesModalActive ? (
<ImportFromModheaderModal
isOpen={isImportModheaderRulesModalActive}
toggle={toggleImportModheaderRulesModal}
triggeredBy={SOURCE.GETTING_STARTED}
/>
) : null}
{isImportRulesModalActive ? (
<ImportRulesModal isOpen={isImportRulesModalActive} toggle={toggleImportRulesModal} />
) : null}
</>
);
};
``` | /content/code_sandbox/app/src/features/rules/screens/rulesList/components/RulesList/components/GettingStarted/v2/index.tsx | xml | 2016-12-01T04:36:06 | 2024-08-16T19:12:19 | requestly | requestly/requestly | 2,121 | 2,648 |
```xml
export function serverAutoImported () {
return 'serverAutoImported'
}
export const someUtils = 'utils'
``` | /content/code_sandbox/test/fixtures/basic/modules/auto-registered/runtime/some-server-import.ts | xml | 2016-10-26T11:18:47 | 2024-08-16T19:32:46 | nuxt | nuxt/nuxt | 53,705 | 26 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
path_to_url
Unless required by applicable law or agreed to in writing,
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
specific language governing permissions and limitations
-->
<!DOCTYPE concept PUBLIC "-//OASIS//DTD DITA Concept//EN" "concept.dtd">
<concept id="limit">
<title>LIMIT Clause</title>
<prolog>
<metadata>
<data name="Category" value="Impala"/>
<data name="Category" value="SQL"/>
<data name="Category" value="Querying"/>
<data name="Category" value="Reports"/>
<data name="Category" value="Developers"/>
<data name="Category" value="Data Analysts"/>
</metadata>
</prolog>
<conbody>
<p>
The <codeph>LIMIT</codeph> clause in a <codeph>SELECT</codeph> query sets a maximum number of rows for the
result set. Pre-selecting the maximum size of the result set helps Impala to optimize memory usage while
processing a distributed query.
</p>
<p conref="../shared/impala_common.xml#common/syntax_blurb"/>
<codeblock>LIMIT <varname>constant_integer_expression</varname></codeblock>
<p>
The argument to the <codeph>LIMIT</codeph> clause must evaluate to a constant value. It can be a numeric
literal, or another kind of numeric expression involving operators, casts, and function return values. You
cannot refer to a column or use a subquery.
</p>
<p conref="../shared/impala_common.xml#common/usage_notes_blurb"/>
<p>
This clause is useful in contexts such as:
</p>
<ul>
<li>
To return exactly N items from a top-N query, such as the 10 highest-rated items in a shopping category or
the 50 hostnames that refer the most traffic to a web site.
</li>
<li>
To demonstrate some sample values from a table or a particular query. (To display some arbitrary items, use
a query with no <codeph>ORDER BY</codeph> clause. An <codeph>ORDER BY</codeph> clause causes additional
memory and/or disk usage during the query.)
</li>
<li>
To keep queries from returning huge result sets by accident if a table is larger than expected, or a
<codeph>WHERE</codeph> clause matches more rows than expected.
</li>
</ul>
<p rev="1.2.1">
Originally, the value for the <codeph>LIMIT</codeph> clause had to be a numeric literal. In Impala 1.2.1 and
higher, it can be a numeric expression.
</p>
<p rev="obwl" conref="../shared/impala_common.xml#common/order_by_limit"/>
<p>
See <xref href="impala_order_by.xml#order_by"/> for details.
</p>
<p conref="../shared/impala_common.xml#common/limit_and_offset"/>
<p conref="../shared/impala_common.xml#common/restrictions_blurb"/>
<p conref="../shared/impala_common.xml#common/subquery_no_limit"/>
<p conref="../shared/impala_common.xml#common/example_blurb"/>
<p>
The following example shows how the <codeph>LIMIT</codeph> clause caps the size of the result set, with the
limit being applied after any other clauses such as <codeph>WHERE</codeph>.
</p>
<codeblock>[localhost:21000] > create database limits;
[localhost:21000] > use limits;
[localhost:21000] > create table numbers (x int);
[localhost:21000] > insert into numbers values (1), (3), (4), (5), (2);
Inserted 5 rows in 1.34s
[localhost:21000] > select x from numbers limit 100;
+---+
| x |
+---+
| 1 |
| 3 |
| 4 |
| 5 |
| 2 |
+---+
Returned 5 row(s) in 0.26s
[localhost:21000] > select x from numbers limit 3;
+---+
| x |
+---+
| 1 |
| 3 |
| 4 |
+---+
Returned 3 row(s) in 0.27s
[localhost:21000] > select x from numbers where x > 2 limit 2;
+---+
| x |
+---+
| 3 |
| 4 |
+---+
Returned 2 row(s) in 0.27s</codeblock>
<p>
For top-N and bottom-N queries, you use the <codeph>ORDER BY</codeph> and <codeph>LIMIT</codeph> clauses
together:
</p>
<codeblock rev="obwl">[localhost:21000] > select x as "Top 3" from numbers order by x desc limit 3;
+-------+
| top 3 |
+-------+
| 5 |
| 4 |
| 3 |
+-------+
[localhost:21000] > select x as "Bottom 3" from numbers order by x limit 3;
+----------+
| bottom 3 |
+----------+
| 1 |
| 2 |
| 3 |
+----------+
</codeblock>
<p>
You can use constant values besides integer literals as the <codeph>LIMIT</codeph> argument:
</p>
<codeblock>-- Other expressions that yield constant integer values work too.
SELECT x FROM t1 LIMIT 1e6; -- Limit is one million.
SELECT x FROM t1 LIMIT length('hello world'); -- Limit is 11.
SELECT x FROM t1 LIMIT 2+2; -- Limit is 4.
SELECT x FROM t1 LIMIT cast(truncate(9.9) AS INT); -- Limit is 9.
</codeblock>
</conbody>
</concept>
``` | /content/code_sandbox/docs/topics/impala_limit.xml | xml | 2016-04-13T07:00:08 | 2024-08-16T10:10:44 | impala | apache/impala | 1,115 | 1,408 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="EpoxyRecyclerView">
<attr name="itemSpacing" format="dimension" />
</declare-styleable>
</resources>
``` | /content/code_sandbox/epoxy-adapter/src/main/res/values/attrs.xml | xml | 2016-08-08T23:05:11 | 2024-08-16T16:11:07 | epoxy | airbnb/epoxy | 8,486 | 52 |
```xml
import * as React from 'react';
import fakeRestProvider from 'ra-data-fakerest';
import defaultMessages from 'ra-language-english';
import polyglotI18nProvider from 'ra-i18n-polyglot';
import {
Resource,
useListContext,
useInfinitePaginationContext,
TestMemoryRouter,
} from 'ra-core';
import { Box, Button, Card, Typography } from '@mui/material';
import { InfiniteList } from './InfiniteList';
import { SimpleList } from './SimpleList';
import { Datagrid } from './datagrid';
import {
InfinitePagination,
Pagination as DefaultPagination,
} from './pagination';
import { AdminUI } from '../AdminUI';
import { AdminContext } from '../AdminContext';
import { TextField } from '../field';
import { SearchInput } from '../input';
import { SortButton } from '../button';
import { TopToolbar, Layout } from '../layout';
export default {
title: 'ra-ui-materialui/list/InfiniteList',
};
const data = {
books: [
{ id: 1, title: 'War and Peace', author: 'Leo Tolstoy' },
{
id: 2,
title: 'The Little Prince',
author: 'Antoine de Saint-Exupry',
},
{ id: 3, title: "Swann's Way", author: 'Marcel Proust' },
{ id: 4, title: 'A Tale of Two Cities', author: 'Charles Dickens' },
{ id: 5, title: 'The Lord of the Rings', author: 'J. R. R. Tolkien' },
{ id: 6, title: 'And Then There Were None', author: 'Agatha Christie' },
{ id: 7, title: 'Dream of the Red Chamber', author: 'Cao Xueqin' },
{ id: 8, title: 'The Hobbit', author: 'J. R. R. Tolkien' },
{
id: 9,
title: 'She: A History of Adventure',
author: 'H. Rider Haggard',
},
{
id: 10,
title: 'The Lion, the Witch and the Wardrobe',
author: 'C. S. Lewis',
},
{ id: 11, title: 'The Chronicles of Narnia', author: 'C. S. Lewis' },
{ id: 12, title: 'Pride and Prejudice', author: 'Jane Austen' },
{ id: 13, title: 'Ulysses', author: 'James Joyce' },
{ id: 14, title: 'The Catcher in the Rye', author: 'J. D. Salinger' },
{
id: 15,
title: 'The Little Mermaid',
author: 'Hans Christian Andersen',
},
{
id: 16,
title: 'The Secret Garden',
author: 'Frances Hodgson Burnett',
},
{ id: 17, title: 'The Wind in the Willows', author: 'Kenneth Grahame' },
{ id: 18, title: 'The Wizard of Oz', author: 'L. Frank Baum' },
{ id: 19, title: 'Madam Bovary', author: 'Gustave Flaubert' },
{ id: 20, title: 'The Little House', author: 'Louisa May Alcott' },
{ id: 21, title: 'The Phantom of the Opera', author: 'Gaston Leroux' },
{ id: 22, title: 'The Adventures of Tom Sawyer', author: 'Mark Twain' },
{
id: 23,
title: 'The Adventures of Huckleberry Finn',
author: 'Mark Twain',
},
{ id: 24, title: 'The Time Machine', author: 'H. G. Wells' },
{ id: 25, title: 'The War of the Worlds', author: 'H. G. Wells' },
],
};
const dataProvider = fakeRestProvider(
data,
process.env.NODE_ENV === 'development',
500
);
const Admin = ({ children, dataProvider, layout }: any) => (
<TestMemoryRouter>
<AdminContext
dataProvider={dataProvider}
i18nProvider={polyglotI18nProvider(() => defaultMessages, 'en')}
>
<AdminUI layout={layout}>{children}</AdminUI>
</AdminContext>
</TestMemoryRouter>
);
const bookFilters = [<SearchInput source="q" alwaysOn />];
export const Aside = () => (
<Admin dataProvider={dataProvider}>
<Resource
name="books"
list={() => (
<InfiniteList aside={<div>Aside</div>}>
<SimpleList
primaryText="%{title}"
secondaryText="%{author}"
/>
</InfiniteList>
)}
/>
</Admin>
);
export const Filter = () => (
<Admin dataProvider={dataProvider}>
<Resource
name="books"
list={() => (
<InfiniteList filter={{ author: 'H. G. Wells' }}>
<SimpleList
primaryText="%{title}"
secondaryText="%{author}"
/>
</InfiniteList>
)}
/>
</Admin>
);
export const Filters = () => (
<Admin dataProvider={dataProvider}>
<Resource
name="books"
list={() => (
<InfiniteList filters={bookFilters}>
<SimpleList
primaryText="%{title}"
secondaryText="%{author}"
/>
</InfiniteList>
)}
/>
</Admin>
);
export const PaginationClassic = () => (
<Admin dataProvider={dataProvider}>
<Resource
name="books"
list={() => (
<InfiniteList pagination={<DefaultPagination />}>
<SimpleList
primaryText="%{title}"
secondaryText="%{author}"
/>
</InfiniteList>
)}
/>
</Admin>
);
export const PaginationInfinite = () => (
<Admin dataProvider={dataProvider}>
<Resource
name="books"
list={() => (
<InfiniteList
pagination={<InfinitePagination sx={{ py: 5 }} />}
>
<SimpleList
primaryText="%{title}"
secondaryText="%{author}"
/>
</InfiniteList>
)}
/>
</Admin>
);
const LoadMore = () => {
const { hasNextPage, fetchNextPage, isFetchingNextPage } =
useInfinitePaginationContext();
return hasNextPage ? (
<Box mt={1} textAlign="center">
<Button
disabled={isFetchingNextPage}
onClick={() => fetchNextPage()}
>
Load more
</Button>
</Box>
) : null;
};
export const PaginationLoadMore = () => (
<Admin dataProvider={dataProvider}>
<Resource
name="books"
list={() => (
<InfiniteList pagination={<LoadMore />}>
<Datagrid>
<TextField source="id" />
<TextField source="title" />
<TextField source="author" />
</Datagrid>
</InfiniteList>
)}
/>
</Admin>
);
const CustomPagination = () => {
const { total } = useListContext();
return (
<>
<InfinitePagination />
{total > 0 && (
<Box position="sticky" bottom={0} textAlign="center">
<Card
elevation={2}
sx={{
px: 2,
py: 1,
mb: 1,
display: 'inline-block',
}}
>
<Typography variant="body2">{total} results</Typography>
</Card>
</Box>
)}
</>
);
};
export const PaginationCustom = () => (
<Admin dataProvider={dataProvider}>
<Resource
name="books"
list={() => (
<InfiniteList pagination={<CustomPagination />}>
<Datagrid>
<TextField source="id" />
<TextField source="title" />
<TextField source="author" />
</Datagrid>
</InfiniteList>
)}
/>
</Admin>
);
export const PerPage = () => (
<Admin dataProvider={dataProvider}>
<Resource
name="books"
list={() => (
<InfiniteList perPage={5}>
<SimpleList
primaryText="%{title}"
secondaryText="%{author}"
/>
</InfiniteList>
)}
/>
</Admin>
);
// Useful to check that on a large window, the list fetches beyond page 2
export const PerPageSmall = () => (
<Admin dataProvider={dataProvider}>
<Resource
name="books"
list={() => (
<InfiniteList perPage={1}>
<Datagrid>
<TextField source="id" />
<TextField source="title" />
<TextField source="author" />
</Datagrid>
</InfiniteList>
)}
/>
</Admin>
);
export const Sort = () => (
<Admin dataProvider={dataProvider}>
<Resource
name="books"
list={() => (
<InfiniteList sort={{ field: 'title', order: 'ASC' }}>
<SimpleList
primaryText="%{title}"
secondaryText="%{author}"
/>
</InfiniteList>
)}
/>
</Admin>
);
export const Title = () => (
<Admin dataProvider={dataProvider}>
<Resource
name="books"
list={() => (
<InfiniteList title="The Books">
<SimpleList
primaryText="%{title}"
secondaryText="%{author}"
/>
</InfiniteList>
)}
/>
</Admin>
);
const LayoutWithFooter = ({ children }) => (
<>
<Layout>{children}</Layout>
<div style={{ height: '100px', backgroundColor: 'red' }}>Footer</div>
</>
);
export const WithFooter = () => (
<Admin dataProvider={dataProvider} layout={LayoutWithFooter}>
<Resource
name="books"
list={() => (
<InfiniteList>
<SimpleList
primaryText="%{title}"
secondaryText="%{author}"
/>
</InfiniteList>
)}
/>
</Admin>
);
export const WithDatagrid = () => (
<Admin dataProvider={dataProvider}>
<Resource
name="books"
list={() => (
<InfiniteList>
<Datagrid>
<TextField source="id" />
<TextField source="title" />
<TextField source="author" />
</Datagrid>
</InfiniteList>
)}
/>
</Admin>
);
const BookActions = () => (
<TopToolbar>
<SortButton fields={['id', 'title']} />
</TopToolbar>
);
export const WithSimpleList = () => (
<Admin dataProvider={dataProvider}>
<Resource
name="books"
list={() => (
<InfiniteList filters={bookFilters} actions={<BookActions />}>
<SimpleList
primaryText="%{title}"
secondaryText="%{author}"
/>
</InfiniteList>
)}
/>
</Admin>
);
``` | /content/code_sandbox/packages/ra-ui-materialui/src/list/InfiniteList.stories.tsx | xml | 2016-07-13T07:58:54 | 2024-08-16T18:32:27 | react-admin | marmelab/react-admin | 24,624 | 2,464 |
```xml
import {getValue} from "@tsed/core";
export function getRef(schema: any, options: any) {
if (schema.$ref) {
return getValue(options, schema.$ref.replace("#/", "").replace(/\//g, "."));
}
return schema;
}
``` | /content/code_sandbox/packages/third-parties/schema-formio/src/utils/getRef.ts | xml | 2016-02-21T18:38:47 | 2024-08-14T21:19:48 | tsed | tsedio/tsed | 2,817 | 58 |
```xml
import { createRoot } from 'react-dom/client';
import '@proton/polyfill';
import './01-style';
import LiteApp from './LiteApp';
const container = document.querySelector('.app-root');
const root = createRoot(container!);
root.render(<LiteApp />);
``` | /content/code_sandbox/applications/account/src/lite/index.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 56 |
```xml
import { RuleModule } from '@typescript-eslint/utils/ts-eslint';
import { ESLint } from 'eslint';
import { rules } from './rules';
type RuleKey = keyof typeof rules;
interface Plugin extends Omit<ESLint.Plugin, 'rules'> {
rules: Record<RuleKey, RuleModule<any, any, any>>;
}
const plugin: Plugin = {
meta: {
name: 'eslint-plugin-expo',
version: '0.0.1',
},
rules,
};
export = plugin;
``` | /content/code_sandbox/packages/eslint-plugin-expo/src/index.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 109 |
```xml
import { bind } from 'decko';
import * as React from 'react';
import ResizeDetector from 'react-resize-detector';
import { Link } from 'react-router-dom';
import ProjectEntityTagsManager from 'features/tagsManager/view/ProjectEntityTagsManager/ProjectEntityTagsManager';
import {
makeDefaultExprNameFilter,
makeDefaultDateCreatedFilter,
} from 'shared/models/Filters';
import { getFormattedDateTime } from 'shared/utils/formatters/dateTime';
import Draggable from 'shared/view/elements/Draggable/Draggable';
import ScrollableContainer from 'shared/view/elements/ScrollableContainer/ScrollableContainer';
import routes from 'shared/routes';
import { IRow } from '../types';
import styles from './SummaryColumn.module.css';
interface ILocalProps {
row: IRow;
onHeightChanged(experimentRunId: string, height: number): void;
}
type AllProps = ILocalProps;
class SummaryColumn extends React.PureComponent<AllProps> {
private rootRef = React.createRef<HTMLDivElement>();
public render() {
const {
experimentRun: {
id,
projectId,
shortExperiment: experiment,
name,
tags,
dateCreated,
},
} = this.props.row;
return (
<div
className={styles.root}
ref={this.rootRef}
data-column-name={'experiment-runs-summary-column'}
data-column-id={id}
>
<ResizeDetector handleHeight={true} onResize={this.onHeightChanged} />
<Link
className={styles.model_link}
to={routes.modelRecord.getRedirectPathWithCurrentWorkspace({
projectId,
modelRecordId: id,
})}
>
<div className={styles.modelName_block}>
<div className={styles.model_name} data-test="experiment-run-name">
{name}
</div>
</div>
</Link>
<div className={styles.expName_block}>
Experiment Name:
<Draggable
additionalClassName={styles.param_draggable}
type="filter"
data={makeDefaultExprNameFilter(experiment.name)}
>
<div className={styles.expName_value}>{experiment.name}</div>
</Draggable>
</div>
{dateCreated && (
<div className={styles.timeStamp_block}>
Timestamp:{' '}
<Draggable
additionalClassName={styles.param_draggable}
type="filter"
data={makeDefaultDateCreatedFilter(+dateCreated)}
>
<div className={styles.timeStamp_value}>
{getFormattedDateTime(dateCreated)}
</div>
</Draggable>
</div>
)}
{/* limit 5 tags after which a scrollable container is rendered */}
{tags.length > 5 ? (
<ScrollableContainer
maxHeight={90}
containerOffsetValue={4}
children={
<ProjectEntityTagsManager
id={id}
projectId={projectId}
tags={tags}
isDraggableTags={true}
entityType="experimentRun"
/>
}
/>
) : (
<ProjectEntityTagsManager
id={id}
projectId={projectId}
tags={tags}
isDraggableTags={true}
entityType="experimentRun"
/>
)}
</div>
);
}
@bind
private onHeightChanged(width: number, height: number) {
this.props.onHeightChanged(this.props.row.experimentRun.id, height);
}
}
export default SummaryColumn;
``` | /content/code_sandbox/webapp/client/src/features/experimentRuns/view/ExperimentRuns/Table/ColumnDefinitions/Summary/SummaryColumn.tsx | xml | 2016-10-19T01:07:26 | 2024-08-14T03:53:55 | modeldb | VertaAI/modeldb | 1,689 | 742 |
```xml
import { useEffect } from 'react';
import { createSelector } from '@reduxjs/toolkit';
import type { WasmApiExchangeRate } from '@proton/andromeda';
import { baseUseSelector } from '@proton/react-redux-store';
import { useWalletSettings } from '@proton/wallet';
import { useGetExchangeRate } from '../store/hooks';
import { selectExchangeRate } from '../store/slices';
export const useUserExchangeRate = () => {
const [walletSettings] = useWalletSettings();
const getExchangeRate = useGetExchangeRate();
const exchangeRateSimpleSelector = createSelector(
selectExchangeRate,
(result): [WasmApiExchangeRate | undefined, boolean] => {
const { error, value } = result;
const rate = walletSettings?.FiatCurrency && value?.[walletSettings.FiatCurrency];
const loading = rate === undefined && error === undefined;
return [rate, loading];
}
);
useEffect(() => {
if (walletSettings?.FiatCurrency) {
void getExchangeRate(walletSettings.FiatCurrency);
}
}, [walletSettings?.FiatCurrency, getExchangeRate]);
return baseUseSelector(exchangeRateSimpleSelector);
};
``` | /content/code_sandbox/applications/wallet/src/app/hooks/useUserExchangeRate.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 260 |
```xml
import * as React from 'react';
import {
Animated,
Dimensions,
Easing,
EmitterSubscription,
findNodeHandle,
I18nManager,
Keyboard,
KeyboardEvent as RNKeyboardEvent,
LayoutRectangle,
NativeEventSubscription,
Platform,
ScrollView,
ScrollViewProps,
StyleProp,
StyleSheet,
View,
ViewStyle,
Pressable,
} from 'react-native';
import MenuItem from './MenuItem';
import { APPROX_STATUSBAR_HEIGHT } from '../../constants';
import { withInternalTheme } from '../../core/theming';
import type { $Omit, InternalTheme, MD3Elevation } from '../../types';
import { ElevationLevels } from '../../types';
import { addEventListener } from '../../utils/addEventListener';
import { BackHandler } from '../../utils/BackHandler/BackHandler';
import Portal from '../Portal/Portal';
import Surface from '../Surface';
export type Props = {
/**
* Whether the Menu is currently visible.
*/
visible: boolean;
/**
* The anchor to open the menu from. In most cases, it will be a button that opens the menu.
*/
anchor: React.ReactNode | { x: number; y: number };
/**
* Whether the menu should open at the top of the anchor or at its bottom.
* Applied only when anchor is a node, not an x/y position.
*/
anchorPosition?: 'top' | 'bottom';
/**
* Extra margin to add at the top of the menu to account for translucent status bar on Android.
* If you are using Expo, we assume translucent status bar and set a height for status bar automatically.
* Pass `0` or a custom value to and customize it.
* This is automatically handled on iOS.
*/
statusBarHeight?: number;
/**
* Callback called when Menu is dismissed. The `visible` prop needs to be updated when this is called.
*/
onDismiss?: () => void;
/**
* Accessibility label for the overlay. This is read by the screen reader when the user taps outside the menu.
*/
overlayAccessibilityLabel?: string;
/**
* Content of the `Menu`.
*/
children: React.ReactNode;
/**
* Style of menu's inner content.
*/
contentStyle?: Animated.WithAnimatedValue<StyleProp<ViewStyle>>;
style?: StyleProp<ViewStyle>;
/**
* Elevation level of the menu's content. Shadow styles are calculated based on this value. Default `backgroundColor` is taken from the corresponding `theme.colors.elevation` property. By default equals `2`.
* @supported Available in v5.x with theme version 3
*/
elevation?: MD3Elevation;
/**
* Mode of the menu's content.
* - `elevated` - Surface with a shadow and background color corresponding to set `elevation` value.
* - `flat` - Surface without a shadow, with the background color corresponding to set `elevation` value.
*
* @supported Available in v5.x with theme version 3
*/
mode?: 'flat' | 'elevated';
/**
* @optional
*/
theme: InternalTheme;
/**
* Inner ScrollView prop
*/
keyboardShouldPersistTaps?: ScrollViewProps['keyboardShouldPersistTaps'];
/**
* testID to be used on tests.
*/
testID?: string;
};
type Layout = $Omit<$Omit<LayoutRectangle, 'x'>, 'y'>;
type State = {
rendered: boolean;
top: number;
left: number;
menuLayout: Layout;
anchorLayout: Layout;
opacityAnimation: Animated.Value;
scaleAnimation: Animated.ValueXY;
windowLayout: Layout;
};
// Minimum padding between the edge of the screen and the menu
const SCREEN_INDENT = 8;
// From path_to_url#duration
const ANIMATION_DURATION = 250;
// From the 'Standard easing' section of path_to_url#easing
const EASING = Easing.bezier(0.4, 0, 0.2, 1);
const WINDOW_LAYOUT = Dimensions.get('window');
const DEFAULT_ELEVATION: MD3Elevation = 2;
export const ELEVATION_LEVELS_MAP = Object.values(
ElevationLevels
) as ElevationLevels[];
const DEFAULT_MODE = 'elevated';
/**
* Menus display a list of choices on temporary elevated surfaces. Their placement varies based on the element that opens them.
*
* ## Usage
* ```js
* import * as React from 'react';
* import { View } from 'react-native';
* import { Button, Menu, Divider, PaperProvider } from 'react-native-paper';
*
* const MyComponent = () => {
* const [visible, setVisible] = React.useState(false);
*
* const openMenu = () => setVisible(true);
*
* const closeMenu = () => setVisible(false);
*
* return (
* <PaperProvider>
* <View
* style={{
* paddingTop: 50,
* flexDirection: 'row',
* justifyContent: 'center',
* }}>
* <Menu
* visible={visible}
* onDismiss={closeMenu}
* anchor={<Button onPress={openMenu}>Show menu</Button>}>
* <Menu.Item onPress={() => {}} title="Item 1" />
* <Menu.Item onPress={() => {}} title="Item 2" />
* <Divider />
* <Menu.Item onPress={() => {}} title="Item 3" />
* </Menu>
* </View>
* </PaperProvider>
* );
* };
*
* export default MyComponent;
* ```
*
* ### Note
* When using `Menu` within a React Native's `Modal` component, you need to wrap all
* `Modal` contents within a `PaperProvider` in order for the menu to show. This
* wrapping is not necessary if you use Paper's `Modal` instead.
*/
class Menu extends React.Component<Props, State> {
// @component ./MenuItem.tsx
static Item = MenuItem;
static defaultProps = {
statusBarHeight: APPROX_STATUSBAR_HEIGHT,
overlayAccessibilityLabel: 'Close menu',
testID: 'menu',
};
static getDerivedStateFromProps(nextProps: Props, prevState: State) {
if (nextProps.visible && !prevState.rendered) {
return { rendered: true };
}
return null;
}
state = {
rendered: this.props.visible,
top: 0,
left: 0,
menuLayout: { width: 0, height: 0 },
anchorLayout: { width: 0, height: 0 },
opacityAnimation: new Animated.Value(0),
scaleAnimation: new Animated.ValueXY({ x: 0, y: 0 }),
windowLayout: {
width: WINDOW_LAYOUT.width,
height: WINDOW_LAYOUT.height,
},
};
componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
this.keyboardDidShow
);
this.keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
this.keyboardDidHide
);
}
componentDidUpdate(prevProps: Props) {
if (prevProps.visible !== this.props.visible) {
this.updateVisibility();
}
}
componentWillUnmount() {
this.removeListeners();
this.keyboardDidShowListener?.remove();
this.keyboardDidHideListener?.remove();
}
private anchor?: View | null = null;
private menu?: View | null = null;
private backHandlerSubscription: NativeEventSubscription | undefined;
private dimensionsSubscription: NativeEventSubscription | undefined;
private keyboardDidShowListener: EmitterSubscription | undefined;
private keyboardDidHideListener: EmitterSubscription | undefined;
private keyboardHeight: number = 0;
private isCoordinate = (anchor: any): anchor is { x: number; y: number } =>
!React.isValidElement(anchor) &&
typeof anchor?.x === 'number' &&
typeof anchor?.y === 'number';
private measureMenuLayout = () =>
new Promise<LayoutRectangle>((resolve) => {
if (this.menu) {
this.menu.measureInWindow((x, y, width, height) => {
resolve({ x, y, width, height });
});
}
});
private measureAnchorLayout = () =>
new Promise<LayoutRectangle>((resolve) => {
const { anchor } = this.props;
if (this.isCoordinate(anchor)) {
resolve({ x: anchor.x, y: anchor.y, width: 0, height: 0 });
return;
}
if (this.anchor) {
this.anchor.measureInWindow((x, y, width, height) => {
resolve({ x, y, width, height });
});
}
});
private updateVisibility = async () => {
// Menu is rendered in Portal, which updates items asynchronously
// We need to do the same here so that the ref is up-to-date
await Promise.resolve();
if (this.props.visible) {
this.show();
} else {
this.hide();
}
};
private isBrowser = () => Platform.OS === 'web' && 'document' in global;
private focusFirstDOMNode = (el: View | null | undefined) => {
if (el && this.isBrowser()) {
// When in the browser, we want to focus the first focusable item on toggle
// For example, when menu is shown, focus the first item in the menu
// And when menu is dismissed, send focus back to the button to resume tabbing
const node: any = findNodeHandle(el);
const focusableNode = node.querySelector(
// This is a rough list of selectors that can be focused
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
focusableNode?.focus();
}
};
private handleDismiss = () => {
if (this.props.visible) {
this.props.onDismiss?.();
}
return true;
};
private handleKeypress = (e: KeyboardEvent) => {
if (e.key === 'Escape') {
this.props.onDismiss?.();
}
};
private attachListeners = () => {
this.backHandlerSubscription = addEventListener(
BackHandler,
'hardwareBackPress',
this.handleDismiss
);
this.dimensionsSubscription = addEventListener(
Dimensions,
'change',
this.handleDismiss
);
this.isBrowser() && document.addEventListener('keyup', this.handleKeypress);
};
private removeListeners = () => {
this.backHandlerSubscription?.remove();
this.dimensionsSubscription?.remove();
this.isBrowser() &&
document.removeEventListener('keyup', this.handleKeypress);
};
private show = async () => {
const windowLayout = Dimensions.get('window');
const [menuLayout, anchorLayout] = await Promise.all([
this.measureMenuLayout(),
this.measureAnchorLayout(),
]);
// When visible is true for first render
// native views can be still not rendered and
// measureMenuLayout/measureAnchorLayout functions
// return wrong values e.g { x:0, y: 0, width: 0, height: 0 }
// so we have to wait until views are ready
// and rerun this function to show menu
if (
!windowLayout.width ||
!windowLayout.height ||
!menuLayout.width ||
!menuLayout.height ||
(!anchorLayout.width && !this.isCoordinate(this.props.anchor)) ||
(!anchorLayout.height && !this.isCoordinate(this.props.anchor))
) {
requestAnimationFrame(this.show);
return;
}
this.setState(
() => ({
left: anchorLayout.x,
top: anchorLayout.y,
anchorLayout: {
height: anchorLayout.height,
width: anchorLayout.width,
},
menuLayout: {
width: menuLayout.width,
height: menuLayout.height,
},
windowLayout: {
height: windowLayout.height - this.keyboardHeight,
width: windowLayout.width,
},
}),
() => {
this.attachListeners();
const { animation } = this.props.theme;
Animated.parallel([
Animated.timing(this.state.scaleAnimation, {
toValue: { x: menuLayout.width, y: menuLayout.height },
duration: ANIMATION_DURATION * animation.scale,
easing: EASING,
useNativeDriver: true,
}),
Animated.timing(this.state.opacityAnimation, {
toValue: 1,
duration: ANIMATION_DURATION * animation.scale,
easing: EASING,
useNativeDriver: true,
}),
]).start(({ finished }) => {
if (finished) {
this.focusFirstDOMNode(this.menu);
}
});
}
);
};
private hide = () => {
this.removeListeners();
const { animation } = this.props.theme;
Animated.timing(this.state.opacityAnimation, {
toValue: 0,
duration: ANIMATION_DURATION * animation.scale,
easing: EASING,
useNativeDriver: true,
}).start(({ finished }) => {
if (finished) {
this.setState({ menuLayout: { width: 0, height: 0 }, rendered: false });
this.state.scaleAnimation.setValue({ x: 0, y: 0 });
this.focusFirstDOMNode(this.anchor);
}
});
};
private keyboardDidShow = (e: RNKeyboardEvent) => {
const keyboardHeight = e.endCoordinates.height;
this.keyboardHeight = keyboardHeight;
};
private keyboardDidHide = () => {
this.keyboardHeight = 0;
};
render() {
const {
visible,
anchor,
anchorPosition,
contentStyle,
style,
elevation = DEFAULT_ELEVATION,
mode = DEFAULT_MODE,
children,
theme,
statusBarHeight,
onDismiss,
overlayAccessibilityLabel,
keyboardShouldPersistTaps,
testID,
} = this.props;
const {
rendered,
menuLayout,
anchorLayout,
opacityAnimation,
scaleAnimation,
windowLayout,
} = this.state;
let { left, top } = this.state;
if (!this.isCoordinate(this.anchor) && anchorPosition === 'bottom') {
top += anchorLayout.height;
}
// I don't know why but on Android measure function is wrong by 24
const additionalVerticalValue = Platform.select({
android: statusBarHeight,
default: 0,
});
const scaleTransforms = [
{
scaleX: scaleAnimation.x.interpolate({
inputRange: [0, menuLayout.width],
outputRange: [0, 1],
}),
},
{
scaleY: scaleAnimation.y.interpolate({
inputRange: [0, menuLayout.height],
outputRange: [0, 1],
}),
},
];
// We need to translate menu while animating scale to imitate transform origin for scale animation
const positionTransforms = [];
// Check if menu fits horizontally and if not align it to right.
if (left <= windowLayout.width - menuLayout.width - SCREEN_INDENT) {
positionTransforms.push({
translateX: scaleAnimation.x.interpolate({
inputRange: [0, menuLayout.width],
outputRange: [-(menuLayout.width / 2), 0],
}),
});
// Check if menu position has enough space from left side
if (left < SCREEN_INDENT) {
left = SCREEN_INDENT;
}
} else {
positionTransforms.push({
translateX: scaleAnimation.x.interpolate({
inputRange: [0, menuLayout.width],
outputRange: [menuLayout.width / 2, 0],
}),
});
left += anchorLayout.width - menuLayout.width;
const right = left + menuLayout.width;
// Check if menu position has enough space from right side
if (right > windowLayout.width - SCREEN_INDENT) {
left = windowLayout.width - SCREEN_INDENT - menuLayout.width;
}
}
// If the menu is larger than available vertical space,
// calculate the height of scrollable view
let scrollableMenuHeight = 0;
// Check if the menu should be scrollable
if (
// Check if the menu overflows from bottom side
top >=
windowLayout.height -
menuLayout.height -
SCREEN_INDENT -
additionalVerticalValue &&
// And bottom side of the screen has more space than top side
top <= windowLayout.height - top
) {
// Scrollable menu should be below the anchor (expands downwards)
scrollableMenuHeight =
windowLayout.height - top - SCREEN_INDENT - additionalVerticalValue;
} else if (
// Check if the menu overflows from bottom side
top >=
windowLayout.height -
menuLayout.height -
SCREEN_INDENT -
additionalVerticalValue &&
// And top side of the screen has more space than bottom side
top >= windowLayout.height - top &&
// And menu overflows from top side
top <=
menuLayout.height -
anchorLayout.height +
SCREEN_INDENT -
additionalVerticalValue
) {
// Scrollable menu should be above the anchor (expands upwards)
scrollableMenuHeight =
top + anchorLayout.height - SCREEN_INDENT + additionalVerticalValue;
}
// Scrollable menu max height
scrollableMenuHeight =
scrollableMenuHeight > windowLayout.height - 2 * SCREEN_INDENT
? windowLayout.height - 2 * SCREEN_INDENT
: scrollableMenuHeight;
// Menu is typically positioned below the element that generates it
// So first check if it fits below the anchor (expands downwards)
if (
// Check if menu fits vertically
top <=
windowLayout.height -
menuLayout.height -
SCREEN_INDENT -
additionalVerticalValue ||
// Or if the menu overflows from bottom side
(top >=
windowLayout.height -
menuLayout.height -
SCREEN_INDENT -
additionalVerticalValue &&
// And bottom side of the screen has more space than top side
top <= windowLayout.height - top)
) {
positionTransforms.push({
translateY: scaleAnimation.y.interpolate({
inputRange: [0, menuLayout.height],
outputRange: [-((scrollableMenuHeight || menuLayout.height) / 2), 0],
}),
});
// Check if menu position has enough space from top side
if (top < SCREEN_INDENT) {
top = SCREEN_INDENT;
}
} else {
positionTransforms.push({
translateY: scaleAnimation.y.interpolate({
inputRange: [0, menuLayout.height],
outputRange: [(scrollableMenuHeight || menuLayout.height) / 2, 0],
}),
});
top += anchorLayout.height - (scrollableMenuHeight || menuLayout.height);
const bottom =
top +
(scrollableMenuHeight || menuLayout.height) +
additionalVerticalValue;
// Check if menu position has enough space from bottom side
if (bottom > windowLayout.height - SCREEN_INDENT) {
top =
scrollableMenuHeight === windowLayout.height - 2 * SCREEN_INDENT
? -SCREEN_INDENT * 2
: windowLayout.height -
menuLayout.height -
SCREEN_INDENT -
additionalVerticalValue;
}
}
const shadowMenuContainerStyle = {
opacity: opacityAnimation,
transform: scaleTransforms,
borderRadius: theme.roundness,
...(!theme.isV3 && { elevation: 8 }),
...(scrollableMenuHeight ? { height: scrollableMenuHeight } : {}),
};
const positionStyle = {
top: this.isCoordinate(anchor) ? top : top + additionalVerticalValue,
...(I18nManager.getConstants().isRTL ? { right: left } : { left }),
};
const pointerEvents = visible ? 'box-none' : 'none';
return (
<View
ref={(ref) => {
this.anchor = ref;
}}
collapsable={false}
>
{this.isCoordinate(anchor) ? null : anchor}
{rendered ? (
<Portal>
<Pressable
accessibilityLabel={overlayAccessibilityLabel}
accessibilityRole="button"
onPress={onDismiss}
style={styles.pressableOverlay}
/>
<View
ref={(ref) => {
this.menu = ref;
}}
collapsable={false}
accessibilityViewIsModal={visible}
style={[styles.wrapper, positionStyle, style]}
pointerEvents={pointerEvents}
onAccessibilityEscape={onDismiss}
testID={`${testID}-view`}
>
<Animated.View
pointerEvents={pointerEvents}
style={{
transform: positionTransforms,
}}
>
<Surface
mode={mode}
pointerEvents={pointerEvents}
style={[
styles.shadowMenuContainer,
shadowMenuContainerStyle,
theme.isV3 && {
backgroundColor:
theme.colors.elevation[ELEVATION_LEVELS_MAP[elevation]],
},
contentStyle,
]}
{...(theme.isV3 && { elevation })}
testID={`${testID}-surface`}
theme={theme}
>
{(scrollableMenuHeight && (
<ScrollView
keyboardShouldPersistTaps={keyboardShouldPersistTaps}
>
{children}
</ScrollView>
)) || <React.Fragment>{children}</React.Fragment>}
</Surface>
</Animated.View>
</View>
</Portal>
) : null}
</View>
);
}
}
const styles = StyleSheet.create({
wrapper: {
position: 'absolute',
},
shadowMenuContainer: {
opacity: 0,
paddingVertical: 8,
},
pressableOverlay: {
...StyleSheet.absoluteFillObject,
...(Platform.OS === 'web' && {
cursor: 'default',
}),
width: '100%',
},
});
export default withInternalTheme(Menu);
``` | /content/code_sandbox/src/components/Menu/Menu.tsx | xml | 2016-10-19T05:56:53 | 2024-08-16T08:48:04 | react-native-paper | callstack/react-native-paper | 12,646 | 4,741 |
```xml
export const movementParams = `
_id:String,
branches:[String],
departments:[String],
customers:[String],
teamMember:[String],
company:[String],
`;
export const movementFilters = `
movementId:String,
branchId:String,
departmentId:String,
customerId:String,
companyId:String,
teamMemberId:String,
assetId:String,
parentId:String,
assetIds:[String]
movedAtFrom:String,
movedAtTo:String,
modifiedAtFrom:String,
modifiedAtTo:String,
createdAtFrom:String,
createdAtTo:String,
searchValue:String,
userId:String,
withKnowledgebase:Boolean,
onlyCurrent:Boolean,
`;
export const commonFilterParams = `
perPage:Int,
page:Int,
`;
``` | /content/code_sandbox/packages/plugin-assets-api/src/common/graphql/movement.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 161 |
```xml
<clickhouse>
<profiles>
<default>
<enable_zstd_qat_codec>1</enable_zstd_qat_codec>
</default>
</profiles>
</clickhouse>
``` | /content/code_sandbox/tests/integration/test_non_default_compression/configs/enable_zstdqat_codec.xml | xml | 2016-06-02T08:28:18 | 2024-08-16T18:39:33 | ClickHouse | ClickHouse/ClickHouse | 36,234 | 43 |
```xml
//
//
// path_to_url
//
// Unless required by applicable law or agreed to in writing, software
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
import { debounceTime, finalize, switchMap } from 'rxjs/operators';
import { TranslateService } from '@ngx-translate/core';
import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router';
import { MessageHandlerService } from '../../../../shared/services/message-handler.service';
import { Project } from '../../project';
import {
clone,
getPageSizeFromLocalStorage,
getSortingString,
PageSizeMapKeys,
setPageSizeToLocalStorage,
} from '../../../../shared/units/utils';
import { forkJoin, Observable, Subject, Subscription } from 'rxjs';
import {
UserPermissionService,
USERSTATICPERMISSION,
} from '../../../../shared/services';
import { ClrDatagridStateInterface, ClrLoadingState } from '@clr/angular';
import {
EXECUTION_STATUS,
FILTER_TYPE,
P2pProviderService,
PROJECT_SEVERITY_LEVEL_TO_TEXT_MAP,
TIME_OUT,
TRIGGER,
TRIGGER_I18N_MAP,
} from '../p2p-provider.service';
import { PreheatPolicy } from '../../../../../../ng-swagger-gen/models/preheat-policy';
import { PreheatService } from '../../../../../../ng-swagger-gen/services/preheat.service';
import { AddP2pPolicyComponent } from '../add-p2p-policy/add-p2p-policy.component';
import { Execution } from '../../../../../../ng-swagger-gen/models/execution';
import { Metrics } from '../../../../../../ng-swagger-gen/models/metrics';
import { ProviderUnderProject } from '../../../../../../ng-swagger-gen/models/provider-under-project';
import { ConfirmationDialogComponent } from '../../../../shared/components/confirmation-dialog';
import {
ConfirmationButtons,
ConfirmationState,
ConfirmationTargets,
} from '../../../../shared/entities/shared.const';
import { ConfirmationMessage } from '../../../global-confirmation-dialog/confirmation-message';
import {
EventService,
HarborEvent,
} from '../../../../services/event-service/event.service';
import { JobserviceService } from '../../../../../../ng-swagger-gen/services/jobservice.service';
import { ScheduleService } from '../../../../../../ng-swagger-gen/services/schedule.service';
import { JobType } from '../../../left-side-nav/job-service-dashboard/job-service-dashboard.interface';
// The route path which will display this component
const URL_TO_DISPLAY: RegExp =
/\/harbor\/projects\/(\d+)\/p2p-provider\/policies/;
@Component({
templateUrl: './policy.component.html',
styleUrls: ['./policy.component.scss'],
})
export class PolicyComponent implements OnInit, OnDestroy {
@ViewChild(AddP2pPolicyComponent)
addP2pPolicyComponent: AddP2pPolicyComponent;
@ViewChild('confirmationDialogComponent')
confirmationDialogComponent: ConfirmationDialogComponent;
projectId: number;
projectName: string;
selectedRow: PreheatPolicy;
policyList: PreheatPolicy[] = [];
providers: ProviderUnderProject[] = [];
metadata: any;
loading: boolean = true;
hasCreatPermission: boolean = false;
hasUpdatePermission: boolean = false;
hasDeletePermission: boolean = false;
addBtnState: ClrLoadingState = ClrLoadingState.DEFAULT;
executing: boolean = false;
isOpenFilterTag: boolean = false;
selectedExecutionRow: Execution;
jobsLoading: boolean = false;
stopLoading: boolean = false;
executionList: Execution[] = [];
currentExecutionPage: number = 1;
pageSize: number = getPageSizeFromLocalStorage(
PageSizeMapKeys.P2P_POLICY_COMPONENT_EXECUTIONS
);
totalExecutionCount: number = 0;
filterKey: string = 'id';
searchString: string;
private _searchSubject: Subject<string> = new Subject<string>();
private _searchSubscription: Subscription;
project: Project;
severity_map: any = PROJECT_SEVERITY_LEVEL_TO_TEXT_MAP;
timeout: any;
hasAddModalInit: boolean = false;
routerSub: Subscription;
scrollSub: Subscription;
scrollTop: number;
policyPageSize: number = getPageSizeFromLocalStorage(
PageSizeMapKeys.P2P_POLICY_COMPONENT,
10
);
policyPage: number = 1;
totalPolicy: number = 0;
state: ClrDatagridStateInterface;
paused: boolean = false;
constructor(
private route: ActivatedRoute,
private router: Router,
private translate: TranslateService,
private p2pProviderService: P2pProviderService,
private messageHandlerService: MessageHandlerService,
private userPermissionService: UserPermissionService,
private preheatService: PreheatService,
private event: EventService,
private scheduleService: ScheduleService
) {}
ngOnInit() {
this.scheduleService
.getSchedulePaused({
jobType: JobType.ALL,
})
.subscribe(res => {
this.paused = res?.paused;
});
if (!this.scrollSub) {
this.scrollSub = this.event.subscribe(HarborEvent.SCROLL, v => {
if (v && URL_TO_DISPLAY.test(v.url)) {
this.scrollTop = v.scrollTop;
}
});
}
if (!this.routerSub) {
this.routerSub = this.router.events.subscribe(e => {
if (e instanceof NavigationEnd) {
if (e && URL_TO_DISPLAY.test(e.url)) {
// Into view
this.event.publish(
HarborEvent.SCROLL_TO_POSITION,
this.scrollTop
);
} else {
this.event.publish(HarborEvent.SCROLL_TO_POSITION, 0);
}
}
});
}
this.subscribeSearch();
this.projectId = +this.route.snapshot.parent.parent.params['id'];
const resolverData = this.route.snapshot.parent.parent.data;
if (resolverData) {
const project = <Project>resolverData['projectResolver'];
this.projectName = project.name;
}
this.getPermissions();
}
ngOnDestroy(): void {
if (this.routerSub) {
this.routerSub.unsubscribe();
this.routerSub = null;
}
if (this.scrollSub) {
this.scrollSub.unsubscribe();
this.scrollSub = null;
}
if (this._searchSubscription) {
this._searchSubscription.unsubscribe();
this._searchSubscription = null;
}
this.clearLoop();
}
addModalInit() {
this.hasAddModalInit = true;
}
getPermissions() {
const permissionsList: Observable<boolean>[] = [];
permissionsList.push(
this.userPermissionService.getPermission(
this.projectId,
USERSTATICPERMISSION.P2P_PROVIDER.KEY,
USERSTATICPERMISSION.P2P_PROVIDER.VALUE.CREATE
)
);
permissionsList.push(
this.userPermissionService.getPermission(
this.projectId,
USERSTATICPERMISSION.P2P_PROVIDER.KEY,
USERSTATICPERMISSION.P2P_PROVIDER.VALUE.UPDATE
)
);
permissionsList.push(
this.userPermissionService.getPermission(
this.projectId,
USERSTATICPERMISSION.P2P_PROVIDER.KEY,
USERSTATICPERMISSION.P2P_PROVIDER.VALUE.DELETE
)
);
this.addBtnState = ClrLoadingState.LOADING;
forkJoin(...permissionsList).subscribe(
Rules => {
[
this.hasCreatPermission,
this.hasUpdatePermission,
this.hasDeletePermission,
] = Rules;
this.addBtnState = ClrLoadingState.SUCCESS;
if (this.hasCreatPermission) {
this.getProviders();
}
},
error => {
this.messageHandlerService.error(error);
this.addBtnState = ClrLoadingState.ERROR;
}
);
}
getProviders() {
this.preheatService
.ListProvidersUnderProject({ projectName: this.projectName })
.subscribe(res => {
if (res && res.length) {
this.providers = res.filter(provider => {
return provider.enabled;
});
}
});
}
refresh() {
this.selectedRow = null;
this.policyPage = 1;
this.totalPolicy = 0;
this.getPolicies(this.state);
}
getPolicies(state?: ClrDatagridStateInterface) {
if (state) {
this.state = state;
}
if (state && state.page) {
this.policyPageSize = state.page.size;
setPageSizeToLocalStorage(
PageSizeMapKeys.P2P_POLICY_COMPONENT,
this.policyPageSize
);
}
let q: string;
if (state && state.filters && state.filters.length) {
q = encodeURIComponent(
`${state.filters[0].property}=~${state.filters[0].value}`
);
}
let sort: string;
if (state && state.sort && state.sort.by) {
sort = getSortingString(state);
} else {
// sort by creation_time desc by default
sort = `-creation_time`;
}
this.loading = true;
this.preheatService
.ListPoliciesResponse({
projectName: this.projectName,
sort: sort,
q: q,
page: this.policyPage,
pageSize: this.policyPageSize,
})
.pipe(finalize(() => (this.loading = false)))
.subscribe(
response => {
// Get total count
if (response.headers) {
let xHeader: string =
response.headers.get('X-Total-Count');
if (xHeader) {
this.totalPolicy = parseInt(xHeader, 0);
}
}
this.policyList = response.body || [];
},
error => {
this.messageHandlerService.handleError(error);
}
);
}
switchStatus() {
let content = '';
this.translate
.get(
!this.selectedRow.enabled
? 'P2P_PROVIDER.ENABLED_POLICY_SUMMARY'
: 'P2P_PROVIDER.DISABLED_POLICY_SUMMARY',
{ name: this.selectedRow.name }
)
.subscribe(res => {
content = res;
let message = new ConfirmationMessage(
!this.selectedRow.enabled
? 'P2P_PROVIDER.ENABLED_POLICY_TITLE'
: 'P2P_PROVIDER.DISABLED_POLICY_TITLE',
content,
'',
{},
ConfirmationTargets.P2P_PROVIDER,
!this.selectedRow.enabled
? ConfirmationButtons.ENABLE_CANCEL
: ConfirmationButtons.DISABLE_CANCEL
);
this.confirmationDialogComponent.open(message);
});
}
confirmSwitch(message) {
if (
message &&
message.source === ConfirmationTargets.P2P_PROVIDER_STOP &&
message.state === ConfirmationState.CONFIRMED
) {
this.stopLoading = true;
const execution: Execution = clone(this.selectedExecutionRow);
execution.status = EXECUTION_STATUS.STOPPED;
this.preheatService
.StopExecution({
projectName: this.projectName,
preheatPolicyName: this.selectedRow.name,
executionId: this.selectedExecutionRow.id,
execution: execution,
})
.pipe(finalize(() => (this.executing = false)))
.subscribe(
response => {
this.messageHandlerService.showSuccess(
'P2P_PROVIDER.STOP_SUCCESSFULLY'
);
},
error => {
this.messageHandlerService.error(error);
}
);
}
if (
message &&
message.source === ConfirmationTargets.P2P_PROVIDER_EXECUTE &&
message.state === ConfirmationState.CONFIRMED
) {
this.executing = true;
this.preheatService
.ManualPreheat({
projectName: this.projectName,
preheatPolicyName: this.selectedRow.name,
policy: this.selectedRow,
})
.pipe(finalize(() => (this.executing = false)))
.subscribe(
response => {
this.messageHandlerService.showSuccess(
'P2P_PROVIDER.EXECUTE_SUCCESSFULLY'
);
if (this.selectedRow) {
this.refreshJobs();
}
},
error => {
this.messageHandlerService.error(error);
}
);
}
if (
message &&
message.source === ConfirmationTargets.P2P_PROVIDER &&
message.state === ConfirmationState.CONFIRMED
) {
if (JSON.stringify(message.data) === '{}') {
this.preheatService
.UpdatePolicy({
projectName: this.projectName,
preheatPolicyName: this.selectedRow.name,
policy: Object.assign({}, this.selectedRow, {
enabled: !this.selectedRow.enabled,
}),
})
.subscribe(
response => {
this.messageHandlerService.showSuccess(
'P2P_PROVIDER.UPDATED_SUCCESSFULLY'
);
this.refresh();
},
error => {
this.messageHandlerService.handleError(error);
}
);
}
}
if (
message &&
message.source === ConfirmationTargets.P2P_PROVIDER_DELETE &&
message.state === ConfirmationState.CONFIRMED
) {
const observableLists: Observable<any>[] = [];
observableLists.push(
this.preheatService.DeletePolicy({
projectName: this.projectName,
preheatPolicyName: this.selectedRow.name,
})
);
forkJoin(...observableLists).subscribe(
response => {
this.messageHandlerService.showSuccess(
'P2P_PROVIDER.DELETE_SUCCESSFULLY'
);
this.refresh();
},
error => {
this.messageHandlerService.handleError(error);
}
);
}
}
newPolicy() {
this.addP2pPolicyComponent.isOpen = true;
this.addP2pPolicyComponent.isEdit = false;
this.addP2pPolicyComponent.resetForAdd();
}
editPolicy() {
if (this.selectedRow) {
this.addP2pPolicyComponent.repos = null;
this.addP2pPolicyComponent.tags = null;
this.addP2pPolicyComponent.labels = null;
this.addP2pPolicyComponent.isOpen = true;
this.addP2pPolicyComponent.isEdit = true;
this.addP2pPolicyComponent.isNameExisting = false;
this.addP2pPolicyComponent.inlineAlert.close();
this.addP2pPolicyComponent.policy = clone(this.selectedRow);
const filter: any[] = JSON.parse(this.selectedRow.filters);
if (filter && filter.length) {
filter.forEach(item => {
if (item.type === FILTER_TYPE.REPOS && item.value) {
let str: string = item.value;
if (/^{\S+}$/.test(str)) {
return str.slice(1, str.length - 1);
}
this.addP2pPolicyComponent.repos = str;
}
if (item.type === FILTER_TYPE.TAG && item.value) {
let str: string = item.value;
if (/^{\S+}$/.test(str)) {
return str.slice(1, str.length - 1);
}
this.addP2pPolicyComponent.tags = str;
}
if (item.type === FILTER_TYPE.LABEL && item.value) {
let str: string = item.value;
if (/^{\S+}$/.test(str)) {
return str.slice(1, str.length - 1);
}
this.addP2pPolicyComponent.labels = str;
}
});
}
const trigger: any = JSON.parse(this.selectedRow.trigger);
if (trigger) {
this.addP2pPolicyComponent.triggerType = trigger.type;
this.addP2pPolicyComponent.cron = trigger.trigger_setting.cron;
}
this.addP2pPolicyComponent.currentForm.reset({
provider: this.addP2pPolicyComponent.policy.provider_id,
name: this.addP2pPolicyComponent.policy.name,
description: this.addP2pPolicyComponent.policy.description,
repo: this.addP2pPolicyComponent.repos,
tag: this.addP2pPolicyComponent.tags,
onlySignedImages: this.addP2pPolicyComponent.enableContentTrust,
severity: this.addP2pPolicyComponent.severity,
label: this.addP2pPolicyComponent.labels,
triggerType: this.addP2pPolicyComponent.triggerType,
});
this.addP2pPolicyComponent.originPolicyForEdit = clone(
this.selectedRow
);
this.addP2pPolicyComponent.originReposForEdit =
this.addP2pPolicyComponent.repos;
this.addP2pPolicyComponent.originTagsForEdit =
this.addP2pPolicyComponent.tags;
this.addP2pPolicyComponent.originOnlySignedImagesForEdit =
this.addP2pPolicyComponent.onlySignedImages;
this.addP2pPolicyComponent.originSeverityForEdit =
this.addP2pPolicyComponent.severity;
this.addP2pPolicyComponent.originLabelsForEdit =
this.addP2pPolicyComponent.labels;
this.addP2pPolicyComponent.originTriggerTypeForEdit =
this.addP2pPolicyComponent.triggerType;
this.addP2pPolicyComponent.originCronForEdit =
this.addP2pPolicyComponent.cron;
}
}
deletePolicy() {
const names: string[] = [];
names.push(this.selectedRow.name);
let content = '';
this.translate
.get('P2P_PROVIDER.DELETE_POLICY_SUMMARY', {
names: names.join(','),
})
.subscribe(res => (content = res));
const msg: ConfirmationMessage = new ConfirmationMessage(
'SCANNER.CONFIRM_DELETION',
content,
names.join(','),
this.selectedRow,
ConfirmationTargets.P2P_PROVIDER_DELETE,
ConfirmationButtons.DELETE_CANCEL
);
this.confirmationDialogComponent.open(msg);
}
executePolicy() {
if (this.selectedRow && this.selectedRow.enabled) {
const message = new ConfirmationMessage(
'P2P_PROVIDER.EXECUTE_TITLE',
'P2P_PROVIDER.EXECUTE_SUMMARY',
this.selectedRow.name,
this.selectedRow,
ConfirmationTargets.P2P_PROVIDER_EXECUTE,
ConfirmationButtons.CONFIRM_CANCEL
);
this.confirmationDialogComponent.open(message);
}
}
success(isAdd: boolean) {
let message: string;
if (isAdd) {
message = 'P2P_PROVIDER.ADDED_SUCCESS';
} else {
message = 'P2P_PROVIDER.UPDATED_SUCCESS';
}
this.messageHandlerService.showSuccess(message);
this.refresh();
}
clrLoadJobs(
chosenPolicy: PreheatPolicy,
withLoading: boolean,
state?: ClrDatagridStateInterface
) {
if (this.selectedRow) {
if (state && state.page) {
this.pageSize = state.page.size;
setPageSizeToLocalStorage(
PageSizeMapKeys.P2P_POLICY_COMPONENT_EXECUTIONS,
this.pageSize
);
}
if (withLoading) {
// if datagrid is under control of *ngIf, should add timeout in case of ng changes checking error
setTimeout(() => {
this.jobsLoading = true;
});
}
let params: string;
if (this.searchString) {
params = encodeURIComponent(
`${this.filterKey}=~${this.searchString}`
);
}
this.preheatService
.ListExecutionsResponse({
projectName: this.projectName,
preheatPolicyName: chosenPolicy
? chosenPolicy.name
: this.selectedRow.name,
page: this.currentExecutionPage,
pageSize: this.pageSize,
q: params,
})
.pipe(finalize(() => (this.jobsLoading = false)))
.subscribe(
response => {
if (response.headers) {
let xHeader: string =
response.headers.get('X-Total-Count');
if (xHeader) {
this.totalExecutionCount = parseInt(xHeader, 0);
}
}
this.executionList = response.body;
this.setLoop();
},
error => {
this.messageHandlerService.handleError(error);
}
);
}
}
refreshJobs(chosenPolicy?: PreheatPolicy) {
this.executionList = [];
this.currentExecutionPage = 1;
this.totalExecutionCount = 0;
this.filterKey = 'id';
this.searchString = null;
this.clrLoadJobs(chosenPolicy, true);
}
openStopExecutionsDialog() {
if (this.selectedExecutionRow) {
const stopExecutionsMessage = new ConfirmationMessage(
'P2P_PROVIDER.STOP_TITLE',
'P2P_PROVIDER.STOP_SUMMARY',
this.selectedExecutionRow.id + '',
this.selectedExecutionRow,
ConfirmationTargets.P2P_PROVIDER_STOP,
ConfirmationButtons.CONFIRM_CANCEL
);
this.confirmationDialogComponent.open(stopExecutionsMessage);
}
}
goToLink(executionId: number) {
const linkUrl = [
'harbor',
'projects',
`${this.projectId}`,
'p2p-provider',
`${this.selectedRow.name}`,
'executions',
`${executionId}`,
'tasks',
];
this.router.navigate(linkUrl);
}
getTriggerTypeI18n(trigger: string): string {
if (JSON.parse(trigger).type) {
if (this.paused && JSON.parse(trigger).type === TRIGGER.SCHEDULED) {
return TRIGGER_I18N_MAP[TRIGGER.SCHEDULED_PAUSED];
}
return TRIGGER_I18N_MAP[JSON.parse(trigger).type];
}
return TRIGGER_I18N_MAP[TRIGGER.MANUAL];
}
getTriggerTypeI18nForExecution(trigger: string) {
if (trigger && TRIGGER_I18N_MAP[trigger]) {
return TRIGGER_I18N_MAP[trigger];
}
return trigger;
}
isScheduled(trigger: string): boolean {
return JSON.parse(trigger).type === TRIGGER.SCHEDULED;
}
isEventBased(trigger: string): boolean {
return JSON.parse(trigger).type === TRIGGER.EVENT_BASED;
}
getScheduledCron(trigger: string): string {
return JSON.parse(trigger).trigger_setting.cron;
}
getDuration(e: Execution): string {
return this.p2pProviderService.getDuration(e.start_time, e.end_time);
}
getValue(filter: string, type: string): string {
const arr: any[] = JSON.parse(filter);
if (arr && arr.length) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].type === type && arr[i].value) {
let str: string = arr[i].value;
if (/^{\S+}$/.test(str)) {
return str.slice(1, str.length - 1);
}
return str;
}
}
}
return '';
}
getSuccessRate(m: Metrics): number {
if (m && m.task_count && m.success_task_count) {
return m.success_task_count / m.task_count;
}
return 0;
}
selectFilterKey($event: any): void {
this.filterKey = $event['target'].value;
}
openFilter(isOpen: boolean): void {
this.isOpenFilterTag = isOpen;
}
doFilter(terms: string): void {
this.searchString = terms;
if (terms.trim()) {
this._searchSubject.next(terms.trim());
} else {
this.clrLoadJobs(null, true);
}
}
subscribeSearch() {
if (!this._searchSubscription) {
this._searchSubscription = this._searchSubject
.pipe(
debounceTime(500),
switchMap(searchString => {
this.jobsLoading = true;
let params: string;
if (this.searchString) {
params = encodeURIComponent(
`${this.filterKey}=~${searchString}`
);
}
return this.preheatService
.ListExecutionsResponse({
projectName: this.projectName,
preheatPolicyName: this.selectedRow.name,
page: 1,
pageSize: this.pageSize,
q: params,
})
.pipe(finalize(() => (this.jobsLoading = false)));
})
)
.subscribe(response => {
if (response.headers) {
let xHeader: string =
response.headers.get('x-total-count');
if (xHeader) {
this.totalExecutionCount = parseInt(xHeader, 0);
}
}
this.executionList = response.body;
this.setLoop();
});
}
}
canStop(): boolean {
return (
this.selectedExecutionRow &&
this.p2pProviderService.willChangStatus(
this.selectedExecutionRow.status
)
);
}
clearLoop() {
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
}
setLoop() {
this.clearLoop();
if (this.executionList && this.executionList.length) {
for (let i = 0; i < this.executionList.length; i++) {
if (
this.p2pProviderService.willChangStatus(
this.executionList[i].status
)
) {
if (!this.timeout) {
this.timeout = setTimeout(() => {
this.clrLoadJobs(null, false);
}, TIME_OUT);
}
}
}
}
}
}
``` | /content/code_sandbox/src/portal/src/app/base/project/p2p-provider/policy/policy.component.ts | xml | 2016-01-28T21:10:28 | 2024-08-16T15:28:34 | harbor | goharbor/harbor | 23,335 | 5,385 |
```xml
import { useCallback, useEffect } from 'react';
import { c } from 'ttag';
import { useNotifications, useOnline, usePreventLeave } from '@proton/components';
import { HTTP_ERROR_CODES } from '@proton/shared/lib/errors';
import { ScanResultItem } from '@proton/shared/lib/interfaces/drive/file';
import { TransferState } from '../../../components/TransferManager/transfer';
import { useDownloadIsTooBigModal } from '../../../components/modals/DownloadIsTooBigModal';
import { logError, sendErrorReport } from '../../../utils/errorHandling';
import { bufferToStream } from '../../../utils/stream';
import {
isTransferCancelError,
isTransferOngoing,
isTransferPausedByConnection,
isTransferProgress,
} from '../../../utils/transfer';
import { SignatureIssues } from '../../_links';
import { useTransferLog } from '../../_transfer';
import { MAX_DOWNLOADING_BLOCKS_LOAD } from '../constants';
import FileSaver from '../fileSaver/fileSaver';
import { InitDownloadCallback, LinkDownload } from '../interface';
import { UpdateFilter } from './interface';
import useDownloadContainsDocument from './useDownloadContainsDocument';
import useDownloadControl from './useDownloadControl';
import useDownloadQueue from './useDownloadQueue';
import useDownloadScanIssue from './useDownloadScanIssue';
import useDownloadSignatureIssue from './useDownloadSignatureIssue';
export default function useDownloadProvider(initDownload: InitDownloadCallback) {
const onlineStatus = useOnline();
const { createNotification } = useNotifications();
const { preventLeave } = usePreventLeave();
const [downloadIsTooBigModal, showDownloadIsTooBigModal] = useDownloadIsTooBigModal();
const { log, downloadLogs, clearLogs } = useTransferLog('download');
const queue = useDownloadQueue((id, message) => log(id, `queue: ${message}`));
const control = useDownloadControl(queue.downloads, queue.updateWithCallback, queue.remove, queue.clear);
const { handleSignatureIssue, signatureIssueModal } = useDownloadSignatureIssue(
queue.downloads,
queue.updateState,
queue.updateWithData,
control.cancelDownloads
);
const { handleScanIssue } = useDownloadScanIssue(queue.updateWithData, control.cancelDownloads);
const { handleContainsDocument, containsDocumentModal } = useDownloadContainsDocument(control.cancelDownloads);
/**
* download should be considered as main entry point for download files
* in Drive app. It does all necessary checks, such as checking if the
* same files are not currently already downloading, and it adds transfer
* to the queue.
*/
const download = async (links: LinkDownload[], options?: { virusScan?: boolean }): Promise<void> => {
await queue.add(links, options).catch((err: any) => {
if ((err as Error).name === 'DownloadUserError') {
createNotification({
text: err.message,
type: 'error',
});
} else {
createNotification({
text: c('Notification').t`Failed to download files: ${err}`,
type: 'error',
});
console.error(err);
}
});
};
const restartDownloads = useCallback(
async (idOrFilter: UpdateFilter) => {
queue.updateWithData(idOrFilter, TransferState.Pending);
},
[queue.downloads, queue.updateState]
);
// Effect to start next download if there is enough capacity to do so.
useEffect(() => {
const { nextDownload } = queue;
if (!nextDownload) {
return;
}
// If link contains the whole buffer already, there is no need to
// calculate load or wait for anything else. It can be downloaded
// right away.
if (nextDownload.links.every(({ buffer }) => !!buffer)) {
const buffer = nextDownload.links.flatMap(({ buffer }) => buffer);
const stream = bufferToStream(buffer as Uint8Array[]);
void preventLeave(
FileSaver.saveAsFile(stream, nextDownload.meta, (message) => log(nextDownload.id, message))
).catch(logError);
queue.updateState(nextDownload.id, TransferState.Done);
return;
}
const loadSizes = queue.downloads.filter(isTransferProgress).map((download) => download.meta.size);
if (loadSizes.some((size) => size === undefined)) {
return;
}
const load = control.calculateDownloadBlockLoad();
if (load === undefined || load > MAX_DOWNLOADING_BLOCKS_LOAD) {
return;
}
// Set progress right away to not start the download more than once.
queue.updateState(nextDownload.id, TransferState.Progress);
const controls = initDownload(
nextDownload.meta.filename,
nextDownload.links,
{
onInit: (size: number, linkSizes: { [linkId: string]: number }) => {
log(nextDownload.id, `loaded size: ${size}, number of links: ${Object.keys(linkSizes).length}`);
// Keep the previous state for cases when the download is paused.
queue.updateWithData(nextDownload.id, ({ state }) => state, { size });
control.updateLinkSizes(nextDownload.id, linkSizes);
if (FileSaver.isFileTooBig(size)) {
void showDownloadIsTooBigModal({ onCancel: () => control.cancelDownloads(nextDownload.id) });
}
},
onProgress: (linkIds: string[], increment: number) => {
control.updateProgress(nextDownload.id, linkIds, increment);
},
onNetworkError: (error: any) => {
log(nextDownload.id, `network issue: ${error}`);
queue.updateWithData(nextDownload.id, TransferState.NetworkError, { error });
},
onScanIssue: async (abortSignal: AbortSignal, error?: Error, response?: ScanResultItem) => {
log(
nextDownload.id,
`scan issue error: ${JSON.stringify(error || '')}; response: ${JSON.stringify(response || '')}`
);
await handleScanIssue(abortSignal, nextDownload, error);
},
onSignatureIssue: async (
abortSignal: AbortSignal,
link: LinkDownload,
signatureIssues: SignatureIssues
) => {
log(nextDownload.id, `signature issue: ${JSON.stringify(signatureIssues)}`);
await handleSignatureIssue(abortSignal, nextDownload, link, signatureIssues);
},
onContainsDocument: async (abortSignal: AbortSignal) => {
await handleContainsDocument(abortSignal, nextDownload);
},
},
(message: string) => log(nextDownload.id, message),
nextDownload.options
);
control.add(nextDownload.id, controls);
void preventLeave(
controls
.start()
.then(() => {
queue.updateState(nextDownload.id, TransferState.Done);
})
.catch((error: any) => {
if (isTransferCancelError(error)) {
queue.updateState(nextDownload.id, TransferState.Canceled);
} else {
queue.updateWithData(nextDownload.id, TransferState.Error, { error });
sendErrorReport(error);
}
// If the error is 429 (rate limited), we should not continue
// with other downloads in the queue and fail fast, otherwise
// it just triggers more strict jails and leads to nowhere.
if (error?.status === HTTP_ERROR_CODES.TOO_MANY_REQUESTS) {
log(nextDownload.id, `Got 429, canceling ongoing uploads`);
control.cancelDownloads(isTransferOngoing);
}
})
.finally(() => {
control.remove(nextDownload.id);
})
);
}, [queue.nextDownload, queue.downloads]);
useEffect(() => {
if (onlineStatus) {
const ids = queue.downloads.filter(isTransferPausedByConnection).map(({ id }) => id);
control.resumeDownloads(({ id }) => ids.includes(id));
}
}, [onlineStatus]);
return {
downloads: queue.downloads,
hasDownloads: queue.hasDownloads,
download,
getProgresses: control.getProgresses,
getLinksProgress: control.getLinksProgress,
pauseDownloads: control.pauseDownloads,
resumeDownloads: control.resumeDownloads,
cancelDownloads: control.cancelDownloads,
restartDownloads,
removeDownloads: control.removeDownloads,
clearDownloads: () => {
control.clearDownloads();
clearLogs();
},
updateWithData: queue.updateWithData,
downloadDownloadLogs: downloadLogs,
modals: (
<>
{downloadIsTooBigModal}
{signatureIssueModal}
{containsDocumentModal}
</>
),
};
}
``` | /content/code_sandbox/packages/drive-store/store/_downloads/DownloadProvider/useDownloadProvider.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 1,820 |
```xml
export function load(appId: string) {
;(function () {
const w = window as any
const ic = w.Intercom
w.intercomSettings = {
...(w.intercomSettings || {}),
hide_default_launcher: true,
}
if (typeof ic === 'function') {
ic('reattach_activator')
ic('update', w.intercomSettings)
} else {
const d = document
const i: any = function () {
// eslint-disable-next-line prefer-rest-params
i.c(arguments)
}
i.q = []
i.c = function (args: any) {
i.q.push(args)
}
w.Intercom = i
const l = function () {
const s = d.createElement('script')
s.type = 'text/javascript'
s.async = true
s.src = `path_to_url{appId}`
const x = d.getElementsByTagName('script')[0]
x.parentNode!.insertBefore(s, x)
}
if (w.attachEvent) {
w.attachEvent('onload', l)
} else {
w.addEventListener('load', l, false)
}
}
})()
}
export function boot(appId: string, options = {}) {
const w = window as any
w &&
w.Intercom &&
w.Intercom('boot', {
app_id: appId,
...options,
hide_default_launcher: true,
})
}
export function update() {
const w = window as any
w && w.Intercom && w.Intercom('update')
}
export function shutdown() {
const w = window as any
w && w.Intercom && w.Intercom('shutdown')
}
``` | /content/code_sandbox/src/cloud/lib/intercom/index.ts | xml | 2016-11-19T14:30:34 | 2024-08-16T03:13:45 | BoostNote-App | BoostIO/BoostNote-App | 3,745 | 366 |
```xml
import React, { CSSProperties } from 'react';
import ReactDOM from 'react-dom';
import { InjectedComponentSet } from 'mailspring-component-kit';
import { EventOccurrence } from './calendar-data-source';
import { calcColor } from './calendar-helpers';
interface CalendarEventProps {
event: EventOccurrence;
order: number;
selected: boolean;
scopeEnd: number;
scopeStart: number;
direction: 'horizontal' | 'vertical';
fixedSize: number;
focused: boolean;
concurrentEvents: number;
onClick: (e: React.MouseEvent<any>, event: EventOccurrence) => void;
onDoubleClick: (event: EventOccurrence) => void;
onFocused: (event: EventOccurrence) => void;
}
export class CalendarEvent extends React.Component<CalendarEventProps> {
static displayName = 'CalendarEvent';
static defaultProps = {
order: 1,
direction: 'vertical',
fixedSize: -1,
concurrentEvents: 1,
onClick: () => {},
onDoubleClick: () => {},
onFocused: () => {},
};
componentDidMount() {
this._scrollFocusedEventIntoView();
}
componentDidUpdate() {
this._scrollFocusedEventIntoView();
}
_scrollFocusedEventIntoView() {
const { focused } = this.props;
if (!focused) {
return;
}
const eventNode = ReactDOM.findDOMNode(this);
if (!eventNode) {
return;
}
const { event, onFocused } = this.props;
(eventNode as any).scrollIntoViewIfNeeded(true);
onFocused(event);
}
_getDimensions() {
const scopeLen = this.props.scopeEnd - this.props.scopeStart;
const duration = this.props.event.end - this.props.event.start;
let top: number | string = Math.max(
(this.props.event.start - this.props.scopeStart) / scopeLen,
0
);
let height: number | string = Math.min((duration - this._overflowBefore()) / scopeLen, 1);
let width: number | string = 1;
let left: number | string;
if (this.props.fixedSize === -1) {
width = 1 / this.props.concurrentEvents;
left = width * (this.props.order - 1);
width = `${width * 100}%`;
left = `${left * 100}%`;
} else {
width = this.props.fixedSize;
left = this.props.fixedSize * (this.props.order - 1);
}
top = `${top * 100}%`;
height = `${height * 100}%`;
return { left, width, height, top };
}
_getStyles() {
let styles: CSSProperties = {};
if (this.props.direction === 'vertical') {
styles = this._getDimensions();
} else if (this.props.direction === 'horizontal') {
const d = this._getDimensions();
styles = {
left: d.top,
width: d.height,
height: d.width,
top: d.left,
};
}
styles.backgroundColor = calcColor(this.props.event.calendarId);
return styles;
}
_overflowBefore() {
return Math.max(this.props.scopeStart - this.props.event.start, 0);
}
render() {
const { direction, event, onClick, onDoubleClick, selected } = this.props;
return (
<div
id={event.id}
tabIndex={0}
style={this._getStyles()}
className={`calendar-event ${direction} ${selected ? 'selected' : null}`}
onClick={e => onClick(e, event)}
onDoubleClick={() => onDoubleClick(event)}
>
<span className="default-header" style={{ order: 0 }}>
{event.title}
</span>
<InjectedComponentSet
className="event-injected-components"
style={{ position: 'absolute' }}
matching={{ role: 'Calendar:Event' }}
exposedProps={{ event: event }}
direction="row"
/>
</div>
);
}
}
``` | /content/code_sandbox/app/internal_packages/main-calendar/lib/core/calendar-event.tsx | xml | 2016-10-13T06:45:50 | 2024-08-16T18:14:37 | Mailspring | Foundry376/Mailspring | 15,331 | 880 |
```xml
/*
* @license Apache-2.0
*
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/
import incrrange = require( './index' );
// TESTS //
// The function returns an accumulator function...
{
incrrange(); // $ExpectType accumulator
}
// The compiler throws an error if the function is provided arguments...
{
incrrange( '5' ); // $ExpectError
incrrange( 5 ); // $ExpectError
incrrange( true ); // $ExpectError
incrrange( false ); // $ExpectError
incrrange( null ); // $ExpectError
incrrange( undefined ); // $ExpectError
incrrange( [] ); // $ExpectError
incrrange( {} ); // $ExpectError
incrrange( ( x: number ): number => x ); // $ExpectError
}
// The function returns an accumulator function which returns an accumulated result...
{
const acc = incrrange();
acc(); // $ExpectType number | null
acc( 3.14 ); // $ExpectType number | null
}
// The compiler throws an error if the returned accumulator function is provided invalid arguments...
{
const acc = incrrange();
acc( '5' ); // $ExpectError
acc( true ); // $ExpectError
acc( false ); // $ExpectError
acc( null ); // $ExpectError
acc( [] ); // $ExpectError
acc( {} ); // $ExpectError
acc( ( x: number ): number => x ); // $ExpectError
}
``` | /content/code_sandbox/lib/node_modules/@stdlib/stats/incr/range/docs/types/test.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 372 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="tests/bootstrap.php"
colors="true"
verbose="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
>
<testsuites>
<testsuite name="Voyager Test Suite">
<directory>tests</directory>
</testsuite>
</testsuites>
<logging>
<log type="junit" target="build/report.junit.xml"/>
<log type="coverage-html" target="build/coverage" />
<log type="coverage-text" target="php://stdout" showUncoveredFiles="false" showOnlySummary="true"/>
</logging>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./src/</directory>
</whitelist>
</filter>
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_DEBUG" value="true"/>
<env name="APP_URL" value="path_to_url"/>
<env name="APP_KEY" value="base64:M1igrxNfAWlVGyxxDholHqvVqvtPjAzCoJ+2/ILAVPw="/>
</php>
</phpunit>
``` | /content/code_sandbox/phpunit.xml | xml | 2016-10-27T03:56:49 | 2024-08-16T07:52:06 | voyager | thedevdojo/voyager | 11,745 | 323 |
```xml
import { expect, it, describe } from 'vitest';
import { addAsPromised, add } from './add.js';
describe(addAsPromised.name, () => {
it('should be able to add two numbers', () => {
const actual = addAsPromised(40, 2);
actual.then((val) => {
expect(val).toEqual(42);
})
});
});
describe(add.name, () => {
it('should be able to add two numbers', () => {
const actual = add(40, 0);
expect(actual).toEqual(40);
});
});
``` | /content/code_sandbox/packages/vitest-runner/testResources/async-failure/src/add.spec.ts | xml | 2016-02-12T13:14:28 | 2024-08-15T18:38:25 | stryker-js | stryker-mutator/stryker-js | 2,561 | 130 |
```xml
<resources>
<string name="app_name">AndroidThreadTest</string>
</resources>
``` | /content/code_sandbox/chapter10/AndroidThreadTest/app/src/main/res/values/strings.xml | xml | 2016-10-04T02:55:57 | 2024-08-16T11:00:26 | booksource | guolindev/booksource | 3,105 | 21 |
```xml
/*
* Wire
*
* This program is free software: you can redistribute it and/or modify
* (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
*
* along with this program. If not, see path_to_url
*
*/
import {DefaultConversationRoleName as DefaultRole} from '@wireapp/api-client/lib/conversation/';
import {createUuid} from 'Util/uuid';
import {ConversationRoleRepository, Permissions} from './ConversationRoleRepository';
import {TestFactory} from '../../../test/helper/TestFactory';
import {Conversation} from '../entity/Conversation';
import {User} from '../entity/User';
import {TeamEntity} from '../team/TeamEntity';
describe('ConversationRoleRepository', () => {
const testFactory = new TestFactory();
let roleRepository: ConversationRoleRepository;
beforeEach(async () => {
await testFactory.exposeConversationActors();
roleRepository = new ConversationRoleRepository(
testFactory.team_repository,
testFactory.conversation_service,
testFactory.user_repository['userState'],
testFactory.team_repository['teamState'],
);
});
describe('constructor', () => {
it('knows if you are in a team', () => {
expect(roleRepository['teamState'].isTeam()).toBe(false);
testFactory.team_repository['teamState'].team(new TeamEntity(createUuid()));
expect(roleRepository['teamState'].isTeam()).toBe(true);
});
});
describe('loadTeamRoles', () => {
it('initializes all team roles', async () => {
spyOn(testFactory.team_repository, 'getTeamConversationRoles').and.returnValue(
Promise.resolve({
conversation_roles: [
{
actions: [Permissions.leaveConversation],
conversation_role: DefaultRole.WIRE_MEMBER,
},
],
}),
);
testFactory.team_repository['teamState'].team(new TeamEntity(createUuid()));
await roleRepository.loadTeamRoles();
expect(roleRepository.teamRoles.length).toBe(1);
});
});
describe('canAddParticipants', () => {
it('checks if a user can add participants to a group', async () => {
const conversationEntity = new Conversation(createUuid());
const userEntity = new User(createUuid(), null);
conversationEntity.participating_user_ets.push(userEntity);
let canAddParticipants = roleRepository.canAddParticipants(conversationEntity, userEntity);
expect(canAddParticipants).toBe(false);
conversationEntity.roles({
[userEntity.id]: DefaultRole.WIRE_ADMIN,
});
canAddParticipants = roleRepository.canAddParticipants(conversationEntity, userEntity);
expect(canAddParticipants).toBe(true);
});
});
});
``` | /content/code_sandbox/src/script/conversation/ConversationRoleRepository.test.ts | xml | 2016-07-21T15:34:05 | 2024-08-16T11:40:13 | wire-webapp | wireapp/wire-webapp | 1,125 | 590 |
```xml
export const EXAMPLE_REVISION_1 = '1-12080c42d471e3d2625e49dcca3b8e1a';
export const EXAMPLE_REVISION_2 = '2-22080c42d471e3d2625e49dcca3b8e2b';
export const EXAMPLE_REVISION_3 = '3-32080c42d471e3d2625e49dcca3b8e3c';
export const EXAMPLE_REVISION_4 = '4-42080c42d471e3d2625e49dcca3b8e3c';
``` | /content/code_sandbox/src/plugins/test-utils/revisions.ts | xml | 2016-12-02T19:34:42 | 2024-08-16T15:47:20 | rxdb | pubkey/rxdb | 21,054 | 133 |
```xml
<?xml version="1.0"?>
<!--
-->
<info>
<id>spreedcheats</id>
<name>Talk cheats app for Intergration tests</name>
<namespace>SpreedCheats</namespace>
<description/>
<licence>AGPL</licence>
<author>Joas Schilling</author>
<version>21.0.0</version>
<types>
<logging/>
</types>
<dependencies>
<nextcloud min-version="31" max-version="31" />
</dependencies>
</info>
``` | /content/code_sandbox/tests/integration/spreedcheats/appinfo/info.xml | xml | 2016-09-01T08:08:37 | 2024-08-16T18:09:32 | spreed | nextcloud/spreed | 1,593 | 127 |
```xml
import React from 'react';
import { observer } from 'mobx-react';
import { Input } from 'react-polymorph/lib/components/Input';
import { InputSkin } from 'react-polymorph/lib/skins/simple/InputSkin';
import { doTermsNeedAcceptance } from './helpers';
import { PasswordInputProps as Props } from './types';
import HardwareWalletStatus from '../../../../components/hardware-wallet/HardwareWalletStatus';
import styles from './styles.scss';
function Component({
isFlight,
isTrezor,
isHardwareWallet,
areTermsAccepted,
passphraseField,
walletName,
hwDeviceStatus,
onExternalLinkClick,
handleSubmitOnEnter,
}: Props) {
if (doTermsNeedAcceptance({ isFlight, areTermsAccepted })) {
return null;
}
return isHardwareWallet ? (
<div className={styles.hardwareWalletStatusWrapper}>
<HardwareWalletStatus
hwDeviceStatus={hwDeviceStatus}
walletName={walletName}
isTrezor={isTrezor}
onExternalLinkClick={onExternalLinkClick}
/>
</div>
) : (
<Input
type="password"
className={styles.passphrase}
{...passphraseField.bind()}
error={passphraseField.error}
skin={InputSkin}
onKeyPress={handleSubmitOnEnter}
autoFocus
/>
);
}
export const PasswordInput = observer(Component);
``` | /content/code_sandbox/source/renderer/app/containers/wallet/dialogs/send-confirmation/PasswordInput.tsx | xml | 2016-10-05T13:48:54 | 2024-08-13T22:03:19 | daedalus | input-output-hk/daedalus | 1,230 | 302 |
```xml
import { noopRenderer, Renderer } from '@fluentui/react-northstar-styles-renderer';
import { emptyTheme, ThemeInput, ThemePrepared } from '@fluentui/styles';
import * as React from 'react';
import { Telemetry } from './telemetry/types';
export interface StylesContextPerformance {
enableSanitizeCssPlugin: boolean;
enableStylesCaching: boolean;
enableVariablesCaching: boolean;
enableBooleanVariablesCaching: boolean;
}
export type StylesContextPerformanceInput = Partial<StylesContextPerformance>;
export type ProviderContextInput = {
rtl?: boolean;
disableAnimations?: boolean;
performance?: StylesContextPerformanceInput;
renderer?: Renderer;
theme?: ThemeInput;
target?: Document;
telemetry?: Telemetry;
};
export type ProviderContextPrepared = {
rtl: boolean;
disableAnimations: boolean;
performance: StylesContextPerformance;
renderer: Renderer;
theme: ThemePrepared;
telemetry: Telemetry | undefined;
// `target` can be undefined for SSR
target: Document | undefined;
};
export const defaultPerformanceFlags: StylesContextPerformance = {
enableSanitizeCssPlugin: process.env.NODE_ENV !== 'production',
enableStylesCaching: true,
enableVariablesCaching: true,
enableBooleanVariablesCaching: false,
};
export const defaultContextValue: ProviderContextPrepared = {
// A default value for `rtl` is undefined to let compute `Provider` a proper one
rtl: undefined as any,
disableAnimations: false,
performance: defaultPerformanceFlags,
renderer: noopRenderer,
theme: emptyTheme,
telemetry: undefined,
target: undefined,
};
const FluentContext = React.createContext<ProviderContextPrepared>(defaultContextValue);
export function useFluentContext(): ProviderContextPrepared {
return React.useContext(FluentContext);
}
export const Unstable_FluentContextProvider = FluentContext.Provider;
``` | /content/code_sandbox/packages/fluentui/react-bindings/src/context.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 408 |
```xml
import { Environment, RecordProxy, RecordSourceProxy } from "relay-runtime";
import { GQLResolver } from "coral-framework/schema";
import { CreateTestRendererParams } from "coral-framework/testHelpers";
import createTopLevel, {
createContext as createTopLevelContext,
} from "../create";
const initLocalState = (
localRecord: RecordProxy<{}>,
source: RecordSourceProxy,
environment: Environment,
params: CreateTestRendererParams<GQLResolver>
) => {
localRecord.setValue("COMMENTS", "activeTab");
localRecord.setValue("ALL_COMMENTS", "commentsTab");
localRecord.setValue("jti", "accessTokenJTI");
localRecord.setValue("CREATED_AT_DESC", "commentsOrderBy");
localRecord.setValue(false, "refreshStream");
if (params.initLocalState) {
params.initLocalState(localRecord, source, environment);
}
};
export default function create(params: CreateTestRendererParams<GQLResolver>) {
return createTopLevel({
...params,
initLocalState: (localRecord, source, environment) => {
initLocalState(localRecord, source, environment, params);
},
});
}
export function createContext(params: CreateTestRendererParams<GQLResolver>) {
return createTopLevelContext({
...params,
initLocalState: (localRecord, source, environment) => {
initLocalState(localRecord, source, environment, params);
},
});
}
``` | /content/code_sandbox/client/src/core/client/stream/test/comments/create.ts | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 307 |
```xml
import { Linking } from 'react-native';
export default Linking;
``` | /content/code_sandbox/packages/expo-linking/src/RNLinking.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 16 |
```xml
import React from 'react'
import {
mdiSortClockAscending,
mdiSortAlphabeticalAscending,
mdiSortAlphabeticalDescending,
} from '@mdi/js'
import FormSelect, {
FormSelectOption,
} from '../../../design/components/molecules/Form/atoms/FormSelect'
import Flexbox from '../../../design/components/atoms/Flexbox'
import Icon from '../../../design/components/atoms/Icon'
import styled from '../../../design/lib/styled'
import { menuHeight } from '../../../design/lib/stores/contextMenu'
export const sortingOrders: (FormSelectOption & { icon: React.ReactNode })[] = [
{
label: (
<Flexbox>
<Icon
path={mdiSortClockAscending}
size={16}
className='select__option__icon'
/>{' '}
<span className='select__option__label'>Latest Updated</span>
</Flexbox>
),
icon: (
<Icon
path={mdiSortClockAscending}
size={20}
className='select__option__icon'
/>
),
value: 'Latest Updated',
},
{
label: (
<Flexbox>
<Icon
path={mdiSortAlphabeticalAscending}
size={16}
className='select__option__icon'
/>{' '}
<span className='select__option__label'>Title A-Z</span>
</Flexbox>
),
icon: (
<Icon
path={mdiSortAlphabeticalAscending}
size={20}
className='select__option__icon'
/>
),
value: 'Title A-Z',
},
{
label: (
<Flexbox>
<Icon
path={mdiSortAlphabeticalDescending}
size={16}
className='select__option__icon'
/>{' '}
<span className='select__option__label'>Title Z-A</span>
</Flexbox>
),
icon: (
<Icon
path={mdiSortAlphabeticalDescending}
size={20}
className='select__option__icon'
/>
),
value: 'Title Z-A',
},
]
interface SortingOptionProps {
value: typeof sortingOrders[number]['value']
onChange: (value: FormSelectOption) => void
isDisabled?: boolean
}
const SortingOption = ({ value, onChange, isDisabled }: SortingOptionProps) => {
const val = sortingOrders.find((ORDER) => ORDER.value === value)
return (
<StyledSortingOption>
<FormSelect
options={sortingOrders}
value={val != null ? { label: val.icon, value: val.value } : undefined}
onChange={onChange}
className='sorting-options__select'
isSearchable={false}
isMulti={false}
isDisabled={isDisabled}
/>
</StyledSortingOption>
)
}
const StyledSortingOption = styled.div`
margin-left: ${({ theme }) => theme.sizes.spaces.sm}px;
.form__select__control {
flex-wrap: inherit;
min-width: 32px !important;
width: 32px;
min-height: 32px;
height: 34px;
border: 0 !important;
box-shadow: none !important;
background-color: transparent;
cursor: pointer;
.form__select__single-value,
.form__select__dropdown-indicator {
color: ${({ theme }) => theme.colors.text.subtle} !important;
transition: color 150ms;
.form__select__option__icon {
width: 20px !important;
height: 20px !important;
}
.form__select__option__label {
display: none;
}
}
.form__select__value-container,
.form__select__dropdown-indicator {
padding: 2px;
svg {
margin-right: 0;
}
}
&:hover {
.form__select__single-value,
.form__select__dropdown-indicator {
color: ${({ theme }) => theme.colors.text.secondary} !important;
}
}
}
.form__select__menu {
right: 0;
width: 180px;
background-color: ${({ theme }) => theme.colors.background.primary};
box-shadow: ${({ theme }) => theme.colors.shadow};
}
.form__select__indicators {
display: none;
}
.form__select__option {
display: flex;
align-items: center;
justify-content: space-between;
width: 100%;
height: ${menuHeight}px;
padding: 0 ${({ theme }) => theme.sizes.spaces.df}px;
background-color: transparent;
border: none;
box-sizing: border-box;
color: ${({ theme }) => theme.colors.text.primary};
font-size: ${({ theme }) => theme.sizes.fonts.sm}px;
text-align: left;
transition: 200ms color;
&:hover {
background-color: ${({ theme }) => theme.colors.background.quaternary};
color: ${({ theme }) => theme.colors.text.primary};
}
&:focus,
&--is-selected {
background-color: ${({ theme }) => theme.colors.background.tertiary};
color: ${({ theme }) => theme.colors.text.primary};
}
&:disabled {
color: ${({ theme }) => theme.colors.text.subtle};
&:hover,
&:focus {
color: ${({ theme }) => theme.colors.text.subtle};
background-color: transparent;
cursor: not-allowed;
}
}
}
.form__select__option__icon {
margin-right: ${({ theme }) => theme.sizes.spaces.xsm}px;
}
`
export default SortingOption
``` | /content/code_sandbox/src/cloud/components/ContentManager/SortingOption.tsx | xml | 2016-11-19T14:30:34 | 2024-08-16T03:13:45 | BoostNote-App | BoostIO/BoostNote-App | 3,745 | 1,233 |
```xml
import React, { useState } from "react";
import { isEnabled } from "@erxes/ui/src/utils/core";
import {
__,
ControlLabel,
FormControl,
FormGroup,
Toggle,
} from "@erxes/ui/src";
import {
Block,
BlockRow,
BlockRowUp,
FlexColumn,
FlexItem,
} from "../../../styles";
import { LeftItem } from "@erxes/ui/src/components/step/styles";
import { IPos } from "../../../types";
import Select from "react-select";
import SelectBranches from "@erxes/ui/src/team/containers/SelectBranches";
type Props = {
onChange: (
name: "pos" | "erkhetConfig" | "checkRemainder",
value: any
) => void;
pos: IPos;
checkRemainder: boolean;
};
const ErkhetConfig = (props: Props) => {
const { pos, onChange } = props;
const [config, setConfig] = useState<any>(
pos && pos.erkhetConfig
? pos.erkhetConfig
: {
isSyncErkhet: false,
userEmail: "",
defaultPay: "",
getRemainder: false,
}
);
const [checkRemainder, setCheckRemainder] = useState<boolean>(
props.checkRemainder
);
const onChangeConfig = (code: string, value) => {
const newConfig = { ...config, [code]: value };
setConfig(newConfig);
onChange("erkhetConfig", newConfig);
};
const onChangeInput = (code: string, e) => {
onChangeConfig(code, e.target.value);
};
const onChangeInputSub = (code: string, key1: string, e) => {
onChangeConfig(code, { ...config[code], [key1]: e.target.value });
};
const onChangeSwitch = (e) => {
onChangeConfig("isSyncErkhet", e.target.checked);
};
const onChangeSwitchCheckErkhet = (e) => {
let val = e.target.checked;
if (!config.isSyncErkhet) {
val = false;
}
if (val && checkRemainder) {
onChange("checkRemainder", false);
setCheckRemainder(false);
}
onChangeConfig("getRemainder", val);
};
const onChangeSwitchCheckInv = (e) => {
let val = e.target.checked;
if (!isEnabled("inventories")) {
val = false;
}
if (val && config.getRemainder) {
onChangeConfig("getRemainder", false);
}
onChange("checkRemainder", val);
setCheckRemainder(val);
};
const onChangeSelect = (key, option) => {
onChangeConfig(key, option.value);
};
const renderInput = (
key: string,
title?: string,
description?: string,
type?: string
) => {
return (
<FormGroup>
<ControlLabel>{title || key}</ControlLabel>
{description && <p>{__(description)}</p>}
<FormControl
defaultValue={config[key]}
type={type || "text"}
onChange={onChangeInput.bind(this, key)}
required={true}
/>
</FormGroup>
);
};
const renderInputSub = (
key: string,
key1: string,
title: string,
description?: string,
type?: string
) => {
return (
<FormGroup>
<ControlLabel>{title}</ControlLabel>
{description && <p>{__(description)}</p>}
<FormControl
defaultValue={(config[key] && config[key][key1]) || ""}
type={type || "text"}
onChange={onChangeInputSub.bind(this, key, key1)}
required={true}
/>
</FormGroup>
);
};
const renderAccLoc = () => {
if (!pos.isOnline) {
return (
<BlockRow>
{renderInput("account", "Account", "")}
{renderInput("location", "Location", "")}
</BlockRow>
);
}
return (
<>
{(pos.allowBranchIds || []).map((branchId) => {
return (
<BlockRow key={branchId}>
<FormGroup>
<ControlLabel>Branch</ControlLabel>
<SelectBranches
label="Choose branch"
name="branchId"
initialValue={branchId}
onSelect={() => {}}
multi={false}
/>
</FormGroup>
{renderInputSub(`${branchId}`, "account", "Account", "")}
{renderInputSub(`${branchId}`, "location", "Location", "")}
</BlockRow>
);
})}
</>
);
};
const renderSelectType = (key, value) => {
const options = [
{ value: "debtAmount", label: "debt Amount" },
{ value: "cashAmount", label: "cash Amount" },
{ value: "cardAmount", label: "card Amount" },
{ value: "card2Amount", label: "card2 Amount" },
{ value: "mobileAmount", label: "mobile Amount" },
{ value: "debtBarterAmount", label: "barter Amount" },
];
return (
<Select
key={Math.random()}
value={options.find((o) => o.value === (value || ""))}
onChange={onChangeSelect.bind(this, key)}
isClearable={false}
required={true}
options={options}
/>
);
};
const renderOther = () => {
if (!config.isSyncErkhet) {
return <></>;
}
return (
<Block>
<h4>{__("Other")}</h4>
<BlockRow>
{renderInput("userEmail", "user Email", "")}
{renderInput("beginNumber", "Begin bill number", "")}
<FormGroup>
<ControlLabel>{"defaultPay"}</ControlLabel>
{renderSelectType("defaultPay", config.defaultPay)}
</FormGroup>
</BlockRow>
{renderAccLoc()}
<BlockRow>
{(pos.paymentTypes || []).map((pt) => (
<FormGroup key={pt.type}>
<ControlLabel>{pt.title}</ControlLabel>
{renderSelectType(`_${pt.type}`, config[`_${pt.type}`])}
</FormGroup>
))}
</BlockRow>
</Block>
);
};
return (
<FlexItem>
<FlexColumn>
<LeftItem>
<Block>
<h4>{__("Main")}</h4>
<BlockRow>
<FormGroup>
<ControlLabel>Is Sync erkhet</ControlLabel>
<Toggle
id={"isSyncErkhet"}
checked={config.isSyncErkhet || false}
onChange={onChangeSwitch}
icons={{
checked: <span>Yes</span>,
unchecked: <span>No</span>,
}}
/>
</FormGroup>
</BlockRow>
</Block>
{renderOther()}
<Block>
<h4>{__("Remainder")}</h4>
<BlockRow>
<FormGroup>
<ControlLabel>Check erkhet</ControlLabel>
<Toggle
id={"getRemainder"}
checked={config.getRemainder || false}
onChange={onChangeSwitchCheckErkhet}
icons={{
checked: <span>Yes</span>,
unchecked: <span>No</span>,
}}
/>
</FormGroup>
<FormGroup>
<ControlLabel>Check inventories</ControlLabel>
<Toggle
id={"checkRemainder"}
checked={checkRemainder}
onChange={onChangeSwitchCheckInv}
icons={{
checked: <span>Yes</span>,
unchecked: <span>No</span>,
}}
/>
</FormGroup>
</BlockRow>
</Block>
<Block />
</LeftItem>
</FlexColumn>
</FlexItem>
);
};
export default ErkhetConfig;
``` | /content/code_sandbox/packages/plugin-pos-ui/src/pos/components/step/ErkhetConfig.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 1,758 |
```xml
import type { compile as mdxCompile } from '@mdx-js/mdx';
export type MdxCompileOptions = Parameters<typeof mdxCompile>[1];
export interface CompileOptions {
mdxCompileOptions?: MdxCompileOptions;
}
``` | /content/code_sandbox/code/addons/docs/src/compiler/types.ts | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 50 |
```xml
<vector xmlns:android="path_to_url" android:height="34.0dp" android:tint="?attr/colorControlNormal" android:viewportHeight="15" android:viewportWidth="15" android:width="34.0dp">
<path android:fillColor="@android:color/white" android:pathData="M5 1L7 4L10.5 2.5L14.97 13L0 13L5 1ZM8 5L7 5C6.75 5 6.55 5.18 6.51 5.41L6.5 5.5L6.5 7.5L4.5 7.5C4.25 7.5 4.05 7.68 4.01 7.91L4 8L4 9C4 9.25 4.18 9.45 4.41 9.49L4.5 9.5L6.5 9.5L6.5 11.5C6.5 11.75 6.68 11.95 6.91 11.99L7 12L8 12C8.25 12 8.45 11.82 8.49 11.59L8.5 11.5L8.5 9.5L10.5 9.5C10.75 9.5 10.95 9.32 10.99 9.09L11 9L11 8C11 7.75 10.82 7.55 10.59 7.51L10.5 7.5L8.5 7.5L8.5 5.5C8.5 5.25 8.32 5.05 8.09 5.01L8 5Z"/>
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_preset_temaki_mountain_cross.xml | xml | 2016-07-02T10:44:04 | 2024-08-16T18:55:54 | StreetComplete | streetcomplete/StreetComplete | 3,781 | 421 |
```xml
import {app, clipboard} from 'electron';
import Store from 'electron-store';
import got, {GotFn, GotPromise} from 'got';
import {ApertureOptions, Format} from '../common/types';
import {InstalledPlugin} from './plugin';
import {addPluginPromise} from '../utils/deep-linking';
import {notify} from '../utils/notifications';
import PCancelable from 'p-cancelable';
import {getFormatExtension} from '../common/constants';
interface ServiceContextOptions {
plugin: InstalledPlugin;
}
class ServiceContext {
requests: Array<GotPromise<any>> = [];
config: Store;
private readonly plugin: InstalledPlugin;
constructor(options: ServiceContextOptions) {
this.plugin = options.plugin;
this.config = this.plugin.config;
}
request = (...args: Parameters<GotFn>) => {
const request = got(...args);
this.requests.push(request);
return request;
};
copyToClipboard = (text: string) => {
clipboard.writeText(text);
};
notify = (text: string, action?: () => any) => {
return notify({
body: text,
title: this.plugin.isBuiltIn ? app.name : this.plugin.prettyName,
click: action
});
};
openConfigFile = () => {
this.config.openInEditor();
};
waitForDeepLink = async () => {
return new Promise(resolve => {
addPluginPromise(this.plugin.name, resolve);
});
};
}
interface ShareServiceContextOptions extends ServiceContextOptions {
onProgress: (text: string, percentage: number) => void;
filePath: (options?: {fileType?: Format}) => Promise<string>;
format: Format;
prettyFormat: string;
defaultFileName: string;
onCancel: () => void;
}
export class ShareServiceContext extends ServiceContext {
isCanceled = false;
private readonly options: ShareServiceContextOptions;
constructor(options: ShareServiceContextOptions) {
super(options);
this.options = options;
}
get format() {
return this.options.format;
}
get prettyFormat() {
return this.options.prettyFormat;
}
get defaultFileName() {
return `${this.options.defaultFileName}.${getFormatExtension(this.options.format)}`;
}
filePath = async (options?: {fileType?: Format}) => {
return this.options.filePath(options);
};
setProgress = (text: string, percentage: number) => {
this.options.onProgress(text, percentage);
};
cancel = () => {
this.isCanceled = true;
this.options.onCancel();
for (const request of this.requests) {
request.cancel();
}
};
}
interface EditServiceContextOptions extends ServiceContextOptions {
onProgress: (text: string, percentage: number) => void;
inputPath: string;
outputPath: string;
exportOptions: {
width: number;
height: number;
format: Format;
fps: number;
duration: number;
isMuted: boolean;
loop: boolean;
};
convert: (args: string[], text?: string) => PCancelable<void>;
onCancel: () => void;
}
export class EditServiceContext extends ServiceContext {
isCanceled = false;
private readonly options: EditServiceContextOptions;
constructor(options: EditServiceContextOptions) {
super(options);
this.options = options;
}
get inputPath() {
return this.options.inputPath;
}
get outputPath() {
return this.options.outputPath;
}
get exportOptions() {
return this.options.exportOptions;
}
get convert() {
return this.options.convert;
}
setProgress = (text: string, percentage: number) => {
this.options.onProgress(text, percentage);
};
cancel = () => {
this.isCanceled = true;
this.options.onCancel();
for (const request of this.requests) {
request.cancel();
}
};
}
export type RecordServiceState<PersistedState extends Record<string, unknown> = Record<string, unknown>> = {
persistedState?: PersistedState;
};
export interface RecordServiceContextOptions<State extends RecordServiceState> extends ServiceContextOptions {
apertureOptions: ApertureOptions;
state: State;
setRecordingName: (name: string) => void;
}
export class RecordServiceContext<State extends RecordServiceState> extends ServiceContext {
private readonly options: RecordServiceContextOptions<State>;
constructor(options: RecordServiceContextOptions<State>) {
super(options);
this.options = options;
}
get state() {
return this.options.state;
}
get apertureOptions() {
return this.options.apertureOptions;
}
get setRecordingName() {
return this.options.setRecordingName;
}
}
``` | /content/code_sandbox/main/plugins/service-context.ts | xml | 2016-08-10T19:37:08 | 2024-08-16T07:01:58 | Kap | wulkano/Kap | 17,864 | 1,018 |
```xml
import { DatePipe, Location } from "@angular/common";
import { Component, OnInit } from "@angular/core";
import { FormBuilder } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
import { first } from "rxjs/operators";
import { AddEditComponent as BaseAddEditComponent } from "@bitwarden/angular/tools/send/add-edit.component";
import { PolicyService } from "@bitwarden/common/admin-console/abstractions/policy/policy.service.abstraction";
import { AccountService } from "@bitwarden/common/auth/abstractions/account.service";
import { BillingAccountProfileStateService } from "@bitwarden/common/billing/abstractions/account/billing-account-profile-state.service";
import { EnvironmentService } from "@bitwarden/common/platform/abstractions/environment.service";
import { I18nService } from "@bitwarden/common/platform/abstractions/i18n.service";
import { LogService } from "@bitwarden/common/platform/abstractions/log.service";
import { MessagingService } from "@bitwarden/common/platform/abstractions/messaging.service";
import { PlatformUtilsService } from "@bitwarden/common/platform/abstractions/platform-utils.service";
import { StateService } from "@bitwarden/common/platform/abstractions/state.service";
import { SendApiService } from "@bitwarden/common/tools/send/services/send-api.service.abstraction";
import { SendService } from "@bitwarden/common/tools/send/services/send.service.abstraction";
import { DialogService, ToastService } from "@bitwarden/components";
import BrowserPopupUtils from "../../../platform/popup/browser-popup-utils";
import { FilePopoutUtilsService } from "../services/file-popout-utils.service";
@Component({
selector: "app-send-add-edit",
templateUrl: "send-add-edit.component.html",
})
// eslint-disable-next-line rxjs-angular/prefer-takeuntil
export class SendAddEditComponent extends BaseAddEditComponent implements OnInit {
// Options header
showOptions = false;
// File visibility
isFirefox = false;
inPopout = false;
showFileSelector = false;
constructor(
i18nService: I18nService,
platformUtilsService: PlatformUtilsService,
stateService: StateService,
messagingService: MessagingService,
policyService: PolicyService,
environmentService: EnvironmentService,
datePipe: DatePipe,
sendService: SendService,
private route: ActivatedRoute,
private router: Router,
private location: Location,
logService: LogService,
sendApiService: SendApiService,
dialogService: DialogService,
formBuilder: FormBuilder,
private filePopoutUtilsService: FilePopoutUtilsService,
billingAccountProfileStateService: BillingAccountProfileStateService,
accountService: AccountService,
toastService: ToastService,
) {
super(
i18nService,
platformUtilsService,
environmentService,
datePipe,
sendService,
messagingService,
policyService,
logService,
stateService,
sendApiService,
dialogService,
formBuilder,
billingAccountProfileStateService,
accountService,
toastService,
);
}
popOutWindow() {
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
BrowserPopupUtils.openCurrentPagePopout(window);
}
async ngOnInit() {
// File visibility
this.showFileSelector =
!this.editMode && !this.filePopoutUtilsService.showFilePopoutMessage(window);
this.inPopout = BrowserPopupUtils.inPopout(window);
this.isFirefox = this.platformUtilsService.isFirefox();
// eslint-disable-next-line rxjs-angular/prefer-takeuntil, rxjs/no-async-subscribe
this.route.queryParams.pipe(first()).subscribe(async (params) => {
if (params.sendId) {
this.sendId = params.sendId;
}
if (params.type) {
const type = parseInt(params.type, null);
this.type = type;
}
await super.ngOnInit();
});
window.setTimeout(() => {
if (!this.editMode) {
document.getElementById("name").focus();
}
}, 200);
}
async submit(): Promise<boolean> {
if (await super.submit()) {
this.cancel();
return true;
}
return false;
}
async delete(): Promise<boolean> {
if (await super.delete()) {
this.cancel();
return true;
}
return false;
}
cancel() {
// If true, the window was pop'd out on the add-send page. location.back will not work
const isPopup = (window as any)?.previousPopupUrl?.startsWith("/add-send") ?? false;
if (!isPopup) {
// FIXME: Verify that this floating promise is intentional. If it is, add an explanatory comment and ensure there is proper error handling.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.router.navigate(["tabs/send"]);
} else {
this.location.back();
}
}
}
``` | /content/code_sandbox/apps/browser/src/tools/popup/send/send-add-edit.component.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 1,089 |
```xml
import { Injectable } from '@angular/core';
import { CameraType, CustomDevice, DeviceType } from '../../models/device.model';
import { ILogger } from '../../models/logger.model';
import { LoggerService } from '../logger/logger.service';
import { PlatformService } from '../platform/platform.service';
import { StorageService } from '../storage/storage.service';
import { LocalTrack, Room, createLocalTracks } from 'livekit-client';
/**
* @internal
*/
@Injectable({
providedIn: 'root'
})
export class DeviceService {
private devices: MediaDeviceInfo[];
private cameras: CustomDevice[] = [];
private microphones: CustomDevice[] = [];
private cameraSelected?: CustomDevice;
private microphoneSelected?: CustomDevice;
private log: ILogger;
private videoDevicesEnabled: boolean = true;
private audioDevicesEnabled: boolean = true;
private deviceAccessDeniedError: boolean = false;
constructor(
private loggerSrv: LoggerService,
private platformSrv: PlatformService,
private storageSrv: StorageService
) {
this.log = this.loggerSrv.get('DevicesService');
}
/**
* Initialize media devices and select a devices checking in local storage (if exists) or
* first devices found by default
*/
async initializeDevices() {
this.clear();
try {
this.devices = await this.getLocalDevices();
if (this.deviceAccessDeniedError) {
this.log.w('Media devices permissions were not granted.');
return;
}
this.initializeCustomDevices();
this.updateSelectedDevices();
this.log.d('Media devices', this.cameras, this.microphones);
} catch (error) {
this.log.e('Error getting media devices', error);
}
}
/**
* Check and update the media devices available
*/
async refreshDevices() {
if (!this.deviceAccessDeniedError) {
this.devices = await this.getLocalDevices();
this.initializeCustomDevices();
}
}
private initializeCustomDevices(): void {
this.cameras = this.devices
.filter((d) => d.kind === DeviceType.VIDEO_INPUT)
.map((d) => this.createCustomDevice(d, CameraType.BACK));
this.microphones = this.devices
.filter((d) => d.kind === DeviceType.AUDIO_INPUT)
.map((d) => ({ label: d.label, device: d.deviceId }));
if (this.platformSrv.isMobile()) {
this.cameras.forEach((c) => {
if (c.label.toLowerCase().includes(CameraType.FRONT.toLowerCase())) {
c.type = CameraType.FRONT;
}
});
} else if (this.cameras.length > 0) {
this.cameras[0].type = CameraType.FRONT;
}
}
private createCustomDevice(device: MediaDeviceInfo, defaultType: CameraType): CustomDevice {
return {
label: device.label,
device: device.deviceId,
type: defaultType
};
}
private updateSelectedDevices() {
this.cameraSelected = this.getDeviceFromStorage(this.cameras, this.storageSrv.getVideoDevice()) || this.cameras[0];
this.microphoneSelected = this.getDeviceFromStorage(this.microphones, this.storageSrv.getAudioDevice()) || this.microphones[0];
}
private getDeviceFromStorage(devices: CustomDevice[], storageDevice: CustomDevice | null): CustomDevice | undefined {
if (!storageDevice) return;
return devices.find((d) => d.device === storageDevice.device);
}
/**
* @internal
*/
isCameraEnabled(): boolean {
return this.hasVideoDeviceAvailable() && this.storageSrv.isCameraEnabled();
}
isMicrophoneEnabled(): boolean {
return this.hasAudioDeviceAvailable() && this.storageSrv.isMicrophoneEnabled();
}
getCameraSelected(): CustomDevice | undefined {
return this.cameraSelected;
}
getMicrophoneSelected(): CustomDevice | undefined {
return this.microphoneSelected;
}
setCameraSelected(deviceId: any) {
this.cameraSelected = this.getDeviceById(this.cameras, deviceId);
const saveFunction = (device) => this.storageSrv.setVideoDevice(device);
this.saveDeviceToStorage(this.cameraSelected, saveFunction);
}
setMicSelected(deviceId: string) {
this.microphoneSelected = this.getDeviceById(this.microphones, deviceId);
const saveFunction = (device) => this.storageSrv.setAudioDevice(device);
this.saveDeviceToStorage(this.microphoneSelected, saveFunction);
}
needUpdateVideoTrack(newDevice: CustomDevice): boolean {
return this.cameraSelected?.device !== newDevice.device || this.cameraSelected?.label !== newDevice.label;
}
needUpdateAudioTrack(newDevice: CustomDevice): boolean {
return this.microphoneSelected?.device !== newDevice.device || this.microphoneSelected?.label !== newDevice.label;
}
getCameras(): CustomDevice[] {
return this.cameras;
}
getMicrophones(): CustomDevice[] {
return this.microphones;
}
hasVideoDeviceAvailable(): boolean {
return this.videoDevicesEnabled && this.cameras.length > 0;
}
hasAudioDeviceAvailable(): boolean {
return this.audioDevicesEnabled && this.microphones.length > 0;
}
clear() {
this.devices = [];
this.cameras = [];
this.microphones = [];
this.cameraSelected = undefined;
this.microphoneSelected = undefined;
this.videoDevicesEnabled = true;
this.audioDevicesEnabled = true;
}
private getDeviceById(devices: CustomDevice[], deviceId: string): CustomDevice | undefined {
return devices.find((d) => d.device === deviceId);
}
private saveDeviceToStorage(device: CustomDevice | undefined, saveFunction: (device: CustomDevice) => void) {
if (device) saveFunction(device);
}
/**
* Retrieves the local media devices (audio and video) available for the user.
*
* @returns A promise that resolves to an array of `MediaDeviceInfo` objects representing the available local devices.
*/
private async getLocalDevices(): Promise<MediaDeviceInfo[]> {
// Forcing media permissions request.
let localTracks: LocalTrack[] = [];
try {
localTracks = await createLocalTracks({ audio: true, video: true });
localTracks.forEach((track) => track.stop());
const devices = this.platformSrv.isFirefox() ? await this.getMediaDevicesFirefox() : await Room.getLocalDevices();
return devices.filter((d: MediaDeviceInfo) => d.label && d.deviceId && d.deviceId !== 'default');
} catch (error) {
this.log.e('Error getting local devices', error);
this.deviceAccessDeniedError = true;
return [];
}
}
private async getMediaDevicesFirefox(): Promise<MediaDeviceInfo[]> {
// Firefox requires to get user media to get the devices
await navigator.mediaDevices.getUserMedia({ audio: true, video: true });
return navigator.mediaDevices.enumerateDevices();
}
}
``` | /content/code_sandbox/openvidu-components-angular/projects/openvidu-components-angular/src/lib/services/device/device.service.ts | xml | 2016-10-10T13:31:27 | 2024-08-15T12:14:04 | openvidu | OpenVidu/openvidu | 1,859 | 1,486 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
*
*
* path_to_url
*
* Unless required by applicable law or agreed to in writing, software
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-->
<project xmlns="path_to_url" xmlns:xsi="path_to_url"
xsi:schemaLocation="path_to_url path_to_url">
<modelVersion>4.0.0</modelVersion>
<groupId>com.google.training</groupId>
<artifactId>appdev</artifactId>
<version>0.0.1</version>
<packaging>jar</packaging>
<name>appdev</name>
<description>Quiz Application</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.6.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<google.datastore.version>1.6.0</google.datastore.version>
<google.pubsub.version>0.24.0-beta</google.pubsub.version>
<google.languageapi.version>0.24.0-beta</google.languageapi.version>
<google.spanner.version>0.24.0-beta</google.spanner.version>
<google.cloudstorage.version>1.6.0</google.cloudstorage.version>
<google-api-pubsub.version>v1-rev8-1.21.0</google-api-pubsub.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>com.vaadin.external.google</groupId>
<artifactId>android-json</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-datastore</artifactId>
<version>${google.datastore.version}</version>
<exclusions>
<exclusion>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-storage</artifactId>
<version>${google.cloudstorage.version}</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-language</artifactId>
<version>${google.languageapi.version}</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-spanner</artifactId>
<version>${google.spanner.version}</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-tcnative-boringssl-static</artifactId>
<version>2.0.3.Final</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-core</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-pubsub</artifactId>
<version>0.24.0-beta</version>
</dependency>
<dependency>
<groupId>com.google.cloud</groupId>
<artifactId>google-cloud-core-grpc</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>com.google.api.grpc</groupId>
<artifactId>proto-google-cloud-pubsub-v1</artifactId>
<version>0.1.20</version>
</dependency>
<dependency>
<groupId>com.google.api.grpc</groupId>
<artifactId>grpc-google-cloud-pubsub-v1</artifactId>
<version>0.1.20</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-all</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>worker</id>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>com.google.training.appdev.backend.ConsoleApp</mainClass>
</configuration>
</execution>
<execution>
<id>create-entities</id>
<goals>
<goal>java</goal>
</goals>
<configuration>
<mainClass>com.google.training.appdev.setup.QuestionBuilder</mainClass>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
``` | /content/code_sandbox/courses/developingapps/java/pubsub-languageapi-spanner/end/pom.xml | xml | 2016-04-17T21:39:27 | 2024-08-16T17:22:27 | training-data-analyst | GoogleCloudPlatform/training-data-analyst | 7,726 | 1,494 |
```xml
import NativeModulesProxy from './NativeModulesProxy';
import { ensureNativeModulesAreInstalled } from './ensureNativeModulesAreInstalled';
/**
* Imports the native module registered with given name. In the first place it tries to load
* the module installed through the JSI host object and then falls back to the bridge proxy module.
* Notice that the modules loaded from the proxy may not support some features like synchronous functions.
*
* @param moduleName Name of the requested native module.
* @returns Object representing the native module.
* @throws Error when there is no native module with given name.
*/
export function requireNativeModule<ModuleType = any>(moduleName: string): ModuleType {
const nativeModule = requireOptionalNativeModule<ModuleType>(moduleName);
if (!nativeModule) {
throw new Error(`Cannot find native module '${moduleName}'`);
}
return nativeModule;
}
/**
* Imports the native module registered with the given name. The same as `requireNativeModule`,
* but returns `null` when the module cannot be found instead of throwing an error.
*
* @param moduleName Name of the requested native module.
* @returns Object representing the native module or `null` when it cannot be found.
*/
export function requireOptionalNativeModule<ModuleType = any>(
moduleName: string
): ModuleType | null {
ensureNativeModulesAreInstalled();
return globalThis.expo?.modules?.[moduleName] ?? NativeModulesProxy[moduleName] ?? null;
}
``` | /content/code_sandbox/packages/expo-modules-core/src/requireNativeModule.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 304 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.