type
stringclasses 7
values | content
stringlengths 4
9.55k
| repo
stringlengths 7
96
| path
stringlengths 4
178
| language
stringclasses 1
value |
---|---|---|---|---|
ArrowFunction |
async (logger) => {
const protocol = new TestProtocol();
const pollSent = new PromiseSource<HttpRequest>();
const pollCompleted = new PromiseSource<HttpResponse>();
let negotiateRequest!: HttpRequest;
const testClient = createTestClient(pollSent, pollCompleted.promise)
.on("POST", "http://example.com?id=123abc", (req) => {
// Respond from the poll with the handshake response
negotiateRequest = req;
pollCompleted.resolve(new HttpResponse(204, "No Content", "{}"));
return new HttpResponse(202);
});
const connection = createConnectionBuilder()
.withUrl("http://example.com", {
...commonHttpOptions,
httpClient: testClient,
logger,
})
.withHubProtocol(protocol)
.build();
await expect(connection.start()).rejects.toThrow("The underlying connection was closed before the hub handshake could complete.");
expect(connection.state).toBe(HubConnectionState.Disconnected);
expect(negotiateRequest.content).toBe(`{"protocol":"${protocol.name}","version":1}\x1E`);
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
(req) => {
// Respond from the poll with the handshake response
negotiateRequest = req;
pollCompleted.resolve(new HttpResponse(204, "No Content", "{}"));
return new HttpResponse(202);
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
() => {
function testLogLevels(logger: ILogger, minLevel: LogLevel) {
const capturingConsole = new CapturingConsole();
(logger as ConsoleLogger).out = capturingConsole;
for (let level = LogLevel.Trace; level < LogLevel.None; level++) {
const message = `Message at LogLevel.${LogLevel[level]}`;
const expectedMessage = `${LogLevel[level]}: Message at LogLevel.${LogLevel[level]}`;
logger.log(level, message);
if (level >= minLevel) {
expect(capturingConsole.messages).toContain(expectedMessage);
} else {
expect(capturingConsole.messages).not.toContain(expectedMessage);
}
}
}
eachMissingValue((val, name) => {
it(`throws if logger is ${name}`, () => {
const builder = new HubConnectionBuilder();
expect(() => builder.configureLogging(val!)).toThrow("The 'logging' argument is required.");
});
});
[
LogLevel.None,
LogLevel.Critical,
LogLevel.Error,
LogLevel.Warning,
LogLevel.Information,
LogLevel.Debug,
LogLevel.Trace,
].forEach((minLevel) => {
const levelName = LogLevel[minLevel];
it(`accepts LogLevel.${levelName}`, async () => {
const builder = new HubConnectionBuilder()
.configureLogging(minLevel);
expect(builder.logger).toBeDefined();
expect(builder.logger).toBeInstanceOf(ConsoleLogger);
testLogLevels(builder.logger!, minLevel);
});
});
const levelNames = Object.keys(ExpectedLogLevelMappings) as (keyof typeof ExpectedLogLevelMappings)[];
for (const str of levelNames) {
const mapped = ExpectedLogLevelMappings[str];
const mappedName = LogLevel[mapped];
it(`accepts "${str}" as an alias for LogLevel.${mappedName}`, async () => {
const builder = new HubConnectionBuilder()
.configureLogging(str);
expect(builder.logger).toBeDefined();
expect(builder.logger).toBeInstanceOf(ConsoleLogger);
testLogLevels(builder.logger!, mapped);
});
}
it("allows logger to be replaced", async () => {
let loggedMessages = 0;
const logger = {
log() {
loggedMessages += 1;
},
};
const pollSent = new PromiseSource<HttpRequest>();
const pollCompleted = new PromiseSource<HttpResponse>();
const testClient = createTestClient(pollSent, pollCompleted.promise)
.on("POST", "http://example.com?id=123abc", (req) => {
// Respond from the poll with the handshake response
pollCompleted.resolve(new HttpResponse(204, "No Content", "{}"));
return new HttpResponse(202);
});
const connection = createConnectionBuilder(logger)
.withUrl("http://example.com", {
...commonHttpOptions,
httpClient: testClient,
})
.build();
try {
await connection.start();
} catch {
// Ignore failures
}
expect(loggedMessages).toBeGreaterThan(0);
});
it("configures logger for both HttpConnection and HubConnection", async () => {
const pollSent = new PromiseSource<HttpRequest>();
const pollCompleted = new PromiseSource<HttpResponse>();
const testClient = createTestClient(pollSent, pollCompleted.promise)
.on("POST", "http://example.com?id=123abc", (req) => {
// Respond from the poll with the handshake response
pollCompleted.resolve(new HttpResponse(204, "No Content", "{}"));
return new HttpResponse(202);
});
const logger = new CaptureLogger();
const connection = createConnectionBuilder(logger)
.withUrl("http://example.com", {
...commonHttpOptions,
httpClient: testClient,
})
.build();
try {
await connection.start();
} catch {
// Ignore failures
}
// A HubConnection message
expect(logger.messages).toContain("Starting HubConnection.");
// An HttpConnection message
expect(logger.messages).toContain("Starting connection with transfer format 'Text'.");
});
it("does not replace HttpConnectionOptions logger if provided", async () => {
const pollSent = new PromiseSource<HttpRequest>();
const pollCompleted = new PromiseSource<HttpResponse>();
const testClient = createTestClient(pollSent, pollCompleted.promise)
.on("POST", "http://example.com?id=123abc", (req) => {
// Respond from the poll with the handshake response
pollCompleted.resolve(new HttpResponse(204, "No Content", "{}"));
return new HttpResponse(202);
});
const hubConnectionLogger = new CaptureLogger();
const httpConnectionLogger = new CaptureLogger();
const connection = createConnectionBuilder(hubConnectionLogger)
.withUrl("http://example.com", {
httpClient: testClient,
logger: httpConnectionLogger,
})
.build();
try {
await connection.start();
} catch {
// Ignore failures
}
// A HubConnection message
expect(hubConnectionLogger.messages).toContain("Starting HubConnection.");
expect(httpConnectionLogger.messages).not.toContain("Starting HubConnection.");
// An HttpConnection message
expect(httpConnectionLogger.messages).toContain("Starting connection with transfer format 'Text'.");
expect(hubConnectionLogger.messages).not.toContain("Starting connection with transfer format 'Text'.");
});
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
(val, name) => {
it(`throws if logger is ${name}`, () => {
const builder = new HubConnectionBuilder();
expect(() => builder.configureLogging(val!)).toThrow("The 'logging' argument is required.");
});
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
() => {
const builder = new HubConnectionBuilder();
expect(() => builder.configureLogging(val!)).toThrow("The 'logging' argument is required.");
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
() => builder.configureLogging(val!) | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
(minLevel) => {
const levelName = LogLevel[minLevel];
it(`accepts LogLevel.${levelName}`, async () => {
const builder = new HubConnectionBuilder()
.configureLogging(minLevel);
expect(builder.logger).toBeDefined();
expect(builder.logger).toBeInstanceOf(ConsoleLogger);
testLogLevels(builder.logger!, minLevel);
});
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
async () => {
const builder = new HubConnectionBuilder()
.configureLogging(minLevel);
expect(builder.logger).toBeDefined();
expect(builder.logger).toBeInstanceOf(ConsoleLogger);
testLogLevels(builder.logger!, minLevel);
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
async () => {
const builder = new HubConnectionBuilder()
.configureLogging(str);
expect(builder.logger).toBeDefined();
expect(builder.logger).toBeInstanceOf(ConsoleLogger);
testLogLevels(builder.logger!, mapped);
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
async () => {
let loggedMessages = 0;
const logger = {
log() {
loggedMessages += 1;
},
};
const pollSent = new PromiseSource<HttpRequest>();
const pollCompleted = new PromiseSource<HttpResponse>();
const testClient = createTestClient(pollSent, pollCompleted.promise)
.on("POST", "http://example.com?id=123abc", (req) => {
// Respond from the poll with the handshake response
pollCompleted.resolve(new HttpResponse(204, "No Content", "{}"));
return new HttpResponse(202);
});
const connection = createConnectionBuilder(logger)
.withUrl("http://example.com", {
...commonHttpOptions,
httpClient: testClient,
})
.build();
try {
await connection.start();
} catch {
// Ignore failures
}
expect(loggedMessages).toBeGreaterThan(0);
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
async () => {
const pollSent = new PromiseSource<HttpRequest>();
const pollCompleted = new PromiseSource<HttpResponse>();
const testClient = createTestClient(pollSent, pollCompleted.promise)
.on("POST", "http://example.com?id=123abc", (req) => {
// Respond from the poll with the handshake response
pollCompleted.resolve(new HttpResponse(204, "No Content", "{}"));
return new HttpResponse(202);
});
const logger = new CaptureLogger();
const connection = createConnectionBuilder(logger)
.withUrl("http://example.com", {
...commonHttpOptions,
httpClient: testClient,
})
.build();
try {
await connection.start();
} catch {
// Ignore failures
}
// A HubConnection message
expect(logger.messages).toContain("Starting HubConnection.");
// An HttpConnection message
expect(logger.messages).toContain("Starting connection with transfer format 'Text'.");
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
async () => {
const pollSent = new PromiseSource<HttpRequest>();
const pollCompleted = new PromiseSource<HttpResponse>();
const testClient = createTestClient(pollSent, pollCompleted.promise)
.on("POST", "http://example.com?id=123abc", (req) => {
// Respond from the poll with the handshake response
pollCompleted.resolve(new HttpResponse(204, "No Content", "{}"));
return new HttpResponse(202);
});
const hubConnectionLogger = new CaptureLogger();
const httpConnectionLogger = new CaptureLogger();
const connection = createConnectionBuilder(hubConnectionLogger)
.withUrl("http://example.com", {
httpClient: testClient,
logger: httpConnectionLogger,
})
.build();
try {
await connection.start();
} catch {
// Ignore failures
}
// A HubConnection message
expect(hubConnectionLogger.messages).toContain("Starting HubConnection.");
expect(httpConnectionLogger.messages).not.toContain("Starting HubConnection.");
// An HttpConnection message
expect(httpConnectionLogger.messages).toContain("Starting connection with transfer format 'Text'.");
expect(hubConnectionLogger.messages).not.toContain("Starting connection with transfer format 'Text'.");
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
() => {
const builder = new HubConnectionBuilder().withUrl("http://example.com");
expect(builder.reconnectPolicy).toBeUndefined();
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
() => {
const builder = new HubConnectionBuilder().withAutomaticReconnect();
expect(() => builder.withAutomaticReconnect()).toThrow("A reconnectPolicy has already been set.");
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
() => builder.withAutomaticReconnect() | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
() => {
// From DefaultReconnectPolicy.ts
const DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2000, 10000, 30000, null];
const builder = new HubConnectionBuilder()
.withAutomaticReconnect();
let retryCount = 0;
for (const delay of DEFAULT_RETRY_DELAYS_IN_MILLISECONDS) {
const retryContext = {
previousRetryCount: retryCount++,
elapsedMilliseconds: 0,
retryReason: new Error(),
};
expect(builder.reconnectPolicy!.nextRetryDelayInMilliseconds(retryContext)).toBe(delay);
}
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
() => {
const customRetryDelays = [3, 1, 4, 1, 5, 9];
const builder = new HubConnectionBuilder()
.withAutomaticReconnect(customRetryDelays);
let retryCount = 0;
for (const delay of customRetryDelays) {
const retryContext = {
previousRetryCount: retryCount++,
elapsedMilliseconds: 0,
retryReason: new Error(),
};
expect(builder.reconnectPolicy!.nextRetryDelayInMilliseconds(retryContext)).toBe(delay);
}
const retryContextFinal = {
previousRetryCount: retryCount++,
elapsedMilliseconds: 0,
retryReason: new Error(),
};
expect(builder.reconnectPolicy!.nextRetryDelayInMilliseconds(retryContextFinal)).toBe(null);
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
() => {
const customRetryDelays = [127, 0, 0, 1];
const builder = new HubConnectionBuilder()
.withAutomaticReconnect(new DefaultReconnectPolicy(customRetryDelays));
let retryCount = 0;
for (const delay of customRetryDelays) {
const retryContext = {
previousRetryCount: retryCount++,
elapsedMilliseconds: 0,
retryReason: new Error(),
};
expect(builder.reconnectPolicy!.nextRetryDelayInMilliseconds(retryContext)).toBe(delay);
}
const retryContextFinal = {
previousRetryCount: retryCount++,
elapsedMilliseconds: 0,
retryReason: new Error(),
};
expect(builder.reconnectPolicy!.nextRetryDelayInMilliseconds(retryContextFinal)).toBe(null);
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
() => negotiateResponse || longPollingNegotiateResponse | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
(req) => {
if (firstRequest) {
firstRequest = false;
return new HttpResponse(200);
} else {
pollSent.resolve(req);
return pollCompleted;
}
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ClassDeclaration |
class CapturingConsole {
public messages: any[] = [];
public error(message: any) {
this.messages.push(CapturingConsole._stripPrefix(message));
}
public warn(message: any) {
this.messages.push(CapturingConsole._stripPrefix(message));
}
public info(message: any) {
this.messages.push(CapturingConsole._stripPrefix(message));
}
public log(message: any) {
this.messages.push(CapturingConsole._stripPrefix(message));
}
private static _stripPrefix(input: any): any {
if (typeof input === "string") {
input = input.replace(/\[.*\]\s+/, "");
}
return input;
}
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ClassDeclaration |
class CaptureLogger implements ILogger {
public readonly messages: string[] = [];
public log(logLevel: LogLevel, message: string): void {
this.messages.push(message);
}
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ClassDeclaration |
class TestProtocol implements IHubProtocol {
public name: string = "test";
public version: number = 1;
public transferFormat: TransferFormat = TransferFormat.Text;
public parseMessages(input: string | ArrayBuffer, logger: ILogger): HubMessage[] {
throw new Error("Method not implemented.");
}
public writeMessage(message: HubMessage): string | ArrayBuffer {
// builds ping message in the `hubConnection` constructor
return "";
}
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
MethodDeclaration |
public error(message: any) {
this.messages.push(CapturingConsole._stripPrefix(message));
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
MethodDeclaration |
public warn(message: any) {
this.messages.push(CapturingConsole._stripPrefix(message));
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
MethodDeclaration |
public info(message: any) {
this.messages.push(CapturingConsole._stripPrefix(message));
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
MethodDeclaration |
public log(message: any) {
this.messages.push(CapturingConsole._stripPrefix(message));
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
MethodDeclaration |
private static _stripPrefix(input: any): any {
if (typeof input === "string") {
input = input.replace(/\[.*\]\s+/, "");
}
return input;
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
MethodDeclaration |
log() {
loggedMessages += 1;
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
MethodDeclaration |
public log(logLevel: LogLevel, message: string): void {
this.messages.push(message);
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
MethodDeclaration |
public parseMessages(input: string | ArrayBuffer, logger: ILogger): HubMessage[] {
throw new Error("Method not implemented.");
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
MethodDeclaration |
public writeMessage(message: HubMessage): string | ArrayBuffer {
// builds ping message in the `hubConnection` constructor
return "";
} | 1175169074/aspnetcore | src/SignalR/clients/ts/signalr/tests/HubConnectionBuilder.test.ts | TypeScript |
ArrowFunction |
({ variant, token, density }: StyledProps) => {
if (!variant) {
return ``
}
const {
states: {
focus: { outline: focusOutline },
active: { outline: activeOutline },
},
boxShadow,
} = token
let spacings = input.spacings
if (density === 'compact') {
spacings = input.modes.compact.spacings
}
return css`
border: none;
${spacingsTemplate(spacings)}
${outlineTemplate(activeOutline)}
box-shadow: ${boxShadow};
&:active,
&:focus {
outline-offset: 0;
box-shadow: none;
${outlineTemplate(focusOutline)}
}
&:disabled {
cursor: not-allowed;
box-shadow: none;
outline: none;
&:focus,
&:active {
outline: none;
}
}
`
} | berland/design-system | packages/eds-core-react/src/components/Textarea/Textarea.tsx | TypeScript |
TypeAliasDeclaration |
type StyledProps = {
token: InputToken
variant: string
density: string
} | berland/design-system | packages/eds-core-react/src/components/Textarea/Textarea.tsx | TypeScript |
TypeAliasDeclaration |
export type TextareaProps = {
/** Placeholder */
placeholder?: string
/** Variant */
variant?: Variants
/** Disabled state */
disabled?: boolean
/** Type */
type?: string
/** Read Only */
readOnly?: boolean
/** Specifies max rows for multiline input */
rowsMax?: number
} & TextareaHTMLAttributes<HTMLTextAreaElement> | berland/design-system | packages/eds-core-react/src/components/Textarea/Textarea.tsx | TypeScript |
ArrowFunction |
async (
opts: {
alwaysAuth?: boolean,
ca?: string,
cert?: string,
fetchRetries?: number,
fetchRetryFactor?: number,
fetchRetryMaxtimeout?: number,
fetchRetryMintimeout?: number,
httpsProxy?: string,
ignoreFile?: (filename: string) => boolean,
key?: string,
localAddress?: string,
lock: boolean,
lockStaleDuration?: number,
networkConcurrency?: number,
offline?: boolean,
packageImportMethod?: 'auto' | 'hardlink' | 'copy' | 'reflink',
proxy?: string,
rawNpmConfig: object,
registry?: string,
store: string,
strictSsl?: boolean,
userAgent?: string,
verifyStoreIntegrity?: boolean,
},
) => {
// TODO: either print a warning or just log if --no-lock is used
const sopts = Object.assign(opts, {
locks: opts.lock ? path.join(opts.store, '_locks') : undefined,
registry: opts.registry || 'https://registry.npmjs.org/',
})
const resolve = createResolver(Object.assign(sopts, {
fullMetadata: false,
metaCache: new LRU({
max: 10000,
maxAge: 120 * 1000, // 2 minutes
}) as any, // tslint:disable-line:no-any
}))
await mkdirp(sopts.store)
const fsIsCaseSensitive = await dirIsCaseSensitive(sopts.store)
logger.debug({
// An undefined field would cause a crash of the logger
// so converting it to null
isCaseSensitive: typeof fsIsCaseSensitive === 'boolean'
? fsIsCaseSensitive : null,
store: sopts.store,
})
const fetchers = createFetcher({ ...sopts, fsIsCaseSensitive })
return {
ctrl: await createStore(resolve, fetchers as {}, {
locks: sopts.locks,
lockStaleDuration: sopts.lockStaleDuration,
networkConcurrency: sopts.networkConcurrency,
packageImportMethod: sopts.packageImportMethod,
store: sopts.store,
verifyStoreIntegrity: typeof sopts.verifyStoreIntegrity === 'boolean' ?
sopts.verifyStoreIntegrity : true,
}),
path: sopts.store,
}
} | johnroot/pnpm | packages/pnpm/src/createStore.ts | TypeScript |
ArrowFunction |
(traceFilters: TraceFilters) => {
return {
type: ActionTypes.updateTraceFilters,
payload: traceFilters,
};
} | PixelmonToGo/signoz | frontend/src/store/actions/traceFilters.ts | TypeScript |
InterfaceDeclaration |
export interface TagItem {
key: string;
value: string;
operator: "equals" | "contains";
} | PixelmonToGo/signoz | frontend/src/store/actions/traceFilters.ts | TypeScript |
InterfaceDeclaration |
export interface LatencyValue {
min: string;
max: string;
} | PixelmonToGo/signoz | frontend/src/store/actions/traceFilters.ts | TypeScript |
InterfaceDeclaration |
export interface TraceFilters {
tags?: TagItem[];
service?: string;
latency?: LatencyValue;
operation?: string;
} | PixelmonToGo/signoz | frontend/src/store/actions/traceFilters.ts | TypeScript |
InterfaceDeclaration | //define interface for action. Action creator always returns object of this type
export interface updateTraceFiltersAction {
type: ActionTypes.updateTraceFilters;
payload: TraceFilters;
} | PixelmonToGo/signoz | frontend/src/store/actions/traceFilters.ts | TypeScript |
ArrowFunction |
file => !file.includes("/node_modules/") | mkalygin/harp.gl | test/LicenseHeaderTest.ts | TypeScript |
ArrowFunction |
file => !file.includes("/dist/") | mkalygin/harp.gl | test/LicenseHeaderTest.ts | TypeScript |
ArrowFunction |
file => !file.endsWith(".d.ts") | mkalygin/harp.gl | test/LicenseHeaderTest.ts | TypeScript |
ArrowFunction |
() => (
<ul
role="list" | Itsnotaka/Kaka | src/components/about/FavSigners.tsx | TypeScript |
ArrowFunction |
file => (
<li key={file.source} | Itsnotaka/Kaka | src/components/about/FavSigners.tsx | TypeScript |
ArrowFunction |
(message: Message, error: Error, command: Command): Promise<Message> => {
const embed = BetterEmbed.fromTemplate('complete', {
client: message.client,
color: 0xee2200,
title: 'Code error :',
description: cutIfTooLong(error.stack ?? error.toString(), 2048),
});
Logger.error(error, 'CodeError');
return isOwner(message.author.id) ? message.channel.send(embed) : message.channel.send(`An error occurred while executing the \`${command.name}\` command.`);
} | Dergash/Advanced-Command-Handler | src/utils/codeError.ts | TypeScript |
InterfaceDeclaration |
export interface IOptions extends LoadOptions {
/**
* List of extensions to use for directory imports. Defaults to `['.yml', '.yaml']`.
*/
ext?: string[];
/**
* Whether `safeLoad` or `load` should be used when loading YAML files via *js-yaml*. Defaults to `true`.
*/
safe?: boolean;
} | rafamel/yaml-import | src/types.ts | TypeScript |
InterfaceDeclaration |
export interface IPayload {
paths: string | string[];
strategy?: TStrategy;
data?: any;
recursive?: boolean;
} | rafamel/yaml-import | src/types.ts | TypeScript |
InterfaceDeclaration |
export interface IFileDefinition {
cwd: string;
directory: string;
name: string;
} | rafamel/yaml-import | src/types.ts | TypeScript |
TypeAliasDeclaration |
export type TStrategy = 'sequence' | 'shallow' | 'merge' | 'deep'; | rafamel/yaml-import | src/types.ts | TypeScript |
ArrowFunction |
item => item.id === +id | SuryaUpadhyayula/nestjs | src/coffees/coffees.service.ts | TypeScript |
ClassDeclaration |
@Injectable()
export class CoffeesService {
private coffees: Coffee[] = [
{
id: 1,
name: 'Shipwreck Roast',
brand: 'Buddy Brew',
flavors: ['chocolate','hazlenut'],
},
];
findAll() {
return this.coffees;
}
findOne(id: string) {
// throw 'A random error';
const coffee = this.coffees.find(item => item.id === +id);
if (!coffee) {
// throw new HttpException(`Coffee #${id} not found`, HttpStatus.NOT_FOUND);
throw new NotFoundException(`Coffee #${id} not found--custom`)
}
return coffee;
}
create(createCoffeeDto: any) {
this.coffees.push(createCoffeeDto);
return createCoffeeDto;
}
update(id: string, updateCoffeeDto: any) {
const existingCoffee = this.findOne(id);
if (existingCoffee) {
// update the existing entity
}
}
remove(id: string) {
const coffeeIndex = this.coffees.findIndex(item => item.id === +id);
if (coffeeIndex >= 0) {
this.coffees.splice(coffeeIndex, 1);
}
}
} | SuryaUpadhyayula/nestjs | src/coffees/coffees.service.ts | TypeScript |
MethodDeclaration |
findAll() {
return this.coffees;
} | SuryaUpadhyayula/nestjs | src/coffees/coffees.service.ts | TypeScript |
MethodDeclaration |
findOne(id: string) {
// throw 'A random error';
const coffee = this.coffees.find(item => item.id === +id);
if (!coffee) {
// throw new HttpException(`Coffee #${id} not found`, HttpStatus.NOT_FOUND);
throw new NotFoundException(`Coffee #${id} not found--custom`)
}
return coffee;
} | SuryaUpadhyayula/nestjs | src/coffees/coffees.service.ts | TypeScript |
MethodDeclaration |
create(createCoffeeDto: any) {
this.coffees.push(createCoffeeDto);
return createCoffeeDto;
} | SuryaUpadhyayula/nestjs | src/coffees/coffees.service.ts | TypeScript |
MethodDeclaration |
update(id: string, updateCoffeeDto: any) {
const existingCoffee = this.findOne(id);
if (existingCoffee) {
// update the existing entity
}
} | SuryaUpadhyayula/nestjs | src/coffees/coffees.service.ts | TypeScript |
MethodDeclaration |
remove(id: string) {
const coffeeIndex = this.coffees.findIndex(item => item.id === +id);
if (coffeeIndex >= 0) {
this.coffees.splice(coffeeIndex, 1);
}
} | SuryaUpadhyayula/nestjs | src/coffees/coffees.service.ts | TypeScript |
ClassDeclaration |
export default class LiveDemoComponent extends React.Component {
state = { language: 'react' };
props: {
javascript?: string;
react: string;
};
render(): JSX.Element {
return (
<div>
<div
style={{
display: 'block',
marginBottom: '8px',
fontFamily: 'sans-serif',
}} | animaliads/animalia-web-components | stories/helpers/components/live-demo.tsx | TypeScript |
MethodDeclaration |
render(): JSX.Element {
return (
<div>
<div
style={{
display: 'block',
marginBottom: '8px',
fontFamily: 'sans-serif',
}} | animaliads/animalia-web-components | stories/helpers/components/live-demo.tsx | TypeScript |
InterfaceDeclaration |
export interface IApplication extends LeasilyDocument {
property: IProperty
lease: ILease
stage: APPLICATION_STAGES
isClosed: boolean
fee: number
waitPeriodInDays: number
} | Olencki-Development/leasily-api | src/models/Application/index.ts | TypeScript |
InterfaceDeclaration |
export interface IApplicationModel extends LeasilyModel<IApplication> {} | Olencki-Development/leasily-api | src/models/Application/index.ts | TypeScript |
EnumDeclaration |
export enum APPLICATION_STAGES {
AWAITING_COMPLETION,
REQUESTING_BACKGROUND_CHECK,
AWAITING_APPLICATION_REVIEW,
RENTED
} | Olencki-Development/leasily-api | src/models/Application/index.ts | TypeScript |
FunctionDeclaration |
export default async function potalnode(kad: Kademlia, port: number) {
const app = Express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use((_, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS"
);
next();
});
app.listen(port, () => {
console.log("Example app listening on port " + port);
});
app.post("/join", async (req: Express.Request, res: Express.Response) => {
try {
console.log("join", req.body);
const kid = req.body.kid;
if (kid) {
console.log({ kid });
const peer = PeerModule(kid);
peers[kid] = peer;
const offer = await peer.createOffer();
return res.send({ offer, kid: kad.kid });
}
} catch (error) {}
});
app.post("/answer", async (req: Express.Request, res: Express.Response) => {
try {
const { answer, kid } = req.body;
if (answer && kid) {
const peer = peers[kid];
await peer.setAnswer(answer);
kad.add(peer);
delete peers[kid];
console.log("connected");
return res.send("connected");
}
} catch (error) {}
});
} | shinyoshiaki/kad-rtc | examples/express/src/portal/index.ts | TypeScript |
ArrowFunction |
(_, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS"
);
next();
} | shinyoshiaki/kad-rtc | examples/express/src/portal/index.ts | TypeScript |
ArrowFunction |
() => {
console.log("Example app listening on port " + port);
} | shinyoshiaki/kad-rtc | examples/express/src/portal/index.ts | TypeScript |
ArrowFunction |
async (req: Express.Request, res: Express.Response) => {
try {
console.log("join", req.body);
const kid = req.body.kid;
if (kid) {
console.log({ kid });
const peer = PeerModule(kid);
peers[kid] = peer;
const offer = await peer.createOffer();
return res.send({ offer, kid: kad.kid });
}
} catch (error) {}
} | shinyoshiaki/kad-rtc | examples/express/src/portal/index.ts | TypeScript |
ArrowFunction |
async (req: Express.Request, res: Express.Response) => {
try {
const { answer, kid } = req.body;
if (answer && kid) {
const peer = peers[kid];
await peer.setAnswer(answer);
kad.add(peer);
delete peers[kid];
console.log("connected");
return res.send("connected");
}
} catch (error) {}
} | shinyoshiaki/kad-rtc | examples/express/src/portal/index.ts | TypeScript |
ArrowFunction |
(api: FormikProps<any>) => (
<>
<div className="c-statblock-editor__headers">
<TextField label | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
ArrowFunction |
keywordType => (
<div key={keywordType} | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
ArrowFunction |
powerType => (
<div key={powerType} | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
ArrowFunction |
api => (
<div className="c-statblock-editor__json-section">
{this.state.renderError && (
<p className="c-statblock-editor__error">
There was a problem with your statblock JSON, falling back to JSON
editor.
</p>
)} | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
ArrowFunction |
submittedValues => {
const {
SaveAs,
SaveAsCharacter,
StatBlockJSON,
...submittedStatBlock
} = submittedValues;
let statBlockFromActiveEditor: StatBlock;
if (this.state.editorMode == "standard") {
statBlockFromActiveEditor = submittedStatBlock;
} else {
statBlockFromActiveEditor = JSON.parse(StatBlockJSON);
}
const editedStatBlock: StatBlock = {
...StatBlock.Default(),
...statBlockFromActiveEditor,
Id: submittedStatBlock.Id,
Name: submittedStatBlock.Name,
Path: submittedStatBlock.Path,
Version: process.env.VERSION || "unknown"
};
ConvertStringsToNumbersWhereNeeded(editedStatBlock);
if (SaveAsCharacter && this.props.onSaveAsCharacter) {
editedStatBlock.Id = probablyUniqueString();
this.props.onSaveAsCharacter(editedStatBlock);
} else if (SaveAs && this.props.onSaveAsCopy) {
editedStatBlock.Id = probablyUniqueString();
this.props.onSaveAsCopy(editedStatBlock);
} else {
this.props.onSave(editedStatBlock);
}
this.props.onClose();
} | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
ArrowFunction |
() => {
this.props.onClose();
} | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
ArrowFunction |
() => {
if (
this.props.onDelete &&
confirm(`Delete Statblock for ${this.props.statBlock.Name}?`)
) {
this.props.onDelete();
this.props.onClose();
}
} | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
ArrowFunction |
(path: string, name: string) =>
this.props.currentListings?.some(
l => l.Meta().Path == path && l.Meta().Name == name
) | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
ArrowFunction |
l => l.Meta().Path == path && l.Meta().Name == name | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
ArrowFunction |
(path: string, name: string) => JSON.stringify({ path, name }) | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
ArrowFunction |
values => {
const errors: any = {};
if (_.isEmpty(values.Name)) {
errors.NameMissing = "Error: Name is required.";
}
if (this.state.editorMode === "json") {
try {
JSON.parse(values.StatBlockJSON);
} catch (e) {
errors.JSONParseError = e.message;
}
}
if (!values.SaveAs) {
return errors;
}
const path = values.Path || "";
const name = values.Name || "";
if (this.willOverwriteStatBlock(path, name)) {
errors.PathAndName =
"Error: This will overwrite an existing custom statblock.";
}
return errors;
} | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
ClassDeclaration |
export class StatBlockEditor extends React.Component<
StatBlockEditorProps,
StatBlockEditorState
> {
constructor(props) {
super(props);
this.state = { editorMode: "standard" };
}
public componentDidCatch(error, info) {
this.setState({
editorMode: "json",
renderError: JSON.stringify(error)
});
}
public render() {
if (!this.props.statBlock) {
return null;
}
const header =
{
combatant: "Edit Combatant Statblock",
library: "Edit Library Statblock",
persistentcharacter: "Edit Character Statblock"
}[this.props.editorTarget] || "Edit StatBlock";
const buttons = (
<>
<Button onClick={this.close} fontAwesomeIcon="times" />
{this.props.onDelete && (
<Button onClick={this.delete} fontAwesomeIcon="trash" />
)} | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
InterfaceDeclaration |
export interface StatBlockEditorProps {
statBlock: StatBlock;
onSave: (statBlock: StatBlock) => void;
onDelete?: () => void;
onSaveAsCopy?: (statBlock: StatBlock) => void;
onSaveAsCharacter?: (statBlock: StatBlock) => void;
onClose: () => void;
editorTarget: StatBlockEditorTarget;
currentListings?: Listing<Listable>[];
} | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
InterfaceDeclaration |
interface StatBlockEditorState {
editorMode: "standard" | "json";
renderError?: string;
} | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
TypeAliasDeclaration |
export type StatBlockEditorTarget =
| "library"
| "combatant"
| "persistentcharacter"; | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
MethodDeclaration |
public componentDidCatch(error, info) {
this.setState({
editorMode: "json",
renderError: JSON.stringify(error)
});
} | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
MethodDeclaration |
public render() {
if (!this.props.statBlock) {
return null;
}
const header =
{
combatant: "Edit Combatant Statblock",
library: "Edit Library Statblock",
persistentcharacter: "Edit Character Statblock"
}[this.props.editorTarget] || "Edit StatBlock";
const buttons = (
<>
<Button onClick={this.close} fontAwesomeIcon="times" />
{this.props.onDelete && (
<Button onClick={this.delete} fontAwesomeIcon="trash" />
)} | 5eMagic/improved-initiative | client/StatBlockEditor/StatBlockEditor.tsx | TypeScript |
ClassDeclaration |
@NgModule({
imports: [
JigsawMobileListLiteModule, CommonModule,
JigsawDemoDescriptionModule
],
declarations: [ListLiteFullDemoComponent],
exports: [ListLiteFullDemoComponent]
})
export class ListLiteFullDemoModule {
} | sweetPoppy/jigsaw | src/app/demo/mobile/list-lite/full/demo.module.ts | TypeScript |
ClassDeclaration |
export class ClearNotificationAction extends Action {
static readonly ID = CLEAR_NOTIFICATION;
static readonly LABEL = localize('clearNotification', "Clear Notification");
constructor(
id: string,
label: string,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label, ThemeIcon.asClassName(clearIcon));
}
override async run(notification: INotificationViewItem): Promise<void> {
this.commandService.executeCommand(CLEAR_NOTIFICATION, notification);
}
} | AaronNGray/vscode | src/vs/workbench/browser/parts/notifications/notificationsActions.ts | TypeScript |
ClassDeclaration |
export class ClearAllNotificationsAction extends Action {
static readonly ID = CLEAR_ALL_NOTIFICATIONS;
static readonly LABEL = localize('clearNotifications', "Clear All Notifications");
constructor(
id: string,
label: string,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label, ThemeIcon.asClassName(clearAllIcon));
}
override async run(): Promise<void> {
this.commandService.executeCommand(CLEAR_ALL_NOTIFICATIONS);
}
} | AaronNGray/vscode | src/vs/workbench/browser/parts/notifications/notificationsActions.ts | TypeScript |
ClassDeclaration |
export class HideNotificationsCenterAction extends Action {
static readonly ID = HIDE_NOTIFICATIONS_CENTER;
static readonly LABEL = localize('hideNotificationsCenter', "Hide Notifications");
constructor(
id: string,
label: string,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label, ThemeIcon.asClassName(hideIcon));
}
override async run(): Promise<void> {
this.commandService.executeCommand(HIDE_NOTIFICATIONS_CENTER);
}
} | AaronNGray/vscode | src/vs/workbench/browser/parts/notifications/notificationsActions.ts | TypeScript |
ClassDeclaration |
export class ExpandNotificationAction extends Action {
static readonly ID = EXPAND_NOTIFICATION;
static readonly LABEL = localize('expandNotification', "Expand Notification");
constructor(
id: string,
label: string,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label, ThemeIcon.asClassName(expandIcon));
}
override async run(notification: INotificationViewItem): Promise<void> {
this.commandService.executeCommand(EXPAND_NOTIFICATION, notification);
}
} | AaronNGray/vscode | src/vs/workbench/browser/parts/notifications/notificationsActions.ts | TypeScript |
ClassDeclaration |
export class CollapseNotificationAction extends Action {
static readonly ID = COLLAPSE_NOTIFICATION;
static readonly LABEL = localize('collapseNotification', "Collapse Notification");
constructor(
id: string,
label: string,
@ICommandService private readonly commandService: ICommandService
) {
super(id, label, ThemeIcon.asClassName(collapseIcon));
}
override async run(notification: INotificationViewItem): Promise<void> {
this.commandService.executeCommand(COLLAPSE_NOTIFICATION, notification);
}
} | AaronNGray/vscode | src/vs/workbench/browser/parts/notifications/notificationsActions.ts | TypeScript |
ClassDeclaration |
export class ConfigureNotificationAction extends Action {
static readonly ID = 'workbench.action.configureNotification';
static readonly LABEL = localize('configureNotification', "Configure Notification");
constructor(
id: string,
label: string,
readonly configurationActions: readonly IAction[]
) {
super(id, label, ThemeIcon.asClassName(configureIcon));
}
} | AaronNGray/vscode | src/vs/workbench/browser/parts/notifications/notificationsActions.ts | TypeScript |
ClassDeclaration |
export class CopyNotificationMessageAction extends Action {
static readonly ID = 'workbench.action.copyNotificationMessage';
static readonly LABEL = localize('copyNotification', "Copy Text");
constructor(
id: string,
label: string,
@IClipboardService private readonly clipboardService: IClipboardService
) {
super(id, label);
}
override run(notification: INotificationViewItem): Promise<void> {
return this.clipboardService.writeText(notification.message.raw);
}
} | AaronNGray/vscode | src/vs/workbench/browser/parts/notifications/notificationsActions.ts | TypeScript |
ClassDeclaration |
export class NotificationActionRunner extends ActionRunner {
constructor(
@ITelemetryService private readonly telemetryService: ITelemetryService,
@INotificationService private readonly notificationService: INotificationService
) {
super();
}
protected override async runAction(action: IAction, context: unknown): Promise<void> {
this.telemetryService.publicLog2<WorkbenchActionExecutedEvent, WorkbenchActionExecutedClassification>('workbenchActionExecuted', { id: action.id, from: 'message' });
if (isNotificationViewItem(context)) {
// Log some additional telemetry specifically for actions
// that are triggered from within notifications.
this.telemetryService.publicLog2<NotificationActionMetrics, NotificationActionMetricsClassification>('notification:actionExecuted', {
id: hash(context.message.original.toString()).toString(),
actionLabel: action.label,
source: context.sourceId || 'core',
silent: context.silent
});
}
// Run and make sure to notify on any error again
try {
await super.runAction(action, context);
} catch (error) {
this.notificationService.error(error);
}
}
} | AaronNGray/vscode | src/vs/workbench/browser/parts/notifications/notificationsActions.ts | TypeScript |
InterfaceDeclaration |
interface NotificationActionMetrics {
id: string;
actionLabel: string;
source: string;
silent: boolean;
} | AaronNGray/vscode | src/vs/workbench/browser/parts/notifications/notificationsActions.ts | TypeScript |
TypeAliasDeclaration |
type NotificationActionMetricsClassification = {
id: { classification: 'SystemMetaData'; purpose: 'FeatureInsight' };
actionLabel: { classification: 'SystemMetaData'; purpose: 'FeatureInsight' };
source: { classification: 'SystemMetaData'; purpose: 'FeatureInsight' };
silent: { classification: 'SystemMetaData'; purpose: 'FeatureInsight' };
}; | AaronNGray/vscode | src/vs/workbench/browser/parts/notifications/notificationsActions.ts | TypeScript |
MethodDeclaration |
override async run(notification: INotificationViewItem): Promise<void> {
this.commandService.executeCommand(CLEAR_NOTIFICATION, notification);
} | AaronNGray/vscode | src/vs/workbench/browser/parts/notifications/notificationsActions.ts | TypeScript |
MethodDeclaration |
override async run(): Promise<void> {
this.commandService.executeCommand(CLEAR_ALL_NOTIFICATIONS);
} | AaronNGray/vscode | src/vs/workbench/browser/parts/notifications/notificationsActions.ts | TypeScript |
MethodDeclaration |
override async run(): Promise<void> {
this.commandService.executeCommand(HIDE_NOTIFICATIONS_CENTER);
} | AaronNGray/vscode | src/vs/workbench/browser/parts/notifications/notificationsActions.ts | TypeScript |
MethodDeclaration |
override async run(notification: INotificationViewItem): Promise<void> {
this.commandService.executeCommand(EXPAND_NOTIFICATION, notification);
} | AaronNGray/vscode | src/vs/workbench/browser/parts/notifications/notificationsActions.ts | TypeScript |
Subsets and Splits