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 { ChatMessageDetails } from 'src/components/Chat/ChatMessageDetails';
import { isConformant } from 'test/specs/commonTests';
describe('ChatMessage', () => {
isConformant(ChatMessageDetails, {
testPath: __filename,
constructorName: 'ChatMessageDetails',
});
});
``` | /content/code_sandbox/packages/fluentui/react-northstar/test/specs/components/Chat/ChatMessageDetails-test.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 70 |
```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.
*/
// TypeScript Version: 4.1
/**
* Interface describing `dapxsumors`.
*/
interface Routine {
/**
* Adds a constant to each double-precision floating-point strided array element and computes the sum using ordinary recursive summation.
*
* @param N - number of indexed elements
* @param alpha - constant
* @param x - input array
* @param stride - stride length
* @returns sum
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 1.0, -2.0, 2.0 ] );
*
* var v = dapxsumors( x.length, 5.0, x, 1 );
* // returns 16.0
*/
( N: number, alpha: number, x: Float64Array, stride: number ): number;
/**
* Adds a constant to each double-precision floating-point strided array element and computes the sum using ordinary recursive summation and alternative indexing semantics.
*
* @param N - number of indexed elements
* @param alpha - constant
* @param x - input array
* @param stride - stride length
* @param offset - starting index
* @returns sum
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 1.0, -2.0, 2.0 ] );
*
* var v = dapxsumors.ndarray( x.length, 5.0, x, 1, 0 );
* // returns 16.0
*/
ndarray( N: number, alpha: number, x: Float64Array, stride: number, offset: number ): number;
}
/**
* Adds a constant to each double-precision floating-point strided array element and computes the sum using ordinary recursive summation.
*
* @param N - number of indexed elements
* @param alpha - constant
* @param x - input array
* @param stride - stride length
* @returns sum
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 1.0, -2.0, 2.0 ] );
*
* var v = dapxsumors( x.length, 5.0, x, 1 );
* // returns 16.0
*
* @example
* var Float64Array = require( '@stdlib/array/float64' );
*
* var x = new Float64Array( [ 1.0, -2.0, 2.0 ] );
*
* var v = dapxsumors.ndarray( x.length, 5.0, x, 1, 0 );
* // returns 16.0
*/
declare var dapxsumors: Routine;
// EXPORTS //
export = dapxsumors;
``` | /content/code_sandbox/lib/node_modules/@stdlib/blas/ext/base/dapxsumors/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 713 |
```xml
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import * as path from 'path';
import * as glob from 'glob';
import * as Mocha from 'mocha';
export function run(): Promise<void> {
// Create the mocha test
const mocha = new Mocha({
ui: 'tdd',
color: true,
reporter: 'mochawesome'
});
const testsRoot = path.resolve(__dirname, '..');
const globPattern = process.env['TEST_GLOB_PATTER'] ? process.env['TEST_GLOB_PATTER'] : '**/*.test.js';
console.log(globPattern);
return new Promise((c, e) => {
glob(globPattern, { cwd: testsRoot }, (err, files) => {
if (err) {
return e(err);
}
// Add files to the test suite
files.forEach(f => mocha.addFile(path.resolve(testsRoot, f)));
try {
// Run the mocha test
mocha.run(failures => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
c();
}
});
} catch (err) {
console.error(err);
e(err);
}
});
});
}
``` | /content/code_sandbox/integrations/vscode/src/test/suite/index.ts | xml | 2016-09-12T14:44:30 | 2024-08-16T14:41:50 | visualvm | oracle/visualvm | 2,821 | 484 |
```xml
import { render, screen } from '@testing-library/react';
import * as React from 'react';
import type { FullOption, ValueEditorProps, ValueSelectorProps } from 'react-querybuilder';
import { toFullOption, toFullOptionList } from 'react-querybuilder';
import { basicSchema, findSelect, hasOrInheritsClass, userEventSetup } from './utils';
type ValueSelectorTestsToSkip = Partial<{
multi: boolean;
optgroup: boolean;
disabledOptions: boolean;
}>;
export const defaultValueSelectorProps = {
handleOnChange: () => {},
options: [
{ name: 'foo', label: 'Foo' },
{ name: 'bar', label: 'Bar' },
{ name: 'baz', label: 'Baz' },
].map(o => toFullOption(o)),
level: 0,
path: [],
schema: basicSchema,
} satisfies ValueSelectorProps;
export const testSelect = (
title: string,
Component: React.ComponentType<ValueEditorProps> | React.ComponentType<ValueSelectorProps>,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
props: any,
skip: ValueSelectorTestsToSkip = {}
) => {
const user = userEventSetup();
const testValues = toFullOptionList(props.values ?? props.options) as FullOption[];
const testVal = testValues[1];
describe(title, () => {
it('should have the options passed into the <select />', () => {
render(<Component {...props} />);
expect(screen.getByTitle(title).querySelectorAll('option')).toHaveLength(testValues.length);
});
it('should render the correct number of options', () => {
render(<Component {...props} />);
const getSelect = () => findSelect(screen.getByTitle(title));
expect(getSelect).not.toThrow();
expect(getSelect().querySelectorAll('option')).toHaveLength(testValues.length);
});
if (!skip.optgroup) {
it('should render optgroups', () => {
const optGroups = [
{ label: 'Test Option Group', options: 'values' in props ? props.values : props.options },
];
const newProps =
'values' in props ? { ...props, values: optGroups } : { ...props, options: optGroups };
render(<Component {...newProps} />);
const getSelect = () => findSelect(screen.getByTitle(title));
expect(getSelect).not.toThrow();
expect(getSelect().querySelectorAll('optgroup')).toHaveLength(optGroups.length);
expect(getSelect().querySelectorAll('option')).toHaveLength(testValues.length);
});
}
// Test as multiselect for <ValueEditor type="multiselect" /> and <ValueSelector />
if (
!skip.multi &&
(('values' in props && props.type === 'multiselect') || 'options' in props)
) {
it('should have the values passed into the <select multiple />', () => {
const onChange = jest.fn();
const value = testValues.map(v => v.name).join(',');
const multiselectProps = 'values' in props ? { type: 'multiselect' } : { multiple: true };
render(
<Component {...props} value={value} {...multiselectProps} handleOnChange={onChange} />
);
const select = findSelect(screen.getByTitle(title));
expect(select).toHaveProperty('multiple', true);
expect(select.selectedOptions).toHaveLength(testValues.length);
});
it('should call the handleOnChange callback properly for <select multiple />', async () => {
const onChange = jest.fn();
const multiselectProps = 'values' in props ? { type: 'multiselect' } : { multiple: true };
const allValuesExceptFirst = testValues.slice(1, 3).map(v => v.name);
render(
<Component
{...props}
{...multiselectProps}
value={allValuesExceptFirst[0]}
handleOnChange={onChange}
/>
);
const select = findSelect(screen.getByTitle(title));
await user.selectOptions(select, allValuesExceptFirst);
expect(onChange).toHaveBeenCalledWith(allValuesExceptFirst.join(','));
});
it('should respect the listsAsArrays option', async () => {
const onChange = jest.fn();
const multiselectProps = 'values' in props ? { type: 'multiselect' } : { multiple: true };
render(
<Component
{...props}
{...multiselectProps}
handleOnChange={onChange}
listsAsArrays
value={[]}
/>
);
await user.selectOptions(findSelect(screen.getByTitle(title)), testVal.name);
expect(onChange).toHaveBeenCalledWith([testVal.name]);
});
}
// Test as single-value selector
if (('values' in props && props.type !== 'multiselect') || 'options' in props) {
it('should have the value passed into the <select />', () => {
render(<Component {...props} value={testVal.name} />);
expect(findSelect(screen.getByTitle(title))).toHaveValue(testVal.name);
});
}
it('should have the className passed into the <select />', () => {
render(<Component {...props} className="foo" />);
expect(hasOrInheritsClass(screen.getByTitle(title), 'foo')).toBe(true);
});
it('should call the onChange method passed in', async () => {
const onChange = jest.fn();
render(<Component {...props} handleOnChange={onChange} />);
await user.selectOptions(findSelect(screen.getByTitle(title)), testVal.name);
expect(onChange).toHaveBeenCalledWith(testVal.name);
});
it('should be disabled by the disabled prop', async () => {
const onChange = jest.fn();
render(<Component {...props} handleOnChange={onChange} disabled />);
expect(findSelect(screen.getByTitle(title))).toBeDisabled();
await user.selectOptions(findSelect(screen.getByTitle(title)), testVal.name);
expect(onChange).not.toHaveBeenCalled();
});
if (!skip.disabledOptions) {
it('should disable individual options', async () => {
const onChange = jest.fn();
const disabledOption = { name: 'disabled', label: 'Disabled', disabled: true };
const newValues = [...testValues, disabledOption];
const propsWithDisabledOption =
'values' in props ? { ...props, values: newValues } : { ...props, options: newValues };
render(<Component {...propsWithDisabledOption} handleOnChange={onChange} />);
await user.selectOptions(findSelect(screen.getByTitle(title)), 'disabled');
expect(onChange).not.toHaveBeenCalled();
});
}
});
};
export const testValueSelector = (
ValueSelector: React.ComponentType<ValueSelectorProps>,
skip: ValueSelectorTestsToSkip = {}
) => {
const title = ValueSelector.name ?? 'ValueSelector';
const props = { ...defaultValueSelectorProps, title };
testSelect(title, ValueSelector, props, skip);
};
``` | /content/code_sandbox/utils/testing/testValueSelector.tsx | xml | 2016-06-17T22:03:19 | 2024-08-16T10:28:42 | react-querybuilder | react-querybuilder/react-querybuilder | 1,131 | 1,478 |
```xml
import JitsiConference from '../../JitsiConference';
export default class P2PDominantSpeakerDetection {
constructor( conference: JitsiConference );
}
``` | /content/code_sandbox/types/hand-crafted/modules/detection/P2PDominantSpeakerDetection.d.ts | xml | 2016-01-27T22:44:09 | 2024-08-16T02:51:56 | lib-jitsi-meet | jitsi/lib-jitsi-meet | 1,328 | 35 |
```xml
import serviceFactory, {
ConsumerPact,
ConsumerInteraction,
makeConsumerPact,
} from '@pact-foundation/pact-core';
import clc from 'cli-color';
import * as path from 'path';
import process from 'process';
import { isEmpty } from 'lodash';
import {
Interaction,
InteractionObject,
interactionToInteractionObject,
} from '../dsl/interaction';
import { freePort, isPortAvailable } from '../common/net';
import logger, { setLogLevel } from '../common/logger';
import { LogLevel, PactOptions, PactOptionsComplete } from '../dsl/options';
import VerificationError from '../errors/verificationError';
import ConfigurationError from '../errors/configurationError';
import { SpecificationVersion } from '../v3';
import { version as pactPackageVersion } from '../../package.json';
import { generateMockServerError } from '../v3/display';
import { numberToSpec } from '../common/spec';
import { MockService } from '../dsl/mockService';
import { setRequestDetails, setResponseDetails } from './ffi';
const logErrorNoMockServer = () => {
logger.error(
"The pact mock service doesn't appear to be running\n" +
' - Please check the logs above to ensure that there are no pact service startup failures\n' +
' - Please check that pact lifecycle methods are called in the correct order (setup() needs to be called before this method)\n' +
' - Please check that your test code waits for the promises returned from lifecycle methods to complete before calling the next one\n' +
" - To learn more about what is happening during your pact run, try setting logLevel: 'DEBUG'"
);
};
/**
* Creates a new {@link PactProvider}.
* @memberof Pact
* @name create
* @param {PactOptions} opts
* @return {@link PactProvider}
*/
export class Pact {
public static defaults = {
consumer: '',
cors: false,
dir: path.resolve(process.cwd(), 'pacts'),
host: '127.0.0.1',
log: path.resolve(process.cwd(), 'logs', 'pact.log'),
logLevel: 'info',
pactfileWriteMode: 'merge',
provider: '',
spec: 2,
ssl: false,
port: 0,
} as PactOptions;
public static createOptionsWithDefaults(
opts: PactOptions
): PactOptionsComplete {
return { ...Pact.defaults, ...opts } as PactOptionsComplete;
}
public mockService: MockService;
public opts: PactOptionsComplete;
private mockServerStartedPort?: number;
private pact: ConsumerPact;
private interaction: ConsumerInteraction;
private finalized: boolean;
constructor(config: PactOptions) {
this.opts = Pact.createOptionsWithDefaults(config);
if (this.opts.pactfileWriteMode === 'overwrite') {
logger.warn(
"WARNING: the behaviour of pactfileWriteMode 'overwrite' has changed since version 9.x.x. See the type definition or the MIGRATION.md guide for details."
);
}
if (isEmpty(this.opts.consumer)) {
throw new ConfigurationError(
'You must specify a Consumer for this pact.'
);
}
if (isEmpty(this.opts.provider)) {
throw new ConfigurationError(
'You must specify a Provider for this pact.'
);
}
setLogLevel(this.opts.logLevel as LogLevel);
serviceFactory.logLevel(this.opts.logLevel);
// TODO: this now hangs the process
// if (this.opts.logLevel === 'trace') {
// traceHttpInteractions();
// }
this.reset();
}
/**
* Setup the pact framework, including allocating a port for the dynamic
* mock server
*
* @returns {Promise}
*/
public async setup(): Promise<PactOptionsComplete> {
if (this.opts.port > 0) {
await isPortAvailable(this.opts.port, this.opts.host);
} else {
const port = await freePort();
logger.debug(`free port discovered: ${port}`);
this.opts.port = port;
}
// create the mock service
this.mockService = {
baseUrl: `${this.opts.ssl ? 'https' : 'http'}://${this.opts.host}:${
this.opts.port
}`,
pactDetails: {
pactfile_write_mode: this.opts.pactfileWriteMode || 'merge',
consumer: {
name: this.opts.consumer,
},
provider: { name: this.opts.provider },
},
};
return this.opts;
}
/**
* Add an interaction to the {@link MockService}.
* @memberof PactProvider
* @instance
* @param {Interaction} interactionObj
* @returns {Promise}
*/
public addInteraction(
interactionObj: InteractionObject | Interaction
): Promise<string> {
if (!this.mockService) {
logErrorNoMockServer();
return Promise.reject(
new Error(
"The pact mock service wasn't configured when addInteraction was called"
)
);
}
let interaction: InteractionObject;
if (interactionObj instanceof Interaction) {
// This will throw if not valid
const interactionState = interactionObj.json();
// Convert into the same type
interaction = interactionToInteractionObject(interactionState);
} else {
interaction = interactionObj;
}
this.interaction.uponReceiving(interaction.uponReceiving);
if (interaction.state) {
this.interaction.given(interaction.state);
}
setRequestDetails(this.interaction, interaction.withRequest);
setResponseDetails(this.interaction, interaction.willRespondWith);
this.startMockServer();
return Promise.resolve('');
}
/**
* Checks with the Mock Service if the expected interactions have been exercised.
* @memberof PactProvider
* @instance
* @returns {Promise}
*/
public verify(): Promise<string> {
if (!this.mockService) {
logErrorNoMockServer();
return Promise.reject(
new Error("The pact mock service wasn't running when verify was called")
);
}
const matchingResults = this.pact.mockServerMismatches(this.opts.port);
const success = this.pact.mockServerMatchedSuccessfully(this.opts.port);
// Feature flag: allow missing requests on the mock service
if (!success) {
let error = 'Test failed for the following reasons:';
error += `\n\n ${generateMockServerError(matchingResults, '\t')}`;
/* eslint-disable no-console */
console.error('');
console.error(clc.red('Pact verification failed!'));
console.error(clc.red(error));
/* eslint-enable */
this.reset();
throw new VerificationError(
'Pact verification failed - expected interactions did not match actual.'
);
}
return this.writePact()
.then(() => this.reset())
.then(() => '');
}
/**
* Writes the Pact and clears any interactions left behind and shutdown the
* mock server
* @memberof PactProvider
* @instance
* @returns {Promise}
*/
public finalize(): Promise<void> {
if (this.finalized) {
logger.warn(
'finalize() has already been called, this is probably a logic error in your test setup. ' +
'In the future this will be an error.'
);
}
this.finalized = true;
return Promise.resolve();
}
/**
* Writes the pact file out to file. Should be called when all tests have been performed for a
* given Consumer <-> Provider pair. It will write out the Pact to the
* configured file.
* @memberof PactProvider
* @instance
* @returns {Promise}
*/
public writePact(): Promise<string> {
if (!this.mockService) {
logErrorNoMockServer();
return Promise.reject(
new Error(
"The pact mock service wasn't running when writePact was called"
)
);
}
this.pact.writePactFile(
this.opts.dir || './pacts',
this.opts.pactfileWriteMode !== 'overwrite'
);
return Promise.resolve('');
}
/**
* Clear up any interactions in the Provider Mock Server.
* @memberof PactProvider
* @instance
* @returns {Promise}
*/
public removeInteractions(): Promise<string> {
logger.info(
'removeInteractions() is no longer required to be called, but has been kept for compatibility with upgrade from 9.x.x. You should remove any use of this method.'
);
return Promise.resolve('');
}
private startMockServer() {
logger.debug(`Setting up Pact mock server with Consumer "${this.opts.consumer}" and Provider "${this.opts.provider}"
using mock service on Port: "${this.opts.port}"`);
const port = this.pact.createMockServer(
this.opts.host,
this.opts.port,
this.opts.ssl
);
this.mockServerStartedPort = port;
logger.debug(`mock service started on port: ${port}`);
}
// reset the internal state
// (this.pact cannot be re-used between tests)
private reset() {
this.pact = makeConsumerPact(
this.opts.consumer,
this.opts.provider,
numberToSpec(
this.opts.spec,
SpecificationVersion.SPECIFICATION_VERSION_V2
),
this.opts.logLevel ?? 'info'
);
this.interaction = this.pact.newInteraction('');
if (this.mockServerStartedPort) {
logger.debug(`cleaning up old mock server on port ${this.opts.port}`);
const res = this.pact.cleanupMockServer(this.mockServerStartedPort);
if (!res) {
logger.warn('Unable to cleanup the Pact mock server. ');
}
this.mockServerStartedPort = undefined;
}
this.pact.addMetadata('pact-js', 'version', pactPackageVersion);
}
}
``` | /content/code_sandbox/src/httpPact/index.ts | xml | 2016-06-03T12:02:17 | 2024-08-15T05:47:24 | pact-js | pact-foundation/pact-js | 1,596 | 2,132 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!-- You may freely edit this file. See harness/README in the NetBeans platform -->
<!-- for some information on what you could do (e.g. targets to override). -->
<!-- If you delete this file and reopen the project it will be recreated. -->
<project basedir="." default="netbeans" name="org/graalvm/visualizer/upgrader">
<description>Builds, tests, and runs the project Upgrader.</description>
<import file="nbproject/build-impl.xml"/>
<target name="-init-migration">
<property name="test.includes" value="**/UpgraderTestDist.class"/>
</target>
<target name="test-migration" depends="init,test-init,test-build,-init-migration,test-unit" if="exists.test.unit.src.dir"/>
</project>
``` | /content/code_sandbox/visualizer/IdealGraphVisualizer/Upgrade/build.xml | xml | 2016-01-14T17:11:35 | 2024-08-16T17:54:25 | graal | oracle/graal | 20,129 | 191 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<!--
~ All Rights Reserved.
-->
<vector
xmlns:android="path_to_url"
android:width="24dp"
android:height="24dp"
android:viewportWidth="24"
android:viewportHeight="24">
<path
android:fillColor="#FFFFFFFF"
android:pathData="M 24,12 A 12,12 0 0 1 12,24 12,12 0 0 1 0,12 12,12 0 0 1 12,0 12,12 0 0 1 24,12 Z" />
<path
android:fillColor="#FF000000"
android:pathData="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z" />
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/remove_image_icon_24dp.xml | xml | 2016-02-01T13:44:19 | 2024-08-15T05:23:34 | Douya | zhanghai/Douya | 4,549 | 303 |
```xml
'use strict';
import * as assert from 'assert';
import * as fs from 'fs';
import * as path from 'path';
import { anything, instance, mock, verify, when } from 'ts-mockito';
import { DebugSession, WorkspaceFolder } from 'vscode';
import { DebugProtocol } from 'vscode-debugprotocol';
import { FileSystem } from '../../../../client/common/platform/fileSystem';
import { EXTENSION_ROOT_DIR } from '../../../../client/constants';
import { DebugSessionLoggingFactory } from '../../../../client/debugger/extension/adapter/logging';
suite('Debugging - Session Logging', () => {
const oldValueOfVSC_PYTHON_UNIT_TEST = process.env.VSC_PYTHON_UNIT_TEST;
const oldValueOfVSC_PYTHON_CI_TEST = process.env.VSC_PYTHON_CI_TEST;
let loggerFactory: DebugSessionLoggingFactory;
let fsService: FileSystem;
let writeStream: fs.WriteStream;
setup(() => {
fsService = mock(FileSystem);
writeStream = mock(fs.WriteStream);
process.env.VSC_PYTHON_UNIT_TEST = undefined;
process.env.VSC_PYTHON_CI_TEST = undefined;
loggerFactory = new DebugSessionLoggingFactory(instance(fsService));
});
teardown(() => {
process.env.VSC_PYTHON_UNIT_TEST = oldValueOfVSC_PYTHON_UNIT_TEST;
process.env.VSC_PYTHON_CI_TEST = oldValueOfVSC_PYTHON_CI_TEST;
});
function createSession(id: string, workspaceFolder?: WorkspaceFolder): DebugSession {
return {
configuration: {
name: '',
request: 'launch',
type: 'python',
},
id: id,
name: 'python',
type: 'python',
workspaceFolder,
customRequest: () => Promise.resolve(),
getDebugProtocolBreakpoint: () => Promise.resolve(undefined),
};
}
function createSessionWithLogging(id: string, logToFile: boolean, workspaceFolder?: WorkspaceFolder): DebugSession {
const session = createSession(id, workspaceFolder);
session.configuration.logToFile = logToFile;
return session;
}
class TestMessage implements DebugProtocol.ProtocolMessage {
public seq: number;
public type: string;
public id: number;
public format: string;
public variables?: { [key: string]: string };
public sendTelemetry?: boolean;
public showUser?: boolean;
public url?: string;
public urlLabel?: string;
constructor(id: number, seq: number, type: string) {
this.id = id;
this.format = 'json';
this.seq = seq;
this.type = type;
}
}
test('Create logger using session without logToFile', async () => {
const session = createSession('test1');
const filePath = path.join(EXTENSION_ROOT_DIR, `debugger.vscode_${session.id}.log`);
await loggerFactory.createDebugAdapterTracker(session);
verify(fsService.createWriteStream(filePath)).never();
});
test('Create logger using session with logToFile set to false', async () => {
const session = createSessionWithLogging('test2', false);
const filePath = path.join(EXTENSION_ROOT_DIR, `debugger.vscode_${session.id}.log`);
when(fsService.createWriteStream(filePath)).thenReturn(instance(writeStream));
when(writeStream.write(anything())).thenReturn(true);
const logger = await loggerFactory.createDebugAdapterTracker(session);
if (logger) {
logger.onWillStartSession!();
}
verify(fsService.createWriteStream(filePath)).never();
verify(writeStream.write(anything())).never();
});
test('Create logger using session with logToFile set to true', async () => {
const session = createSessionWithLogging('test3', true);
const filePath = path.join(EXTENSION_ROOT_DIR, `debugger.vscode_${session.id}.log`);
const logs: string[] = [];
when(fsService.createWriteStream(filePath)).thenReturn(instance(writeStream));
when(writeStream.write(anything())).thenCall((msg) => logs.push(msg));
const message = new TestMessage(1, 1, 'test-message');
const logger = await loggerFactory.createDebugAdapterTracker(session);
if (logger) {
logger.onWillStartSession!();
assert.ok(logs.pop()!.includes('Starting Session'));
logger.onDidSendMessage!(message);
const sentLog = logs.pop();
assert.ok(sentLog!.includes('Client <-- Adapter'));
assert.ok(sentLog!.includes('test-message'));
logger.onWillReceiveMessage!(message);
const receivedLog = logs.pop();
assert.ok(receivedLog!.includes('Client --> Adapter'));
assert.ok(receivedLog!.includes('test-message'));
logger.onWillStopSession!();
assert.ok(logs.pop()!.includes('Stopping Session'));
logger.onError!(new Error('test error message'));
assert.ok(logs.pop()!.includes('Error'));
logger.onExit!(111, '222');
const exitLog1 = logs.pop();
assert.ok(exitLog1!.includes('Exit-Code: 111'));
assert.ok(exitLog1!.includes('Signal: 222'));
logger.onExit!(undefined, undefined);
const exitLog2 = logs.pop();
assert.ok(exitLog2!.includes('Exit-Code: 0'));
assert.ok(exitLog2!.includes('Signal: none'));
}
verify(fsService.createWriteStream(filePath)).once();
verify(writeStream.write(anything())).times(7);
assert.deepEqual(logs, []);
});
});
``` | /content/code_sandbox/src/test/debugger/extension/adapter/logging.unit.test.ts | xml | 2016-01-19T10:50:01 | 2024-08-12T21:05:24 | pythonVSCode | DonJayamanne/pythonVSCode | 2,078 | 1,166 |
```xml
export * from 'rxjs-compat/operator/dematerialize';
``` | /content/code_sandbox/deps/node-10.15.3/tools/node_modules/eslint/node_modules/rxjs/operator/dematerialize.d.ts | xml | 2016-09-05T10:18:44 | 2024-08-11T13:21:40 | LiquidCore | LiquidPlayer/LiquidCore | 1,010 | 14 |
```xml
import 'reflect-metadata';
import { plainToInstance } from '../../src/index';
import { defaultMetadataStorage } from '../../src/storage';
import { Expose, Type } from '../../src/decorators';
describe('implicit type conversion', () => {
it('should run only when enabled', () => {
defaultMetadataStorage.clear();
class SimpleExample {
@Expose()
readonly implicitTypeNumber: number;
@Expose()
readonly implicitTypeString: string;
}
const result1: SimpleExample = plainToInstance(
SimpleExample,
{
implicitTypeNumber: '100',
implicitTypeString: 133123,
},
{ enableImplicitConversion: true }
);
const result2: SimpleExample = plainToInstance(
SimpleExample,
{
implicitTypeNumber: '100',
implicitTypeString: 133123,
},
{ enableImplicitConversion: false }
);
expect(result1).toEqual({ implicitTypeNumber: 100, implicitTypeString: '133123' });
expect(result2).toEqual({ implicitTypeNumber: '100', implicitTypeString: 133123 });
});
});
describe('implicit and explicity type declarations', () => {
defaultMetadataStorage.clear();
class Example {
@Expose()
readonly implicitTypeViaOtherDecorator: Date;
@Type()
readonly implicitTypeViaEmptyTypeDecorator: number;
@Type(() => String)
readonly explicitType: string;
}
const result: Example = plainToInstance(
Example,
{
implicitTypeViaOtherDecorator: '2018-12-24T12:00:00Z',
implicitTypeViaEmptyTypeDecorator: '100',
explicitType: 100,
},
{ enableImplicitConversion: true }
);
it('should use implicitly defined design:type to convert value when no @Type decorator is used', () => {
expect(result.implicitTypeViaOtherDecorator).toBeInstanceOf(Date);
expect(result.implicitTypeViaOtherDecorator.getTime()).toEqual(new Date('2018-12-24T12:00:00Z').getTime());
});
it('should use implicitly defined design:type to convert value when empty @Type() decorator is used', () => {
expect(typeof result.implicitTypeViaEmptyTypeDecorator).toBe('number');
expect(result.implicitTypeViaEmptyTypeDecorator).toEqual(100);
});
it('should use explicitly defined type when @Type(() => Construtable) decorator is used', () => {
expect(typeof result.explicitType).toBe('string');
expect(result.explicitType).toEqual('100');
});
});
describe('plainToInstance transforms built-in primitive types properly', () => {
defaultMetadataStorage.clear();
class Example {
@Type()
date: Date;
@Type()
string: string;
@Type()
string2: string;
@Type()
number: number;
@Type()
number2: number;
@Type()
boolean: boolean;
@Type()
boolean2: boolean;
}
const result: Example = plainToInstance(
Example,
{
date: '2018-12-24T12:00:00Z',
string: '100',
string2: 100,
number: '100',
number2: 100,
boolean: 1,
boolean2: 0,
},
{ enableImplicitConversion: true }
);
it('should recognize and convert to Date', () => {
expect(result.date).toBeInstanceOf(Date);
expect(result.date.getTime()).toEqual(new Date('2018-12-24T12:00:00Z').getTime());
});
it('should recognize and convert to string', () => {
expect(typeof result.string).toBe('string');
expect(typeof result.string2).toBe('string');
expect(result.string).toEqual('100');
expect(result.string2).toEqual('100');
});
it('should recognize and convert to number', () => {
expect(typeof result.number).toBe('number');
expect(typeof result.number2).toBe('number');
expect(result.number).toEqual(100);
expect(result.number2).toEqual(100);
});
it('should recognize and convert to boolean', () => {
expect(result.boolean).toBeTruthy();
expect(result.boolean2).toBeFalsy();
});
});
``` | /content/code_sandbox/test/functional/implicit-type-declarations.spec.ts | xml | 2016-02-09T13:26:52 | 2024-08-16T11:51:20 | class-transformer | typestack/class-transformer | 6,715 | 920 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="path_to_url">
<background android:drawable="@color/ic_launcher_background"/>
<foreground android:drawable="@drawable/ic_launcher_foreground"/>
<monochrome android:drawable="@drawable/ic_launcher_monochrome" />
</adaptive-icon>
``` | /content/code_sandbox/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml | xml | 2016-07-02T10:44:04 | 2024-08-16T18:55:54 | StreetComplete | streetcomplete/StreetComplete | 3,781 | 70 |
```xml
<layout xmlns:android="path_to_url"
xmlns:app="path_to_url">
<data>
<variable
name="name"
type="String" />
<variable
name="value"
type="String" />
</data>
<LinearLayout
android:orientation="vertical"
app:showIfTrueAnimatedFastOff="@{value.length() > 0}"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingTop="5dp"
android:paddingBottom="5dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="end"
android:paddingRight="5dp"
android:text="@{name}"
android:textSize="14sp" />
<TextView
android:layout_width="5dp"
android:layout_height="wrap_content"
android:layout_weight="0"
android:gravity="center_horizontal"
android:paddingStart="2dp"
android:paddingEnd="2dp"
android:text=":"
android:textSize="14sp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="start"
android:paddingLeft="5dp"
android:text="@{value}"
android:textSize="14sp" />
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="?android:attr/listDivider" />
</LinearLayout>
</layout>
``` | /content/code_sandbox/app/src/main/res/layout/bound_status_item.xml | xml | 2016-09-23T13:33:17 | 2024-08-15T09:51:19 | xDrip | NightscoutFoundation/xDrip | 1,365 | 389 |
```xml
import { FallbackRequestedError } from "@bitwarden/common/platform/abstractions/fido2/fido2-client.service.abstraction";
import { Message, MessageType } from "./message";
const SENDER = "bitwarden-webauthn";
type PostMessageFunction = (message: MessageWithMetadata, remotePort: MessagePort) => void;
export type Channel = {
addEventListener: (listener: (message: MessageEvent<MessageWithMetadata>) => void) => void;
removeEventListener: (listener: (message: MessageEvent<MessageWithMetadata>) => void) => void;
postMessage: PostMessageFunction;
};
export type Metadata = { SENDER: typeof SENDER; senderId: string };
export type MessageWithMetadata = Message & Metadata;
type Handler = (
message: MessageWithMetadata,
abortController?: AbortController,
) => void | Promise<Message | undefined>;
/**
* A class that handles communication between the page and content script. It converts
* the browser's broadcasting API into a request/response API with support for seamlessly
* handling aborts and exceptions across separate execution contexts.
*/
export class Messenger {
private messageEventListener: (event: MessageEvent<MessageWithMetadata>) => void | null = null;
private onDestroy = new EventTarget();
/**
* Creates a messenger that uses the browser's `window.postMessage` API to initiate
* requests in the content script. Every request will then create it's own
* `MessageChannel` through which all subsequent communication will be sent through.
*
* @param window the window object to use for communication
* @returns a `Messenger` instance
*/
static forDOMCommunication(window: Window) {
const windowOrigin = window.location.origin;
return new Messenger({
postMessage: (message, port) => window.postMessage(message, windowOrigin, [port]),
addEventListener: (listener) => window.addEventListener("message", listener),
removeEventListener: (listener) => window.removeEventListener("message", listener),
});
}
/**
* The handler that will be called when a message is received. The handler should return
* a promise that resolves to the response message. If the handler throws an error, the
* error will be sent back to the sender.
*/
handler?: Handler;
private messengerId = this.generateUniqueId();
constructor(private broadcastChannel: Channel) {
this.messageEventListener = this.createMessageEventListener();
this.broadcastChannel.addEventListener(this.messageEventListener);
}
/**
* Sends a request to the content script and returns the response.
* AbortController signals will be forwarded to the content script.
*
* @param request data to send to the content script
* @param abortSignal the abort controller that might be used to abort the request
* @returns the response from the content script
*/
async request(request: Message, abortSignal?: AbortSignal): Promise<Message> {
const requestChannel = new MessageChannel();
const { port1: localPort, port2: remotePort } = requestChannel;
try {
const promise = new Promise<Message>((resolve) => {
localPort.onmessage = (event: MessageEvent<MessageWithMetadata>) => resolve(event.data);
});
const abortListener = () =>
localPort.postMessage({
metadata: { SENDER },
type: MessageType.AbortRequest,
});
abortSignal?.addEventListener("abort", abortListener);
this.broadcastChannel.postMessage(
{ ...request, SENDER, senderId: this.messengerId },
remotePort,
);
const response = await promise;
abortSignal?.removeEventListener("abort", abortListener);
if (response.type === MessageType.ErrorResponse) {
const error = new Error();
Object.assign(error, JSON.parse(response.error));
throw error;
}
return response;
} finally {
localPort.close();
}
}
private createMessageEventListener() {
return async (event: MessageEvent<MessageWithMetadata>) => {
const windowOrigin = window.location.origin;
if (event.origin !== windowOrigin || !this.handler) {
return;
}
const message = event.data;
const port = event.ports?.[0];
if (message?.SENDER !== SENDER || message.senderId == this.messengerId || port == null) {
return;
}
const abortController = new AbortController();
port.onmessage = (event: MessageEvent<MessageWithMetadata>) => {
if (event.data.type === MessageType.AbortRequest) {
abortController.abort();
}
};
let onDestroyListener;
const destroyPromise: Promise<never> = new Promise((_, reject) => {
onDestroyListener = () => reject(new FallbackRequestedError());
this.onDestroy.addEventListener("destroy", onDestroyListener);
});
try {
const handlerResponse = await Promise.race([
this.handler(message, abortController),
destroyPromise,
]);
port.postMessage({ ...handlerResponse, SENDER });
} catch (error) {
port.postMessage({
SENDER,
type: MessageType.ErrorResponse,
error: JSON.stringify(error, Object.getOwnPropertyNames(error)),
});
} finally {
this.onDestroy.removeEventListener("destroy", onDestroyListener);
port.close();
}
};
}
/**
* Cleans up the messenger by removing the message event listener
*/
async destroy() {
this.onDestroy.dispatchEvent(new Event("destroy"));
if (this.messageEventListener) {
await this.sendDisconnectCommand();
this.broadcastChannel.removeEventListener(this.messageEventListener);
this.messageEventListener = null;
}
}
private async sendDisconnectCommand() {
await this.request({ type: MessageType.DisconnectRequest });
}
private generateUniqueId() {
return Date.now().toString(36) + Math.random().toString(36).substring(2);
}
}
``` | /content/code_sandbox/apps/browser/src/autofill/fido2/content/messaging/messenger.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 1,221 |
```xml
import type {Rect} from '@floating-ui/utils';
export function paintDebugRects(elementRect: Rect, clippingRect: Rect) {
const elNode = document.getElementById('elementRect') as HTMLElement;
elNode.style.left = `${elementRect.x}px`;
elNode.style.top = `${elementRect.y}px`;
elNode.style.width = `${elementRect.width}px`;
elNode.style.height = `${elementRect.height}px`;
const clNode = document.getElementById('clippingRect') as HTMLElement;
clNode.style.left = `${clippingRect.x}px`;
clNode.style.top = `${clippingRect.y}px`;
clNode.style.width = `${clippingRect.width}px`;
clNode.style.height = `${clippingRect.height}px`;
}
``` | /content/code_sandbox/packages/core/src/utils/debugRects.ts | xml | 2016-03-29T17:00:47 | 2024-08-16T16:29:40 | floating-ui | floating-ui/floating-ui | 29,450 | 159 |
```xml
/**
* A list of time units with their associated value in milliseconds.
*/
const UNITS: { name: Intl.RelativeTimeFormatUnit; milliseconds: number }[] = [
{ name: 'years', milliseconds: 365 * 24 * 60 * 60 * 1000 },
{ name: 'months', milliseconds: 30 * 24 * 60 * 60 * 1000 },
{ name: 'days', milliseconds: 24 * 60 * 60 * 1000 },
{ name: 'hours', milliseconds: 60 * 60 * 1000 },
{ name: 'minutes', milliseconds: 60 * 1000 },
{ name: 'seconds', milliseconds: 1000 }
];
/**
* The namespace for date functions.
*/
export namespace Time {
export type HumanStyle = Intl.ResolvedRelativeTimeFormatOptions['style'];
/**
* Convert a timestring to a human readable string (e.g. 'two minutes ago').
*
* @param value - The date timestring or date object.
*
* @returns A formatted date.
*/
export function formatHuman(
value: string | Date,
format: HumanStyle = 'long'
): string {
const lang = document.documentElement.lang || 'en';
const formatter = new Intl.RelativeTimeFormat(lang, {
numeric: 'auto',
style: format
});
const delta = new Date(value).getTime() - Date.now();
for (let unit of UNITS) {
const amount = Math.ceil(delta / unit.milliseconds);
if (amount === 0) {
continue;
}
return formatter.format(amount, unit.name);
}
return formatter.format(0, 'seconds');
}
/**
* Convenient helper to convert a timestring to a date format.
*
* @param value - The date timestring or date object.
*
* @returns A formatted date.
*/
export function format(value: string | Date): string {
const lang = document.documentElement.lang || 'en';
const formatter = new Intl.DateTimeFormat(lang, {
dateStyle: 'short',
timeStyle: 'short'
});
return formatter.format(new Date(value));
}
}
``` | /content/code_sandbox/packages/coreutils/src/time.ts | xml | 2016-06-03T20:09:17 | 2024-08-16T19:12:44 | jupyterlab | jupyterlab/jupyterlab | 14,019 | 481 |
```xml
import { nextTestSetup } from 'e2e-utils'
describe('app-dir - metadata-icons-parallel-routes', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should present favicon with other icons when parallel routes are presented', async () => {
const $ = await next.render$('/')
expect($('link[type="image/x-icon"]').length).toBe(1)
expect($('link[type="image/svg+xml"]').length).toBe(1)
expect($('link[rel="apple-touch-icon"]').length).toBe(1)
})
it('should override parent icon when both static icon presented', async () => {
const $ = await next.render$('/nested')
expect($('link[type="image/x-icon"]').length).toBe(1)
expect($('link[rel="icon"][type="image/png"]').length).toBe(1)
})
it('should inherit parent apple icon when child does not present but parent contain static apple icon', async () => {
const $ = await next.render$('/nested')
expect($('link[rel="apple-touch-icon"][type="image/png"]').length).toBe(1)
})
})
``` | /content/code_sandbox/test/e2e/app-dir/metadata-icons-parallel-routes/metadata-icons-parallel-routes.test.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 252 |
```xml
import { AudioMode, AudioSource, AudioStatus, RecorderState, RecordingOptions, RecordingStatus } from './Audio.types';
import AudioModule from './AudioModule';
import { AudioPlayer, AudioRecorder } from './AudioModule.types';
export declare function useAudioPlayer(source?: AudioSource | string | number | null, updateInterval?: number): AudioPlayer;
export declare function useAudioPlayerStatus(player: AudioPlayer): AudioStatus;
export declare function useAudioSampleListener(player: AudioPlayer, listener: (data: {
channels: {
frames: number[];
}[];
timestamp: number;
}) => void): void;
export declare function useAudioRecorder(options: RecordingOptions, statusListener?: (status: RecordingStatus) => void): AudioRecorder;
export declare function useAudioRecorderState(recorder: AudioRecorder, interval?: number): RecorderState;
export declare function setIsAudioActiveAsync(active: boolean): Promise<void>;
export declare function setAudioModeAsync(mode: AudioMode): Promise<void>;
export { AudioModule, AudioPlayer, AudioRecorder };
export * from './Audio.types';
//# sourceMappingURL=ExpoAudio.d.ts.map
``` | /content/code_sandbox/packages/expo-audio/build/ExpoAudio.d.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 229 |
```xml
import type { ComponentPropsWithoutRef } from 'react';
import clsx from '@proton/utils/clsx';
const SettingsSection = ({ className, ...rest }: ComponentPropsWithoutRef<'div'>) => {
return <div className={clsx(['max-w-custom', className])} style={{ '--max-w-custom': '46em' }} {...rest} />;
};
export default SettingsSection;
``` | /content/code_sandbox/packages/components/containers/account/SettingsSection.tsx | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 83 |
```xml
export { Modal } from './Modal';
export { openModal } from './open-modal';
export { ModalType } from './types';
export { type OnSubmit } from './Modal/types';
``` | /content/code_sandbox/app/react/components/modals/index.ts | xml | 2016-05-19T20:15:28 | 2024-08-16T19:15:14 | portainer | portainer/portainer | 30,083 | 39 |
```xml
<!--
~ 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.
-->
<dataset>
<metadata>
<column name="schemaname" />
<column name="tablename" />
<column name="statistics_schemaname" />
<column name="statistics_name" />
<column name="statistics_owner" />
<column name="expr" />
<column name="null_frac" />
<column name="avg_width" />
<column name="n_distinct" />
<column name="most_common_vals" />
<column name="most_common_freqs" />
<column name="histogram_bounds" />
<column name="correlation" />
<column name="most_common_elems" />
<column name="most_common_elem_freqs" />
<column name="elem_count_histogram" />
</metadata>
</dataset>
``` | /content/code_sandbox/test/e2e/sql/src/test/resources/cases/dql/dataset/empty_storage_units/postgresql/select_postgresql_pg_catalog_pg_stats_ext_exprs.xml | xml | 2016-01-18T12:49:26 | 2024-08-16T15:48:11 | shardingsphere | apache/shardingsphere | 19,707 | 241 |
```xml
import value from '../components/generics'
export default () => <div id="value">{value}</div>
``` | /content/code_sandbox/test/integration/typescript/pages/generics.tsx | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 24 |
```xml
function hasScheme(url: string): Boolean {
return url.startsWith('path_to_url || url.startsWith('path_to_url
}
export function normalizeURL(url: string): string {
return hasScheme(url) ? url : `path_to_url{url}`;
}
``` | /content/code_sandbox/packages/cli/src/util/bisect/normalize-url.ts | xml | 2016-09-09T01:12:08 | 2024-08-16T17:39:45 | vercel | vercel/vercel | 12,545 | 54 |
```xml
import { Localized } from "@fluent/react/compat";
import cn from "classnames";
import React, {
ChangeEventHandler,
ComponentType,
FocusEventHandler,
FunctionComponent,
MouseEventHandler,
} from "react";
import CLASSES from "coral-stream/classes";
import { SvgIcon } from "coral-ui/components/icons";
import styles from "./StarRatingIcon.css";
interface Props {
id?: string;
value: number;
checked: boolean;
Icon: ComponentType;
name?: string;
readOnly?: boolean;
filled?: boolean;
size?: "xl" | "lg";
onFocus?: FocusEventHandler<HTMLInputElement>;
onBlur?: FocusEventHandler<HTMLInputElement>;
onChange?: ChangeEventHandler<HTMLInputElement>;
onClick?: MouseEventHandler<HTMLInputElement>;
}
const StarRatingIcon: FunctionComponent<Props> = ({
id,
value,
readOnly = false,
size = "lg",
Icon,
filled,
...props
}) => {
const container = (
<Localized
id="framework-starRating"
vars={{ value }}
attrs={{ "aria-label": true }}
>
<SvgIcon
Icon={Icon}
filled={filled ? "currentColor" : "none"}
className={cn(
styles.icons,
!readOnly && styles.interactive,
CLASSES.ratingsAndReview.stars.icon
)}
tab-index={value}
aria-label={`${value} Star`}
size={size}
/>
</Localized>
);
if (readOnly) {
return <span>{container}</span>;
}
return (
<>
<label htmlFor={id}>{container}</label>
<input
id={id}
className={styles.visuallyhidden}
value={value}
type="radio"
{...props}
/>
</>
);
};
export default StarRatingIcon;
``` | /content/code_sandbox/client/src/core/client/ui/components/v3/StarRating/StarRatingIcon.tsx | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 388 |
```xml
import { Box, IconButton, Tab, Tabs, Typography } from "@mui/material";
import React, { useEffect, useState } from "react";
import { RiExternalLinkLine, RiSortAsc, RiSortDesc } from "react-icons/ri";
import { Link } from "react-router-dom";
import { useLocalStorage } from "usehooks-ts";
import { useStateApiLogs } from "../pages/log/hooks";
import { LogViewer } from "../pages/log/LogViewer";
import { HideableBlock } from "./CollapsibleSection";
import { ClassNameProps } from "./props";
export type MultiTabLogViewerTabDetails = {
title: string;
} & LogViewerData;
export type MultiTabLogViewerProps = {
tabs: MultiTabLogViewerTabDetails[];
otherLogsLink?: string;
/**
* If set, this multi-tab log viewer will remember the last selected tab and start on that tab
* the next time this component is rendered.
*
* Different string values to provide different contexts for this memory. For example, if you
* want all multi-tab log viewers in the actor detail page to share one memory, they should have
* the same string value here.
*/
contextKey?: string;
} & ClassNameProps;
export const MultiTabLogViewer = ({
tabs,
otherLogsLink,
contextKey,
className,
}: MultiTabLogViewerProps) => {
// DO NOT use `cachedTab` or `setCachedTab` when `contextKey` is undefined!
const [cachedTab, setCachedTab] = useLocalStorage(
`MultiTabLogViewer-tabMemory-${contextKey}`,
null,
);
const [value, setValue] = useState(
contextKey && cachedTab ? cachedTab : tabs[0]?.title,
);
const [expanded, setExpanded] = useState(false);
useEffect(() => {
// If current tab value is not valid, reset to first tab.
if (!tabs.some((tab) => tab.title === value)) {
setValue(tabs[0]?.title);
}
}, [tabs, value]);
const currentTab = tabs.find((tab) => tab.title === value);
if (tabs.length === 0) {
return <Typography>No logs to display.</Typography>;
}
return (
<div className={className}>
<Box
display="flex"
flexDirection="row"
alignItems="flex-start"
justifyContent="space-between"
>
<Box
display="flex"
flexDirection="column"
alignItems="stretch"
flexGrow={1}
>
{(tabs.length > 1 || otherLogsLink) && (
<Tabs
sx={{
borderBottom: (theme) => `1px solid ${theme.palette.divider}`,
}}
value={value}
onChange={(_, newValue) => {
if (contextKey) {
setCachedTab(newValue);
}
setValue(newValue);
}}
indicatorColor="primary"
>
{tabs.map(({ title }) => (
<Tab key={title} label={title} value={title} />
))}
{otherLogsLink && (
<Tab
label={
<Box display="flex" alignItems="center">
Other logs <RiExternalLinkLine size={20} />
</Box>
}
onClick={(event) => {
// Prevent the tab from changing by setting value to the current value
setValue(value);
}}
component={Link}
to={otherLogsLink}
target="_blank"
rel="noopener noreferrer"
/>
)}
</Tabs>
)}
{!currentTab ? (
<Typography color="error">Please select a tab.</Typography>
) : (
tabs.map((tab) => {
const { title, ...data } = tab;
return (
<HideableBlock
key={title}
visible={title === currentTab?.title}
keepRendered
>
<StateApiLogViewer
data={data}
height={expanded ? 800 : 300}
/>
</HideableBlock>
);
})
)}
</Box>
<IconButton
onClick={() => {
setExpanded(!expanded);
}}
size="large"
>
{expanded ? <RiSortAsc /> : <RiSortDesc />}
</IconButton>
</Box>
</div>
);
};
type TextData = {
contents: string;
};
type FileData = {
nodeId: string | null;
filename?: string;
};
type ActorData = {
actorId: string | null;
suffix: "out" | "err";
};
type TaskData = {
taskId: string | null;
suffix: "out" | "err";
};
type LogViewerData = TextData | FileData | ActorData | TaskData;
const isLogViewerDataText = (data: LogViewerData): data is TextData =>
"contents" in data;
const isLogViewerDataActor = (data: LogViewerData): data is ActorData =>
"actorId" in data;
const isLogViewerDataTask = (data: LogViewerData): data is TaskData =>
"taskId" in data;
export type StateApiLogViewerProps = {
height?: number;
data: LogViewerData;
};
export const StateApiLogViewer = ({
height = 300,
data,
}: StateApiLogViewerProps) => {
if (isLogViewerDataText(data)) {
return <TextLogViewer height={height} contents={data.contents} />;
} else if (isLogViewerDataActor(data)) {
return <ActorLogViewer height={height} {...data} />;
} else if (isLogViewerDataTask(data)) {
return <TaskLogViewer height={height} {...data} />;
} else {
return <FileLogViewer height={height} {...data} />;
}
};
const TextLogViewer = ({
height = 300,
contents,
}: {
height: number;
contents: string;
}) => {
return <LogViewer log={contents} height={height} />;
};
const FileLogViewer = ({
height = 300,
nodeId,
filename,
}: {
height: number;
} & FileData) => {
const apiData = useStateApiLogs({ nodeId, filename }, filename);
return <ApiLogViewer apiData={apiData} height={height} />;
};
const ActorLogViewer = ({
height = 300,
actorId,
suffix,
}: {
height: number;
} & ActorData) => {
const apiData = useStateApiLogs(
{ actorId, suffix },
`actor-log-${actorId}.${suffix}`,
);
return <ApiLogViewer apiData={apiData} height={height} />;
};
const TaskLogViewer = ({
height = 300,
taskId,
suffix,
}: {
height: number;
} & TaskData) => {
const apiData = useStateApiLogs(
{ taskId, suffix },
`task-log-${taskId}.${suffix}`,
);
return <ApiLogViewer apiData={apiData} height={height} />;
};
const ApiLogViewer = ({
apiData: { downloadUrl, log, path, refresh },
height = 300,
}: {
apiData: ReturnType<typeof useStateApiLogs>;
height: number;
}) => {
return typeof log === "string" ? (
<LogViewer
log={log}
path={path}
downloadUrl={downloadUrl !== null ? downloadUrl : undefined}
height={height}
onRefreshClick={refresh}
/>
) : (
<Typography color="error">Failed to load</Typography>
);
};
``` | /content/code_sandbox/python/ray/dashboard/client/src/common/MultiTabLogViewer.tsx | xml | 2016-10-25T19:38:30 | 2024-08-16T19:46:34 | ray | ray-project/ray | 32,670 | 1,639 |
```xml
export interface RegisterPayload {
firstname: string;
email: string;
password: string;
}
``` | /content/code_sandbox/src/app/modules/auth/shared/interfaces/register-payload.interface.ts | xml | 2016-11-22T17:10:18 | 2024-08-14T21:36:59 | angular-example-app | Ismaestro/angular-example-app | 2,150 | 22 |
```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 { NgModule, Type } from '@angular/core';
import {
QrCodeWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/qrcode-widget-settings.component';
import { CommonModule } from '@angular/common';
import { SharedModule } from '@shared/shared.module';
import { SharedHomeComponentsModule } from '@home/components/shared-home-components.module';
import { IWidgetSettingsComponent } from '@shared/models/widget.models';
import {
TimeseriesTableWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/timeseries-table-widget-settings.component';
import {
TimeseriesTableKeySettingsComponent
} from '@home/components/widget/lib/settings/cards/timeseries-table-key-settings.component';
import {
TimeseriesTableLatestKeySettingsComponent
} from '@home/components/widget/lib/settings/cards/timeseries-table-latest-key-settings.component';
import {
MarkdownWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/markdown-widget-settings.component';
import { LabelWidgetLabelComponent } from '@home/components/widget/lib/settings/cards/label-widget-label.component';
import {
LabelWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/label-widget-settings.component';
import {
SimpleCardWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/simple-card-widget-settings.component';
import {
DashboardStateWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/dashboard-state-widget-settings.component';
import {
EntitiesHierarchyWidgetSettingsComponent
} from '@home/components/widget/lib/settings/entity/entities-hierarchy-widget-settings.component';
import {
HtmlCardWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/html-card-widget-settings.component';
import {
EntitiesTableWidgetSettingsComponent
} from '@home/components/widget/lib/settings/entity/entities-table-widget-settings.component';
import {
EntitiesTableKeySettingsComponent
} from '@home/components/widget/lib/settings/entity/entities-table-key-settings.component';
import {
AlarmsTableWidgetSettingsComponent
} from '@home/components/widget/lib/settings/alarm/alarms-table-widget-settings.component';
import {
AlarmsTableKeySettingsComponent
} from '@home/components/widget/lib/settings/alarm/alarms-table-key-settings.component';
import {
AnalogueRadialGaugeWidgetSettingsComponent
} from '@home/components/widget/lib/settings/gauge/analogue-radial-gauge-widget-settings.component';
import {
AnalogueLinearGaugeWidgetSettingsComponent
} from '@home/components/widget/lib/settings/gauge/analogue-linear-gauge-widget-settings.component';
import {
AnalogueCompassWidgetSettingsComponent
} from '@home/components/widget/lib/settings/gauge/analogue-compass-widget-settings.component';
import {
DigitalGaugeWidgetSettingsComponent
} from '@home/components/widget/lib/settings/gauge/digital-gauge-widget-settings.component';
import { TickValueComponent } from '@home/components/widget/lib/settings/gauge/tick-value.component';
import { FlotWidgetSettingsComponent } from '@home/components/widget/lib/settings/chart/flot-widget-settings.component';
import {
FlotLineWidgetSettingsComponent
} from '@home/components/widget/lib/settings/chart/flot-line-widget-settings.component';
import { LabelDataKeyComponent } from '@home/components/widget/lib/settings/chart/label-data-key.component';
import {
FlotBarWidgetSettingsComponent
} from '@home/components/widget/lib/settings/chart/flot-bar-widget-settings.component';
import { FlotThresholdComponent } from '@home/components/widget/lib/settings/chart/flot-threshold.component';
import { FlotKeySettingsComponent } from '@home/components/widget/lib/settings/chart/flot-key-settings.component';
import {
FlotLineKeySettingsComponent
} from '@home/components/widget/lib/settings/chart/flot-line-key-settings.component';
import {
FlotBarKeySettingsComponent
} from '@home/components/widget/lib/settings/chart/flot-bar-key-settings.component';
import {
FlotLatestKeySettingsComponent
} from '@home/components/widget/lib/settings/chart/flot-latest-key-settings.component';
import {
FlotPieWidgetSettingsComponent
} from '@home/components/widget/lib/settings/chart/flot-pie-widget-settings.component';
import {
FlotPieKeySettingsComponent
} from '@home/components/widget/lib/settings/chart/flot-pie-key-settings.component';
import {
ChartWidgetSettingsComponent
} from '@home/components/widget/lib/settings/chart/chart-widget-settings.component';
import {
DoughnutChartWidgetSettingsComponent
} from '@home/components/widget/lib/settings/chart/doughnut-chart-widget-settings.component';
import { SwitchRpcSettingsComponent } from '@home/components/widget/lib/settings/control/switch-rpc-settings.component';
import {
RoundSwitchWidgetSettingsComponent
} from '@home/components/widget/lib/settings/control/round-switch-widget-settings.component';
import {
SwitchControlWidgetSettingsComponent
} from '@home/components/widget/lib/settings/control/switch-control-widget-settings.component';
import {
SlideToggleWidgetSettingsComponent
} from '@home/components/widget/lib/settings/control/slide-toggle-widget-settings.component';
import {
PersistentTableWidgetSettingsComponent
} from '@home/components/widget/lib/settings/control/persistent-table-widget-settings.component';
import { RpcButtonStyleComponent } from '@home/components/widget/lib/settings/control/rpc-button-style.component';
import {
UpdateDeviceAttributeWidgetSettingsComponent
} from '@home/components/widget/lib/settings/control/update-device-attribute-widget-settings.component';
import {
SendRpcWidgetSettingsComponent
} from '@home/components/widget/lib/settings/control/send-rpc-widget-settings.component';
import {
LedIndicatorWidgetSettingsComponent
} from '@home/components/widget/lib/settings/control/led-indicator-widget-settings.component';
import {
KnobControlWidgetSettingsComponent
} from '@home/components/widget/lib/settings/control/knob-control-widget-settings.component';
import {
RpcTerminalWidgetSettingsComponent
} from '@home/components/widget/lib/settings/control/rpc-terminal-widget-settings.component';
import {
RpcShellWidgetSettingsComponent
} from '@home/components/widget/lib/settings/control/rpc-shell-widget-settings.component';
import {
DateRangeNavigatorWidgetSettingsComponent
} from '@home/components/widget/lib/settings/date/date-range-navigator-widget-settings.component';
import {
EdgeQuickOverviewWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/edge-quick-overview-widget-settings.component';
import {
GatewayConfigWidgetSettingsComponent
} from '@home/components/widget/lib/settings/gateway/gateway-config-widget-settings.component';
import {
GatewayConfigSingleDeviceWidgetSettingsComponent
} from '@home/components/widget/lib/settings/gateway/gateway-config-single-device-widget-settings.component';
import {
GatewayEventsWidgetSettingsComponent
} from '@home/components/widget/lib/settings/gateway/gateway-events-widget-settings.component';
import { GpioItemComponent } from '@home/components/widget/lib/settings/gpio/gpio-item.component';
import {
GpioControlWidgetSettingsComponent
} from '@home/components/widget/lib/settings/gpio/gpio-control-widget-settings.component';
import {
GpioPanelWidgetSettingsComponent
} from '@home/components/widget/lib/settings/gpio/gpio-panel-widget-settings.component';
import {
NavigationCardWidgetSettingsComponent
} from '@home/components/widget/lib/settings/navigation/navigation-card-widget-settings.component';
import {
NavigationCardsWidgetSettingsComponent
} from '@home/components/widget/lib/settings/navigation/navigation-cards-widget-settings.component';
import {
DeviceClaimingWidgetSettingsComponent
} from '@home/components/widget/lib/settings/input/device-claiming-widget-settings.component';
import {
UpdateAttributeGeneralSettingsComponent
} from '@home/components/widget/lib/settings/input/update-attribute-general-settings.component';
import {
UpdateIntegerAttributeWidgetSettingsComponent
} from '@home/components/widget/lib/settings/input/update-integer-attribute-widget-settings.component';
import {
UpdateDoubleAttributeWidgetSettingsComponent
} from '@home/components/widget/lib/settings/input/update-double-attribute-widget-settings.component';
import {
UpdateStringAttributeWidgetSettingsComponent
} from '@home/components/widget/lib/settings/input/update-string-attribute-widget-settings.component';
import {
UpdateBooleanAttributeWidgetSettingsComponent
} from '@home/components/widget/lib/settings/input/update-boolean-attribute-widget-settings.component';
import {
UpdateImageAttributeWidgetSettingsComponent
} from '@home/components/widget/lib/settings/input/update-image-attribute-widget-settings.component';
import {
UpdateDateAttributeWidgetSettingsComponent
} from '@home/components/widget/lib/settings/input/update-date-attribute-widget-settings.component';
import {
UpdateLocationAttributeWidgetSettingsComponent
} from '@home/components/widget/lib/settings/input/update-location-attribute-widget-settings.component';
import {
UpdateJsonAttributeWidgetSettingsComponent
} from '@home/components/widget/lib/settings/input/update-json-attribute-widget-settings.component';
import {
PhotoCameraInputWidgetSettingsComponent
} from '@home/components/widget/lib/settings/input/photo-camera-input-widget-settings.component';
import {
UpdateMultipleAttributesWidgetSettingsComponent
} from '@home/components/widget/lib/settings/input/update-multiple-attributes-widget-settings.component';
import {
DataKeySelectOptionComponent
} from '@home/components/widget/lib/settings/input/datakey-select-option.component';
import {
UpdateMultipleAttributesKeySettingsComponent
} from '@home/components/widget/lib/settings/input/update-multiple-attributes-key-settings.component';
import {
OpenStreetMapProviderSettingsComponent
} from '@home/components/widget/lib/settings/map/openstreet-map-provider-settings.component';
import { MapProviderSettingsComponent } from '@home/components/widget/lib/settings/map/map-provider-settings.component';
import { MapSettingsComponent } from '@home/components/widget/lib/settings/map/map-settings.component';
import { MapWidgetSettingsComponent } from '@home/components/widget/lib/settings/map/map-widget-settings.component';
import {
GoogleMapProviderSettingsComponent
} from '@home/components/widget/lib/settings/map/google-map-provider-settings.component';
import {
HereMapProviderSettingsComponent
} from '@home/components/widget/lib/settings/map/here-map-provider-settings.component';
import {
TencentMapProviderSettingsComponent
} from '@home/components/widget/lib/settings/map/tencent-map-provider-settings.component';
import {
ImageMapProviderSettingsComponent
} from '@home/components/widget/lib/settings/map/image-map-provider-settings.component';
import {
DatasourcesKeyAutocompleteComponent
} from '@home/components/widget/lib/settings/map/datasources-key-autocomplete.component';
import { CommonMapSettingsComponent } from '@home/components/widget/lib/settings/map/common-map-settings.component';
import { MarkersSettingsComponent } from '@home/components/widget/lib/settings/map/markers-settings.component';
import { PolygonSettingsComponent } from '@home/components/widget/lib/settings/map/polygon-settings.component';
import { CircleSettingsComponent } from '@home/components/widget/lib/settings/map/circle-settings.component';
import {
MarkerClusteringSettingsComponent
} from '@home/components/widget/lib/settings/map/marker-clustering-settings.component';
import { MapEditorSettingsComponent } from '@home/components/widget/lib/settings/map/map-editor-settings.component';
import { RouteMapSettingsComponent } from '@home/components/widget/lib/settings/map/route-map-settings.component';
import {
RouteMapWidgetSettingsComponent
} from '@home/components/widget/lib/settings/map/route-map-widget-settings.component';
import {
TripAnimationWidgetSettingsComponent
} from '@home/components/widget/lib/settings/map/trip-animation-widget-settings.component';
import {
TripAnimationCommonSettingsComponent
} from '@home/components/widget/lib/settings/map/trip-animation-common-settings.component';
import {
TripAnimationMarkerSettingsComponent
} from '@home/components/widget/lib/settings/map/trip-animation-marker-settings.component';
import {
TripAnimationPathSettingsComponent
} from '@home/components/widget/lib/settings/map/trip-animation-path-settings.component';
import {
TripAnimationPointSettingsComponent
} from '@home/components/widget/lib/settings/map/trip-animation-point-settings.component';
import {
GatewayLogsSettingsComponent
} from '@home/components/widget/lib/settings/gateway/gateway-logs-settings.component';
import {
GatewayServiceRPCSettingsComponent
} from '@home/components/widget/lib/settings/gateway/gateway-service-rpc-settings.component';
import {
DocLinksWidgetSettingsComponent
} from '@home/components/widget/lib/settings/home-page/doc-links-widget-settings.component';
import {
QuickLinksWidgetSettingsComponent
} from '@home/components/widget/lib/settings/home-page/quick-links-widget-settings.component';
import {
ValueCardWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/value-card-widget-settings.component';
import { WidgetSettingsCommonModule } from '@home/components/widget/lib/settings/common/widget-settings-common.module';
import {
AggregatedValueCardKeySettingsComponent
} from '@home/components/widget/lib/settings/cards/aggregated-value-card-key-settings.component';
import {
AggregatedValueCardWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/aggregated-value-card-widget-settings.component';
import {
AlarmCountWidgetSettingsComponent
} from '@home/components/widget/lib/settings/alarm/alarm-count-widget-settings.component';
import {
EntityCountWidgetSettingsComponent
} from '@home/components/widget/lib/settings/entity/entity-count-widget-settings.component';
import {
BatteryLevelWidgetSettingsComponent
} from '@home/components/widget/lib/settings/indicator/battery-level-widget-settings.component';
import {
WindSpeedDirectionWidgetSettingsComponent
} from '@home/components/widget/lib/settings/weather/wind-speed-direction-widget-settings.component';
import {
SignalStrengthWidgetSettingsComponent
} from '@home/components/widget/lib/settings/indicator/signal-strength-widget-settings.component';
import {
ValueChartCardWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/value-chart-card-widget-settings.component';
import {
ProgressBarWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/progress-bar-widget-settings.component';
import {
LiquidLevelCardWidgetSettingsComponent
} from '@home/components/widget/lib/settings/indicator/liquid-level-card-widget-settings.component';
import {
DoughnutWidgetSettingsComponent
} from '@home/components/widget/lib/settings/chart/doughnut-widget-settings.component';
import {
RangeChartWidgetSettingsComponent
} from '@home/components/widget/lib/settings/chart/range-chart-widget-settings.component';
import {
BarChartWithLabelsWidgetSettingsComponent
} from '@home/components/widget/lib/settings/chart/bar-chart-with-labels-widget-settings.component';
import {
SingleSwitchWidgetSettingsComponent
} from '@home/components/widget/lib/settings/control/single-switch-widget-settings.component';
import {
ActionButtonWidgetSettingsComponent
} from '@home/components/widget/lib/settings/button/action-button-widget-settings.component';
import {
CommandButtonWidgetSettingsComponent
} from '@home/components/widget/lib/settings/button/command-button-widget-settings.component';
import {
PowerButtonWidgetSettingsComponent
} from '@home/components/widget/lib/settings/button/power-button-widget-settings.component';
import {
SliderWidgetSettingsComponent
} from '@home/components/widget/lib/settings/control/slider-widget-settings.component';
import {
ToggleButtonWidgetSettingsComponent
} from '@home/components/widget/lib/settings/button/toggle-button-widget-settings.component';
import {
TimeSeriesChartKeySettingsComponent
} from '@home/components/widget/lib/settings/chart/time-series-chart-key-settings.component';
import {
TimeSeriesChartLineSettingsComponent
} from '@home/components/widget/lib/settings/chart/time-series-chart-line-settings.component';
import {
TimeSeriesChartWidgetSettingsComponent
} from '@home/components/widget/lib/settings/chart/time-series-chart-widget-settings.component';
import {
StatusWidgetSettingsComponent
} from '@home/components/widget/lib/settings/indicator/status-widget-settings.component';
import {
PieChartWidgetSettingsComponent
} from '@home/components/widget/lib/settings/chart/pie-chart-widget-settings.component';
import {
BarChartWidgetSettingsComponent
} from '@home/components/widget/lib/settings/chart/bar-chart-widget-settings.component';
import {
PolarAreaChartWidgetSettingsComponent
} from '@home/components/widget/lib/settings/chart/polar-area-chart-widget-settings.component';
import {
RadarChartWidgetSettingsComponent
} from '@home/components/widget/lib/settings/chart/radar-chart-widget-settings.component';
import {
MobileAppQrCodeWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/mobile-app-qr-code-widget-settings.component';
import {
LabelCardWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/label-card-widget-settings.component';
import {
LabelValueCardWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/label-value-card-widget-settings.component';
import {
UnreadNotificationWidgetSettingsComponent
} from '@home/components/widget/lib/settings/cards/unread-notification-widget-settings.component';
import {
ScadaSymbolWidgetSettingsComponent
} from '@home/components/widget/lib/settings/scada/scada-symbol-widget-settings.component';
@NgModule({
declarations: [
QrCodeWidgetSettingsComponent,
MobileAppQrCodeWidgetSettingsComponent,
TimeseriesTableWidgetSettingsComponent,
TimeseriesTableKeySettingsComponent,
TimeseriesTableLatestKeySettingsComponent,
MarkdownWidgetSettingsComponent,
LabelWidgetLabelComponent,
LabelWidgetSettingsComponent,
SimpleCardWidgetSettingsComponent,
DashboardStateWidgetSettingsComponent,
EntitiesHierarchyWidgetSettingsComponent,
HtmlCardWidgetSettingsComponent,
EntitiesTableWidgetSettingsComponent,
EntitiesTableKeySettingsComponent,
AlarmsTableWidgetSettingsComponent,
AlarmsTableKeySettingsComponent,
AnalogueRadialGaugeWidgetSettingsComponent,
AnalogueLinearGaugeWidgetSettingsComponent,
AnalogueCompassWidgetSettingsComponent,
DigitalGaugeWidgetSettingsComponent,
TickValueComponent,
FlotWidgetSettingsComponent,
LabelDataKeyComponent,
FlotLineWidgetSettingsComponent,
FlotBarWidgetSettingsComponent,
FlotThresholdComponent,
FlotKeySettingsComponent,
FlotLineKeySettingsComponent,
FlotBarKeySettingsComponent,
FlotLatestKeySettingsComponent,
FlotPieWidgetSettingsComponent,
FlotPieKeySettingsComponent,
ChartWidgetSettingsComponent,
DoughnutChartWidgetSettingsComponent,
SwitchRpcSettingsComponent,
RoundSwitchWidgetSettingsComponent,
SwitchControlWidgetSettingsComponent,
SlideToggleWidgetSettingsComponent,
PersistentTableWidgetSettingsComponent,
RpcButtonStyleComponent,
UpdateDeviceAttributeWidgetSettingsComponent,
SendRpcWidgetSettingsComponent,
LedIndicatorWidgetSettingsComponent,
KnobControlWidgetSettingsComponent,
RpcTerminalWidgetSettingsComponent,
RpcShellWidgetSettingsComponent,
DateRangeNavigatorWidgetSettingsComponent,
EdgeQuickOverviewWidgetSettingsComponent,
GatewayConfigWidgetSettingsComponent,
GatewayConfigSingleDeviceWidgetSettingsComponent,
GatewayEventsWidgetSettingsComponent,
GpioItemComponent,
GpioControlWidgetSettingsComponent,
GpioPanelWidgetSettingsComponent,
NavigationCardWidgetSettingsComponent,
NavigationCardsWidgetSettingsComponent,
DeviceClaimingWidgetSettingsComponent,
UpdateAttributeGeneralSettingsComponent,
UpdateIntegerAttributeWidgetSettingsComponent,
UpdateDoubleAttributeWidgetSettingsComponent,
UpdateStringAttributeWidgetSettingsComponent,
UpdateBooleanAttributeWidgetSettingsComponent,
UpdateImageAttributeWidgetSettingsComponent,
UpdateDateAttributeWidgetSettingsComponent,
UpdateLocationAttributeWidgetSettingsComponent,
UpdateJsonAttributeWidgetSettingsComponent,
PhotoCameraInputWidgetSettingsComponent,
UpdateMultipleAttributesWidgetSettingsComponent,
DataKeySelectOptionComponent,
UpdateMultipleAttributesKeySettingsComponent,
GoogleMapProviderSettingsComponent,
OpenStreetMapProviderSettingsComponent,
HereMapProviderSettingsComponent,
ImageMapProviderSettingsComponent,
TencentMapProviderSettingsComponent,
MapProviderSettingsComponent,
DatasourcesKeyAutocompleteComponent,
CommonMapSettingsComponent,
MarkersSettingsComponent,
PolygonSettingsComponent,
CircleSettingsComponent,
MarkerClusteringSettingsComponent,
MapEditorSettingsComponent,
RouteMapSettingsComponent,
MapSettingsComponent,
TripAnimationCommonSettingsComponent,
TripAnimationMarkerSettingsComponent,
TripAnimationPathSettingsComponent,
TripAnimationPointSettingsComponent,
MapWidgetSettingsComponent,
RouteMapWidgetSettingsComponent,
GatewayLogsSettingsComponent,
GatewayServiceRPCSettingsComponent,
TripAnimationWidgetSettingsComponent,
DocLinksWidgetSettingsComponent,
QuickLinksWidgetSettingsComponent,
ValueCardWidgetSettingsComponent,
AggregatedValueCardKeySettingsComponent,
AggregatedValueCardWidgetSettingsComponent,
AlarmCountWidgetSettingsComponent,
EntityCountWidgetSettingsComponent,
BatteryLevelWidgetSettingsComponent,
WindSpeedDirectionWidgetSettingsComponent,
SignalStrengthWidgetSettingsComponent,
ValueChartCardWidgetSettingsComponent,
ProgressBarWidgetSettingsComponent,
LiquidLevelCardWidgetSettingsComponent,
DoughnutWidgetSettingsComponent,
RangeChartWidgetSettingsComponent,
BarChartWithLabelsWidgetSettingsComponent,
SingleSwitchWidgetSettingsComponent,
ActionButtonWidgetSettingsComponent,
CommandButtonWidgetSettingsComponent,
PowerButtonWidgetSettingsComponent,
SliderWidgetSettingsComponent,
ToggleButtonWidgetSettingsComponent,
TimeSeriesChartKeySettingsComponent,
TimeSeriesChartLineSettingsComponent,
TimeSeriesChartWidgetSettingsComponent,
StatusWidgetSettingsComponent,
PieChartWidgetSettingsComponent,
BarChartWidgetSettingsComponent,
PolarAreaChartWidgetSettingsComponent,
RadarChartWidgetSettingsComponent,
LabelCardWidgetSettingsComponent,
LabelValueCardWidgetSettingsComponent,
UnreadNotificationWidgetSettingsComponent,
ScadaSymbolWidgetSettingsComponent
],
imports: [
CommonModule,
SharedModule,
SharedHomeComponentsModule,
WidgetSettingsCommonModule
],
exports: [
QrCodeWidgetSettingsComponent,
MobileAppQrCodeWidgetSettingsComponent,
TimeseriesTableWidgetSettingsComponent,
TimeseriesTableKeySettingsComponent,
TimeseriesTableLatestKeySettingsComponent,
MarkdownWidgetSettingsComponent,
LabelWidgetLabelComponent,
LabelWidgetSettingsComponent,
SimpleCardWidgetSettingsComponent,
DashboardStateWidgetSettingsComponent,
EntitiesHierarchyWidgetSettingsComponent,
HtmlCardWidgetSettingsComponent,
EntitiesTableWidgetSettingsComponent,
EntitiesTableKeySettingsComponent,
AlarmsTableWidgetSettingsComponent,
AlarmsTableKeySettingsComponent,
AnalogueRadialGaugeWidgetSettingsComponent,
AnalogueLinearGaugeWidgetSettingsComponent,
AnalogueCompassWidgetSettingsComponent,
DigitalGaugeWidgetSettingsComponent,
TickValueComponent,
FlotWidgetSettingsComponent,
LabelDataKeyComponent,
FlotLineWidgetSettingsComponent,
FlotBarWidgetSettingsComponent,
FlotThresholdComponent,
FlotKeySettingsComponent,
FlotLineKeySettingsComponent,
FlotBarKeySettingsComponent,
FlotLatestKeySettingsComponent,
FlotPieWidgetSettingsComponent,
FlotPieKeySettingsComponent,
ChartWidgetSettingsComponent,
DoughnutChartWidgetSettingsComponent,
SwitchRpcSettingsComponent,
RoundSwitchWidgetSettingsComponent,
SwitchControlWidgetSettingsComponent,
SlideToggleWidgetSettingsComponent,
PersistentTableWidgetSettingsComponent,
RpcButtonStyleComponent,
UpdateDeviceAttributeWidgetSettingsComponent,
SendRpcWidgetSettingsComponent,
LedIndicatorWidgetSettingsComponent,
KnobControlWidgetSettingsComponent,
RpcTerminalWidgetSettingsComponent,
RpcShellWidgetSettingsComponent,
DateRangeNavigatorWidgetSettingsComponent,
EdgeQuickOverviewWidgetSettingsComponent,
GatewayConfigWidgetSettingsComponent,
GatewayConfigSingleDeviceWidgetSettingsComponent,
GatewayEventsWidgetSettingsComponent,
GpioItemComponent,
GpioControlWidgetSettingsComponent,
GpioPanelWidgetSettingsComponent,
NavigationCardWidgetSettingsComponent,
NavigationCardsWidgetSettingsComponent,
DeviceClaimingWidgetSettingsComponent,
UpdateAttributeGeneralSettingsComponent,
UpdateIntegerAttributeWidgetSettingsComponent,
UpdateDoubleAttributeWidgetSettingsComponent,
UpdateStringAttributeWidgetSettingsComponent,
UpdateBooleanAttributeWidgetSettingsComponent,
UpdateImageAttributeWidgetSettingsComponent,
UpdateDateAttributeWidgetSettingsComponent,
UpdateLocationAttributeWidgetSettingsComponent,
UpdateJsonAttributeWidgetSettingsComponent,
PhotoCameraInputWidgetSettingsComponent,
UpdateMultipleAttributesWidgetSettingsComponent,
DataKeySelectOptionComponent,
UpdateMultipleAttributesKeySettingsComponent,
GoogleMapProviderSettingsComponent,
OpenStreetMapProviderSettingsComponent,
HereMapProviderSettingsComponent,
ImageMapProviderSettingsComponent,
TencentMapProviderSettingsComponent,
MapProviderSettingsComponent,
DatasourcesKeyAutocompleteComponent,
CommonMapSettingsComponent,
MarkersSettingsComponent,
PolygonSettingsComponent,
CircleSettingsComponent,
MarkerClusteringSettingsComponent,
MapEditorSettingsComponent,
RouteMapSettingsComponent,
MapSettingsComponent,
TripAnimationCommonSettingsComponent,
TripAnimationMarkerSettingsComponent,
TripAnimationPathSettingsComponent,
TripAnimationPointSettingsComponent,
MapWidgetSettingsComponent,
RouteMapWidgetSettingsComponent,
GatewayLogsSettingsComponent,
GatewayServiceRPCSettingsComponent,
TripAnimationWidgetSettingsComponent,
DocLinksWidgetSettingsComponent,
QuickLinksWidgetSettingsComponent,
ValueCardWidgetSettingsComponent,
AggregatedValueCardKeySettingsComponent,
AggregatedValueCardWidgetSettingsComponent,
AlarmCountWidgetSettingsComponent,
EntityCountWidgetSettingsComponent,
BatteryLevelWidgetSettingsComponent,
WindSpeedDirectionWidgetSettingsComponent,
SignalStrengthWidgetSettingsComponent,
ValueChartCardWidgetSettingsComponent,
ProgressBarWidgetSettingsComponent,
LiquidLevelCardWidgetSettingsComponent,
DoughnutWidgetSettingsComponent,
RangeChartWidgetSettingsComponent,
BarChartWithLabelsWidgetSettingsComponent,
SingleSwitchWidgetSettingsComponent,
ActionButtonWidgetSettingsComponent,
CommandButtonWidgetSettingsComponent,
PowerButtonWidgetSettingsComponent,
SliderWidgetSettingsComponent,
ToggleButtonWidgetSettingsComponent,
TimeSeriesChartKeySettingsComponent,
TimeSeriesChartLineSettingsComponent,
TimeSeriesChartWidgetSettingsComponent,
StatusWidgetSettingsComponent,
PieChartWidgetSettingsComponent,
BarChartWidgetSettingsComponent,
PolarAreaChartWidgetSettingsComponent,
RadarChartWidgetSettingsComponent,
LabelCardWidgetSettingsComponent,
LabelValueCardWidgetSettingsComponent,
UnreadNotificationWidgetSettingsComponent,
ScadaSymbolWidgetSettingsComponent
]
})
export class WidgetSettingsModule {
}
export const widgetSettingsComponentsMap: {[key: string]: Type<IWidgetSettingsComponent>} = {
'tb-qrcode-widget-settings': QrCodeWidgetSettingsComponent,
'tb-mobile-app-qr-code-widget-settings': MobileAppQrCodeWidgetSettingsComponent,
'tb-timeseries-table-widget-settings': TimeseriesTableWidgetSettingsComponent,
'tb-timeseries-table-key-settings': TimeseriesTableKeySettingsComponent,
'tb-timeseries-table-latest-key-settings': TimeseriesTableLatestKeySettingsComponent,
'tb-markdown-widget-settings': MarkdownWidgetSettingsComponent,
'tb-label-widget-settings': LabelWidgetSettingsComponent,
'tb-simple-card-widget-settings': SimpleCardWidgetSettingsComponent,
'tb-dashboard-state-widget-settings': DashboardStateWidgetSettingsComponent,
'tb-entities-hierarchy-widget-settings': EntitiesHierarchyWidgetSettingsComponent,
'tb-html-card-widget-settings': HtmlCardWidgetSettingsComponent,
'tb-entities-table-widget-settings': EntitiesTableWidgetSettingsComponent,
'tb-entities-table-key-settings': EntitiesTableKeySettingsComponent,
'tb-alarms-table-widget-settings': AlarmsTableWidgetSettingsComponent,
'tb-alarms-table-key-settings': AlarmsTableKeySettingsComponent,
'tb-analogue-radial-gauge-widget-settings': AnalogueRadialGaugeWidgetSettingsComponent,
'tb-analogue-linear-gauge-widget-settings': AnalogueLinearGaugeWidgetSettingsComponent,
'tb-analogue-compass-widget-settings': AnalogueCompassWidgetSettingsComponent,
'tb-digital-gauge-widget-settings': DigitalGaugeWidgetSettingsComponent,
'tb-flot-line-widget-settings': FlotLineWidgetSettingsComponent,
'tb-flot-bar-widget-settings': FlotBarWidgetSettingsComponent,
'tb-flot-line-key-settings': FlotLineKeySettingsComponent,
'tb-flot-bar-key-settings': FlotBarKeySettingsComponent,
'tb-flot-latest-key-settings': FlotLatestKeySettingsComponent,
'tb-flot-pie-widget-settings': FlotPieWidgetSettingsComponent,
'tb-flot-pie-key-settings': FlotPieKeySettingsComponent,
'tb-chart-widget-settings': ChartWidgetSettingsComponent,
'tb-doughnut-chart-widget-settings': DoughnutChartWidgetSettingsComponent,
'tb-round-switch-widget-settings': RoundSwitchWidgetSettingsComponent,
'tb-switch-control-widget-settings': SwitchControlWidgetSettingsComponent,
'tb-slide-toggle-widget-settings': SlideToggleWidgetSettingsComponent,
'tb-persistent-table-widget-settings': PersistentTableWidgetSettingsComponent,
'tb-update-device-attribute-widget-settings': UpdateDeviceAttributeWidgetSettingsComponent,
'tb-send-rpc-widget-settings': SendRpcWidgetSettingsComponent,
'tb-led-indicator-widget-settings': LedIndicatorWidgetSettingsComponent,
'tb-knob-control-widget-settings': KnobControlWidgetSettingsComponent,
'tb-rpc-terminal-widget-settings': RpcTerminalWidgetSettingsComponent,
'tb-rpc-shell-widget-settings': RpcShellWidgetSettingsComponent,
'tb-date-range-navigator-widget-settings': DateRangeNavigatorWidgetSettingsComponent,
'tb-edge-quick-overview-widget-settings': EdgeQuickOverviewWidgetSettingsComponent,
'tb-gateway-config-widget-settings': GatewayConfigWidgetSettingsComponent,
'tb-gateway-config-single-device-widget-settings': GatewayConfigSingleDeviceWidgetSettingsComponent,
'tb-gateway-events-widget-settings': GatewayEventsWidgetSettingsComponent,
'tb-gpio-control-widget-settings': GpioControlWidgetSettingsComponent,
'tb-gpio-panel-widget-settings': GpioPanelWidgetSettingsComponent,
'tb-navigation-card-widget-settings': NavigationCardWidgetSettingsComponent,
'tb-navigation-cards-widget-settings': NavigationCardsWidgetSettingsComponent,
'tb-device-claiming-widget-settings': DeviceClaimingWidgetSettingsComponent,
'tb-update-integer-attribute-widget-settings': UpdateIntegerAttributeWidgetSettingsComponent,
'tb-update-double-attribute-widget-settings': UpdateDoubleAttributeWidgetSettingsComponent,
'tb-update-string-attribute-widget-settings': UpdateStringAttributeWidgetSettingsComponent,
'tb-update-boolean-attribute-widget-settings': UpdateBooleanAttributeWidgetSettingsComponent,
'tb-update-image-attribute-widget-settings': UpdateImageAttributeWidgetSettingsComponent,
'tb-update-date-attribute-widget-settings': UpdateDateAttributeWidgetSettingsComponent,
'tb-update-location-attribute-widget-settings': UpdateLocationAttributeWidgetSettingsComponent,
'tb-update-json-attribute-widget-settings': UpdateJsonAttributeWidgetSettingsComponent,
'tb-photo-camera-input-widget-settings': PhotoCameraInputWidgetSettingsComponent,
'tb-update-multiple-attributes-widget-settings': UpdateMultipleAttributesWidgetSettingsComponent,
'tb-update-multiple-attributes-key-settings': UpdateMultipleAttributesKeySettingsComponent,
'tb-map-widget-settings': MapWidgetSettingsComponent,
'tb-route-map-widget-settings': RouteMapWidgetSettingsComponent,
'tb-trip-animation-widget-settings': TripAnimationWidgetSettingsComponent,
'tb-gateway-logs-settings': GatewayLogsSettingsComponent,
'tb-gateway-service-rpc-settings':GatewayServiceRPCSettingsComponent,
'tb-doc-links-widget-settings': DocLinksWidgetSettingsComponent,
'tb-quick-links-widget-settings': QuickLinksWidgetSettingsComponent,
'tb-value-card-widget-settings': ValueCardWidgetSettingsComponent,
'tb-aggregated-value-card-key-settings': AggregatedValueCardKeySettingsComponent,
'tb-aggregated-value-card-widget-settings': AggregatedValueCardWidgetSettingsComponent,
'tb-alarm-count-widget-settings': AlarmCountWidgetSettingsComponent,
'tb-entity-count-widget-settings': EntityCountWidgetSettingsComponent,
'tb-battery-level-widget-settings': BatteryLevelWidgetSettingsComponent,
'tb-wind-speed-direction-widget-settings': WindSpeedDirectionWidgetSettingsComponent,
'tb-signal-strength-widget-settings': SignalStrengthWidgetSettingsComponent,
'tb-value-chart-card-widget-settings': ValueChartCardWidgetSettingsComponent,
'tb-progress-bar-widget-settings': ProgressBarWidgetSettingsComponent,
'tb-liquid-level-card-widget-settings': LiquidLevelCardWidgetSettingsComponent,
'tb-doughnut-widget-settings': DoughnutWidgetSettingsComponent,
'tb-range-chart-widget-settings': RangeChartWidgetSettingsComponent,
'tb-bar-chart-with-labels-widget-settings': BarChartWithLabelsWidgetSettingsComponent,
'tb-single-switch-widget-settings': SingleSwitchWidgetSettingsComponent,
'tb-action-button-widget-settings': ActionButtonWidgetSettingsComponent,
'tb-command-button-widget-settings': CommandButtonWidgetSettingsComponent,
'tb-power-button-widget-settings': PowerButtonWidgetSettingsComponent,
'tb-slider-widget-settings': SliderWidgetSettingsComponent,
'tb-toggle-button-widget-settings': ToggleButtonWidgetSettingsComponent,
'tb-time-series-chart-key-settings': TimeSeriesChartKeySettingsComponent,
'tb-time-series-chart-widget-settings': TimeSeriesChartWidgetSettingsComponent,
'tb-status-widget-settings': StatusWidgetSettingsComponent,
'tb-pie-chart-widget-settings': PieChartWidgetSettingsComponent,
'tb-bar-chart-widget-settings': BarChartWidgetSettingsComponent,
'tb-polar-area-chart-widget-settings': PolarAreaChartWidgetSettingsComponent,
'tb-radar-chart-widget-settings': RadarChartWidgetSettingsComponent,
'tb-label-card-widget-settings': LabelCardWidgetSettingsComponent,
'tb-label-value-card-widget-settings': LabelValueCardWidgetSettingsComponent,
'tb-unread-notification-widget-settings': UnreadNotificationWidgetSettingsComponent,
'tb-scada-symbol-widget-settings': ScadaSymbolWidgetSettingsComponent
};
``` | /content/code_sandbox/ui-ngx/src/app/modules/home/components/widget/lib/settings/widget-settings.module.ts | xml | 2016-12-01T09:33:30 | 2024-08-16T19:58:25 | thingsboard | thingsboard/thingsboard | 16,820 | 6,811 |
```xml
import type { ReactNode } from 'react';
export interface SliderMarks {
[key: number]: ReactNode;
}
export default interface BaseSliderProps {
value?: number;
defaultValue?: number;
step?: number;
min?: number;
max?: number;
disabled?: boolean;
vertical?: boolean;
showMark?: boolean;
marks?: SliderMarks;
onSlideChange?: (value: number) => void;
onChange?: (value: number) => void;
}
``` | /content/code_sandbox/packages/zarm/src/slider/interface.ts | xml | 2016-07-13T11:45:37 | 2024-08-12T19:23:48 | zarm | ZhongAnTech/zarm | 1,707 | 105 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="path_to_url"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:focusable="true"
android:orientation="vertical">
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@color/colorYellow"
android:gravity="center"
android:text="1"
android:textColor="@android:color/white"
android:textSize="40dp"/>
</LinearLayout>
``` | /content/code_sandbox/sample/src/main/res/layout/layout_custom_view.xml | xml | 2016-09-13T08:26:29 | 2024-08-15T09:49:27 | XBanner | xiaohaibin/XBanner | 2,159 | 140 |
```xml
// *** WARNING: this file was generated by test. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
import * as runtime from "@pulumi/pulumi/runtime";
import * as pulumi from "@pulumi/pulumi";
export function getEnv(...vars: string[]): string | undefined {
for (const v of vars) {
const value = process.env[v];
if (value) {
return value;
}
}
return undefined;
}
export function getEnvBoolean(...vars: string[]): boolean | undefined {
const s = getEnv(...vars);
if (s !== undefined) {
// NOTE: these values are taken from path_to_url#L1, which is what
// Terraform uses internally when parsing boolean values.
if (["1", "t", "T", "true", "TRUE", "True"].find(v => v === s) !== undefined) {
return true;
}
if (["0", "f", "F", "false", "FALSE", "False"].find(v => v === s) !== undefined) {
return false;
}
}
return undefined;
}
export function getEnvNumber(...vars: string[]): number | undefined {
const s = getEnv(...vars);
if (s !== undefined) {
const f = parseFloat(s);
if (!isNaN(f)) {
return f;
}
}
return undefined;
}
export function getVersion(): string {
let version = require('./package.json').version;
// Node allows for the version to be prefixed by a "v", while semver doesn't.
// If there is a v, strip it off.
if (version.indexOf('v') === 0) {
version = version.slice(1);
}
return version;
}
/** @internal */
export function resourceOptsDefaults(): any {
return { version: getVersion(), pluginDownloadURL: "example.com/download" };
}
/** @internal */
export function lazyLoad(exports: any, props: string[], loadModule: any) {
for (let property of props) {
Object.defineProperty(exports, property, {
enumerable: true,
get: function() {
return loadModule()[property];
},
});
}
}
export async function callAsync<T>(
tok: string,
props: pulumi.Inputs,
res?: pulumi.Resource,
opts?: {property?: string},
): Promise<T> {
const o: any = runtime.call<T>(tok, props, res);
const value = await o.promise(true /*withUnknowns*/);
const isKnown = await o.isKnown;
const isSecret = await o.isSecret;
const problem: string|undefined =
!isKnown ? "an unknown value"
: isSecret ? "a secret value"
: undefined;
// Ingoring o.resources silently. They are typically non-empty, r.f() calls include r as a dependency.
if (problem) {
throw new Error(`Plain resource method "${tok}" incorrectly returned ${problem}. ` +
"This is an error in the provider, please report this to the provider developer.");
}
// Extract a single property if requested.
if (opts && opts.property) {
return value[opts.property];
}
return value;
}
``` | /content/code_sandbox/tests/testdata/codegen/simple-resource-schema/nodejs/utilities.ts | xml | 2016-10-31T21:02:47 | 2024-08-16T19:47:04 | pulumi | pulumi/pulumi | 20,743 | 700 |
```xml
export const safeResolve = (path: string) => {
try {
return Promise.resolve(require.resolve(path));
} catch (e) {
return Promise.resolve(false as const);
}
};
``` | /content/code_sandbox/code/core/src/builder-manager/utils/safeResolve.ts | xml | 2016-03-18T04:23:44 | 2024-08-16T19:22:08 | storybook | storybookjs/storybook | 83,755 | 42 |
```xml
import { bind } from 'decko';
import * as React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators, Dispatch } from 'redux';
import BulkDeletionManager from 'shared/view/domain/BulkDeletion/WidgetsBulkDeletionComponents/BulkDeletionManager/BulkDeletionManager';
import { ICommunication } from 'shared/utils/redux/communication';
import { IWorkspace } from 'shared/models/Workspace';
import {
selectDatasetIdsForDeleting,
unselectDatasetForDeleting,
deleteDatasets,
selectCommunications,
resetDatasetsForDeleting,
} from 'features/datasets/store';
import { IApplicationState } from 'setup/store/store';
interface ILocalProps {
workspaceName: IWorkspace['name'];
}
interface IPropsFromState {
experimentIdsForDeleting: string[];
deletingDatasets: ICommunication;
}
interface IActionProps {
unselectDatasetForDeleting: typeof unselectDatasetForDeleting;
deleteDatasets: typeof deleteDatasets;
resetDatasetsForDeleting: typeof resetDatasetsForDeleting;
}
type AllProps = ILocalProps & IPropsFromState & IActionProps;
class DeletingDatasetsManager extends React.PureComponent<AllProps> {
public render() {
return (
<BulkDeletionManager
entityName="Dataset"
deleteEntities={this.deleteDatasets}
deletingEntities={this.props.deletingDatasets}
entityIds={this.props.experimentIdsForDeleting}
unselectEntityForDeleting={this.props.unselectDatasetForDeleting}
resetEntities={this.props.resetDatasetsForDeleting}
/>
);
}
@bind
private deleteDatasets(entityIds: string[]) {
this.props.deleteDatasets(entityIds, this.props.workspaceName);
}
}
const mapStateToProps = (state: IApplicationState): IPropsFromState => {
return {
experimentIdsForDeleting: selectDatasetIdsForDeleting(state),
deletingDatasets: selectCommunications(state).deletingDatasets,
};
};
const mapDispatchToProps = (dispatch: Dispatch): IActionProps => {
return bindActionCreators(
{
unselectDatasetForDeleting,
deleteDatasets,
resetDatasetsForDeleting,
},
dispatch
);
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(DeletingDatasetsManager);
``` | /content/code_sandbox/webapp/client/src/pages/authorized/DatasetPages/DeletingDatasetsManager/DeletingDatasetsManager.tsx | xml | 2016-10-19T01:07:26 | 2024-08-14T03:53:55 | modeldb | VertaAI/modeldb | 1,689 | 491 |
```xml
import { useEffect } from 'react'
import { isNextRouterError } from '../../../is-next-router-error'
import { isHydrationError } from '../../../is-hydration-error'
import { attachHydrationErrorState } from './attach-hydration-error-state'
export type ErrorHandler = (error: Error) => void
if (typeof window !== 'undefined') {
try {
// Increase the number of stack frames on the client
Error.stackTraceLimit = 50
} catch {}
}
let hasHydrationError = false
const errorQueue: Array<Error> = []
const rejectionQueue: Array<Error> = []
const errorHandlers: Array<ErrorHandler> = []
const rejectionHandlers: Array<ErrorHandler> = []
export function handleClientError(error: unknown) {
if (!error || !(error instanceof Error) || typeof error.stack !== 'string') {
// A non-error was thrown, we don't have anything to show. :-(
return
}
attachHydrationErrorState(error)
// Only queue one hydration every time
if (isHydrationError(error)) {
if (!hasHydrationError) {
errorQueue.push(error)
}
hasHydrationError = true
}
for (const handler of errorHandlers) {
handler(error)
}
}
if (typeof window !== 'undefined') {
// These event handlers must be added outside of the hook because there is no
// guarantee that the hook will be alive in a mounted component in time to
// when the errors occur.
// uncaught errors go through reportError
window.addEventListener(
'error',
(event: WindowEventMap['error']): void | boolean => {
if (isNextRouterError(event.error)) {
event.preventDefault()
return false
}
handleClientError(event.error)
}
)
window.addEventListener(
'unhandledrejection',
(ev: WindowEventMap['unhandledrejection']): void => {
const reason = ev?.reason
if (
!reason ||
!(reason instanceof Error) ||
typeof reason.stack !== 'string'
) {
// A non-error was thrown, we don't have anything to show. :-(
return
}
const e = reason
rejectionQueue.push(e)
for (const handler of rejectionHandlers) {
handler(e)
}
}
)
}
export function useErrorHandler(
handleOnUnhandledError: ErrorHandler,
handleOnUnhandledRejection: ErrorHandler
) {
useEffect(() => {
// Handle queued errors.
errorQueue.forEach(handleOnUnhandledError)
rejectionQueue.forEach(handleOnUnhandledRejection)
// Listen to new errors.
errorHandlers.push(handleOnUnhandledError)
rejectionHandlers.push(handleOnUnhandledRejection)
return () => {
// Remove listeners.
errorHandlers.splice(errorHandlers.indexOf(handleOnUnhandledError), 1)
rejectionHandlers.splice(
rejectionHandlers.indexOf(handleOnUnhandledRejection),
1
)
}
}, [handleOnUnhandledError, handleOnUnhandledRejection])
}
``` | /content/code_sandbox/packages/next/src/client/components/react-dev-overlay/internal/helpers/use-error-handler.ts | xml | 2016-10-05T23:32:51 | 2024-08-16T19:44:30 | next.js | vercel/next.js | 124,056 | 650 |
```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 React, {useEffect, useRef, useState} from 'react';
import {amplify} from 'amplify';
import cx from 'classnames';
import {WebAppEvents} from '@wireapp/webapp-events';
import {SidebarTabs, useSidebarStore} from 'src/script/page/LeftSidebar/panels/Conversations/useSidebarStore';
import {Conversations} from './panels/Conversations';
import {TemporaryGuestConversations} from './panels/TemporatyGuestConversations';
import {User} from '../../entity/User';
import {ListViewModel} from '../../view_model/ListViewModel';
import {useAppState, ListState} from '../useAppState';
type LeftSidebarProps = {
listViewModel: ListViewModel;
selfUser: User;
isActivatedAccount: boolean;
};
const LeftSidebar: React.FC<LeftSidebarProps> = ({listViewModel, selfUser, isActivatedAccount}) => {
const {conversationRepository, propertiesRepository} = listViewModel;
const repositories = listViewModel.contentViewModel.repositories;
const inputRef = useRef<HTMLInputElement | null>(null);
const [isConversationFilterFocused, setIsConversationFilterFocused] = useState<boolean>(false);
const listState = useAppState(state => state.listState);
const switchList = (list: ListState) => listViewModel.switchList(list);
const {setCurrentTab} = useSidebarStore();
useEffect(() => {
function openCreateGroupModal() {
amplify.publish(WebAppEvents.CONVERSATION.CREATE_GROUP, 'conversation_details');
}
async function jumpToRecentSearch() {
switchList(ListState.CONVERSATIONS);
setCurrentTab(SidebarTabs.RECENT);
setIsConversationFilterFocused(true);
}
amplify.subscribe(WebAppEvents.SHORTCUT.START, openCreateGroupModal);
amplify.subscribe(WebAppEvents.SHORTCUT.SEARCH, jumpToRecentSearch);
return () => {
amplify.unsubscribe(WebAppEvents.SHORTCUT.START, openCreateGroupModal);
amplify.unsubscribe(WebAppEvents.SHORTCUT.SEARCH, jumpToRecentSearch);
};
}, []);
useEffect(() => {
if (isConversationFilterFocused) {
inputRef.current?.focus();
}
}, [inputRef, isConversationFilterFocused]);
return (
<aside id="left-column" className={cx('left-column', {'left-column--light-theme': !isActivatedAccount})}>
{[ListState.CONVERSATIONS, ListState.START_UI, ListState.PREFERENCES, ListState.ARCHIVE].includes(listState) && (
<Conversations
inputRef={inputRef}
isConversationFilterFocused={isConversationFilterFocused}
setIsConversationFilterFocused={setIsConversationFilterFocused}
selfUser={selfUser}
listViewModel={listViewModel}
searchRepository={repositories.search}
teamRepository={repositories.team}
integrationRepository={repositories.integration}
userRepository={repositories.user}
propertiesRepository={propertiesRepository}
conversationRepository={conversationRepository}
preferenceNotificationRepository={repositories.preferenceNotification}
/>
)}
{listState === ListState.TEMPORARY_GUEST && (
<TemporaryGuestConversations
callingViewModel={listViewModel.callingViewModel}
listViewModel={listViewModel}
selfUser={selfUser}
/>
)}
</aside>
);
};
export {LeftSidebar};
``` | /content/code_sandbox/src/script/page/LeftSidebar/LeftSidebar.tsx | xml | 2016-07-21T15:34:05 | 2024-08-16T11:40:13 | wire-webapp | wireapp/wire-webapp | 1,125 | 780 |
```xml
import { default as category } from './categories'
import { default as algorithm } from './algorithmCategories'
import { isStringToBytesConversion, isBytesLengthCheck, getCompilerVersion } from './staticAnalysisCommon'
import { AnalyzerModule, ModuleAlgorithm, ModuleCategory, ReportObj, CompilationResult, MemberAccessAstNode, FunctionCallAstNode, SupportedVersion} from './../../types'
export default class stringBytesLength implements AnalyzerModule {
name: string = `String length: `
description: string = `Bytes length != String length`
category: ModuleCategory = category.MISC
algorithm: ModuleAlgorithm = algorithm.EXACT
version: SupportedVersion = {
start: '0.4.12'
}
stringToBytesConversions: FunctionCallAstNode[] = []
bytesLengthChecks: MemberAccessAstNode[] = []
visit (node: FunctionCallAstNode | MemberAccessAstNode): void {
if (node.nodeType === "FunctionCall" && isStringToBytesConversion(node)) this.stringToBytesConversions.push(node)
else if (node.nodeType === "MemberAccess" && isBytesLengthCheck(node)) this.bytesLengthChecks.push(node)
}
report (compilationResults: CompilationResult): ReportObj[] {
const version = getCompilerVersion(compilationResults.contracts)
if (this.stringToBytesConversions.length > 0 && this.bytesLengthChecks.length > 0) {
return [{
warning: `"bytes" and "string" lengths are not the same since strings are assumed to be UTF-8 encoded (according to the ABI defintion) therefore one character is not nessesarily encoded in one byte of data.`,
location: this.bytesLengthChecks[0].src,
more: `path_to_url{version}/abi-spec.html#argument-encoding`
}]
} else {
return []
}
}
}
``` | /content/code_sandbox/remix-analyzer/src/solidity-analyzer/modules/stringBytesLength.ts | xml | 2016-04-11T09:05:03 | 2024-08-12T19:22:17 | remix | ethereum/remix | 1,177 | 394 |
```xml
import * as React from 'react';
import cx from 'classnames';
import { createSvgIcon } from '../utils/createSvgIcon';
import { iconClassNames } from '../utils/iconClassNames';
export const ScreenshareIcon = createSvgIcon({
svg: ({ classes }) => (
<svg
style={{ overflow: 'visible' }}
role="presentation"
focusable="false"
viewBox="2 2 16 16"
className={classes.svg}
>
<g className={cx(iconClassNames.outline, classes.outlinePart)}>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M13 10C13 8.34315 11.6569 7 10 7H4C2.34315 7 1 8.34315 1 10V16C1 17.6569 2.34315 19 4 19H10C11.6569 19 13 17.6569 13 16V10ZM10 8C11.1046 8 12 8.89543 12 10V16C12 17.1046 11.1046 18 10 18H4C2.89543 18 2 17.1046 2 16V10C2 8.89543 2.89543 8 4 8H10Z"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M19 4C19 2.34315 17.6569 1 16 1H10C8.34315 1 7 2.34315 7 4V6H8V4C8 2.89543 8.89543 2 10 2H16C17.1046 2 18 2.89543 18 4V10C18 11.1046 17.1046 12 16 12H14V13H16C17.6569 13 19 11.6569 19 10V4ZM13 13V12H12.5V13H13ZM8 7H7V7.5H8V7Z"
/>
</g>
<g className={cx(iconClassNames.filled, classes.filledPart)}>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M19 4C19 2.34315 17.6569 1 16 1H10C8.34315 1 7 2.34315 7 4V6H8V4C8 2.89543 8.89543 2 10 2H16C17.1046 2 18 2.89543 18 4V10C18 11.1046 17.1046 12 16 12H14V13H16C17.6569 13 19 11.6569 19 10V4ZM13 13V12H12.5V13H13ZM8 7H7V7.5H8V7Z"
/>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M10 7C11.6569 7 13 8.34315 13 10V16C13 17.6569 11.6569 19 10 19H4C2.34315 19 1 17.6569 1 16V10C1 8.34315 2.34315 7 4 7H10Z"
/>
</g>
</svg>
),
displayName: 'ScreenshareIcon',
});
``` | /content/code_sandbox/packages/fluentui/react-icons-northstar/src/components/ScreenshareIcon.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 828 |
```xml
import { Component } from '@angular/core';
@Component({
selector: 'ngx-earning-card',
styleUrls: ['./earning-card.component.scss'],
templateUrl: './earning-card.component.html',
})
export class EarningCardComponent {
flipped = false;
toggleView() {
this.flipped = !this.flipped;
}
}
``` | /content/code_sandbox/src/app/pages/e-commerce/earning-card/earning-card.component.ts | xml | 2016-05-25T10:09:03 | 2024-08-16T16:34:03 | ngx-admin | akveo/ngx-admin | 25,169 | 70 |
```xml
import type { MaybeNull, SelectedItem } from '@proton/pass/types';
export type ProtonAddressID = string;
export type CustomAddressID = string;
export enum AddressType {
PROTON = 'proton',
ALIAS = 'alias',
CUSTOM = 'custom',
}
export enum BreachFlag {
MonitorDisabled = 1 << 0,
}
export type AddressBreachDTO<T extends AddressType = AddressType> = {
[AddressType.ALIAS]: { type: AddressType.ALIAS } & SelectedItem;
[AddressType.CUSTOM]: { type: AddressType.CUSTOM; addressId: CustomAddressID };
[AddressType.PROTON]: { type: AddressType.PROTON; addressId: CustomAddressID };
}[T];
export type MonitorVerifyDTO = { addressId: CustomAddressID; code: string };
export type MonitorToggleDTO<T extends AddressType = AddressType> = AddressBreachDTO<T> & { monitor: boolean };
export type MonitorDomain = { domain: string; breachedAt: number };
export type MonitorAddressBase = {
breachedAt?: MaybeNull<number>;
breachCount?: number;
breached: boolean;
email: string;
monitored: boolean;
};
export type MonitorAddress<T extends AddressType = AddressType> = MonitorAddressBase &
{
[AddressType.ALIAS]: { type: AddressType.ALIAS } & SelectedItem;
[AddressType.CUSTOM]: {
type: AddressType.CUSTOM;
addressId: CustomAddressID;
verified: boolean;
suggestion: boolean;
};
[AddressType.PROTON]: { type: AddressType.PROTON; addressId: CustomAddressID };
}[T];
``` | /content/code_sandbox/packages/pass/lib/monitor/types.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 361 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="path_to_url"
xmlns:app="path_to_url"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?windowBackground">
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="@+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="250dp"
android:background="?windowBackground"
app:expandedTitleTextAppearance="@style/TextApperance.Album.Title"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:titleEnabled="false">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="56dp"
android:background="?colorPrimary"
android:elevation="5dp"
app:layout_collapseMode="pin" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/dp_56"
android:orientation="vertical"
app:layout_collapseMode="pin">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/areaRsv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/dp_8"
android:layout_marginEnd="@dimen/dp_8"
android:clipToPadding="false"
android:paddingTop="@dimen/dp_8" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/sexRsv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/dp_8"
android:layout_marginEnd="@dimen/dp_8"
android:clipToPadding="false"
android:paddingTop="@dimen/dp_8" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/genreRsv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/dp_8"
android:layout_marginEnd="@dimen/dp_8"
android:clipToPadding="false"
android:paddingTop="@dimen/dp_8" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/indexRsv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/dp_8"
android:layout_marginEnd="@dimen/dp_8"
android:clipToPadding="false"
android:paddingTop="@dimen/dp_8" />
</LinearLayout>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
<TextView
android:id="@+id/titleTv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="@dimen/dp_8"
android:elevation="@dimen/dp_4" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/resultRsv"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="@dimen/dp_8"
android:layout_marginEnd="@dimen/dp_8"
android:clipToPadding="false"
android:paddingTop="@dimen/dp_8" />
</LinearLayout>
<include layout="@layout/item_loading" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
``` | /content/code_sandbox/app/src/main/res/layout/frag_artist_list.xml | xml | 2016-04-09T15:47:45 | 2024-08-14T04:30:04 | MusicLake | caiyonglong/MusicLake | 2,654 | 930 |
```xml
'use strict';
import { expect } from 'chai';
import { FileSystemPathUtils } from '../../../client/common/platform/fs-paths';
import { PathUtils } from '../../../client/common/platform/pathUtils';
import { WINDOWS as IS_WINDOWS } from './utils';
suite('FileSystem - PathUtils', () => {
let utils: PathUtils;
let wrapped: FileSystemPathUtils;
setup(() => {
utils = new PathUtils(IS_WINDOWS);
wrapped = FileSystemPathUtils.withDefaults();
});
suite('home', () => {
test('matches wrapped object', () => {
const expected = wrapped.home;
expect(utils.home).to.equal(expected);
});
});
suite('delimiter', () => {
test('matches wrapped object', () => {
const expected = wrapped.executables.delimiter;
expect(utils.delimiter).to.be.equal(expected);
});
});
suite('separator', () => {
test('matches wrapped object', () => {
const expected = wrapped.paths.sep;
expect(utils.separator).to.be.equal(expected);
});
});
suite('getPathVariableName', () => {
test('matches wrapped object', () => {
const expected = wrapped.executables.envVar;
const envVar = utils.getPathVariableName();
expect(envVar).to.equal(expected);
});
});
suite('getDisplayName', () => {
test('matches wrapped object', () => {
const filename = 'spam.py';
const expected = wrapped.getDisplayName(filename);
const display = utils.getDisplayName(filename);
expect(display).to.equal(expected);
});
});
suite('basename', () => {
test('matches wrapped object', () => {
const filename = 'spam.py';
const expected = wrapped.paths.basename(filename);
const basename = utils.basename(filename);
expect(basename).to.equal(expected);
});
});
});
``` | /content/code_sandbox/src/test/common/platform/pathUtils.functional.test.ts | xml | 2016-01-19T10:50:01 | 2024-08-12T21:05:24 | pythonVSCode | DonJayamanne/pythonVSCode | 2,078 | 392 |
```xml
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { Ref } from "vue-demi";
import type { EChartsType } from "../types";
const METHOD_NAMES = [
"getWidth",
"getHeight",
"getDom",
"getOption",
"resize",
"dispatchAction",
"convertToPixel",
"convertFromPixel",
"containPixel",
"getDataURL",
"getConnectedDataURL",
"appendData",
"clear",
"isDisposed",
"dispose"
] as const;
type MethodName = (typeof METHOD_NAMES)[number];
type PublicMethods = Pick<EChartsType, MethodName>;
export function usePublicAPI(
chart: Ref<EChartsType | undefined>
): PublicMethods {
function makePublicMethod<T extends MethodName>(
name: T
): (...args: Parameters<EChartsType[T]>) => ReturnType<EChartsType[T]> {
return (...args) => {
if (!chart.value) {
throw new Error("ECharts is not initialized yet.");
}
return (chart.value[name] as any).apply(chart.value, args);
};
}
function makePublicMethods(): PublicMethods {
const methods = Object.create(null);
METHOD_NAMES.forEach(name => {
methods[name] = makePublicMethod(name);
});
return methods as PublicMethods;
}
return makePublicMethods();
}
``` | /content/code_sandbox/src/composables/api.ts | xml | 2016-06-17T09:55:24 | 2024-08-16T15:32:02 | vue-echarts | ecomfe/vue-echarts | 9,553 | 293 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="path_to_url"
xmlns:app="path_to_url"
xmlns:tools="path_to_url">
<data>
<variable
name="data"
type="com.topjohnwu.magisk.view.MagiskDialog.Data" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout_width="match_parent">
<androidx.constraintlayout.widget.Guideline
android:id="@+id/dialog_base_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="16dp" />
<androidx.constraintlayout.widget.Guideline
android:id="@+id/dialog_base_end"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_end="16dp" />
<ImageView
android:id="@+id/dialog_base_icon"
style="@style/WidgetFoundation.Image.Big"
gone="@{data.icon == null}"
android:layout_gravity="center"
android:layout_marginTop="@dimen/l1"
android:src="@{data.icon}"
app:layout_constraintBottom_toTopOf="@+id/dialog_base_title"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:src="@drawable/ic_delete_md2" />
<TextView
android:id="@+id/dialog_base_title"
gone="@{data.title.length == 0}"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/l1"
android:gravity="center"
android:text="@{data.title}"
android:textAppearance="@style/AppearanceFoundation.Title"
app:layout_constraintEnd_toEndOf="@+id/dialog_base_end"
app:layout_constraintStart_toStartOf="@+id/dialog_base_start"
app:layout_constraintTop_toBottomOf="@+id/dialog_base_icon"
tools:lines="1"
tools:text="@tools:sample/lorem/random" />
<androidx.core.widget.NestedScrollView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/l_50"
android:overScrollMode="ifContentScrolls"
app:layout_constrainedHeight="true"
app:layout_constraintBottom_toTopOf="@+id/dialog_base_space"
app:layout_constraintEnd_toEndOf="@+id/dialog_base_end"
app:layout_constraintStart_toStartOf="@+id/dialog_base_start"
app:layout_constraintTop_toBottomOf="@+id/dialog_base_title">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/dialog_base_message"
gone="@{data.message.length == 0}"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@{data.message}"
android:textAppearance="@style/AppearanceFoundation.Body"
tools:lines="3"
tools:text="@tools:sample/lorem/random" />
<FrameLayout
android:id="@+id/dialog_base_container"
gone="@{data.message.length != 0}"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</FrameLayout>
</androidx.core.widget.NestedScrollView>
<Space
android:id="@+id/dialog_base_space"
android:layout_width="wrap_content"
android:layout_height="@dimen/l_50"
app:layout_constraintBottom_toTopOf="@+id/dialog_base_buttons"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<androidx.appcompat.widget.ButtonBarLayout
android:id="@+id/dialog_base_buttons"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="bottom|center_horizontal"
android:layoutDirection="locale"
android:orientation="horizontal"
android:paddingStart="12dp"
android:paddingTop="4dp"
android:paddingEnd="12dp"
android:paddingBottom="4dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<Button
android:id="@+id/dialog_base_button_2"
style="@style/WidgetFoundation.Button.Text"
gone="@{data.buttonNeutral.gone}"
isEnabled="@{data.buttonNeutral.isEnabled}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:clickable="@{data.buttonNeutral.isEnabled}"
android:focusable="@{data.buttonNeutral.isEnabled}"
android:onClick="@{() -> data.buttonNeutral.clicked()}"
android:text="@{data.buttonNeutral.message}"
app:icon="@{data.buttonNeutral.icon}"
app:iconGravity="textStart"
tools:icon="@drawable/ic_bug_md2"
tools:text="Button 1" />
<Space
android:id="@+id/spacer"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="1"
android:visibility="invisible" />
<Button
android:id="@+id/dialog_base_button_3"
style="@style/WidgetFoundation.Button.Text"
gone="@{data.buttonNegative.gone}"
isEnabled="@{data.buttonNegative.isEnabled}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:clickable="@{data.buttonNegative.isEnabled}"
android:focusable="@{data.buttonNegative.isEnabled}"
android:onClick="@{() -> data.buttonNegative.clicked()}"
android:text="@{data.buttonNegative.message}"
app:icon="@{data.buttonNegative.icon}"
tools:icon="@drawable/ic_bug_md2"
tools:text="Button 1" />
<Button
android:id="@+id/dialog_base_button_1"
style="@style/WidgetFoundation.Button.Text"
gone="@{data.buttonPositive.gone}"
isEnabled="@{data.buttonPositive.isEnabled}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:clickable="@{data.buttonPositive.isEnabled}"
android:focusable="@{data.buttonPositive.isEnabled}"
android:onClick="@{() -> data.buttonPositive.clicked()}"
android:text="@{data.buttonPositive.message}"
app:icon="@{data.buttonPositive.icon}"
app:iconGravity="textStart"
tools:icon="@drawable/ic_bug_md2"
tools:text="Button 1" />
</androidx.appcompat.widget.ButtonBarLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
``` | /content/code_sandbox/app/apk/src/main/res/layout/dialog_magisk_base.xml | xml | 2016-09-08T12:42:53 | 2024-08-16T19:41:25 | Magisk | topjohnwu/Magisk | 46,424 | 1,548 |
```xml
import { BaseResponse } from "../../../models/response/base.response";
export class TwoFactorRecoverResponse extends BaseResponse {
code: string;
constructor(response: any) {
super(response);
this.code = this.getResponseProperty("Code");
}
}
``` | /content/code_sandbox/libs/common/src/auth/models/response/two-factor-recover.response.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 53 |
```xml
import * as React from 'react';
import { resolveShorthand } from './resolveShorthand';
import type { Slot } from '../types';
type TestProps = {
slotA?: Slot<'div'>;
slotB?: Slot<'div'>;
slotC?: Slot<'div'>;
notASlot?: string;
alsoNotASlot?: number;
};
describe('resolveShorthand', () => {
it('resolves a string', () => {
const props: TestProps = { slotA: 'hello' };
// eslint-disable-next-line deprecation/deprecation
const resolvedProps = resolveShorthand(props.slotA);
expect(resolvedProps).toEqual({
children: 'hello',
});
});
it('resolves a JSX element', () => {
const props: TestProps = { slotA: <div>hello</div> };
// eslint-disable-next-line deprecation/deprecation
const resolvedProps = resolveShorthand(props.slotA);
expect(resolvedProps).toEqual({
children: <div>hello</div>,
});
});
it('resolves a number', () => {
const props: TestProps = { slotA: 42 };
// eslint-disable-next-line deprecation/deprecation
const resolvedProps = resolveShorthand(props.slotA);
expect(resolvedProps).toEqual({
children: 42,
});
});
it('resolves an object as its copy', () => {
const slotA = {};
const props: TestProps = { slotA };
// eslint-disable-next-line deprecation/deprecation
const resolvedProps = resolveShorthand(props.slotA);
expect(resolvedProps).toEqual({});
expect(resolvedProps).not.toBe(slotA);
});
it('resolves "null" without creating a child element', () => {
const props: TestProps = { slotA: null, slotB: null };
// eslint-disable-next-line deprecation/deprecation
expect(resolveShorthand(props.slotA)).toEqual(undefined);
// eslint-disable-next-line deprecation/deprecation
expect(resolveShorthand(null, { required: true })).toEqual(undefined);
});
it('resolves undefined without creating a child element', () => {
const props: TestProps = { slotA: undefined };
// eslint-disable-next-line deprecation/deprecation
const resolvedProps = resolveShorthand(props.slotA);
expect(resolvedProps).toEqual(undefined);
});
it('resolves to empty object creating a child element', () => {
const props: TestProps = { slotA: undefined };
// eslint-disable-next-line deprecation/deprecation
const resolvedProps = resolveShorthand(props.slotA, { required: true });
expect(resolvedProps).toEqual({});
});
});
``` | /content/code_sandbox/packages/react-components/react-utilities/src/compose/deprecated/resolveShorthand.test.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 587 |
```xml
import { create } from 'react-test-renderer'
import { LegendSvg, LegendSvgItem, LegendProps } from '@nivo/legends'
import { ParallelCoordinates } from '../src'
import { ParallelCoordinatesLine } from '../src/svg/ParallelCoordinatesLine'
const testVariables = [
{
id: 'cost',
value: 'cost' as const,
},
{
id: 'weight',
value: 'weight' as const,
},
{
id: 'volume',
value: 'volume' as const,
},
]
const testData = [
{
id: 'A',
cost: 10,
weight: 20,
volume: 30,
},
{
id: 'B',
cost: 110,
weight: 120,
volume: 130,
},
{
id: 'C',
cost: 210,
weight: 220,
volume: 230,
},
]
const testDataGrouped = [
{
group: 'group_0',
id: 'A',
cost: 10,
weight: 20,
volume: 30,
},
{
group: 'group_0',
id: 'B',
cost: 40,
weight: 50,
volume: 60,
},
{
group: 'group_1',
id: 'A',
cost: 110,
weight: 120,
volume: 130,
},
{
group: 'group_1',
id: 'B',
cost: 140,
weight: 150,
volume: 160,
},
]
describe('<Waffle />', () => {
it('should render a basic parallel coordinates chart in SVG', () => {
const component = create(
<ParallelCoordinates
width={500}
height={300}
data={testData}
variables={testVariables}
animate={false}
testIdPrefix="chart"
/>
).root
const lines = component.findAllByType(ParallelCoordinatesLine)
expect(lines).toHaveLength(testData.length)
})
describe('style', () => {
it('should color lines individually in non-grouped mode', () => {
const colors = ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)', 'rgba(0, 0, 255, 1)']
const component = create(
<ParallelCoordinates
width={500}
height={300}
data={testData}
variables={testVariables}
colors={colors}
animate={false}
testIdPrefix="chart"
/>
).root
const lines = component.findAllByType(ParallelCoordinatesLine)
expect(lines).toHaveLength(testData.length)
expect(lines[0].findByType('path').props.stroke).toEqual(colors[0])
expect(lines[1].findByType('path').props.stroke).toEqual(colors[1])
expect(lines[2].findByType('path').props.stroke).toEqual(colors[2])
})
it('should color lines depending on their group in grouped mode', () => {
const colors = ['rgba(255, 0, 0, 1)', 'rgba(0, 255, 0, 1)']
const component = create(
<ParallelCoordinates
width={500}
height={300}
data={testDataGrouped}
variables={testVariables}
groupBy="group"
colors={colors}
animate={false}
testIdPrefix="chart"
/>
).root
const lines = component.findAllByType(ParallelCoordinatesLine)
expect(lines).toHaveLength(testDataGrouped.length)
expect(lines[0].findByType('path').props.stroke).toEqual(colors[0])
expect(lines[1].findByType('path').props.stroke).toEqual(colors[0])
expect(lines[2].findByType('path').props.stroke).toEqual(colors[1])
expect(lines[3].findByType('path').props.stroke).toEqual(colors[1])
})
})
describe('legends', () => {
const legends: LegendProps[] = [
{
anchor: 'top-left',
direction: 'column',
itemWidth: 100,
itemHeight: 20,
},
]
it('should render a legend for each datum in non-grouped mode', () => {
const component = create(
<ParallelCoordinates
width={500}
height={300}
data={testData}
variables={testVariables}
legends={legends}
animate={false}
testIdPrefix="chart"
/>
).root
const legend = component.findByType(LegendSvg)
const legendItems = legend.findAllByType(LegendSvgItem)
expect(legendItems).toHaveLength(testData.length)
expect(legendItems[0].props.data.id).toEqual('A')
expect(legendItems[1].props.data.id).toEqual('B')
expect(legendItems[2].props.data.id).toEqual('C')
})
it('should render a legend for each group in grouped mode', () => {
const component = create(
<ParallelCoordinates
width={500}
height={300}
data={testDataGrouped}
groupBy="group"
variables={testVariables}
legends={legends}
animate={false}
testIdPrefix="chart"
/>
).root
const legend = component.findByType(LegendSvg)
const legendItems = legend.findAllByType(LegendSvgItem)
expect(legendItems).toHaveLength(2)
expect(legendItems[0].props.data.id).toEqual('group_0')
expect(legendItems[1].props.data.id).toEqual('group_1')
})
})
describe('accessibility', () => {
it('should support aria attributes for the root SVG element', () => {
const component = create(
<ParallelCoordinates
width={500}
height={300}
data={testData}
variables={testVariables}
ariaLabel="AriaLabel"
ariaLabelledBy="AriaLabelledBy"
ariaDescribedBy="AriaDescribedBy"
animate={false}
testIdPrefix="chart"
/>
).root
const svg = component.findByType('svg')
expect(svg.props['aria-label']).toBe('AriaLabel')
expect(svg.props['aria-labelledby']).toBe('AriaLabelledBy')
expect(svg.props['aria-describedby']).toBe('AriaDescribedBy')
})
})
})
``` | /content/code_sandbox/packages/parallel-coordinates/tests/ParallelCoordinates.test.tsx | xml | 2016-04-16T03:27:56 | 2024-08-16T03:38:37 | nivo | plouc/nivo | 13,010 | 1,424 |
```xml
import React from "react";
import { gql, useQuery, useMutation } from "@apollo/client";
import Alert from "@erxes/ui/src/utils/Alert/index";
import SelectDashboard from "../../components/utils/SelectDashboard";
import { IReport, SectionsListQueryResponse } from "../../types";
import { queries, mutations } from "../../graphql";
import { useNavigate } from "react-router-dom";
type Props = {
queryParams: any;
data: IReport;
};
const SelectDashboardContainer = (props: Props) => {
const { queryParams, data } = props;
const navigate = useNavigate();
const sectionsQuery = useQuery<SectionsListQueryResponse>(
gql(queries.sectionList),
{
variables: { type: "dashboard" },
}
);
const [dashboardAddToMutation] = useMutation(gql(mutations.dashboardAddTo), {
refetchQueries: [
{
query: gql(queries.sectionList),
variables: { type: "dashboard" },
},
{
query: gql(queries.dashboardList),
},
],
});
const handleMutation = (id: string) => {
dashboardAddToMutation({
variables: {
...data,
serviceNames: [data.serviceName],
serviceTypes: [data.serviceType],
sectionId: id,
},
})
.then((res) => {
Alert.success("Successfully added to dashboard");
const { _id } = res.data.dashboardAddTo;
if (_id) {
navigate(`/insight?dashboardId=${_id}`);
}
})
.catch((err) => {
Alert.error(err.message);
});
};
const sections = sectionsQuery?.data?.sections || [];
const updatedProps = {
...props,
sections,
handleMutation,
};
return <SelectDashboard {...updatedProps} />;
};
export default SelectDashboardContainer;
``` | /content/code_sandbox/packages/plugin-insight-ui/src/containers/utils/SelectDashboard.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 400 |
```xml
import cn from "classnames";
import React, {
AllHTMLAttributes,
ChangeEvent,
EventHandler,
FunctionComponent,
KeyboardEvent,
RefObject,
useCallback,
useState,
} from "react";
import { SvgIcon, ViewIcon, ViewOffIcon } from "coral-ui/components/icons";
import { withForwardRef, withStyles } from "coral-ui/hocs";
import styles from "./PasswordField.css";
export interface PasswordFieldProps {
id?: string;
/**
* The content value of the component.
*/
defaultValue?: string;
/**
* The content value of the component.
*/
value?: string;
/**
* Convenient prop to override the root styling.
*/
className?: string;
/**
* Override or extend the styles applied to the component.
*/
classes: typeof styles;
/**
* Color of the PasswordField
*/
color?: "regular" | "streamBlue" | "error";
/*
* If set renders a full width button
*/
fullWidth?: boolean;
/**
* Placeholder
*/
placeholder?: string;
/**
* Mark as readonly
*/
readOnly?: boolean;
/**
* Name
*/
name?: string;
/**
* onChange
*/
onChange?: EventHandler<ChangeEvent<HTMLInputElement>>;
disabled?: boolean;
autoComplete?: AllHTMLAttributes<HTMLInputElement>["autoComplete"];
autoCorrect?: AllHTMLAttributes<HTMLInputElement>["autoCorrect"];
autoCapitalize?: AllHTMLAttributes<HTMLInputElement>["autoCapitalize"];
spellCheck?: AllHTMLAttributes<HTMLInputElement>["spellCheck"];
showPasswordTitle?: string;
hidePasswordTitle?: string;
forwardRef?: RefObject<HTMLInputElement>;
}
const PasswordField: FunctionComponent<PasswordFieldProps> = ({
color = "regular",
placeholder = "",
showPasswordTitle = "Hide password",
hidePasswordTitle = "Show password",
autoCapitalize = "off",
autoCorrect = "off",
autoComplete = "off",
spellCheck = false,
className,
classes,
fullWidth,
value,
forwardRef,
...rest
}) => {
const [reveal, setReveal] = useState(false);
const toggleVisibility = useCallback(() => {
setReveal((revealed) => !revealed);
}, []);
const handleVisibilityKeyUp = useCallback(
(e: KeyboardEvent) => {
// Number 13 is the "Enter" key on the keyboard
if (e.keyCode === 13) {
toggleVisibility();
}
},
[toggleVisibility]
);
const rootClassName = cn(
{
[classes.fullWidth]: fullWidth,
},
classes.root,
className
);
const inputClassName = cn(
{
[classes.colorRegular]: color === "regular",
[classes.colorStreamBlue]: color === "streamBlue",
[classes.colorError]: color === "error",
[classes.fullWidth]: fullWidth,
},
classes.input
);
return (
<div className={rootClassName}>
<div className={classes.wrapper}>
<input
{...rest}
className={inputClassName}
placeholder={placeholder}
value={value}
type={reveal ? "text" : "password"}
data-testid="password-field"
ref={forwardRef}
/>
<div
role="button"
className={styles.icon}
title={reveal ? hidePasswordTitle : showPasswordTitle}
onClick={toggleVisibility}
onKeyUp={handleVisibilityKeyUp}
tabIndex={0}
>
<SvgIcon Icon={reveal ? ViewOffIcon : ViewIcon} />
</div>
</div>
</div>
);
};
const enhanced = withForwardRef(withStyles(styles)(PasswordField));
export default enhanced;
``` | /content/code_sandbox/client/src/core/client/ui/components/v2/PasswordField/PasswordField.tsx | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 801 |
```xml
import { TestBed } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [RouterTestingModule],
declarations: [AppComponent]
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have as title 'openvidu-testapp-livekit'`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('openvidu-testapp-livekit');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('.content span')?.textContent).toContain('openvidu-testapp-livekit app is running!');
});
});
``` | /content/code_sandbox/openvidu-testapp/src/app/app.component.spec.ts | xml | 2016-10-10T13:31:27 | 2024-08-15T12:14:04 | openvidu | OpenVidu/openvidu | 1,859 | 208 |
```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.
*/
// TypeScript Version: 4.1
/**
* Interface defining function options.
*/
interface Options {
/**
* Language code (default: 'en').
*
* ## Notes
*
* Supported languages:
*
* - **en**: English.
* - **de**: German.
*/
lang?: 'en' | 'de';
}
/**
* Converts a number to a word representation.
*
* @param num - number to convert
* @param options - options
* @param options.lang - language code (default: 'en')
* @returns string representation of a number
*
* @example
* var out = num2words( 12 );
* // returns 'twelve'
*
* @example
* var out = num2words( 21.8 );
* // returns 'twenty-one point eight'
*
* @example
* var out = num2words( 1234 );
* // returns 'one thousand two hundred thirty-four'
*
* @example
* var out = num2words( 100381 );
* // returns 'one hundred thousand three hundred eighty-one'
*/
declare function num2words( num: number, options?: Options ): string;
// EXPORTS //
export = num2words;
``` | /content/code_sandbox/lib/node_modules/@stdlib/string/num2words/docs/types/index.d.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 313 |
```xml
import * as React from 'react';
import { StoryWright } from 'storywright';
import { Meta } from '@storybook/react';
import { Checkbox } from '@fluentui/react-northstar';
import StoryWrightSteps from './commonStoryWrightSteps';
import CheckboxExample from '../../examples/components/Checkbox/Types/CheckboxExample.shorthand';
export default {
component: Checkbox,
title: 'Checkbox',
decorators: [story => <StoryWright steps={StoryWrightSteps}>{story()}</StoryWright>],
} as Meta<typeof Checkbox>;
export { CheckboxExample };
``` | /content/code_sandbox/packages/fluentui/docs/src/vr-tests/Checkbox/CheckboxExample.stories.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 122 |
```xml
import * as React from 'react';
import { styled } from '../../Utilities';
import { IVerticalBarChartProps, IVerticalBarChartStyleProps, IVerticalBarChartStyles } from '../../index';
import { VerticalBarChartBase } from './VerticalBarChart.base';
import { getStyles } from './VerticalBarChart.styles';
// Create a VerticalBarChart variant which uses these default styles and this styled subcomponent.
/**
* VerticalBarchart component
* {@docCategory VerticalBarChart}
*/
export const VerticalBarChart: React.FunctionComponent<IVerticalBarChartProps> = styled<
IVerticalBarChartProps,
IVerticalBarChartStyleProps,
IVerticalBarChartStyles
>(VerticalBarChartBase, getStyles);
``` | /content/code_sandbox/packages/react-charting/src/components/VerticalBarChart/VerticalBarChart.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 154 |
```xml
import { inject, injectable, } from 'inversify';
import { ServiceIdentifiers } from '../../container/ServiceIdentifiers';
import * as ESTree from 'estree';
import { IOptions } from '../../interfaces/options/IOptions';
import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator';
import { IVisitor } from '../../interfaces/node-transformers/IVisitor';
import { NodeTransformer } from '../../enums/node-transformers/NodeTransformer';
import { NodeTransformationStage } from '../../enums/node-transformers/NodeTransformationStage';
import { AbstractNodeTransformer } from '../AbstractNodeTransformer';
import { NodeGuards } from '../../node/NodeGuards';
import { NodeMetadata } from '../../node/NodeMetadata';
/**
* Adds metadata properties to each node
*/
@injectable()
export class MetadataTransformer extends AbstractNodeTransformer {
/**
* @type {NodeTransformer[]}
*/
public override readonly runAfter: NodeTransformer[] = [
NodeTransformer.ParentificationTransformer,
NodeTransformer.VariablePreserveTransformer
];
/**
* @param {IRandomGenerator} randomGenerator
* @param {IOptions} options
*/
public constructor (
@inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator,
@inject(ServiceIdentifiers.IOptions) options: IOptions
) {
super(randomGenerator, options);
}
/**
* @param {NodeTransformationStage} nodeTransformationStage
* @returns {IVisitor | null}
*/
public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null {
switch (nodeTransformationStage) {
case NodeTransformationStage.Preparing:
return {
enter: (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node | undefined => {
return this.transformNode(node, parentNode);
}
};
default:
return null;
}
}
/**
* @param {Node} node
* @param {Node} parentNode
* @returns {Node}
*/
public transformNode (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node {
NodeMetadata.set(node, { ignoredNode: false });
if (NodeGuards.isLiteralNode(node)) {
NodeMetadata.set(node, { stringArrayCallLiteralNode: false });
}
return node;
}
}
``` | /content/code_sandbox/src/node-transformers/preparing-transformers/MetadataTransformer.ts | xml | 2016-05-09T08:16:53 | 2024-08-16T19:43:07 | javascript-obfuscator | javascript-obfuscator/javascript-obfuscator | 13,358 | 504 |
```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
*
*/
export * from './MainContent';
``` | /content/code_sandbox/src/script/page/MainContent/index.ts | xml | 2016-07-21T15:34:05 | 2024-08-16T11:40:13 | wire-webapp | wireapp/wire-webapp | 1,125 | 95 |
```xml
import { attr, FASTElement, nullableNumberConverter, observable, Observable, Updates } from '@microsoft/fast-element';
import { getInitials } from '../utils/get-initials.js';
import { toggleState } from '../utils/element-internals.js';
import {
AvatarActive,
AvatarAppearance,
AvatarColor,
AvatarNamedColor,
AvatarShape,
AvatarSize,
} from './avatar.options.js';
/**
* The base class used for constructing a fluent-avatar custom element
* @public
*/
export class BaseAvatar extends FASTElement {
/**
* The internal {@link path_to_url | `ElementInternals`} instance for the component.
*
* @internal
*/
public elementInternals: ElementInternals = this.attachInternals();
/**
* The name of the person or entity represented by this Avatar. This should always be provided if it is available.
*
* @public
* @remarks
* HTML Attribute: name
*/
@attr
public name?: string | undefined;
/**
* Provide custom initials rather than one generated via the name
*
* @public
* @remarks
* HTML Attribute: name
*/
@attr
public initials?: string | undefined;
/**
* Optional activity indicator
* * active: the avatar will be decorated according to activeAppearance
* * inactive: the avatar will be reduced in size and partially transparent
* * undefined: normal display
*
* @public
* @remarks
* HTML Attribute: active
*/
@attr
public active?: AvatarActive | undefined;
constructor() {
super();
this.elementInternals.role = 'img';
}
}
/**
* An Avatar Custom HTML Element.
* Based on BaseAvatar and includes style and layout specific attributes
*
* @public
*/
export class Avatar extends BaseAvatar {
/**
* The avatar can have a circular or square shape.
*
* @public
* @remarks
* HTML Attribute: shape
*/
@attr
public shape?: AvatarShape | undefined;
/**
* The appearance when `active="active"`
*
* @public
* @remarks
* HTML Attribute: appearance
*/
@attr
public appearance?: AvatarAppearance | undefined;
/**
* Size of the avatar in pixels.
*
* Size is restricted to a limited set of supported values recommended for most uses (see `AvatarSizeValue`) and
* based on design guidelines for the Avatar control.
*
* If a non-supported size is neeeded, set `size` to the next-smaller supported size, and set `width` and `height`
* to override the rendered size.
*
* @public
* @remarks
* HTML Attribute: size
*
*/
@attr({ converter: nullableNumberConverter })
public size?: AvatarSize | undefined;
/**
* The color when displaying either an icon or initials.
* * neutral (default): gray
* * brand: color from the brand palette
* * colorful: picks a color from a set of pre-defined colors, based on a hash of the name (or colorId if provided)
* * [AvatarNamedColor]: a specific color from the theme
*
* @public
* @remarks
* HTML Attribute: color
*/
@attr
public color?: AvatarColor | undefined;
/**
* Specify a string to be used instead of the name, to determine which color to use when color="colorful".
* Use this when a name is not available, but there is another unique identifier that can be used instead.
*/
@attr({ attribute: 'color-id' })
public colorId?: AvatarNamedColor | undefined;
/**
* Holds the current color state
*/
private currentColor: string | undefined;
/**
* Handles changes to observable properties
* @internal
* @param source - the source of the change
* @param propertyName - the property name being changed
*/
public handleChange(source: any, propertyName: string) {
switch (propertyName) {
case 'color':
case 'colorId':
this.generateColor();
break;
default:
break;
}
}
/**
* Generates and sets the initials for the template
* @internal
*/
public generateInitials(): string | void {
if (!this.name && !this.initials) {
return;
}
// size can be undefined since we default it in CSS only
const size = this.size ?? 32;
return (
this.initials ??
getInitials(this.name, window.getComputedStyle(this as unknown as HTMLElement).direction === 'rtl', {
firstInitialOnly: size <= 16,
})
);
}
/**
* Sets the data-color attribute used for the visual presentation
* @internal
*/
public generateColor(): void {
const colorful: boolean = this.color === AvatarColor.colorful;
const prev = this.currentColor;
toggleState(this.elementInternals, `${prev}`, false);
this.currentColor =
colorful && this.colorId
? this.colorId
: colorful
? (Avatar.colors[getHashCode(this.name ?? '') % Avatar.colors.length] as AvatarColor)
: this.color ?? AvatarColor.neutral;
toggleState(this.elementInternals, `${this.currentColor}`, true);
}
/**
* An array of the available Avatar named colors
*/
public static colors = Object.values(AvatarNamedColor);
public connectedCallback(): void {
super.connectedCallback();
Observable.getNotifier(this).subscribe(this);
this.generateColor();
}
public disconnectedCallback(): void {
super.disconnectedCallback();
Observable.getNotifier(this).unsubscribe(this);
}
}
// copied from React avatar
const getHashCode = (str: string): number => {
let hashCode = 0;
for (let len: number = str.length - 1; len >= 0; len--) {
const ch = str.charCodeAt(len);
const shift = len % 8;
hashCode ^= (ch << shift) + (ch >> (8 - shift)); // eslint-disable-line no-bitwise
}
return hashCode;
};
``` | /content/code_sandbox/packages/web-components/src/avatar/avatar.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 1,355 |
```xml
import { makeEnvironmentProviders } from '@angular/core';
import { FEATURE_MANAGEMENT_SETTINGS_PROVIDERS } from './';
export function provideFeatureManagementConfig() {
return makeEnvironmentProviders([FEATURE_MANAGEMENT_SETTINGS_PROVIDERS]);
}
``` | /content/code_sandbox/npm/ng-packs/packages/feature-management/src/lib/providers/feature-management-config.provider.ts | xml | 2016-12-03T22:56:24 | 2024-08-16T16:24:05 | abp | abpframework/abp | 12,657 | 46 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE language SYSTEM "language.dtd">
<language
version="5"
kateversion="3.1"
name="SPDX-Comments"
section="Other"
extensions=""
mimetype=""
author="Alex Turbov (i.zaufi@gmail.com)"
license="MIT"
hidden="true"
>
<highlighting>
<list name="tags">
<item>SPDX-FileContributor:</item>
</list>
<list name="operators">
<item>AND</item>
<item>OR</item>
<item>WITH</item>
</list>
<list name="licenses">
<item>0BSD</item>
<item>AAL</item>
<item>ADSL</item>
<item>AFL-1.1</item>
<item>AFL-1.2</item>
<item>AFL-2.0</item>
<item>AFL-2.1</item>
<item>AFL-3.0</item>
<item>AGPL-1.0-only</item>
<item>AGPL-1.0-or-later</item>
<item>AGPL-3.0-only</item>
<item>AGPL-3.0-or-later</item>
<item>AMDPLPA</item>
<item>AML</item>
<item>AMPAS</item>
<item>ANTLR-PD</item>
<item>ANTLR-PD-fallback</item>
<item>APAFML</item>
<item>APL-1.0</item>
<item>APSL-1.0</item>
<item>APSL-1.1</item>
<item>APSL-1.2</item>
<item>APSL-2.0</item>
<item>Abstyles</item>
<item>Adobe-2006</item>
<item>Adobe-Glyph</item>
<item>Afmparse</item>
<item>Aladdin</item>
<item>Apache-1.0</item>
<item>Apache-1.1</item>
<item>Apache-2.0</item>
<item>Artistic-1.0</item>
<item>Artistic-1.0-Perl</item>
<item>Artistic-1.0-cl8</item>
<item>Artistic-2.0</item>
<item>BSD-1-Clause</item>
<item>BSD-2-Clause</item>
<item>BSD-2-Clause-Patent</item>
<item>BSD-2-Clause-Views</item>
<item>BSD-3-Clause</item>
<item>BSD-3-Clause-Attribution</item>
<item>BSD-3-Clause-Clear</item>
<item>BSD-3-Clause-LBNL</item>
<item>BSD-3-Clause-No-Nuclear-Warranty</item>
<item>BSD-3-Clause-Open-MPI</item>
<item>BSD-4-Clause</item>
<item>BSD-4-Clause-UC</item>
<item>BSD-Protection</item>
<item>BSD-Source-Code</item>
<item>BSL-1.0</item>
<item>BUSL-1.1</item>
<item>Bahyph</item>
<item>Barr</item>
<item>Beerware</item>
<item>BitTorrent-1.0</item>
<item>BitTorrent-1.1</item>
<item>BlueOak-1.0.0</item>
<item>Borceux</item>
<item>CAL-1.0</item>
<item>CAL-1.0-Combined-Work-Exception</item>
<item>CATOSL-1.1</item>
<item>CC-BY-1.0</item>
<item>CC-BY-2.0</item>
<item>CC-BY-2.5</item>
<item>CC-BY-3.0</item>
<item>CC-BY-3.0-AT</item>
<item>CC-BY-3.0-US</item>
<item>CC-BY-4.0</item>
<item>CC-BY-NC-1.0</item>
<item>CC-BY-NC-2.0</item>
<item>CC-BY-NC-2.5</item>
<item>CC-BY-NC-3.0</item>
<item>CC-BY-NC-4.0</item>
<item>CC-BY-NC-ND-1.0</item>
<item>CC-BY-NC-ND-2.0</item>
<item>CC-BY-NC-ND-2.5</item>
<item>CC-BY-NC-ND-3.0</item>
<item>CC-BY-NC-ND-3.0-IGO</item>
<item>CC-BY-NC-ND-4.0</item>
<item>CC-BY-NC-SA-1.0</item>
<item>CC-BY-NC-SA-2.0</item>
<item>CC-BY-NC-SA-2.5</item>
<item>CC-BY-NC-SA-3.0</item>
<item>CC-BY-NC-SA-4.0</item>
<item>CC-BY-ND-1.0</item>
<item>CC-BY-ND-2.0</item>
<item>CC-BY-ND-2.5</item>
<item>CC-BY-ND-3.0</item>
<item>CC-BY-ND-4.0</item>
<item>CC-BY-SA-1.0</item>
<item>CC-BY-SA-2.0</item>
<item>CC-BY-SA-2.0-UK</item>
<item>CC-BY-SA-2.5</item>
<item>CC-BY-SA-3.0</item>
<item>CC-BY-SA-3.0-AT</item>
<item>CC-BY-SA-4.0</item>
<item>CC-PDDC</item>
<item>CC0-1.0</item>
<item>CDDL-1.0</item>
<item>CDDL-1.1</item>
<item>CDLA-Permissive-1.0</item>
<item>CDLA-Sharing-1.0</item>
<item>CECILL-1.0</item>
<item>CECILL-1.1</item>
<item>CECILL-2.0</item>
<item>CECILL-2.1</item>
<item>CECILL-B</item>
<item>CECILL-C</item>
<item>CERN-OHL-1.1</item>
<item>CERN-OHL-1.2</item>
<item>CERN-OHL-P-2.0</item>
<item>CERN-OHL-S-2.0</item>
<item>CERN-OHL-W-2.0</item>
<item>CNRI-Jython</item>
<item>CNRI-Python</item>
<item>CNRI-Python-GPL-Compatible</item>
<item>CPAL-1.0</item>
<item>CPL-1.0</item>
<item>CPOL-1.02</item>
<item>CUA-OPL-1.0</item>
<item>Caldera</item>
<item>ClArtistic</item>
<item>Condor-1.1</item>
<item>Crossword</item>
<item>CrystalStacker</item>
<item>Cube</item>
<item>D-FSL-1.0</item>
<item>DOC</item>
<item>DSDP</item>
<item>Dotseqn</item>
<item>ECL-1.0</item>
<item>ECL-2.0</item>
<item>EFL-1.0</item>
<item>EFL-2.0</item>
<item>EPICS</item>
<item>EPL-1.0</item>
<item>EPL-2.0</item>
<item>EUDatagrid</item>
<item>EUPL-1.0</item>
<item>EUPL-1.1</item>
<item>EUPL-1.2</item>
<item>Entessa</item>
<item>ErlPL-1.1</item>
<item>Eurosym</item>
<item>FSFAP</item>
<item>FSFUL</item>
<item>FSFULLR</item>
<item>FTL</item>
<item>Fair</item>
<item>Frameworx-1.0</item>
<item>FreeImage</item>
<item>GFDL-1.1-invariants-only</item>
<item>GFDL-1.1-invariants-or-later</item>
<item>GFDL-1.1-no-invariants-only</item>
<item>GFDL-1.1-no-invariants-or-later</item>
<item>GFDL-1.1-only</item>
<item>GFDL-1.1-or-later</item>
<item>GFDL-1.2-invariants-only</item>
<item>GFDL-1.2-invariants-or-later</item>
<item>GFDL-1.2-no-invariants-only</item>
<item>GFDL-1.2-no-invariants-or-later</item>
<item>GFDL-1.2-only</item>
<item>GFDL-1.2-or-later</item>
<item>GFDL-1.3-invariants-only</item>
<item>GFDL-1.3-invariants-or-later</item>
<item>GFDL-1.3-no-invariants-only</item>
<item>GFDL-1.3-no-invariants-or-later</item>
<item>GFDL-1.3-only</item>
<item>GFDL-1.3-or-later</item>
<item>GL2PS</item>
<item>GLWTPL</item>
<item>GPL-1.0-only</item>
<item>GPL-1.0-or-later</item>
<item>GPL-2.0-only</item>
<item>GPL-2.0-or-later</item>
<item>GPL-3.0-only</item>
<item>GPL-3.0-or-later</item>
<item>Giftware</item>
<item>Glide</item>
<item>Glulxe</item>
<item>HPND</item>
<item>HPND-sell-variant</item>
<item>HTMLTIDY</item>
<item>HaskellReport</item>
<item>Hippocratic-2.1</item>
<item>IBM-pibs</item>
<item>ICU</item>
<item>IJG</item>
<item>IPA</item>
<item>IPL-1.0</item>
<item>ISC</item>
<item>ImageMagick</item>
<item>Imlib2</item>
<item>Info-ZIP</item>
<item>Intel</item>
<item>Intel-ACPI</item>
<item>Interbase-1.0</item>
<item>JPNIC</item>
<item>JSON</item>
<item>JasPer-2.0</item>
<item>LAL-1.2</item>
<item>LAL-1.3</item>
<item>LGPL-2.0-only</item>
<item>LGPL-2.0-or-later</item>
<item>LGPL-2.1-only</item>
<item>LGPL-2.1-or-later</item>
<item>LGPL-3.0-only</item>
<item>LGPL-3.0-or-later</item>
<item>LGPLLR</item>
<item>LPL-1.0</item>
<item>LPL-1.02</item>
<item>LPPL-1.0</item>
<item>LPPL-1.1</item>
<item>LPPL-1.2</item>
<item>LPPL-1.3a</item>
<item>LPPL-1.3c</item>
<item>Latex2e</item>
<item>Leptonica</item>
<item>LiLiQ-P-1.1</item>
<item>LiLiQ-R-1.1</item>
<item>LiLiQ-Rplus-1.1</item>
<item>Libpng</item>
<item>Linux-OpenIB</item>
<item>MIT</item>
<item>MIT-0</item>
<item>MIT-CMU</item>
<item>MIT-advertising</item>
<item>MIT-enna</item>
<item>MIT-feh</item>
<item>MIT-open-group</item>
<item>MITNFA</item>
<item>MPL-1.0</item>
<item>MPL-1.1</item>
<item>MPL-2.0</item>
<item>MPL-2.0-no-copyleft-exception</item>
<item>MS-PL</item>
<item>MS-RL</item>
<item>MTLL</item>
<item>MakeIndex</item>
<item>MirOS</item>
<item>Motosoto</item>
<item>MulanPSL-1.0</item>
<item>MulanPSL-2.0</item>
<item>Multics</item>
<item>Mup</item>
<item>NASA-1.3</item>
<item>NBPL-1.0</item>
<item>NCGL-UK-2.0</item>
<item>NCSA</item>
<item>NGPL</item>
<item>NIST-PD</item>
<item>NIST-PD-fallback</item>
<item>NLOD-1.0</item>
<item>NLPL</item>
<item>NOSL</item>
<item>NPL-1.0</item>
<item>NPL-1.1</item>
<item>NPOSL-3.0</item>
<item>NRL</item>
<item>NTP</item>
<item>NTP-0</item>
<item>Naumen</item>
<item>Net-SNMP</item>
<item>NetCDF</item>
<item>Newsletr</item>
<item>Nokia</item>
<item>Noweb</item>
<item>O-UDA-1.0</item>
<item>OCCT-PL</item>
<item>OCLC-2.0</item>
<item>ODC-By-1.0</item>
<item>ODbL-1.0</item>
<item>OFL-1.0</item>
<item>OFL-1.0-RFN</item>
<item>OFL-1.0-no-RFN</item>
<item>OFL-1.1</item>
<item>OFL-1.1-RFN</item>
<item>OFL-1.1-no-RFN</item>
<item>OGC-1.0</item>
<item>OGL-Canada-2.0</item>
<item>OGL-UK-1.0</item>
<item>OGL-UK-2.0</item>
<item>OGL-UK-3.0</item>
<item>OGTSL</item>
<item>OLDAP-1.1</item>
<item>OLDAP-1.2</item>
<item>OLDAP-1.3</item>
<item>OLDAP-1.4</item>
<item>OLDAP-2.0</item>
<item>OLDAP-2.0.1</item>
<item>OLDAP-2.1</item>
<item>OLDAP-2.2</item>
<item>OLDAP-2.2.1</item>
<item>OLDAP-2.2.2</item>
<item>OLDAP-2.3</item>
<item>OLDAP-2.4</item>
<item>OLDAP-2.5</item>
<item>OLDAP-2.6</item>
<item>OLDAP-2.7</item>
<item>OLDAP-2.8</item>
<item>OML</item>
<item>OPL-1.0</item>
<item>OSET-PL-2.1</item>
<item>OSL-1.0</item>
<item>OSL-1.1</item>
<item>OSL-2.0</item>
<item>OSL-2.1</item>
<item>OSL-3.0</item>
<item>OpenSSL</item>
<item>PDDL-1.0</item>
<item>PHP-3.0</item>
<item>PHP-3.01</item>
<item>PSF-2.0</item>
<item>Parity-6.0.0</item>
<item>Parity-7.0.0</item>
<item>Plexus</item>
<item>PolyForm-Noncommercial-1.0.0</item>
<item>PolyForm-Small-Business-1.0.0</item>
<item>PostgreSQL</item>
<item>Python-2.0</item>
<item>QPL-1.0</item>
<item>Qhull</item>
<item>RHeCos-1.1</item>
<item>RPL-1.1</item>
<item>RPL-1.5</item>
<item>RPSL-1.0</item>
<item>RSA-MD</item>
<item>RSCPL</item>
<item>Rdisc</item>
<item>Ruby</item>
<item>SAX-PD</item>
<item>SCEA</item>
<item>SGI-B-1.0</item>
<item>SGI-B-1.1</item>
<item>SGI-B-2.0</item>
<item>SHL-0.5</item>
<item>SHL-0.51</item>
<item>SISSL</item>
<item>SISSL-1.2</item>
<item>SMLNJ</item>
<item>SMPPL</item>
<item>SNIA</item>
<item>SPL-1.0</item>
<item>SSH-OpenSSH</item>
<item>SSH-short</item>
<item>SSPL-1.0</item>
<item>SWL</item>
<item>Saxpath</item>
<item>Sendmail</item>
<item>Sendmail-8.23</item>
<item>SimPL-2.0</item>
<item>Sleepycat</item>
<item>Spencer-86</item>
<item>Spencer-94</item>
<item>Spencer-99</item>
<item>SugarCRM-1.1.3</item>
<item>TAPR-OHL-1.0</item>
<item>TCL</item>
<item>TCP-wrappers</item>
<item>TMate</item>
<item>TORQUE-1.1</item>
<item>TOSL</item>
<item>TU-Berlin-1.0</item>
<item>TU-Berlin-2.0</item>
<item>UCL-1.0</item>
<item>UPL-1.0</item>
<item>Unicode-DFS-2015</item>
<item>Unicode-DFS-2016</item>
<item>Unicode-TOU</item>
<item>Unlicense</item>
<item>VOSTROM</item>
<item>VSL-1.0</item>
<item>Vim</item>
<item>W3C</item>
<item>W3C-19980720</item>
<item>W3C-20150513</item>
<item>WTFPL</item>
<item>Watcom-1.0</item>
<item>Wsuipa</item>
<item>X11</item>
<item>XFree86-1.1</item>
<item>XSkat</item>
<item>Xerox</item>
<item>Xnet</item>
<item>YPL-1.0</item>
<item>YPL-1.1</item>
<item>ZPL-1.1</item>
<item>ZPL-2.0</item>
<item>ZPL-2.1</item>
<item>Zed</item>
<item>Zend-2.0</item>
<item>Zimbra-1.3</item>
<item>Zimbra-1.4</item>
<item>Zlib</item>
<item>blessing</item>
<item>bzip2-1.0.5</item>
<item>bzip2-1.0.6</item>
<item>copyleft-next-0.3.0</item>
<item>copyleft-next-0.3.1</item>
<item>curl</item>
<item>diffmark</item>
<item>dvipdfm</item>
<item>eGenix</item>
<item>etalab-2.0</item>
<item>gSOAP-1.3b</item>
<item>gnuplot</item>
<item>iMatix</item>
<item>libpng-2.0</item>
<item>libselinux-1.0</item>
<item>libtiff</item>
<item>mpich2</item>
<item>psfrag</item>
<item>psutils</item>
<item>xinetd</item>
<item>xpp</item>
<item>zlib-acknowledgement</item>
</list>
<list name="deprecated-licenses">
<item>AGPL-1.0</item>
<item>AGPL-3.0</item>
<item>BSD-2-Clause-FreeBSD</item>
<item>BSD-2-Clause-NetBSD</item>
<item>GFDL-1.1</item>
<item>GFDL-1.2</item>
<item>GFDL-1.3</item>
<item>GPL-1.0</item>
<item>GPL-2.0</item>
<item>GPL-2.0-with-GCC-exception</item>
<item>GPL-2.0-with-autoconf-exception</item>
<item>GPL-2.0-with-bison-exception</item>
<item>GPL-2.0-with-classpath-exception</item>
<item>GPL-2.0-with-font-exception</item>
<item>GPL-3.0</item>
<item>GPL-3.0-with-GCC-exception</item>
<item>GPL-3.0-with-autoconf-exception</item>
<item>LGPL-2.0</item>
<item>LGPL-2.1</item>
<item>LGPL-3.0</item>
<item>Nunit</item>
<item>StandardML-NJ</item>
<item>eCos-2.0</item>
<item>wxWindows</item>
</list>
<list name="exceptions">
<item>GCC-exception-2.0</item>
<item>openvpn-openssl-exception</item>
<item>GPL-3.0-linking-exception</item>
<item>Fawkes-Runtime-exception</item>
<item>u-boot-exception-2.0</item>
<item>PS-or-PDF-font-exception-20170817</item>
<item>gnu-javamail-exception</item>
<item>LGPL-3.0-linking-exception</item>
<item>DigiRule-FOSS-exception</item>
<item>LLVM-exception</item>
<item>Linux-syscall-note</item>
<item>GPL-3.0-linking-source-exception</item>
<item>Qwt-exception-1.0</item>
<item>389-exception</item>
<item>mif-exception</item>
<item>eCos-exception-2.0</item>
<item>CLISP-exception-2.0</item>
<item>Bison-exception-2.2</item>
<item>Libtool-exception</item>
<item>LZMA-exception</item>
<item>OpenJDK-assembly-exception-1.0</item>
<item>Font-exception-2.0</item>
<item>OCaml-LGPL-linking-exception</item>
<item>GCC-exception-3.1</item>
<item>Bootloader-exception</item>
<item>SHL-2.0</item>
<item>Classpath-exception-2.0</item>
<item>Swift-exception</item>
<item>Autoconf-exception-2.0</item>
<item>FLTK-exception</item>
<item>freertos-exception-2.0</item>
<item>Universal-FOSS-exception-1.0</item>
<item>WxWindows-exception-3.1</item>
<item>OCCT-exception-1.0</item>
<item>Autoconf-exception-3.0</item>
<item>i2p-gpl-java-exception</item>
<item>GPL-CC-1.0</item>
<item>Qt-LGPL-exception-1.1</item>
<item>SHL-2.1</item>
<item>Qt-GPL-exception-1.0</item>
</list>
<list name="deprecated-exceptions">
<item>Nokia-Qt-exception-1.1</item>
</list>
<contexts>
<context name="Normal" attribute="SPDX Tag" lineEndContext="#pop">
<keyword String="tags" attribute="SPDX Tag" />
</context>
<context name="license-expression" attribute="SPDX Value" lineEndContext="#pop" fallthrough="true" fallthroughContext="#pop">
<DetectSpaces/>
</context>
</contexts>
<itemDatas>
<itemData name="SPDX Tag" defStyleNum="dsAnnotation" italic="true" spellChecking="false" />
<itemData name="SPDX Value" defStyleNum="dsAnnotation" italic="true" spellChecking="false" />
</itemDatas>
</highlighting>
<general>
<keywords casesensitive="1" weakDeliminator=":-." />
</general>
</language>
<!-- kate: indent-width 2; -->
``` | /content/code_sandbox/syntax/spdx-comments.xml | xml | 2016-08-19T16:25:54 | 2024-08-11T08:59:44 | matterhorn | matterhorn-chat/matterhorn | 1,027 | 6,399 |
```xml
<definitions
xmlns="path_to_url"
xmlns:activiti="path_to_url"
targetNamespace="Examples">
<process id="simpleTextOnly" >
<startEvent id="theStart" />
<sequenceFlow sourceRef="theStart" targetRef="sendMail" />
<sendTask id="sendMail" activiti:type="mail">
<extensionElements>
<activiti:field name="to">
<activiti:string>kermit@activiti.org</activiti:string>
</activiti:field>
<activiti:field name="subject">
<activiti:string>Hello Kermit!</activiti:string>
</activiti:field>
<activiti:field name="text">
<activiti:string>This a text only e-mail.</activiti:string>
</activiti:field>
</extensionElements>
</sendTask>
<sequenceFlow sourceRef="sendMail" targetRef="theEnd" />
<endEvent id="theEnd" />
</process>
</definitions>
``` | /content/code_sandbox/modules/flowable5-test/src/test/resources/org/activiti/engine/test/bpmn/mail/EmailSendTaskTest.testSimpleTextMail.bpmn20.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 228 |
```xml
import { createPresenceComponent, motionTokens } from '@fluentui/react-motion';
import { tokens } from '@fluentui/react-theme';
import type { DrawerBaseProps } from './DrawerBase.types';
import { drawerCSSVars } from './useDrawerBaseStyles.styles';
export type DrawerMotionParams = Required<Pick<DrawerBaseProps, 'size' | 'position'>>;
export type OverlayDrawerSurfaceMotionParams = Required<Pick<DrawerBaseProps, 'size'>>;
const durations: Record<NonNullable<DrawerBaseProps['size']>, number> = {
small: motionTokens.durationGentle,
medium: motionTokens.durationSlow,
large: motionTokens.durationSlower,
full: motionTokens.durationUltraSlow,
};
/**
* @internal
*/
export const InlineDrawerMotion = createPresenceComponent<DrawerMotionParams>(({ position, size }) => {
const keyframes: Keyframe[] = [
{
...(position === 'start' && {
transform: `translate3d(calc(var(${drawerCSSVars.drawerSizeVar}) * -1), 0, 0)`,
}),
...(position === 'end' && {
transform: `translate3d(var(${drawerCSSVars.drawerSizeVar}), 0, 0)`,
}),
...(position === 'bottom' && {
transform: `translate3d(0, var(${drawerCSSVars.drawerSizeVar}), 0)`,
}),
opacity: 0,
},
{ transform: 'translate3d(0, 0, 0)', opacity: 1 },
];
const duration = durations[size];
return {
enter: {
keyframes,
duration,
easing: motionTokens.curveDecelerateMid,
},
exit: {
keyframes: [...keyframes].reverse(),
duration,
easing: motionTokens.curveAccelerateMin,
},
};
});
/**
* @internal
*/
export const OverlayDrawerMotion = createPresenceComponent<DrawerMotionParams>(({ position, size }) => {
const keyframes: Keyframe[] = [
{
...(position === 'start' && {
transform: `translate3D(calc(var(${drawerCSSVars.drawerSizeVar}) * -1), 0, 0)`,
}),
...(position === 'end' && {
transform: `translate3d(calc(var(${drawerCSSVars.drawerSizeVar}) * 1), 0, 0)`,
}),
...(position === 'bottom' && {
transform: `translate3d(0, calc(var(${drawerCSSVars.drawerSizeVar}) * 1), 0)`,
}),
boxShadow: `0px ${tokens.colorTransparentBackground}`,
opacity: 0,
},
{
transform: 'translate3d(0, 0, 0)',
boxShadow: tokens.shadow64,
opacity: 1,
},
];
const duration = durations[size];
return {
enter: {
keyframes,
duration,
easing: motionTokens.curveDecelerateMid,
},
exit: {
keyframes: [...keyframes].reverse(),
duration,
easing: motionTokens.curveAccelerateMin,
},
};
});
/**
* @internal
*/
export const OverlaySurfaceBackdropMotion = createPresenceComponent(({ size }: OverlayDrawerSurfaceMotionParams) => {
const keyframes = [{ opacity: 0 }, { opacity: 1 }];
const duration = durations[size];
return {
enter: {
keyframes,
easing: motionTokens.curveLinear,
duration,
},
exit: {
keyframes: [...keyframes].reverse(),
easing: motionTokens.curveLinear,
duration,
},
};
});
``` | /content/code_sandbox/packages/react-components/react-drawer/library/src/shared/drawerMotions.ts | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 782 |
```xml
/**
*/
import type { ContentsWithRoot } from '@nextcloud/files'
import { getCurrentUser } from '@nextcloud/auth'
import { Folder, Permission, davRemoteURL, davRootPath, getFavoriteNodes } from '@nextcloud/files'
import { CancelablePromise } from 'cancelable-promise'
import { getContents as filesContents } from './Files.ts'
import { client } from './WebdavClient.ts'
export const getContents = (path = '/'): CancelablePromise<ContentsWithRoot> => {
// We only filter root files for favorites, for subfolders we can simply reuse the files contents
if (path !== '/') {
return filesContents(path)
}
return new CancelablePromise((resolve, reject, cancel) => {
const promise = getFavoriteNodes(client)
.catch(reject)
.then((contents) => {
if (!contents) {
reject()
return
}
resolve({
contents,
folder: new Folder({
id: 0,
source: `${davRemoteURL}${davRootPath}`,
root: davRootPath,
owner: getCurrentUser()?.uid || null,
permissions: Permission.READ,
}),
})
})
cancel(() => promise.cancel())
})
}
``` | /content/code_sandbox/apps/files/src/services/Favorites.ts | xml | 2016-06-02T07:44:14 | 2024-08-16T18:23:54 | server | nextcloud/server | 26,415 | 275 |
```xml
export function Development() {}
``` | /content/code_sandbox/playground/react/src/development.ts | xml | 2016-10-28T10:37:16 | 2024-07-27T15:17:43 | fuse-box | fuse-box/fuse-box | 4,003 | 6 |
```xml
import asyncComponent from "@erxes/ui/src/components/AsyncComponent";
import React from "react";
import { Route, Routes } from "react-router-dom";
const Home = asyncComponent(
() =>
import(/* webpackChunkName: "Settings - Board Home" */ "./containers/Home")
);
const TaskHome = () => {
return <Home type="task" title="Task" />;
};
const routes = () => (
<Routes>
<Route path="/settings/boards/task" element={<TaskHome />} />
</Routes>
);
export default routes;
``` | /content/code_sandbox/packages/plugin-tasks-ui/src/settings/boards/routes.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 118 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSMainStoryboardFile</key>
<string>Main</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>
``` | /content/code_sandbox/example/OS X/SwiftOCR Example OS X/SwiftOCR Example OS X/Info.plist | xml | 2016-04-22T08:39:02 | 2024-08-16T08:32:39 | SwiftOCR | NMAC427/SwiftOCR | 4,616 | 304 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<definitions
xmlns="path_to_url"
xmlns:activiti="path_to_url"
targetNamespace="Examples">
<process id="oneTaskProcess">
<startEvent id="theStart" />
<sequenceFlow id="flow1" sourceRef="theStart" targetRef="theTask" />
<userTask id="theTask" name="The famous task" activiti:assignee="kermit" />
<sequenceFlow id="flow2" sourceRef="theTask" targetRef="theEnd" />
<endEvent id="theEnd" />
</process>
</definitions>
``` | /content/code_sandbox/modules/flowable-engine/src/test/resources/org/flowable/engine/test/api/v6/Flowable6ExecutionTest.testOneTaskProcess.bpmn20.xml | xml | 2016-10-13T07:21:43 | 2024-08-16T15:23:14 | flowable-engine | flowable/flowable-engine | 7,715 | 150 |
```xml
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
type IPropertyPaneConfiguration,
PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import { PropertyFieldPassword } from '@pnp/spfx-property-controls/lib/PropertyFieldPassword';
import * as strings from 'ChatStreamingWebPartStrings';
import ChatStreaming from './components/ChatStreaming';
import { IChatStreamingProps } from './components/IChatStreamingProps';
import { Providers, SharePointProvider } from '@microsoft/mgt-spfx';
export interface IChatStreamingWebPartProps {
openAiApiKey: string;
openAiApiEndpoint: string;
openAiApiDeploymentName: string;
}
export default class ChatStreamingWebPart extends BaseClientSideWebPart<IChatStreamingWebPartProps> {
private _isDarkTheme: boolean = false;
private _environmentMessage: string = '';
public render(): void {
const element: React.ReactElement<IChatStreamingProps> = React.createElement(
ChatStreaming,
{
openApiOptions: {
apiKey: this.properties.openAiApiKey,
endpoint: this.properties.openAiApiEndpoint,
deploymentName: this.properties.openAiApiDeploymentName
},
isDarkTheme: this._isDarkTheme,
environmentMessage: this._environmentMessage,
hasTeamsContext: !!this.context.sdks.microsoftTeams,
userDisplayName: this.context.pageContext.user.displayName,
httpClient: this.context.httpClient
}
);
ReactDom.render(element, this.domElement);
}
protected onInit(): Promise<void> {
if (!Providers.globalProvider) {
Providers.globalProvider = new SharePointProvider(this.context);
}
return this._getEnvironmentMessage().then(message => {
this._environmentMessage = message;
});
}
private _getEnvironmentMessage(): Promise<string> {
if (!!this.context.sdks.microsoftTeams) { // running in Teams, office.com or Outlook
return this.context.sdks.microsoftTeams.teamsJs.app.getContext()
.then(context => {
let environmentMessage: string = '';
switch (context.app.host.name) {
case 'Office': // running in Office
environmentMessage = this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentOffice : strings.AppOfficeEnvironment;
break;
case 'Outlook': // running in Outlook
environmentMessage = this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentOutlook : strings.AppOutlookEnvironment;
break;
case 'Teams': // running in Teams
case 'TeamsModern':
environmentMessage = this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentTeams : strings.AppTeamsTabEnvironment;
break;
default:
environmentMessage = strings.UnknownEnvironment;
}
return environmentMessage;
});
}
return Promise.resolve(this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentSharePoint : strings.AppSharePointEnvironment);
}
protected onThemeChanged(currentTheme: IReadonlyTheme | undefined): void {
if (!currentTheme) {
return;
}
this._isDarkTheme = !!currentTheme.isInverted;
const {
semanticColors
} = currentTheme;
if (semanticColors) {
this.domElement.style.setProperty('--bodyText', semanticColors.bodyText || null);
this.domElement.style.setProperty('--link', semanticColors.link || null);
this.domElement.style.setProperty('--linkHovered', semanticColors.linkHovered || null);
}
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
groupName: strings.BasicGroupName,
groupFields: [
PropertyPaneTextField('openAiApiEndpoint', {
label: strings.OpenAiApiEndpointFieldLabel
}),
PropertyPaneTextField('openAiApiDeploymentName', {
label: strings.OpenAiApiDeploymentFieldLabel
}),
PropertyFieldPassword("openAiApiKey", {
key: "openAiApiKey",
label: strings.OpenAiApiKeyFieldLabel,
value: this.properties.openAiApiKey
})
]
}
]
}
]
};
}
}
``` | /content/code_sandbox/samples/react-azure-openai-api-stream/src/webparts/chatStreaming/ChatStreamingWebPart.ts | xml | 2016-08-30T17:21:43 | 2024-08-16T18:41:32 | sp-dev-fx-webparts | pnp/sp-dev-fx-webparts | 2,027 | 975 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "path_to_url">
<mapper namespace="com.jsh.erp.datasource.mappers.TenantMapperEx">
<resultMap extends="com.jsh.erp.datasource.mappers.LogMapper.BaseResultMap" id="ResultMapEx" type="com.jsh.erp.datasource.entities.TenantEx">
<result column="userCount" jdbcType="VARCHAR" property="userCount" />
</resultMap>
<select id="selectByConditionTenant" parameterType="com.jsh.erp.datasource.entities.TenantExample" resultMap="ResultMapEx">
select jsh_tenant.*,
(select count(jsh_user.id) from jsh_user where jsh_user.Status='0' and jsh_user.tenant_id=jsh_tenant.tenant_id) userCount
FROM jsh_tenant
where 1=1
<if test="loginName != null">
<bind name="bindLoginName" value="'%'+loginName+'%'"/>
and login_name like #{bindLoginName}
</if>
<if test="type != null and type != ''">
and type = #{type}
</if>
<if test="enabled != null and enabled != ''">
and enabled = #{enabled}
</if>
<if test="remark != null">
<bind name="bindRemark" value="'%'+remark+'%'"/>
and remark like #{bindRemark}
</if>
order by id desc
<if test="offset != null and rows != null">
limit #{offset},#{rows}
</if>
</select>
<select id="countsByTenant" resultType="java.lang.Long">
SELECT
COUNT(id)
FROM jsh_tenant
WHERE 1=1
<if test="loginName != null">
<bind name="bindLoginName" value="'%'+loginName+'%'"/>
and login_name like #{bindLoginName}
</if>
<if test="type != null and type != ''">
and type = #{type}
</if>
<if test="enabled != null and enabled != ''">
and enabled = #{enabled}
</if>
<if test="remark != null">
<bind name="bindRemark" value="'%'+remark+'%'"/>
and remark like #{bindRemark}
</if>
</select>
</mapper>
``` | /content/code_sandbox/jshERP-boot/src/main/resources/mapper_xml/TenantMapperEx.xml | xml | 2016-09-20T04:51:39 | 2024-08-16T16:42:52 | jshERP | jishenghua/jshERP | 3,107 | 542 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<tileset name="sonic_md_bg1" tilewidth="8" tileheight="8" tilecount="304" columns="16">
<image source="Sonic_md_bg1.png" trans="2492db" width="128" height="152"/>
</tileset>
``` | /content/code_sandbox/samples/UsingTilengine/assets/sonic/Sonic_md_bg1.tsx | xml | 2016-03-24T10:29:27 | 2024-08-16T12:53:07 | ring | ring-lang/ring | 1,262 | 74 |
```xml
<resources>
<string name="app_name">Mock Location Detector Sample</string>
<string name="last_location_received_label">Last location received info</string>
<string name="latitude_label">Latitude:</string>
<string name="longitude_label">Longitude:</string>
<string name="last_update_label">Last Update:</string>
<string name="is_location_mock_label">Is Location Mock:</string>
<string name="are_mock_location_apps_present_label">Are Mock Location Apps Present:</string>
<string name="is_allow_mock_locations_on_label">Is Allow Mock Locations On:</string>
</resources>
``` | /content/code_sandbox/sample/src/main/res/values/strings.xml | xml | 2016-05-29T15:57:48 | 2024-08-14T09:53:36 | MockLocationDetector | smarques84/MockLocationDetector | 1,291 | 133 |
```xml
import Button from '@erxes/ui/src/components/Button';
import { IDictionary, IParent } from '../../types';
import Row from './Row';
import { IButtonMutateProps } from '@erxes/ui/src/types';
import { __ } from '@erxes/ui/src/utils';
import React from 'react';
import Form from './Form';
import { Title } from '@erxes/ui-settings/src/styles';
import ModalTrigger from '@erxes/ui/src/components/ModalTrigger';
import Wrapper from '@erxes/ui/src/layout/components/Wrapper';
import Table from '@erxes/ui/src/components/table';
import DataWithLoader from '@erxes/ui/src/components/DataWithLoader';
import asyncComponent from '@erxes/ui/src/components/AsyncComponent';
type Props = {
dictionaries: IDictionary[];
types: IParent[];
parentId: string;
renderButton: (props: IButtonMutateProps) => JSX.Element;
remove: (zms: IDictionary) => void;
loading: boolean;
};
function List({
dictionaries,
parentId,
types,
remove,
renderButton,
loading
}: Props) {
const trigger = (
<Button id={'AddDictionaryButton'} btnStyle="success" icon="plus-circle">
Add Dictionary
</Button>
);
const modalContent = props => (
<Form
{...props}
types={types}
parentId={parentId}
renderButton={renderButton}
/>
);
const actionBarRight = (
<ModalTrigger
title={__('Add Dictionary')}
trigger={trigger}
content={modalContent}
enforceFocus={false}
/>
);
const title = <Title capitalize={true}>{__('Parent')}</Title>;
const actionBar = (
<Wrapper.ActionBar left={title} right={actionBarRight} wideSpacing />
);
const content = (
<Table>
<thead>
<tr>
<th>{__('Startted')}</th>
<th>{__('Code')}</th>
<th>{__('Type')}</th>
<th>{__('Actions')}</th>
</tr>
</thead>
<tbody id={'ZmssShowing'}>
{dictionaries.map(dictionary => {
return (
<Row
space={0}
key={dictionary._id}
dictionary={dictionary}
parentId={parentId}
remove={remove}
renderButton={renderButton}
dictionaries={dictionaries}
parents={types}
/>
);
})}
</tbody>
</Table>
);
const SideBarList = asyncComponent(() =>
import(
/* webpackChunkName: "List - Zmss" */ '../../containers/dictionary/SideBarList'
)
);
return (
<Wrapper
header={
<Wrapper.Header
title={__('Zmss')}
submenu={[
{ title: 'Zms', link: '/plugin-zms/zms' },
{ title: 'Dictionary', link: '/plugin-zms/dictionary' }
]}
/>
}
actionBar={actionBar}
content={
<DataWithLoader
data={content}
loading={loading}
count={dictionaries.length}
emptyText={__('Theres no zms')}
emptyImage="/images/actions/8.svg"
/>
}
leftSidebar={<SideBarList currentTypeId={parentId} />}
transparent={true}
hasBorder
/>
);
}
export default List;
``` | /content/code_sandbox/packages/plugin-zms-ui/src/components/dictionary/List.tsx | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 722 |
```xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE root [
<!ENTITY x0 "DoS">
]>
<root>
test: (&x0;)
</root>
``` | /content/code_sandbox/tests/data/Reader/Xml/XEETestInvalidUTF-8.xml | xml | 2016-06-19T16:58:48 | 2024-08-16T14:51:45 | PhpSpreadsheet | PHPOffice/PhpSpreadsheet | 13,180 | 47 |
```xml
<schemalist>
<schema path="/org/gnome/gnome-screenshot/" id="org.gnome.gnome-screenshot">
<key type="b" name="take-window-shot">
<default>false</default>
<summary>Window-specific screenshot (deprecated)</summary>
<summary lang="an">Captura especifica de finestra (obsoleto)</summary>
<summary lang="ar"> ()</summary>
<summary lang="as"> ()</summary>
<summary lang="ast">Captura especfica de ventana (obsoleto)</summary>
<description>Bla</description>
</key>
</schema>
</schemalist>
``` | /content/code_sandbox/utilities/glib/gio/tests/schema-tests/summary-xmllang-and-attrs.gschema.xml | xml | 2016-10-27T09:31:28 | 2024-08-16T19:00:35 | nexmon | seemoo-lab/nexmon | 2,381 | 147 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>CFBundleDisplayName</key>
<string>SkiaSharp</string>
<key>CFBundleName</key>
<string>SkiaSharp</string>
<key>CFBundleIdentifier</key>
<string>com.companyname.skiasharpsample</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>MinimumOSVersion</key>
<string>9.0</string>
<key>UIDeviceFamily</key>
<array>
<integer>3</integer>
</array>
<key>UIMainStoryboardFile</key>
<string>Main</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>arm64</string>
</array>
<key>XSAppIconAssets</key>
<string>Assets.xcassets/App Icon & Top Shelf Image.brandassets</string>
<key>XSLaunchImageAssets</key>
<string>Assets.xcassets/LaunchImages.launchimage</string>
</dict>
</plist>
``` | /content/code_sandbox/samples/Gallery/tvOS/SkiaSharpSample/Info.plist | xml | 2016-02-22T17:54:43 | 2024-08-16T17:53:42 | SkiaSharp | mono/SkiaSharp | 4,347 | 304 |
```xml
import { OrderedWebRequest } from './ordered-webrequest'
/**
* Installs a web request filter to prevent cross domain leaks of auth headers
*
* GitHub Desktop uses the fetch[1] web API for all of our API requests. When fetch
* is used in a browser and it encounters an http redirect to another origin
* domain CORS policies will apply to prevent submission of credentials[2].
*
* In our case however there's no concept of same-origin (and even if there were
* it'd be problematic because we'd be making cross-origin request constantly to
* GitHub.com and GHE instances) so the `credentials: same-origin` setting won't
* help us.
*
* This is normally not a problem until http redirects get involved. When making
* an authenticated request to an API endpoint which in turn issues a redirect
* to another domain fetch will happily pass along our token to the second
* domain and there's no way for us to prevent that from happening[3] using
* the vanilla fetch API.
*
* That's the reason why this filter exists. It will look at all initiated
* requests and store their origin along with their request ID. The request id
* will be the same for any subsequent redirect requests but the urls will be
* changing. Upon each request we will check to see if we've seen the request
* id before and if so if the origin matches. If the origin doesn't match we'll
* strip some potentially dangerous headers from the redirect request.
*
* 1. path_to_url
* 2. path_to_url#http-network-or-cache-fetch
* 3. path_to_url
*
* @param orderedWebRequest
*/
export function installSameOriginFilter(orderedWebRequest: OrderedWebRequest) {
// A map between the request ID and the _initial_ request origin
const requestOrigin = new Map<number, string>()
const safeProtocols = new Set(['devtools:', 'file:', 'chrome-extension:'])
const unsafeHeaders = new Set(['authentication', 'authorization', 'cookie'])
orderedWebRequest.onBeforeRequest.addEventListener(async details => {
const { protocol, origin } = new URL(details.url)
// This is called once for the initial request and then once for each
// "subrequest" thereafter, i.e. a request to path_to_url which gets
// redirected to path_to_url will trigger this twice and we only
// care about capturing the initial request origin
if (!safeProtocols.has(protocol) && !requestOrigin.has(details.id)) {
requestOrigin.set(details.id, origin)
}
return {}
})
orderedWebRequest.onBeforeSendHeaders.addEventListener(async details => {
const initialOrigin = requestOrigin.get(details.id)
const { origin } = new URL(details.url)
if (initialOrigin === undefined || initialOrigin === origin) {
return { requestHeaders: details.requestHeaders }
}
const sanitizedHeaders: Record<string, string> = {}
for (const [k, v] of Object.entries(details.requestHeaders)) {
if (!unsafeHeaders.has(k.toLowerCase())) {
sanitizedHeaders[k] = v
}
}
log.debug(`Sanitizing cross-origin redirect to ${origin}`)
return { requestHeaders: sanitizedHeaders }
})
orderedWebRequest.onCompleted.addEventListener(details =>
requestOrigin.delete(details.id)
)
}
``` | /content/code_sandbox/app/src/main-process/same-origin-filter.ts | xml | 2016-05-11T15:59:00 | 2024-08-16T17:00:41 | desktop | desktop/desktop | 19,544 | 701 |
```xml
import { Mutant } from '@stryker-mutator/api/core';
import { toPosixFileName } from '../tsconfig-helpers.js';
// This class exist so we can have a two way dependency graph.
// the two way dependency graph is used to search for mutants related to typescript errors
export class TSFileNode {
constructor(
public fileName: string,
public parents: TSFileNode[],
public children: TSFileNode[],
) {}
public getAllParentReferencesIncludingSelf(allParentReferences: Set<TSFileNode> = new Set<TSFileNode>()): Set<TSFileNode> {
allParentReferences.add(this);
this.parents.forEach((parent) => {
if (!allParentReferences.has(parent)) {
parent.getAllParentReferencesIncludingSelf(allParentReferences);
}
});
return allParentReferences;
}
public getAllChildReferencesIncludingSelf(allChildReferences: Set<TSFileNode> = new Set<TSFileNode>()): Set<TSFileNode> {
allChildReferences.add(this);
this.children.forEach((child) => {
if (!allChildReferences.has(child)) {
child.getAllChildReferencesIncludingSelf(allChildReferences);
}
});
return allChildReferences;
}
public getMutantsWithReferenceToChildrenOrSelf(mutants: Mutant[], nodesChecked: string[] = []): Mutant[] {
if (nodesChecked.includes(this.fileName)) {
return [];
}
nodesChecked.push(this.fileName);
const relatedMutants = mutants.filter((m) => toPosixFileName(m.fileName) == this.fileName);
const childResult = this.children.flatMap((c) => c.getMutantsWithReferenceToChildrenOrSelf(mutants, nodesChecked));
return [...relatedMutants, ...childResult];
}
}
``` | /content/code_sandbox/packages/typescript-checker/src/grouping/ts-file-node.ts | xml | 2016-02-12T13:14:28 | 2024-08-15T18:38:25 | stryker-js | stryker-mutator/stryker-js | 2,561 | 377 |
```xml
type CheckableBase = {
checked?: boolean;
};
export type Checkable<T> = T & CheckableBase;
export function isChecked(item: CheckableBase): boolean {
return !!item.checked;
}
``` | /content/code_sandbox/libs/common/src/types/checkable.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 44 |
```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 dnanasumors = require( './index' );
// TESTS //
// The function returns a number...
{
const x = new Float64Array( 10 );
dnanasumors( x.length, x, 1 ); // $ExpectType number
}
// The compiler throws an error if the function is provided a first argument which is not a number...
{
const x = new Float64Array( 10 );
dnanasumors( '10', x, 1 ); // $ExpectError
dnanasumors( true, x, 1 ); // $ExpectError
dnanasumors( false, x, 1 ); // $ExpectError
dnanasumors( null, x, 1 ); // $ExpectError
dnanasumors( undefined, x, 1 ); // $ExpectError
dnanasumors( [], x, 1 ); // $ExpectError
dnanasumors( {}, x, 1 ); // $ExpectError
dnanasumors( ( x: number ): number => x, x, 1 ); // $ExpectError
}
// The compiler throws an error if the function is provided a second argument which is not a Float64Array...
{
const x = new Float64Array( 10 );
dnanasumors( x.length, 10, 1 ); // $ExpectError
dnanasumors( x.length, '10', 1 ); // $ExpectError
dnanasumors( x.length, true, 1 ); // $ExpectError
dnanasumors( x.length, false, 1 ); // $ExpectError
dnanasumors( x.length, null, 1 ); // $ExpectError
dnanasumors( x.length, undefined, 1 ); // $ExpectError
dnanasumors( x.length, [], 1 ); // $ExpectError
dnanasumors( x.length, {}, 1 ); // $ExpectError
dnanasumors( x.length, ( x: number ): number => x, 1 ); // $ExpectError
}
// The compiler throws an error if the function is provided a third argument which is not a number...
{
const x = new Float64Array( 10 );
dnanasumors( x.length, x, '10' ); // $ExpectError
dnanasumors( x.length, x, true ); // $ExpectError
dnanasumors( x.length, x, false ); // $ExpectError
dnanasumors( x.length, x, null ); // $ExpectError
dnanasumors( x.length, x, undefined ); // $ExpectError
dnanasumors( x.length, x, [] ); // $ExpectError
dnanasumors( x.length, x, {} ); // $ExpectError
dnanasumors( x.length, x, ( x: number ): number => x ); // $ExpectError
}
// The compiler throws an error if the function is provided an unsupported number of arguments...
{
const x = new Float64Array( 10 );
dnanasumors(); // $ExpectError
dnanasumors( x.length ); // $ExpectError
dnanasumors( x.length, x ); // $ExpectError
dnanasumors( x.length, x, 1, 10 ); // $ExpectError
}
// Attached to main export is an `ndarray` method which returns a number...
{
const x = new Float64Array( 10 );
dnanasumors.ndarray( x.length, x, 1, 0 ); // $ExpectType number
}
// The compiler throws an error if the `ndarray` method is provided a first argument which is not a number...
{
const x = new Float64Array( 10 );
dnanasumors.ndarray( '10', x, 1, 0 ); // $ExpectError
dnanasumors.ndarray( true, x, 1, 0 ); // $ExpectError
dnanasumors.ndarray( false, x, 1, 0 ); // $ExpectError
dnanasumors.ndarray( null, x, 1, 0 ); // $ExpectError
dnanasumors.ndarray( undefined, x, 1, 0 ); // $ExpectError
dnanasumors.ndarray( [], x, 1, 0 ); // $ExpectError
dnanasumors.ndarray( {}, x, 1, 0 ); // $ExpectError
dnanasumors.ndarray( ( x: number ): number => x, x, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided a second argument which is not a Float64Array...
{
const x = new Float64Array( 10 );
dnanasumors.ndarray( x.length, 10, 1, 0 ); // $ExpectError
dnanasumors.ndarray( x.length, '10', 1, 0 ); // $ExpectError
dnanasumors.ndarray( x.length, true, 1, 0 ); // $ExpectError
dnanasumors.ndarray( x.length, false, 1, 0 ); // $ExpectError
dnanasumors.ndarray( x.length, null, 1, 0 ); // $ExpectError
dnanasumors.ndarray( x.length, undefined, 1, 0 ); // $ExpectError
dnanasumors.ndarray( x.length, [], 1, 0 ); // $ExpectError
dnanasumors.ndarray( x.length, {}, 1, 0 ); // $ExpectError
dnanasumors.ndarray( x.length, ( x: number ): number => x, 1, 0 ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided a third argument which is not a number...
{
const x = new Float64Array( 10 );
dnanasumors.ndarray( x.length, x, '10', 0 ); // $ExpectError
dnanasumors.ndarray( x.length, x, true, 0 ); // $ExpectError
dnanasumors.ndarray( x.length, x, false, 0 ); // $ExpectError
dnanasumors.ndarray( x.length, x, null, 0 ); // $ExpectError
dnanasumors.ndarray( x.length, x, undefined, 0 ); // $ExpectError
dnanasumors.ndarray( x.length, x, [], 0 ); // $ExpectError
dnanasumors.ndarray( x.length, x, {}, 0 ); // $ExpectError
dnanasumors.ndarray( x.length, x, ( x: number ): number => x, 0 ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided a fourth argument which is not a number...
{
const x = new Float64Array( 10 );
dnanasumors.ndarray( x.length, x, 1, '10' ); // $ExpectError
dnanasumors.ndarray( x.length, x, 1, true ); // $ExpectError
dnanasumors.ndarray( x.length, x, 1, false ); // $ExpectError
dnanasumors.ndarray( x.length, x, 1, null ); // $ExpectError
dnanasumors.ndarray( x.length, x, 1, undefined ); // $ExpectError
dnanasumors.ndarray( x.length, x, 1, [] ); // $ExpectError
dnanasumors.ndarray( x.length, x, 1, {} ); // $ExpectError
dnanasumors.ndarray( x.length, x, 1, ( x: number ): number => x ); // $ExpectError
}
// The compiler throws an error if the `ndarray` method is provided an unsupported number of arguments...
{
const x = new Float64Array( 10 );
dnanasumors.ndarray(); // $ExpectError
dnanasumors.ndarray( x.length ); // $ExpectError
dnanasumors.ndarray( x.length, x ); // $ExpectError
dnanasumors.ndarray( x.length, x, 1 ); // $ExpectError
dnanasumors.ndarray( x.length, x, 1, 0, 10 ); // $ExpectError
}
``` | /content/code_sandbox/lib/node_modules/@stdlib/blas/ext/base/dnanasumors/docs/types/test.ts | xml | 2016-03-24T04:19:52 | 2024-08-16T09:03:19 | stdlib | stdlib-js/stdlib | 4,266 | 1,873 |
```xml
import {MShell} from '../model/mshell';
import {MObject} from "../model/mobject";
import {ApplicationContext} from "cad/context";
import {Stream} from "lstream";
import {MFace} from "../model/mface";
import {MEdge} from "../model/medge";
import {MSketchObject} from "../model/msketchObject";
import {MDatum, MDatumAxis} from "../model/mdatum";
import {MLoop} from "../model/mloop";
export function activate(ctx: ApplicationContext) {
const {streams, services} = ctx;
const shells$: Stream<MShell> = streams.craft.models.map(models => models.filter(m => m instanceof MShell)).remember();
const modelIndex$ = streams.craft.models.map(models => {
const index = new Map();
models.forEach(model => model.traverse(m => index.set(m.id, m)));
return index;
}).remember();
function reindexFace(face: MFace) {
face.traverseSketchRelatedEntities(obj => {
modelIndex$.value.set(obj.id, obj);
})
}
streams.cadRegistry = {
shells: shells$, modelIndex: modelIndex$
};
streams.cadRegistry.update = streams.cadRegistry.modelIndex;
const index = () => modelIndex$.value;
function getAllShells(): MShell[] {
return streams.cadRegistry.shells.value;
}
function findShell(shellId) {
return index().get(shellId);
}
function findFace(faceId) {
return index().get(faceId);
}
function findEdge(edgeId) {
return index().get(edgeId);
}
function findSketchObject(sketchObjectGlobalId) {
return index().get(sketchObjectGlobalId);
}
function findDatum(datumId) {
return index().get(datumId);
}
function findDatumAxis(datumAxisId) {
return index().get(datumAxisId);
}
function findLoop(loopId) {
return index().get(loopId);
}
function findEntity(entity, id) {
return index().get(id);
}
function find(id) {
return index().get(id);
}
services.cadRegistry = {
getAllShells, findShell, findFace, findEdge, findSketchObject, findEntity, findDatum, findDatumAxis, findLoop, find,
reindexFace,
get modelIndex() {
return streams.cadRegistry.modelIndex.value;
},
get models() {
return streams.craft.models.value;
},
get shells() {
return getAllShells();
}
};
ctx.cadRegistry = services.cadRegistry;
}
export interface CadRegistry {
getAllShells(): MShell[];
findShell(id: string): MShell;
findFace(id: string): MFace;
findEdge(id: string): MEdge;
findSketchObject(id: string): MSketchObject;
findEntity(id: string): MObject;
findDatum(id: string): MDatum;
findDatumAxis(id: string): MDatumAxis;
findLoop(id: string): MLoop;
find(id: string): MObject;
modelIndex: Map<string, MObject>;
models: MObject[];
shells: MObject[];
reindexFace(face: MFace);
}
export interface CadRegistryBundleContext {
cadRegistry: CadRegistry;
}
export const BundleName = "@CadRegistry";
``` | /content/code_sandbox/web/app/cad/craft/cadRegistryBundle.ts | xml | 2016-08-26T21:55:19 | 2024-08-15T01:02:53 | jsketcher | xibyte/jsketcher | 1,461 | 741 |
```xml
import { ValueObject } from '@standardnotes/domain-core'
import { EventTypeEnum } from './EventTypeEnum'
import type { EventTypeProps } from './EventTypeProps'
export class EventType extends ValueObject<EventTypeProps> {
static TYPES = EventTypeEnum
static create(type: number): EventType {
if (!Object.values(EventType.TYPES).includes(type)) {
throw new Error('Invalid message type')
}
if (typeof type !== 'number') {
throw new Error('Type must be a number')
}
return new EventType({ type })
}
isCommitRequest(): boolean {
return this.props.type === EventType.TYPES.ClientIsDebugRequestingServerToPerformCommit
}
get name(): string {
const keys = Object.keys(EventType.TYPES)
const values = Object.values(EventType.TYPES)
const index = values.indexOf(this.props.type)
return keys[index]
}
get value(): EventTypeEnum {
return this.props.type
}
}
``` | /content/code_sandbox/packages/docs-proto/lib/Event/EventType.ts | xml | 2016-06-08T11:16:51 | 2024-08-16T14:14:27 | WebClients | ProtonMail/WebClients | 4,300 | 207 |
```xml
import { useCallback } from 'react'
import { boostHubBaseUrl, mobileBaseUrl } from '../../cloud/lib/consts'
function useSignOut() {
return useCallback(() => {
window.location.href = `${boostHubBaseUrl}/api/user/signout?redirectTo=${mobileBaseUrl}`
}, [])
}
export default useSignOut
``` | /content/code_sandbox/src/mobile/lib/signOut.ts | xml | 2016-11-19T14:30:34 | 2024-08-16T03:13:45 | BoostNote-App | BoostIO/BoostNote-App | 3,745 | 67 |
```xml
export const data = `name,url,username,password
,android://your_sha512_hash==@com.xyz.example.app.android/,username@example.com,Qh6W4Wz55YGFNU`;
``` | /content/code_sandbox/libs/importer/spec/test-data/chrome-csv/android-data.csv.ts | xml | 2016-03-09T23:14:01 | 2024-08-16T15:07:51 | clients | bitwarden/clients | 8,877 | 42 |
```xml
<vector xmlns:android="path_to_url"
android:width="128dp"
android:height="128dp"
android:viewportWidth="128"
android:viewportHeight="128">
<path
android:pathData="m74,0h4v128h-4z"
android:fillColor="#eee"/>
<path
android:pathData="m72,0h2v128h-2z"
android:fillColor="#bbb"/>
<path
android:pathData="M0,0h72v128h-72z"
android:fillColor="#808080"/>
<path
android:pathData="m74,0v5.4h4v-5.4zM74,14.4v9h4v-9zM74,32.4v9h4v-9zM74,50.4v9h4v-9zM74,68.4v9h4v-9zM74,86.4v9h4v-9zM74,104.4v9h4v-9zM74,122.4v5.6h4v-5.6z"
android:fillColor="#f00"/>
<path
android:pathData="m72,0v5.4h2v-5.4zM72,14.4v9h2v-9zM72,32.4v9h2v-9zM72,50.4v9h2v-9zM72,68.4v9h2v-9zM72,86.4v9h2v-9zM72,104.4v9h2v-9zM72,122.4v5.6h2v-5.6z"
android:fillColor="#a00"/>
<path
android:pathData="m78,0h2v128h-2z"
android:fillColor="#999"/>
</vector>
``` | /content/code_sandbox/app/src/main/res/drawable/ic_street_marking_red_white_dashes_on_curb.xml | xml | 2016-07-02T10:44:04 | 2024-08-16T18:55:54 | StreetComplete | streetcomplete/StreetComplete | 3,781 | 426 |
```xml
import { PageConfig, URLExt } from '@jupyterlab/coreutils';
import { ServerConnection } from '../serverconnection';
/**
* The url for the lab build service.
*/
const BUILD_SETTINGS_URL = 'api/build';
/**
* The build API service manager.
*/
export class BuildManager {
/**
* Create a new setting manager.
*/
constructor(options: BuildManager.IOptions = {}) {
this.serverSettings =
options.serverSettings ?? ServerConnection.makeSettings();
const { baseUrl, appUrl } = this.serverSettings;
this._url = URLExt.join(baseUrl, appUrl, BUILD_SETTINGS_URL);
}
/**
* The server settings used to make API requests.
*/
readonly serverSettings: ServerConnection.ISettings;
/**
* Test whether the build service is available.
*/
get isAvailable(): boolean {
return PageConfig.getOption('buildAvailable').toLowerCase() === 'true';
}
/**
* Test whether to check build status automatically.
*/
get shouldCheck(): boolean {
return PageConfig.getOption('buildCheck').toLowerCase() === 'true';
}
/**
* Get whether the application should be built.
*/
getStatus(): Promise<BuildManager.IStatus> {
const { _url, serverSettings } = this;
const promise = ServerConnection.makeRequest(_url, {}, serverSettings);
return promise
.then(response => {
if (response.status !== 200) {
throw new ServerConnection.ResponseError(response);
}
return response.json();
})
.then(data => {
if (typeof data.status !== 'string') {
throw new Error('Invalid data');
}
if (typeof data.message !== 'string') {
throw new Error('Invalid data');
}
return data;
});
}
/**
* Build the application.
*/
build(): Promise<void> {
const { _url, serverSettings } = this;
const init = { method: 'POST' };
const promise = ServerConnection.makeRequest(_url, init, serverSettings);
return promise.then(response => {
if (response.status === 400) {
throw new ServerConnection.ResponseError(response, 'Build aborted');
}
if (response.status !== 200) {
const message = `Build failed with ${response.status}.
If you are experiencing the build failure after installing an extension (or trying to include previously installed extension after updating JupyterLab) please check the extension repository for new installation instructions as many extensions migrated to the prebuilt extensions system which no longer requires rebuilding JupyterLab (but uses a different installation procedure, typically involving a package manager such as 'pip' or 'conda').
If you specifically intended to install a source extension, please run 'jupyter lab build' on the server for full output.`;
throw new ServerConnection.ResponseError(response, message);
}
});
}
/**
* Cancel an active build.
*/
cancel(): Promise<void> {
const { _url, serverSettings } = this;
const init = { method: 'DELETE' };
const promise = ServerConnection.makeRequest(_url, init, serverSettings);
return promise.then(response => {
if (response.status !== 204) {
throw new ServerConnection.ResponseError(response);
}
});
}
private _url = '';
}
/**
* A namespace for `BuildManager` statics.
*/
export namespace BuildManager {
/**
* The instantiation options for a setting manager.
*/
export interface IOptions {
/**
* The server settings used to make API requests.
*/
serverSettings?: ServerConnection.ISettings;
}
/**
* The build status response from the server.
*/
export interface IStatus {
/**
* Whether a build is needed.
*/
readonly status: 'stable' | 'needed' | 'building';
/**
* The message associated with the build status.
*/
readonly message: string;
}
}
/**
* A namespace for builder API interfaces.
*/
export namespace Builder {
/**
* The interface for the build manager.
*/
export interface IManager extends BuildManager {}
}
``` | /content/code_sandbox/packages/services/src/builder/index.ts | xml | 2016-06-03T20:09:17 | 2024-08-16T19:12:44 | jupyterlab | jupyterlab/jupyterlab | 14,019 | 879 |
```xml
import { getBoolElementToolbox } from '../elements/bool-element';
import { ElementType } from '../elements/elements';
import { getImageElementToolbox } from '../elements/image-element';
import { getStaticTextElementToolbox } from '../elements/static-text-element';
import { getTextElementToolbox } from '../elements/text-element';
export const ToolboxConfig = {
[ElementType.TEXT]: getTextElementToolbox(),
[ElementType.BOOL]: getBoolElementToolbox(),
[ElementType.STATIC_TEXT]: getStaticTextElementToolbox(),
[ElementType.IMAGE]: getImageElementToolbox(),
};
``` | /content/code_sandbox/src/renderer/views/admin/views/add/designer/tabs/details/toolbox/toolbox-config.ts | xml | 2016-05-14T02:18:49 | 2024-08-16T02:46:28 | ElectroCRUD | garrylachman/ElectroCRUD | 1,538 | 121 |
```xml
/* eslint-disable @typescript-eslint/no-empty-function */
import {
Box,
Center,
HStack,
SimpleGrid,
Spacer,
Spinner,
} from '@chakra-ui/react';
import { joiResolver } from '@hookform/resolvers/joi';
import * as Joi from 'joi';
import { omit } from 'underscore';
import { useContext, useEffect } from 'react';
import { FormProvider, useForm } from 'react-hook-form';
import { useNavigate } from 'react-router-dom';
import { Alert } from '@electrocrud/feedback';
import { ConfirmPromiseSaveModal } from 'renderer/components/modals/confirm-promise-save-modal';
import {
ViewScopedContext,
ViewScopedContextProvider,
} from 'renderer/contexts';
import { ViewRO } from 'renderer/defenitions/record-object';
import { useAppDispatch, useAppSelector } from 'renderer/store/hooks';
import { ViewsReducer } from 'renderer/store/reducers';
import { BasicDetailsCard } from './components/basic-details-card';
import { PermissionsCard } from './components/permissions-card';
import { TableColumnsCard } from './components/table-columns-card';
import { TerminologyCard } from './components/terminology-card';
import { ViewsInfoAlert } from './components/views-info-alert';
import { SaveButton } from '@electrocrud/buttons';
type FormData = Omit<ViewRO, 'id' | 'creationDate' | 'modificationDate'>;
const validationSchema = Joi.object<FormData>({
name: Joi.string().min(3).max(30).required(),
table: Joi.string().min(1).max(128).required(),
terminology: Joi.object({
plural: Joi.string().min(3).max(30).required(),
singular: Joi.string().min(3).max(30).required(),
}),
permissions: Joi.object({
create: Joi.boolean(),
read: Joi.boolean(),
update: Joi.boolean(),
delete: Joi.boolean(),
}),
metadata: Joi.object().optional(),
});
export const AddOrEditView = () => {
const { viewState, hasPrimaryKey } = useContext(ViewScopedContext);
const sessionState = useAppSelector((state) => state.session);
const navigate = useNavigate();
const dispatch = useAppDispatch();
const handleCreateOrUpdate = (data: ViewRO) => {
ConfirmPromiseSaveModal({ entityName: data.name || data.table })
.then((value) => {
if (value && viewState?.id) {
const response = dispatch(
ViewsReducer.actions.updateOne({ ...viewState, ...data })
);
} else {
const response = dispatch(
ViewsReducer.actions.addOne({ ...viewState, ...data })
);
if (response && response.payload && response.payload.id) {
navigate(`../${response?.payload?.id}/edit`);
}
}
return true;
})
.catch(() => {});
};
const formContext = useForm<FormData>({
resolver: joiResolver(validationSchema),
reValidateMode: 'onChange',
mode: 'all',
defaultValues: omit(viewState, [
'id',
'creationDate',
'modificationDate',
'accountId',
'columns',
]),
});
const {
watch,
reset,
handleSubmit,
formState: { isValid },
} = formContext;
useEffect(() => {
reset(
omit(viewState, [
'id',
'creationDate',
'modificationDate',
'accountId',
'columns',
])
);
}, [viewState]);
if (!sessionState.isConnected) {
return (
<Center>
<Spinner />
</Center>
);
}
return (
<Box height="-webkit-fill-available" width="100%">
{viewState?.id === undefined && (
<>
<ViewsInfoAlert />
<Spacer p={3} />
</>
)}
<FormProvider {...formContext}>
{viewState && viewState.id && (
<form onSubmit={handleSubmit(handleCreateOrUpdate)}>
<BasicDetailsCard isEditMode={viewState?.id !== undefined} />
<Spacer p={3} />
<>
<TableColumnsCard viewId={viewState?.id} />
<Spacer p={3} />
{!hasPrimaryKey && (
<>
<Alert
status="warning"
title="Primary key is missing"
description="In order to do use Modify operations (Create / Update /
Delete) a primary column must be definded."
/>
<Spacer p={3} />
</>
)}
<SimpleGrid columns={{ sm: 1, md: 2 }} spacing={{ base: '20px' }}>
<TerminologyCard />
<PermissionsCard
key={`permissions-${viewState?.id || ''}`}
canModify={hasPrimaryKey}
/>
</SimpleGrid>
<Spacer p={3} />
</>
<HStack justifyContent="space-between">
<SaveButton type="submit" isDisabled={!isValid} />
</HStack>
</form>
)}
</FormProvider>
</Box>
);
};
export const AddNew = () => {
return (
<ViewScopedContextProvider>
<AddOrEditView />
</ViewScopedContextProvider>
);
};
``` | /content/code_sandbox/src/renderer/views/admin/views/add/index.tsx | xml | 2016-05-14T02:18:49 | 2024-08-16T02:46:28 | ElectroCRUD | garrylachman/ElectroCRUD | 1,538 | 1,126 |
```xml
/**
* @package
* @module index
*/
/* eslint-disable filenames/match-regex */
import * as assert from "assert";
import { BaseOutput } from "./BaseOutput";
export class MainOutput extends BaseOutput {
constructor() {
super();
this._pending = 0;
}
_addSpot(data) {
const x = this.add(data);
this._pending++;
return x;
}
_closeSpot(x) {
assert(this._items[x._spotPos()] === x, "closing unknown pending");
this._pending--;
}
_hasPending() {
return this._pending > 0;
}
}
``` | /content/code_sandbox/packages/xarc-render-context/src/MainOutput.ts | xml | 2016-09-06T19:02:39 | 2024-08-11T11:43:11 | electrode | electrode-io/electrode | 2,103 | 140 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "path_to_url">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.debugger</key>
<true/>
</dict>
</plist>
``` | /content/code_sandbox/gnu/llvm/lldb/resources/debugserver-macosx-entitlements.plist | xml | 2016-08-30T18:18:25 | 2024-08-16T17:21:09 | src | openbsd/src | 3,139 | 71 |
```xml
import { ModalType } from '@@/modals';
import { ConfirmCallback, openConfirm } from '@@/modals/confirm';
import { buildConfirmButton } from '@@/modals/utils';
export async function confirmImageExport(callback: ConfirmCallback) {
const result = await openConfirm({
modalType: ModalType.Warn,
title: 'Caution',
message:
'The export may take several minutes, do not navigate away whilst the export is in progress.',
confirmButton: buildConfirmButton('Continue'),
});
callback(result);
}
``` | /content/code_sandbox/app/react/docker/images/common/ConfirmExportModal.tsx | xml | 2016-05-19T20:15:28 | 2024-08-16T19:15:14 | portainer | portainer/portainer | 30,083 | 119 |
```xml
import {
gql,
HydrogenRouteProps,
type HydrogenApiRouteOptions,
type HydrogenRequest,
useLocalization,
useShopQuery,
useUrl,
} from '@shopify/hydrogen';
import {PRODUCT_CARD_FRAGMENT} from '~/lib/fragments';
import {ProductGrid, Section, Text} from '~/components';
import {NoResultRecommendations, SearchPage} from '~/components/index.server';
import {PAGINATION_SIZE} from '~/lib/const';
import type {Collection} from '@shopify/hydrogen/storefront-api-types';
import {Suspense} from 'react';
export default function Search({
pageBy = PAGINATION_SIZE,
params,
}: {
pageBy?: number;
params: HydrogenRouteProps['params'];
}) {
const {
language: {isoCode: languageCode},
country: {isoCode: countryCode},
} = useLocalization();
const {handle} = params;
const {searchParams} = useUrl();
const searchTerm = searchParams.get('q');
const {data} = useShopQuery<any>({
query: SEARCH_QUERY,
variables: {
handle,
country: countryCode,
language: languageCode,
pageBy,
searchTerm,
},
preload: true,
});
const products = data?.products;
const noResults = products?.nodes?.length === 0;
if (!searchTerm || noResults) {
return (
<SearchPage searchTerm={searchTerm ? decodeURI(searchTerm) : null}>
{noResults && (
<Section padding="x">
<Text className="opacity-50">No results, try something else.</Text>
</Section>
)}
<Suspense>
<NoResultRecommendations
country={countryCode}
language={languageCode}
/>
</Suspense>
</SearchPage>
);
}
return (
<SearchPage searchTerm={decodeURI(searchTerm)}>
<Section>
<ProductGrid
key="search"
url={`/search?country=${countryCode}&q=${searchTerm}`}
collection={{products} as Collection}
/>
</Section>
</SearchPage>
);
}
// API to paginate the results of the search query.
// @see templates/demo-store/src/components/product/ProductGrid.client.tsx
export async function api(
request: HydrogenRequest,
{params, queryShop}: HydrogenApiRouteOptions,
) {
if (request.method !== 'POST') {
return new Response('Method not allowed', {
status: 405,
headers: {Allow: 'POST'},
});
}
const url = new URL(request.url);
const cursor = url.searchParams.get('cursor');
const country = url.searchParams.get('country');
const searchTerm = url.searchParams.get('q');
const {handle} = params;
return await queryShop({
query: PAGINATE_SEARCH_QUERY,
variables: {
handle,
cursor,
pageBy: PAGINATION_SIZE,
country,
searchTerm,
},
});
}
const SEARCH_QUERY = gql`
${PRODUCT_CARD_FRAGMENT}
query search(
$searchTerm: String
$country: CountryCode
$language: LanguageCode
$pageBy: Int!
$after: String
) @inContext(country: $country, language: $language) {
products(
first: $pageBy
sortKey: RELEVANCE
query: $searchTerm
after: $after
) {
nodes {
...ProductCard
}
pageInfo {
startCursor
endCursor
hasNextPage
hasPreviousPage
}
}
}
`;
const PAGINATE_SEARCH_QUERY = gql`
${PRODUCT_CARD_FRAGMENT}
query ProductsPage(
$searchTerm: String
$pageBy: Int!
$cursor: String
$country: CountryCode
$language: LanguageCode
) @inContext(country: $country, language: $language) {
products(
sortKey: RELEVANCE
query: $searchTerm
first: $pageBy
after: $cursor
) {
nodes {
...ProductCard
}
pageInfo {
hasNextPage
endCursor
}
}
}
`;
``` | /content/code_sandbox/packages/hydrogen/test/fixtures/demo-store-ts/src/routes/search.server.tsx | xml | 2016-09-09T01:12:08 | 2024-08-16T17:39:45 | vercel | vercel/vercel | 12,545 | 925 |
```xml
import * as React from 'react';
import createSvgIcon from '../utils/createSvgIcon';
const AsteriskIcon = createSvgIcon({
svg: ({ classes }) => (
<svg xmlns="path_to_url" viewBox="0 0 2048 2048" className={classes.svg} focusable="false">
<path d="M1943 568l-791 456 791 456-64 112-791-457v913H960v-913l-791 457-64-112 791-456-791-456 64-112 791 457V0h128v913l791-457 64 112z" />
</svg>
),
displayName: 'AsteriskIcon',
});
export default AsteriskIcon;
``` | /content/code_sandbox/packages/react-icons-mdl2/src/components/AsteriskIcon.tsx | xml | 2016-06-06T15:03:44 | 2024-08-16T18:49:29 | fluentui | microsoft/fluentui | 18,221 | 166 |
```xml
import cn from "classnames";
import React, { FunctionComponent, TextareaHTMLAttributes } from "react";
import styles from "./Textarea.css";
interface Props extends TextareaHTMLAttributes<HTMLTextAreaElement> {
className?: string;
fullwidth?: boolean;
}
const Textarea: FunctionComponent<Props> = ({
className,
children,
fullwidth,
...rest
}) => (
<textarea
{...rest}
className={cn(
styles.root,
{
[styles.fullwidth]: fullwidth,
},
className
)}
>
{children}
</textarea>
);
export default Textarea;
``` | /content/code_sandbox/client/src/core/client/ui/components/v2/Textarea/Textarea.tsx | xml | 2016-10-31T16:14:05 | 2024-08-06T16:15:57 | talk | coralproject/talk | 1,881 | 132 |
```xml
/*
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
path_to_url
*/
import {
Asset,
Chunk,
Compilation,
ModuleFilenameHelpers,
WebpackError,
} from 'webpack';
import {transformManifest} from 'workbox-build/build/lib/transform-manifest';
import {
WebpackGenerateSWOptions,
WebpackInjectManifestOptions,
ManifestEntry,
FileDetails,
} from 'workbox-build';
import {getAssetHash} from './get-asset-hash';
import {resolveWebpackURL} from './resolve-webpack-url';
/**
* For a given asset, checks whether at least one of the conditions matches.
*
* @param {Asset} asset The webpack asset in question. This will be passed
* to any functions that are listed as conditions.
* @param {Compilation} compilation The webpack compilation. This will be passed
* to any functions that are listed as conditions.
* @param {Array<string|RegExp|Function>} conditions
* @return {boolean} Whether or not at least one condition matches.
* @private
*/
function checkConditions(
asset: Asset,
compilation: Compilation,
conditions: Array<
//eslint-disable-next-line @typescript-eslint/ban-types
string | RegExp | ((arg0: any) => boolean)
> = [],
): boolean {
for (const condition of conditions) {
if (typeof condition === 'function') {
return condition({asset, compilation});
//return compilation !== null;
} else {
if (ModuleFilenameHelpers.matchPart(asset.name, condition)) {
return true;
}
}
}
// We'll only get here if none of the conditions applied.
return false;
}
/**
* Returns the names of all the assets in all the chunks in a chunk group,
* if provided a chunk group name.
* Otherwise, if provided a chunk name, return all the assets in that chunk.
* Otherwise, if there isn't a chunk group or chunk with that name, return null.
*
* @param {Compilation} compilation
* @param {string} chunkOrGroup
* @return {Array<string>|null}
* @private
*/
function getNamesOfAssetsInChunkOrGroup(
compilation: Compilation,
chunkOrGroup: string,
): Array<string> | null {
const chunkGroup =
compilation.namedChunkGroups &&
compilation.namedChunkGroups.get(chunkOrGroup);
if (chunkGroup) {
const assetNames = [];
for (const chunk of chunkGroup.chunks) {
assetNames.push(...getNamesOfAssetsInChunk(chunk));
}
return assetNames;
} else {
const chunk =
compilation.namedChunks && compilation.namedChunks.get(chunkOrGroup);
if (chunk) {
return getNamesOfAssetsInChunk(chunk);
}
}
// If we get here, there's no chunkGroup or chunk with that name.
return null;
}
/**
* Returns the names of all the assets in a chunk.
*
* @param {Chunk} chunk
* @return {Array<string>}
* @private
*/
function getNamesOfAssetsInChunk(chunk: Chunk): Array<string> {
const assetNames: Array<string> = [];
assetNames.push(...chunk.files);
// This only appears to be set in webpack v5.
if (chunk.auxiliaryFiles) {
assetNames.push(...chunk.auxiliaryFiles);
}
return assetNames;
}
/**
* Filters the set of assets out, based on the configuration options provided:
* - chunks and excludeChunks, for chunkName-based criteria.
* - include and exclude, for more general criteria.
*
* @param {Compilation} compilation The webpack compilation.
* @param {Object} config The validated configuration, obtained from the plugin.
* @return {Set<Asset>} The assets that should be included in the manifest,
* based on the criteria provided.
* @private
*/
function filterAssets(
compilation: Compilation,
config: WebpackInjectManifestOptions | WebpackGenerateSWOptions,
): Set<Asset> {
const filteredAssets = new Set<Asset>();
const assets = compilation.getAssets();
const allowedAssetNames = new Set<string>();
// See path_to_url
if (Array.isArray(config.chunks)) {
for (const name of config.chunks) {
// See path_to_url
const assetsInChunkOrGroup = getNamesOfAssetsInChunkOrGroup(
compilation,
name,
);
if (assetsInChunkOrGroup) {
for (const assetName of assetsInChunkOrGroup) {
allowedAssetNames.add(assetName);
}
} else {
compilation.warnings.push(
new Error(
`The chunk '${name}' was ` +
`provided in your Workbox chunks config, but was not found in the ` +
`compilation.`,
) as WebpackError,
);
}
}
}
const deniedAssetNames = new Set();
if (Array.isArray(config.excludeChunks)) {
for (const name of config.excludeChunks) {
// See path_to_url
const assetsInChunkOrGroup = getNamesOfAssetsInChunkOrGroup(
compilation,
name,
);
if (assetsInChunkOrGroup) {
for (const assetName of assetsInChunkOrGroup) {
deniedAssetNames.add(assetName);
}
} // Don't warn if the chunk group isn't found.
}
}
for (const asset of assets) {
// chunk based filtering is funky because:
// - Each asset might belong to one or more chunks.
// - If *any* of those chunk names match our config.excludeChunks,
// then we skip that asset.
// - If the config.chunks is defined *and* there's no match
// between at least one of the chunkNames and one entry, then
// we skip that assets as well.
if (deniedAssetNames.has(asset.name)) {
continue;
}
if (Array.isArray(config.chunks) && !allowedAssetNames.has(asset.name)) {
continue;
}
// Next, check asset-level checks via includes/excludes:
const isExcluded = checkConditions(asset, compilation, config.exclude);
if (isExcluded) {
continue;
}
// Treat an empty config.includes as an implicit inclusion.
const isIncluded =
!Array.isArray(config.include) ||
checkConditions(asset, compilation, config.include);
if (!isIncluded) {
continue;
}
// If we've gotten this far, then add the asset.
filteredAssets.add(asset);
}
return filteredAssets;
}
export async function getManifestEntriesFromCompilation(
compilation: Compilation,
config: WebpackGenerateSWOptions | WebpackInjectManifestOptions,
): Promise<{size: number; sortedEntries: ManifestEntry[]}> {
const filteredAssets = filterAssets(compilation, config);
const {publicPath} = compilation.options.output;
const fileDetails = Array.from(filteredAssets).map((asset) => {
return {
file: resolveWebpackURL(publicPath as string, asset.name),
hash: getAssetHash(asset),
size: asset.source.size() || 0,
} as FileDetails;
});
const {manifestEntries, size, warnings} = await transformManifest({
fileDetails,
additionalManifestEntries: config.additionalManifestEntries,
dontCacheBustURLsMatching: config.dontCacheBustURLsMatching,
manifestTransforms: config.manifestTransforms,
maximumFileSizeToCacheInBytes: config.maximumFileSizeToCacheInBytes,
modifyURLPrefix: config.modifyURLPrefix,
transformParam: compilation,
});
// See path_to_url
for (const warning of warnings) {
compilation.warnings.push(new Error(warning) as WebpackError);
}
// Ensure that the entries are properly sorted by URL.
const sortedEntries = manifestEntries.sort((a, b) =>
a.url === b.url ? 0 : a.url > b.url ? 1 : -1,
);
return {size, sortedEntries};
}
``` | /content/code_sandbox/packages/workbox-webpack-plugin/src/lib/get-manifest-entries-from-compilation.ts | xml | 2016-04-04T15:55:19 | 2024-08-16T08:33:26 | workbox | GoogleChrome/workbox | 12,245 | 1,732 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="path_to_url"
android:duration="300"
android:fromYDelta="0%"
android:toYDelta="50%"
android:interpolator="@android:anim/decelerate_interpolator"
android:fromXDelta="0%"
android:toXDelta="50%"
android:fillAfter="true">
</translate>
``` | /content/code_sandbox/app/src/main/res/anim/move_out.xml | xml | 2016-01-18T09:57:32 | 2024-08-02T07:44:55 | coolMenu | notice501/coolMenu | 1,286 | 95 |
```xml
<controls:ContentPopup x:Class="Telegram.Views.Settings.Popups.SettingsDataAutoPopup"
xmlns="path_to_url"
xmlns:x="path_to_url"
xmlns:local="using:Telegram.Views"
xmlns:controls="using:Telegram.Controls"
xmlns:d="path_to_url"
xmlns:mc="path_to_url"
mc:Ignorable="d"
Title="{x:Bind ViewModel.Title, Mode=OneWay}"
PrimaryButtonClick="{x:Bind ViewModel.Save}">
<Grid>
<ScrollViewer x:Name="ScrollingHost"
VerticalScrollBarVisibility="Auto"
VerticalScrollMode="Auto">
<StackPanel Spacing="8">
<TextBlock Text="{x:Bind ViewModel.Header, Mode=OneWay}"
Style="{StaticResource BaseTextBlockStyle}" />
<CheckBox IsChecked="{x:Bind ViewModel.Contacts, Mode=TwoWay}"
Content="{CustomResource AutodownloadContacts}" />
<CheckBox IsChecked="{x:Bind ViewModel.PrivateChats, Mode=TwoWay}"
Content="{CustomResource AutodownloadPrivateChats}" />
<CheckBox IsChecked="{x:Bind ViewModel.Groups, Mode=TwoWay}"
Content="{CustomResource AutodownloadGroupChats}" />
<CheckBox IsChecked="{x:Bind ViewModel.Channels, Mode=TwoWay}"
Content="{CustomResource AutodownloadChannels}" />
<StackPanel Visibility="{x:Bind ViewModel.IsLimitSupported, Mode=OneWay, Converter={StaticResource BooleanToVisibilityConverter}}">
<TextBlock Text="{CustomResource AutoDownloadMaxFileSize}"
Style="{StaticResource BaseTextBlockStyle}"
Margin="0,16,0,0" />
<Slider Value="{x:Bind ConvertLimit(ViewModel.Limit), Mode=TwoWay, BindBack=ConvertLimitBack}"
Minimum="0"
Maximum="1"
SmallChange="0.01"
LargeChange="0.1"
StepFrequency="0.01"
TickFrequency="0.25"
TickPlacement="Outside"
IsThumbToolTipEnabled="False"
Margin="0,8,0,8" />
<TextBlock Text="{x:Bind ConvertUpTo(ViewModel.Limit), Mode=OneWay}"
Style="{StaticResource InfoCaptionTextBlockStyle}"
Margin="0,0,0,8" />
</StackPanel>
</StackPanel>
</ScrollViewer>
</Grid>
</controls:ContentPopup>
``` | /content/code_sandbox/Telegram/Views/Settings/Popups/SettingsDataAutoPopup.xaml | xml | 2016-05-23T09:03:33 | 2024-08-16T16:17:48 | Unigram | UnigramDev/Unigram | 3,744 | 520 |
```xml
/**
* Type representing base dev launcher configuration.
*/
export type PluginConfigType = PluginConfigOptionsByPlatform & PluginConfigOptions;
/**
* Type representing available configuration for each platform.
*/
export type PluginConfigOptionsByPlatform = {
/**
* Type representing available configuration for Android dev launcher.
* @platform android
*/
android?: PluginConfigOptions;
/**
* Type representing available configuration for iOS dev launcher.
* @platform ios
*/
ios?: PluginConfigOptions;
};
/**
* Type representing available configuration for dev launcher.
*/
export type PluginConfigOptions = {
/**
* Determines whether to launch the most recently opened project or navigate to the launcher screen.
*
* - `'most-recent'` - Attempt to launch directly into a previously opened project and if unable to connect,
* fall back to the launcher screen.
*
* - `'launcher'` - Opens the launcher screen.
*
* @default 'most-recent'
*/
launchMode?: 'most-recent' | 'launcher';
/**
* @deprecated use the `launchMode` property instead
*/
launchModeExperimental?: 'most-recent' | 'launcher';
};
/**
* @ignore
*/
export declare function validateConfig<T>(config: T): PluginConfigType;
``` | /content/code_sandbox/packages/expo-dev-launcher/plugin/build/pluginConfig.d.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 272 |
```xml
import { mode } from '../tools';
function baseStyle({ isVertical, ...props }: Record<string, any>) {
return {
flexDirection: isVertical ? 'column-reverse' : 'row-reverse',
space: -4,
_avatar: {
borderColor: mode('gray.50', 'gray.800')(props),
borderWidth: 2,
},
_hiddenAvatarPlaceholder: {
bg: mode('gray.600', 'gray.100')(props),
},
};
}
export default {
baseStyle,
defaultProps: {
isVertical: false,
},
};
``` | /content/code_sandbox/src/theme/v33x-theme/components/avatar-group.ts | xml | 2016-04-15T11:37:23 | 2024-08-14T16:16:44 | NativeBase | GeekyAnts/NativeBase | 20,132 | 128 |
```xml
<Page x:Class="UITests.App.HomePage"
xmlns="path_to_url"
xmlns:x="path_to_url"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<TextBlock HorizontalAlignment="Center"
VerticalAlignment="Center"
Text="No test loaded." />
</Page>
``` | /content/code_sandbox/UITests/UITests.App/HomePage.xaml | xml | 2016-06-17T21:29:46 | 2024-08-16T09:32:00 | WindowsCommunityToolkit | CommunityToolkit/WindowsCommunityToolkit | 5,842 | 65 |
```xml
import { Asset } from 'expo-asset';
/**
* The different types of assets you can provide to the [`loadAsync()`](#loadasyncfontfamilyorfontmap-source) function.
* A font source can be a URI, a module ID, or an Expo Asset.
*/
export type FontSource = string | number | Asset | FontResource;
/**
* An object used to dictate the resource that is loaded into the provided font namespace when used
* with [`loadAsync`](#loadasyncfontfamilyorfontmap-source).
*/
export type FontResource = {
uri?: string | number;
/**
* Sets the [`font-display`](#fontdisplay) property for a given typeface in the browser.
* @platform web
*/
display?: FontDisplay;
default?: string;
};
/**
* Sets the [font-display](path_to_url
* for a given typeface. The default font value on web is `FontDisplay.AUTO`.
* Even though setting the `fontDisplay` does nothing on native platforms, the default behavior
* emulates `FontDisplay.SWAP` on flagship devices like iOS, Samsung, Pixel, etc. Default
* functionality varies on One Plus devices. In the browser this value is set in the generated
* `@font-face` CSS block and not as a style property meaning you cannot dynamically change this
* value based on the element it's used in.
* @platform web
*/
export declare enum FontDisplay {
/**
* __(Default)__ The font display strategy is defined by the user agent or platform.
* This generally defaults to the text being invisible until the font is loaded.
* Good for buttons or banners that require a specific treatment.
*/
AUTO = "auto",
/**
* Fallback text is rendered immediately with a default font while the desired font is loaded.
* This is good for making the content appear to load instantly and is usually preferred.
*/
SWAP = "swap",
/**
* The text will be invisible until the font has loaded. If the font fails to load then nothing
* will appear - it's best to turn this off when debugging missing text.
*/
BLOCK = "block",
/**
* Splits the behavior between `SWAP` and `BLOCK`.
* There will be a [100ms timeout](path_to_url
* where the text with a custom font is invisible, after that the text will either swap to the
* styled text or it'll show the unstyled text and continue to load the custom font. This is good
* for buttons that need a custom font but should also be quickly available to screen-readers.
*/
FALLBACK = "fallback",
/**
* This works almost identically to `FALLBACK`, the only difference is that the browser will
* decide to load the font based on slow connection speed or critical resource demand.
*/
OPTIONAL = "optional"
}
/**
* Object used to query fonts for unloading.
* @hidden
*/
export type UnloadFontOptions = Pick<FontResource, 'display'>;
//# sourceMappingURL=Font.types.d.ts.map
``` | /content/code_sandbox/packages/expo-font/build/Font.types.d.ts | xml | 2016-08-15T17:14:25 | 2024-08-16T19:54:44 | expo | expo/expo | 32,004 | 655 |
```xml
/**
* You can customize the initial state of the module from the editor initialization, by passing the following [Configuration Object](path_to_url
* ```js
* const editor = grapesjs.init({
* parser: {
* // options
* }
* })
* ```
*
* Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance
*
* ```js
* const { Parser } = editor;
* ```
* ## Available Events
* * `parse:html` - On HTML parse, an object containing the input and the output of the parser is passed as an argument
* * `parse:css` - On CSS parse, an object containing the input and the output of the parser is passed as an argument
*
* ## Methods
* * [getConfig](#getconfig)
* * [parseHtml](#parsehtml)
* * [parseCss](#parsecss)
*
* @module Parser
*/
import { Module } from '../abstract';
import EditorModel from '../editor/model/Editor';
import defaults, { HTMLParserOptions, ParserConfig } from './config/config';
import ParserCss from './model/ParserCss';
import ParserHtml from './model/ParserHtml';
export default class ParserModule extends Module<ParserConfig & { name?: string }> {
parserHtml: ReturnType<typeof ParserHtml>;
parserCss: ReturnType<typeof ParserCss>;
constructor(em: EditorModel) {
super(em, 'Parser', defaults);
const { config } = this;
this.parserCss = ParserCss(em, config);
this.parserHtml = ParserHtml(em, config);
}
/**
* Get configuration object
* @name getConfig
* @function
* @return {Object}
*/
/**
* Parse HTML string and return the object containing the Component Definition
* @param {String} input HTML string to parse
* @param {Object} [options] Options
* @param {String} [options.htmlType] [HTML mime type](path_to_url#Argument02) to parse
* @param {Boolean} [options.allowScripts=false] Allow `<script>` tags
* @param {Boolean} [options.allowUnsafeAttr=false] Allow unsafe HTML attributes (eg. `on*` inline event handlers)
* @returns {Object} Object containing the result `{ html: ..., css: ... }`
* @example
* const resHtml = Parser.parseHtml(`<table><div>Hi</div></table>`, {
* htmlType: 'text/html', // default
* });
* // By using the `text/html`, this will fix automatically all the HTML syntax issues
* // Indeed the final representation, in this case, will be `<div>Hi</div><table></table>`
* const resXml = Parser.parseHtml(`<table><div>Hi</div></table>`, {
* htmlType: 'application/xml',
* });
* // This will preserve the original format as, from the XML point of view, is a valid format
*/
parseHtml(input: string, options: HTMLParserOptions = {}) {
const { em, parserHtml } = this;
parserHtml.compTypes = em.Components.getTypes() || [];
return parserHtml.parse(input, this.parserCss, options);
}
/**
* Parse CSS string and return an array of valid definition objects for CSSRules
* @param {String} input CSS string to parse
* @returns {Array<Object>} Array containing the result
* @example
* const res = Parser.parseCss('.cls { color: red }');
* // [{ ... }]
*/
parseCss(input: string) {
return this.parserCss.parse(input);
}
destroy() {}
}
``` | /content/code_sandbox/src/parser/index.ts | xml | 2016-01-22T00:23:19 | 2024-08-16T11:20:59 | grapesjs | GrapesJS/grapesjs | 21,687 | 811 |
```xml
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
<class>DisplayFilterExpressionDialog</class>
<widget class="QDialog" name="DisplayFilterExpressionDialog">
<property name="geometry">
<rect>
<x>0</x>
<y>0</y>
<width>657</width>
<height>588</height>
</rect>
</property>
<property name="windowTitle">
<string>Dialog</string>
</property>
<layout class="QVBoxLayout" name="verticalLayout_2">
<item>
<layout class="QHBoxLayout" name="horizontalLayout_2">
<item>
<layout class="QVBoxLayout" name="verticalLayout">
<item>
<widget class="QLabel" name="fieldLabel">
<property name="toolTip">
<string>Select a field to start building a display filter.</string>
</property>
<property name="text">
<string>Field Name</string>
</property>
</widget>
</item>
<item>
<widget class="QTreeWidget" name="fieldTreeWidget">
<property name="uniformRowHeights">
<bool>true</bool>
</property>
<property name="headerHidden">
<bool>true</bool>
</property>
<column>
<property name="text">
<string notr="true">1</string>
</property>
</column>
</widget>
</item>
<item>
<layout class="QHBoxLayout" name="horizontalLayout">
<item>
<widget class="QLabel" name="searchLabel">
<property name="toolTip">
<string><html><head/><body><p>Search the list of field names.</p></body></html></string>
</property>
<property name="text">
<string>Search:</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="searchLineEdit"/>
</item>
</layout>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayout_6" stretch="0,1,0,4,1,0">
<item>
<layout class="QVBoxLayout" name="relationLayout">
<item>
<widget class="QLabel" name="relationLabel">
<property name="toolTip">
<string><html><head/><body><p>Relations can be used to restrict fields to specific values. Each relation does the following:</p>
<table><tbody>
<tr><th>is present</th><td>Match any packet that contains this field</td></tr>
<tr><th>==, !=, etc.</th><td>Compare the field to a specific value.</td></tr>
<tr><th>contains, matches</th><td>Check the field against a string (contains) or a regular expression (matches)</td></tr>
</tbody></table>
</body></html></string>
</property>
<property name="text">
<string>Relation</string>
</property>
</widget>
</item>
<item>
<widget class="QListWidget" name="relationListWidget"/>
</item>
</layout>
</item>
<item>
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>12</height>
</size>
</property>
</spacer>
</item>
<item>
<layout class="QVBoxLayout" name="valueLayout">
<item>
<widget class="QLabel" name="valueLabel">
<property name="toolTip">
<string>Match against this value.</string>
</property>
<property name="text">
<string>Value</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="valueLineEdit"/>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="enumLayout">
<item>
<widget class="QLabel" name="enumLabel">
<property name="toolTip">
<string>If the field you have selected has a known set of valid values they will be listed here.</string>
</property>
<property name="text">
<string>Predefined Values</string>
</property>
</widget>
</item>
<item>
<widget class="QListWidget" name="enumListWidget"/>
</item>
</layout>
</item>
<item>
<spacer name="verticalSpacer_2">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>12</height>
</size>
</property>
</spacer>
</item>
<item>
<layout class="QVBoxLayout" name="rangeLayout">
<item>
<widget class="QLabel" name="rangeLabel">
<property name="toolTip">
<string>If the field you have selected covers a range of bytes (e.g. you have selected a protocol) you can restrict the match to a range of bytes here.</string>
</property>
<property name="text">
<string>Range (offset:length)</string>
</property>
</widget>
</item>
<item>
<widget class="QLineEdit" name="rangeLineEdit"/>
</item>
</layout>
</item>
</layout>
</item>
</layout>
</item>
<item>
<widget class="DisplayFilterEdit" name="displayFilterLineEdit">
<property name="readOnly">
<bool>true</bool>
</property>
<property name="placeholderText">
<string>No display filter</string>
</property>
</widget>
</item>
<item>
<widget class="QLabel" name="hintLabel">
<property name="text">
<string><small><i>A hint.</i></small></string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item>
<widget class="QDialogButtonBox" name="buttonBox">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="standardButtons">
<set>QDialogButtonBox::Cancel|QDialogButtonBox::Help|QDialogButtonBox::Ok</set>
</property>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>DisplayFilterEdit</class>
<extends>QLineEdit</extends>
<header>display_filter_edit.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections>
<connection>
<sender>buttonBox</sender>
<signal>accepted()</signal>
<receiver>DisplayFilterExpressionDialog</receiver>
<slot>accept()</slot>
<hints>
<hint type="sourcelabel">
<x>248</x>
<y>254</y>
</hint>
<hint type="destinationlabel">
<x>157</x>
<y>274</y>
</hint>
</hints>
</connection>
<connection>
<sender>buttonBox</sender>
<signal>rejected()</signal>
<receiver>DisplayFilterExpressionDialog</receiver>
<slot>reject()</slot>
<hints>
<hint type="sourcelabel">
<x>316</x>
<y>260</y>
</hint>
<hint type="destinationlabel">
<x>286</x>
<y>274</y>
</hint>
</hints>
</connection>
</connections>
</ui>
``` | /content/code_sandbox/utilities/wireshark/ui/qt/display_filter_expression_dialog.ui | xml | 2016-10-27T09:31:28 | 2024-08-16T19:00:35 | nexmon | seemoo-lab/nexmon | 2,381 | 1,935 |
```xml
const transferMutation = `
mutation KhanbankTransfer($configId: String!, $transfer: 32,57: khanbankTransfer(configId: String!, transfer: KhanbankTransferInput): JSON) {
khanbankTransfer(configId: $configId, transfer: $transfer)
}
`;
export default {
transferMutation
};
``` | /content/code_sandbox/packages/plugin-khanbank-ui/src/modules/corporateGateway/transactions/graphql/mutations.ts | xml | 2016-11-11T06:54:50 | 2024-08-16T10:26:06 | erxes | erxes/erxes | 3,479 | 71 |
```xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="path_to_url"
android:duration="300">
<alpha
android:fromAlpha="0"
android:toAlpha="1" />
<translate
android:fromYDelta="15%"
android:toYDelta="0%"
android:interpolator="@anim/x2_decelerate_interpolator" />
</set>
``` | /content/code_sandbox/app/src/main/res/anim/fragment_manange_enter.xml | xml | 2016-02-21T04:39:19 | 2024-08-16T13:35:51 | GeometricWeather | WangDaYeeeeee/GeometricWeather | 2,420 | 94 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.