repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
SecureAI-Tools | github_2023 | SecureAI-Tools | typescript | DocumentService.getOrCreateByUri | private async getOrCreateByUri(
prisma: TxPrismaClient,
i: DocumentCreateInput,
): Promise<Document> {
const document = await prisma.document.findUnique({
where: {
uri: i.uri,
},
});
if (document) {
return document;
}
return await prisma.document.create({
data: {
id: i.id.toString(),
name: i.name,
mimeType: i.mimeType,
uri: i.uri,
externalId: i.externalId,
},
});
} | // Returns a document with given uri; Creates a new if one does not exist! | https://github.com/SecureAI-Tools/SecureAI-Tools/blob/260ddc5b190108ad7a2c70e273b0632e114d8ba1/packages/backend/src/services/document-service.ts#L71-L94 | 260ddc5b190108ad7a2c70e273b0632e114d8ba1 |
SecureAI-Tools | github_2023 | SecureAI-Tools | typescript | IndexingService.index | async *index(
documentId: Id<IdType.Document>,
collectionId: Id<IdType.DocumentCollection>,
dataSourceConnectionId: Id<IdType.DataSourceConnection>,
): AsyncGenerator<StreamChunkResponse> {
const document = await this.documentService.get(documentId);
if (!document) {
throw new Error(`Document does not exist: ${documentId.toString()}`);
}
const documentCollection =
await this.documentCollectionService.get(collectionId);
if (!documentCollection) {
throw new Error(
`Document collection does not exist: ${collectionId.toString()}`,
);
}
// Check other document collections to see if this document has already been indexed!
const indexedDocumentToCollections =
await this.documentToCollectionService.getAll({
where: {
documentId: documentId.toString(),
indexingStatus: DocumentIndexingStatus.INDEXED,
// Bound to same organization of the document collection
collection: {
organizationId: documentCollection.organizationId,
},
},
});
if (indexedDocumentToCollections.length > 0) {
// Document has already been indexed through some other collection; Reuse data from that indexing run!
yield* this.copyDocumentIndex(
document,
documentCollection,
Id.from(indexedDocumentToCollections[0]!.collectionId),
);
} else {
// Document has not yet been indexed! Compute embeddings and everything it!
yield* this.indexNewDocument(
document,
documentCollection,
dataSourceConnectionId,
);
}
} | // Indexes given document and yields statuses that can be streamed or logged. | https://github.com/SecureAI-Tools/SecureAI-Tools/blob/260ddc5b190108ad7a2c70e273b0632e114d8ba1/packages/backend/src/services/indexing-service.ts#L40-L87 | 260ddc5b190108ad7a2c70e273b0632e114d8ba1 |
SecureAI-Tools | github_2023 | SecureAI-Tools | typescript | IndexingService.indexNewDocument | private async *indexNewDocument(
document: Document,
documentCollection: DocumentCollection,
dataSourceConnectionId: Id<IdType.DataSourceConnection>,
): AsyncGenerator<StreamChunkResponse> {
const textSplitter = new RecursiveCharacterTextSplitter({
chunkSize: process.env.DOCS_INDEXING_CHUNK_SIZE
? parseInt(process.env.DOCS_INDEXING_CHUNK_SIZE)
: 1000,
chunkOverlap: process.env.DOCS_INDEXING_CHUNK_OVERLAP
? parseInt(process.env.DOCS_INDEXING_CHUNK_OVERLAP)
: 200,
});
const dataSourceConnection = await this.dataSourceConnectionService.get(
dataSourceConnectionId,
);
if (!dataSourceConnection) {
throw new Error(
`invalid dataSourceConnectionId ${dataSourceConnectionId}`,
);
}
// Index document and yield stream-chunks
yield { status: "Splitting documents into chunks" };
let langchainDocuments: LangchainDocument[];
switch (document.mimeType) {
case MimeType.PDF:
const blob = await this.documentService.read(
document,
dataSourceConnection,
);
const loader = new PDFLoader(blob);
langchainDocuments = await loader.loadAndSplit(textSplitter);
break;
case MimeType.GOOGLE_DOC:
case MimeType.NOTION_PAGE:
const text = await this.documentService.exportAsText(
document,
dataSourceConnection,
);
langchainDocuments = await textSplitter.createDocuments([text]);
break;
default:
throw new Error(`MimeType not supported: ${document.mimeType}`);
}
logger.debug("langchainDocuments", langchainDocuments);
const embeddingModel =
this.modelProviderService.getEmbeddingModel(documentCollection);
const documentTextChunks: string[] = langchainDocuments.map(
(document) => document.pageContent,
);
yield { status: `Processing ${documentTextChunks.length} chunks` };
let embeddings: number[][] = [];
for (let i = 0; i < documentTextChunks.length; i++) {
yield {
status: `Processing chunk ${i + 1} of ${documentTextChunks.length}`,
};
const documentTextChunk = documentTextChunks[i];
const chunkEmbedding = await embeddingModel.embedDocuments([
documentTextChunk!,
]);
embeddings.push(chunkEmbedding[0]!);
}
const chunkIdsInVectorDb = embeddings.map((_, i) =>
toDocumentChunkId(document.id, i),
);
if (documentTextChunks.length > 0) {
const vectorDbCollection = await this.chromaClient.getOrCreateCollection({
name: documentCollection.internalName,
});
const metadatas = langchainDocuments.map((langchainDocument, i) =>
toDocumentChunkMetadata(document.id, i, langchainDocument),
);
const addResponse = await vectorDbCollection.add({
ids: chunkIdsInVectorDb,
embeddings: embeddings,
documents: documentTextChunks,
metadatas: metadatas,
});
if (!isEmpty(addResponse.error)) {
logger.error("could not add document to vector db", {
documentId: document.id,
documentCollectionId: documentCollection.id,
error: addResponse.error,
});
yield { error: "something went wrong when indexing the doc" };
return;
}
} else {
logger.error("could not get any text chunks from document", {
documentId: document.id,
documentName: document.name,
});
yield { status: "could not get any text chunks from document; Skipping document..." };
}
const documentId = Id.from<IdType.Document>(document.id);
await this.documentService.updateIndexingStatus({
documentId: documentId,
collectionId: Id.from(documentCollection.id),
indexingStatus: DocumentIndexingStatus.INDEXED,
});
// Insert document chunks into db!
await this.documentChunkService.createMany(
chunkIdsInVectorDb.map((vid) => {
return {
vectorDbId: vid,
documentId: documentId,
};
}),
);
yield { status: "Document processed successfully" };
} | // Indexes a document that hasn't been indexed yet! Not safe for an already indexed document. | https://github.com/SecureAI-Tools/SecureAI-Tools/blob/260ddc5b190108ad7a2c70e273b0632e114d8ba1/packages/backend/src/services/indexing-service.ts#L90-L216 | 260ddc5b190108ad7a2c70e273b0632e114d8ba1 |
SecureAI-Tools | github_2023 | SecureAI-Tools | typescript | ModelProviderService.getChatModel | getChatModel({
model: modelName,
modelType: modelTypeStr,
}: {
model: string;
modelType: string | null;
}): BaseChatModel {
const modelType = modelTypeStr
? toModelType(modelTypeStr)
: ModelType.OLLAMA;
const config = this.getConfig(modelType);
if (!config) {
throw new Error(`could not get config for model-type = ${modelType}`);
}
logger.debug("Instantiating chat model", {
modelType: modelType,
config: config,
});
switch (modelType) {
case ModelType.OPENAI:
return new ChatOpenAI({
...config.options,
openAIApiKey: config.apiKey,
modelName: modelName,
streaming: true,
configuration: {
baseURL: config.apiBaseUrl,
},
});
case ModelType.OLLAMA:
return new ChatOllama({
...config.options,
baseUrl: config.apiBaseUrl,
model: modelName,
});
default:
throw new Error(`unsupported model type ${modelType}`);
}
} | // Defaults to Ollama if modelType is null. | https://github.com/SecureAI-Tools/SecureAI-Tools/blob/260ddc5b190108ad7a2c70e273b0632e114d8ba1/packages/backend/src/services/model-provider-service.ts#L22-L65 | 260ddc5b190108ad7a2c70e273b0632e114d8ba1 |
SecureAI-Tools | github_2023 | SecureAI-Tools | typescript | ModelProviderService.getEmbeddingModel | getEmbeddingModel({
model: modelName,
modelType: modelTypeStr,
}: {
model: string;
modelType: string | null;
}): Embeddings {
const modelType = modelTypeStr
? toModelType(modelTypeStr)
: ModelType.OLLAMA;
const config = this.getConfig(modelType);
if (!config) {
throw new Error(`could not get config for model-type = ${modelType}`);
}
logger.debug("Instantiating embedding model", {
modelType: modelType,
config: config,
});
switch (modelType) {
case ModelType.OPENAI:
return new OpenAIEmbeddings({
openAIApiKey: config.apiKey,
// Unlike Ollama, OpenAI has different model names for embedding v/s completion.
// It does not allow completion models for embedding APIs.
// https://platform.openai.com/docs/guides/embeddings/what-are-embeddings
modelName: config.embeddingsModel || "text-embedding-ada-002",
configuration: {
baseURL: config.apiBaseUrl,
},
});
case ModelType.OLLAMA:
return new OllamaEmbeddings({
// OllamaEmbeddings does not like extra slash at the end!
baseUrl: removeTrailingSlash(config.apiBaseUrl),
model: modelName,
requestOptions: config.options,
});
default:
throw new Error(`unsupported model type ${modelType}`);
}
} | // Defaults to Ollama if modelType is null. | https://github.com/SecureAI-Tools/SecureAI-Tools/blob/260ddc5b190108ad7a2c70e273b0632e114d8ba1/packages/backend/src/services/model-provider-service.ts#L69-L114 | 260ddc5b190108ad7a2c70e273b0632e114d8ba1 |
SecureAI-Tools | github_2023 | SecureAI-Tools | typescript | OAuthService.getAccessToken | async getAccessToken({
dataSource,
authorizationCode,
redirectUri,
orgId,
}: {
dataSource: DataSource,
authorizationCode: string,
redirectUri: string,
orgId: Id<IdType.Organization>,
}): Promise<OAuthTokens> {
switch (dataSource) {
case DataSource.GOOGLE_DRIVE:
return await this.getGoogleAccessToken(authorizationCode, redirectUri, orgId);
case DataSource.NOTION:
return await this.getNotionAccessToken(authorizationCode, redirectUri);
default:
throw new Error(`unsupported data source ${dataSource}`);
}
} | // Exchanges temporary authorizationCode for access token | https://github.com/SecureAI-Tools/SecureAI-Tools/blob/260ddc5b190108ad7a2c70e273b0632e114d8ba1/packages/backend/src/services/oauth-service.ts#L57-L76 | 260ddc5b190108ad7a2c70e273b0632e114d8ba1 |
embedded-app-sdk | github_2023 | discord | typescript | getRPCServerSource | function getRPCServerSource(): [Window, string] {
return [window.parent.opener ?? window.parent, !!document.referrer ? document.referrer : '*'];
} | /**
* The embedded application is running in an IFrame either within the main Discord client window or in a popout. The RPC server is always running in the main Discord client window. In either case, the referrer is the correct origin.
*/ | https://github.com/discord/embedded-app-sdk/blob/44bf2d1112a79c4f60473e439377cf6d233a4232/src/Discord.ts#L51-L53 | 44bf2d1112a79c4f60473e439377cf6d233a4232 |
embedded-app-sdk | github_2023 | discord | typescript | DiscordSDK.handleMessage | private handleMessage = (event: MessageEvent) => {
if (!ALLOWED_ORIGINS.has(event.origin)) return;
const tuple = event.data;
if (!Array.isArray(tuple)) {
return;
}
const [opcode, data] = tuple;
switch (opcode) {
case Opcodes.HELLO:
// backwards compat; the Discord client will still send HELLOs for old applications.
//
// TODO: figure out compatibility approach; it would be easier to maintain compatibility at the SDK level, not the underlying RPC protocol level...
return;
case Opcodes.CLOSE:
return this.handleClose(data);
case Opcodes.HANDSHAKE:
return this.handleHandshake();
case Opcodes.FRAME:
return this.handleFrame(data);
default:
throw new Error('Invalid message format');
}
} | /**
* WARNING - All "console" logs are emitted as messages to the Discord client
* If you write "console.log" anywhere in handleMessage or subsequent message handling
* there is a good chance you will cause an infinite loop where you receive a message
* which causes "console.log" which sends a message, which causes the discord client to
* send a reply which causes handleMessage to fire again, and again to inifinity
*
* If you need to log within handleMessage, consider setting
* config.disableConsoleLogOverride to true when initializing the SDK
*/ | https://github.com/discord/embedded-app-sdk/blob/44bf2d1112a79c4f60473e439377cf6d233a4232/src/Discord.ts | 44bf2d1112a79c4f60473e439377cf6d233a4232 |
embedded-app-sdk | github_2023 | discord | typescript | fromHexReverseArray | function fromHexReverseArray(hexValues: number[], start: number, size: number): number {
let value = 0;
for (let i = 0; i < size; i++) {
const byte = hexValues[start + i];
if (byte === undefined) {
break;
}
value += byte * 16 ** i;
}
return value;
} | /**
* Takes the sliced output of `toHexReverseArray` and converts hex to decimal.
*/ | https://github.com/discord/embedded-app-sdk/blob/44bf2d1112a79c4f60473e439377cf6d233a4232/src/utils/BigFlagUtils.ts#L32-L42 | 44bf2d1112a79c4f60473e439377cf6d233a4232 |
embedded-app-sdk | github_2023 | discord | typescript | toHexReverseArray | function toHexReverseArray(value: string): number[] {
const sum: number[] = [];
for (let i = 0; i < value.length; i++) {
let s = Number(value[i]);
for (let j = 0; s || j < sum.length; j++) {
s += (sum[j] || 0) * 10;
sum[j] = s % 16;
s = (s - sum[j]) / 16;
}
}
return sum;
} | /**
* Converts a number string to array of hex bytes based on the implementation found at
* https://stackoverflow.com/questions/18626844/convert-a-large-integer-to-a-hex-string-in-javascript
*
* To avoid extra allocations it returns the values in reverse.
*/ | https://github.com/discord/embedded-app-sdk/blob/44bf2d1112a79c4f60473e439377cf6d233a4232/src/utils/BigFlagUtils.ts#L50-L61 | 44bf2d1112a79c4f60473e439377cf6d233a4232 |
embedded-app-sdk | github_2023 | discord | typescript | splitBigInt | function splitBigInt(value: string): number[] {
const sum = toHexReverseArray(value);
const parts = Array(PARTS);
for (let i = 0; i < PARTS; i++) {
// Highest bits to lowest bits.
parts[PARTS - 1 - i] = fromHexReverseArray(sum, i * PARTS, PARTS);
}
return parts;
} | /**
* Splits a big integers into array of small integers to perform fast bitwise operations.
*/ | https://github.com/discord/embedded-app-sdk/blob/44bf2d1112a79c4f60473e439377cf6d233a4232/src/utils/BigFlagUtils.ts#L66-L74 | 44bf2d1112a79c4f60473e439377cf6d233a4232 |
embedded-app-sdk | github_2023 | discord | typescript | HighLow.toString | toString() {
if (this.str != null) {
return this.str;
}
const array = new Array(MAX_BIG_INT / 4);
this.parts.forEach((value, offset) => {
const hex = toHexReverseArray(value.toString());
for (let i = 0; i < 4; i++) {
array[i + offset * 4] = hex[4 - 1 - i] || 0;
}
});
return (this.str = bigInt.fromArray(array, 16).toString());
} | /**
* For the average case the string representation is provided, but
* when we need to convert high and low to string we just let the
* slower big-integer library do it.
*/ | https://github.com/discord/embedded-app-sdk/blob/44bf2d1112a79c4f60473e439377cf6d233a4232/src/utils/BigFlagUtils.ts#L124-L136 | 44bf2d1112a79c4f60473e439377cf6d233a4232 |
hollama | github_2023 | fmaclen | typescript | isCurrentVersionLatest | function isCurrentVersionLatest(currentVersion: string, latestVersion: string): boolean {
return (
currentVersion === latestVersion ||
semver.gt(
currentVersion.replace(HOLLAMA_DEV_VERSION_SUFFIX, ''),
latestVersion.replace(HOLLAMA_DEV_VERSION_SUFFIX, '')
)
);
} | // In development and test environments we append a '-dev' suffix to the version | https://github.com/fmaclen/hollama/blob/4b59bb8dda9addeb95358a5c9b5ffacbe95b39a5/src/lib/updates.ts#L36-L44 | 4b59bb8dda9addeb95358a5c9b5ffacbe95b39a5 |
luma-web-examples | github_2023 | lumalabs | typescript | createText | function createText() {
// create canvas
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d')!;
canvas.width = 1024;
canvas.height = 512;
// clear white, 0 alpha
context.fillStyle = 'rgba(255, 255, 255, 0)';
context.fillRect(0, 0, canvas.width, canvas.height);
// draw text
context.fillStyle = 'white';
// 100px helvetica, arial, sans-serif
context.font = '200px sans-serif';
context.textAlign = 'center';
context.textBaseline = 'middle';
// stroke
context.strokeStyle = 'rgba(0, 0, 0, 0.5)'
context.lineWidth = 5;
context.fillText('Hello World', canvas.width / 2, canvas.height / 2);
context.strokeText('Hello World', canvas.width / 2, canvas.height / 2);
// create texture from canvas
const texture = new Texture(canvas);
texture.needsUpdate = true;
// create plane geometry and mesh with the texture
const geometry = new PlaneGeometry(5, 2.5);
const material = new MeshStandardMaterial({
map: texture,
transparent: false,
alphaTest: 0.5,
side: DoubleSide,
premultipliedAlpha: true,
emissive: 'white',
emissiveIntensity: 2,
});
const textPlane = new Mesh(geometry, material);
// position and rotate
textPlane.position.set(0.8, -0.9, 0);
textPlane.rotation.y = Math.PI / 2;
textPlane.scale.setScalar(0.6);
return textPlane;
} | // create a plane with "Hello World" text | https://github.com/lumalabs/luma-web-examples/blob/fefe15436908140788d061f962e92684e3413cb8/src/DemoHelloWorld.ts#L37-L83 | fefe15436908140788d061f962e92684e3413cb8 |
luma-web-examples | github_2023 | lumalabs | typescript | toggleGUI | function toggleGUI(e: KeyboardEvent) {
if (e.key === 'h') {
if (showUI) {
gui?.hide();
setShowUI(false);
} else {
gui?.show();
setShowUI(true);
}
}
} | // h key to hide/show gui | https://github.com/lumalabs/luma-web-examples/blob/fefe15436908140788d061f962e92684e3413cb8/src/index.tsx#L131-L141 | fefe15436908140788d061f962e92684e3413cb8 |
luma-web-examples | github_2023 | lumalabs | typescript | onKeyDown | function onKeyDown(e: KeyboardEvent) {
if (e.key === 'e') {
setShowDocs(e => !e);
}
} | // press e to expand demo | https://github.com/lumalabs/luma-web-examples/blob/fefe15436908140788d061f962e92684e3413cb8/src/index.tsx#L220-L224 | fefe15436908140788d061f962e92684e3413cb8 |
astro-theme-typography | github_2023 | moeyua | typescript | createPost | async function createPost(): Promise<void> {
consola.start('Ready to create a new post!')
const filename: string = await consola.prompt('Enter file name: ', { type: 'text' })
const extension: string = await consola.prompt('Select file extension: ', { type: 'select', options: ['.md', '.mdx'] })
const isDraft: boolean = await consola.prompt('Is this a draft?', { type: 'confirm', initial: true })
const targetDir = './src/content/posts/'
const fullPath: string = path.join(targetDir, `${filename}${extension}`)
const frontmatter = getFrontmatter({
title: filename,
pubDate: dayjs().format('YYYY-MM-DD'),
categories: '[]',
description: '\'\'',
slug: filename.toLowerCase().replace(/\s+/g, '-'),
draft: isDraft ? 'true' : 'false',
})
try {
fs.writeFileSync(fullPath, frontmatter)
consola.success('New post created successfully!')
const open: boolean = await consola.prompt('Open the new post?', { type: 'confirm', initial: true })
if (open) {
consola.info(`Opening ${fullPath}...`)
execSync(`code "${fullPath}"`)
}
}
catch (error) {
consola.error((error as Error).message || 'Failed to create new post!')
}
} | /**
* Create a new post.
* Prompts the user for a file name and extension, and creates a new post file with frontmatter.
* If successful, opens the new post file in the default editor.
*/ | https://github.com/moeyua/astro-theme-typography/blob/423e0c4e493a746169b76aedc6b0b59c18342172/scripts/create-post.ts#L14-L46 | 423e0c4e493a746169b76aedc6b0b59c18342172 |
astro-theme-typography | github_2023 | moeyua | typescript | getFrontmatter | function getFrontmatter(data: { [key: string]: string }): string {
const frontmatter = Object.entries(data)
.map(([key, value]) => `${key}: ${value}`)
.join('\n')
return `---\n${frontmatter}\n---`
} | /**
* Create frontmatter from a data object.
* @param data The data object to convert to frontmatter.
* @returns The frontmatter as a string.
*/ | https://github.com/moeyua/astro-theme-typography/blob/423e0c4e493a746169b76aedc6b0b59c18342172/scripts/create-post.ts#L53-L59 | 423e0c4e493a746169b76aedc6b0b59c18342172 |
quickbooks-desktop-node | github_2023 | conductor-is | typescript | AuthSessionsResource.create | public async create(input: AuthSessionCreateInput): Promise<AuthSession> {
const { data } = await this.httpClient.post<AuthSession>(this.ROUTE, input);
return data;
} | /**
* Creates an AuthSession. Pass the returned session’s `authFlowUrl` to the
* client for your end-user to launch the IntegrationConnection authentication
* flow.
*/ | https://github.com/conductor-is/quickbooks-desktop-node/blob/55a445f9b6790da272a93aad14081a6655bb2200/src/resources/AuthSessionsResource.ts#L76-L79 | 55a445f9b6790da272a93aad14081a6655bb2200 |
quickbooks-desktop-node | github_2023 | conductor-is | typescript | AuthSessionsResource.retrieve | public async retrieve(id: AuthSession["id"]): Promise<AuthSession> {
const { data } = await this.httpClient.get<AuthSession>(
`${this.ROUTE}/${id}`,
);
return data;
} | /**
* Retrieves the specified AuthSession.
*/ | https://github.com/conductor-is/quickbooks-desktop-node/blob/55a445f9b6790da272a93aad14081a6655bb2200/src/resources/AuthSessionsResource.ts#L84-L89 | 55a445f9b6790da272a93aad14081a6655bb2200 |
quickbooks-desktop-node | github_2023 | conductor-is | typescript | EndUsersResource.list | public async list(): Promise<ApiListResponse<EndUser>> {
const { data } = await this.httpClient.get<ApiListResponse<EndUser>>(
this.ROUTE,
);
return data;
} | /**
* Returns a list of your EndUsers.
*/ | https://github.com/conductor-is/quickbooks-desktop-node/blob/55a445f9b6790da272a93aad14081a6655bb2200/src/resources/EndUsersResource.ts#L68-L73 | 55a445f9b6790da272a93aad14081a6655bb2200 |
quickbooks-desktop-node | github_2023 | conductor-is | typescript | EndUsersResource.create | public async create(input: EndUserCreateInput): Promise<EndUser> {
const { data } = await this.httpClient.post<EndUser>(this.ROUTE, input);
return data;
} | /**
* Creates a new EndUser.
*/ | https://github.com/conductor-is/quickbooks-desktop-node/blob/55a445f9b6790da272a93aad14081a6655bb2200/src/resources/EndUsersResource.ts#L78-L81 | 55a445f9b6790da272a93aad14081a6655bb2200 |
quickbooks-desktop-node | github_2023 | conductor-is | typescript | EndUsersResource.retrieve | public async retrieve(id: EndUser["id"]): Promise<EndUser> {
const { data } = await this.httpClient.get<EndUser>(`${this.ROUTE}/${id}`);
return data;
} | /**
* Retrieves the specified EndUser.
*/ | https://github.com/conductor-is/quickbooks-desktop-node/blob/55a445f9b6790da272a93aad14081a6655bb2200/src/resources/EndUsersResource.ts#L86-L89 | 55a445f9b6790da272a93aad14081a6655bb2200 |
quickbooks-desktop-node | github_2023 | conductor-is | typescript | EndUsersResource.delete | public async delete(id: EndUser["id"]): Promise<EndUserDeleteOutput> {
const { data } = await this.httpClient.delete<EndUserDeleteOutput>(
`${this.ROUTE}/${id}`,
);
return data;
} | /**
* Deletes the specified EndUser and all of its connections.
*/ | https://github.com/conductor-is/quickbooks-desktop-node/blob/55a445f9b6790da272a93aad14081a6655bb2200/src/resources/EndUsersResource.ts#L94-L99 | 55a445f9b6790da272a93aad14081a6655bb2200 |
quickbooks-desktop-node | github_2023 | conductor-is | typescript | EndUsersResource.ping | public async ping(
id: EndUser["id"],
integrationSlug: IntegrationSlug,
): Promise<EndUserPingOutput> {
const { data } = await this.httpClient.get<EndUserPingOutput>(
`${this.ROUTE}/${id}/ping/${integrationSlug}`,
);
return data;
} | /**
* Checks whether the specified IntegrationConnection can connect and process
* requests end-to-end.
*
* If the connection fails, the error we encountered will be thrown as a
* `ConductorError` (like any request). This information is useful for showing
* a "connection status" indicator in your app. If an error occurs, we
* strongly recommend displaying the property `error.userFacingMessage` to
* your end-user in your app's UI.
*
* @param id The ID of the end-user to ping.
* @param integrationSlug The integration identifier for the end-user's
* connection you want to ping (e.g. "quickbooks_desktop").
* @returns The ping result with the duration in milliseconds.
*/ | https://github.com/conductor-is/quickbooks-desktop-node/blob/55a445f9b6790da272a93aad14081a6655bb2200/src/resources/EndUsersResource.ts#L116-L124 | 55a445f9b6790da272a93aad14081a6655bb2200 |
quickbooks-desktop-node | github_2023 | conductor-is | typescript | ConductorUnknownError.constructor | public constructor(options: ConductorErrorOptions) {
super(options);
} | // not overriding `rawType`. | https://github.com/conductor-is/quickbooks-desktop-node/blob/55a445f9b6790da272a93aad14081a6655bb2200/src/utils/error.ts#L275-L277 | 55a445f9b6790da272a93aad14081a6655bb2200 |
prisma-extension-kysely | github_2023 | eoin-obrien | typescript | kyselyTransaction | const kyselyTransaction =
(target: typeof extendedClient) =>
(...args: Parameters<typeof target.$transaction>) => {
if (typeof args[0] === "function") {
// If the first argument is a function, add a fresh Kysely instance to the transaction client
const [fn, options] = args;
return target.$transaction(async (tx) => {
// The Kysely instance should call the transaction client, not the original client
const driver = new PrismaDriver(tx);
const kysely = extensionArgs.kysely(driver);
tx.$kysely = kysely;
return fn(tx);
}, options);
} else {
// Otherwise, just call the original $transaction method
return target.$transaction(...args);
}
}; | // Wrap the $transaction method to attach a fresh Kysely instance to the transaction client | https://github.com/eoin-obrien/prisma-extension-kysely/blob/ef3811d0202454237024b4fa07515ffd66826172/src/index.ts#L50-L67 | ef3811d0202454237024b4fa07515ffd66826172 |
stackwise | github_2023 | stackwiseai | typescript | checkTranscodeJobStatus | const checkTranscodeJobStatus = async (jobId) => {
const params = { Id: jobId };
return transcoder.readJob(params).promise();
}; | // Function to check the status of a transcoding job | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/app/api/stacks/cover-image-and-subtitle/route.ts#L29-L32 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | waitForJobCompletion | const waitForJobCompletion = async (
jobId,
interval = 1000,
timeout = 30000,
) => {
let timePassed = 0;
while (timePassed < timeout) {
const { Job } = await checkTranscodeJobStatus(jobId);
if (Job) {
console.log('Job status:', Job.Status);
if (Job.Status === 'Complete') {
return true;
} else if (Job.Status === 'Error') {
// Log or return the specific error message from the job
throw new Error(`Transcoding job failed from an Error`);
}
// Wait for the specified interval before checking again
await new Promise((resolve) => setTimeout(resolve, interval));
timePassed += interval;
} else {
throw new Error('Transcoding job failed: Job status not available');
}
}
throw new Error('Transcoding job timed out');
}; | // Function to wait for the job to complete | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/app/api/stacks/cover-image-and-subtitle/route.ts#L35-L62 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | getAudioBase64 | const getAudioBase64 = async (bucketName, audioKey) => {
const params = {
Bucket: bucketName,
Key: audioKey,
};
try {
const data = await s3.getObject(params).promise();
if (data.Body) {
return data.Body.toString('base64');
} else {
throw new Error('No data body in response');
}
} catch (error) {
console.error('Error getting audio base64:', error);
throw error; // Re-throw the error for handling it in the calling function
}
}; | // Function to get the base64 string of the audio file | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/app/api/stacks/cover-image-and-subtitle/route.ts#L74-L90 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | textToSpeech | const textToSpeech = async (
apiKey: string | undefined,
voiceID: string,
fileName: string,
textInput: string,
stability?: number,
similarityBoost?: number,
modelId?: string,
) => {
try {
if (!apiKey || !voiceID || !fileName || !textInput) {
console.log(
'ERR: Missing parameter',
apiKey,
voiceID,
fileName,
textInput,
);
}
const voiceURL = `${elevenLabsAPI}/text-to-speech/${voiceID}`;
const stabilityValue = stability ? stability : 0;
const similarityBoostValue = similarityBoost ? similarityBoost : 0;
const response = await axios({
method: 'POST',
url: voiceURL,
data: {
text: textInput,
voice_settings: {
stability: stabilityValue,
similarity_boost: similarityBoostValue,
},
model_id: modelId ? modelId : undefined,
},
headers: {
Accept: 'audio/mpeg',
'xi-api-key': apiKey,
'Content-Type': 'application/json',
},
responseType: 'stream',
});
return new Promise((resolve, reject) => {
const writeStream = fs.createWriteStream(fileName);
response.data.pipe(writeStream);
writeStream.on('finish', () => resolve(fileName));
writeStream.on('error', reject);
});
} catch (error) {
console.log(error);
}
}; | // Need to adapt from elevenlabs-node because of https://github.com/FelixWaweru/elevenlabs-node/issues/16 | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/app/api/stacks/elevenlabs-tts/route.ts#L11-L64 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | createMessage | const createMessage = (text: string): BaseMessage => {
if (text.startsWith('Q: ')) {
return new HumanMessage({ content: text.slice(3) });
} else if (text.startsWith('A: ')) {
return new AIMessage({ content: text.slice(3) });
} else {
throw new Error('Unrecognized message type');
}
}; | // Function to create a HumanMessage or AIMessage based on the prefix | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/app/api/stacks/rag-pdf-with-langchain/route.ts#L15-L23 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | transformToChatMessageHistory | const transformToChatMessageHistory = (
chatString: string,
): ChatMessageHistory => {
const messageHistory = new ChatMessageHistory();
const messages = chatString.split(chatHistoryDelimiter);
messages.forEach((messagePart) => {
const trimmedMessage = messagePart.trim();
if (trimmedMessage) {
const message = createMessage(trimmedMessage);
messageHistory.addMessage(message);
}
});
return messageHistory;
}; | // Function to transform the specially delimited string into ChatMessageHistory | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/app/api/stacks/rag-pdf-with-langchain/route.ts#L26-L41 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | checkUser | async function checkUser() {
try {
const session = await supabaseClient.auth.getSession();
const token = session?.data?.session?.provider_token;
if (token) {
setIsUserSignedIn(true);
setUsername(
session?.data?.session?.user.user_metadata.preferred_username,
);
setToken(token);
}
} catch {
console.log('Error getting user');
}
} | // Check if user is signed in | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/app/components/stacks/create-stack-boilerplate.tsx#L22-L37 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | multiplyNumbers | async function multiplyNumbers(num1: number, num2: number): Promise<number> {
return num1 * num2;
} | /**
* Brief: Multiply two numbers together
*/ | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/app/components/stacks/utils/actions.ts#L58-L60 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | signInWithGithub | async function signInWithGithub() {
const { data, error } = await supabaseClient.auth.signInWithOAuth({
provider: 'github',
options: {
scopes: 'public_repo',
redirectTo: `${baseUrl}/stacks/create-stack-boilerplate`,
},
});
} | // Default to localhost in development | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/app/components/stacks/utils/signIn.tsx#L11-L19 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | checkUser | async function checkUser() {
try {
const session = await supabaseClient.auth.getSession();
const token = session?.data?.session?.provider_token;
if (token) {
setIsUserSignedIn(true);
setUsername(
session?.data?.session?.user.user_metadata.preferred_username,
);
setToken(token);
}
} catch {
console.log('Error getting user');
}
} | // Check if user is signed in | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/public/stacks/create-stack-boilerplate.tsx#L22-L37 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | checkTranscodeJobStatus | const checkTranscodeJobStatus = async (jobId) => {
const params = { Id: jobId };
return transcoder.readJob(params).promise();
}; | // Function to check the status of a transcoding job | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/public/stacks/stacks/cover-image-and-subtitle/route.ts#L29-L32 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | waitForJobCompletion | const waitForJobCompletion = async (
jobId,
interval = 1000,
timeout = 30000,
) => {
let timePassed = 0;
while (timePassed < timeout) {
const { Job } = await checkTranscodeJobStatus(jobId);
if (Job) {
console.log('Job status:', Job.Status);
if (Job.Status === 'Complete') {
return true;
} else if (Job.Status === 'Error') {
// Log or return the specific error message from the job
throw new Error(`Transcoding job failed from an Error`);
}
// Wait for the specified interval before checking again
await new Promise((resolve) => setTimeout(resolve, interval));
timePassed += interval;
} else {
throw new Error('Transcoding job failed: Job status not available');
}
}
throw new Error('Transcoding job timed out');
}; | // Function to wait for the job to complete | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/public/stacks/stacks/cover-image-and-subtitle/route.ts#L35-L62 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | getAudioBase64 | const getAudioBase64 = async (bucketName, audioKey) => {
const params = {
Bucket: bucketName,
Key: audioKey,
};
try {
const data = await s3.getObject(params).promise();
if (data.Body) {
return data.Body.toString('base64');
} else {
throw new Error('No data body in response');
}
} catch (error) {
console.error('Error getting audio base64:', error);
throw error; // Re-throw the error for handling it in the calling function
}
}; | // Function to get the base64 string of the audio file | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/public/stacks/stacks/cover-image-and-subtitle/route.ts#L74-L90 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | textToSpeech | const textToSpeech = async (
apiKey: string | undefined,
voiceID: string,
fileName: string,
textInput: string,
stability?: number,
similarityBoost?: number,
modelId?: string,
) => {
try {
if (!apiKey || !voiceID || !fileName || !textInput) {
console.log(
'ERR: Missing parameter',
apiKey,
voiceID,
fileName,
textInput,
);
}
const voiceURL = `${elevenLabsAPI}/text-to-speech/${voiceID}`;
const stabilityValue = stability ? stability : 0;
const similarityBoostValue = similarityBoost ? similarityBoost : 0;
const response = await axios({
method: 'POST',
url: voiceURL,
data: {
text: textInput,
voice_settings: {
stability: stabilityValue,
similarity_boost: similarityBoostValue,
},
model_id: modelId ? modelId : undefined,
},
headers: {
Accept: 'audio/mpeg',
'xi-api-key': apiKey,
'Content-Type': 'application/json',
},
responseType: 'stream',
});
return new Promise((resolve, reject) => {
const writeStream = fs.createWriteStream(fileName);
response.data.pipe(writeStream);
writeStream.on('finish', () => resolve(fileName));
writeStream.on('error', reject);
});
} catch (error) {
console.log(error);
}
}; | // Need to adapt from elevenlabs-node because of https://github.com/FelixWaweru/elevenlabs-node/issues/16 | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/public/stacks/stacks/elevenlabs-tts/route.ts#L11-L64 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | createMessage | const createMessage = (text: string): BaseMessage => {
if (text.startsWith('Q: ')) {
return new HumanMessage({ content: text.slice(3) });
} else if (text.startsWith('A: ')) {
return new AIMessage({ content: text.slice(3) });
} else {
throw new Error('Unrecognized message type');
}
}; | // Function to create a HumanMessage or AIMessage based on the prefix | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/public/stacks/stacks/rag-pdf-with-langchain/route.ts#L15-L23 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | transformToChatMessageHistory | const transformToChatMessageHistory = (
chatString: string,
): ChatMessageHistory => {
const messageHistory = new ChatMessageHistory();
const messages = chatString.split(chatHistoryDelimiter);
messages.forEach((messagePart) => {
const trimmedMessage = messagePart.trim();
if (trimmedMessage) {
const message = createMessage(trimmedMessage);
messageHistory.addMessage(message);
}
});
return messageHistory;
}; | // Function to transform the specially delimited string into ChatMessageHistory | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/public/stacks/stacks/rag-pdf-with-langchain/route.ts#L26-L41 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | multiplyNumbers | async function multiplyNumbers(num1: number, num2: number): Promise<number> {
return num1 * num2;
} | /**
* Brief: Multiply two numbers together
*/ | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/public/stacks/utils/actions.ts#L58-L60 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | signInWithGithub | async function signInWithGithub() {
const { data, error } = await supabaseClient.auth.signInWithOAuth({
provider: 'github',
options: {
scopes: 'public_repo',
redirectTo: `${baseUrl}/stacks/create-stack-boilerplate`,
},
});
} | // Default to localhost in development | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/public/stacks/utils/signIn.tsx#L11-L19 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | oneOf | function oneOf(...options) {
return Object.assign(
(value = true) => {
for (let option of options) {
let parsed = option(value)
if (parsed === value) {
return parsed
}
}
throw new Error('...')
},
{ manualParsing: true }
)
} | // --- | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/tooling/tailwind-config/node_modules/tailwindcss/src/oxide/cli/index.ts#L13-L27 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | loadPostCssPlugins | async function loadPostCssPlugins(customPostCssPath) {
let config = customPostCssPath
? await (async () => {
let file = path.resolve(customPostCssPath)
// Implementation, see: https://unpkg.com/browse/postcss-load-config@3.1.0/src/index.js
// @ts-ignore
let { config = {} } = await lilconfig('postcss').load(file)
if (typeof config === 'function') {
config = config()
} else {
config = Object.assign({}, config)
}
if (!config.plugins) {
config.plugins = []
}
return {
file,
plugins: loadPlugins(config, file),
options: loadOptions(config, file),
}
})()
: await postcssrc()
let configPlugins = config.plugins
let configPluginTailwindIdx = configPlugins.findIndex((plugin) => {
if (typeof plugin === 'function' && plugin.name === 'tailwindcss') {
return true
}
if (typeof plugin === 'object' && plugin !== null && plugin.postcssPlugin === 'tailwindcss') {
return true
}
return false
})
let beforePlugins =
configPluginTailwindIdx === -1 ? [] : configPlugins.slice(0, configPluginTailwindIdx)
let afterPlugins =
configPluginTailwindIdx === -1
? configPlugins
: configPlugins.slice(configPluginTailwindIdx + 1)
return [beforePlugins, afterPlugins, config.options]
} | /**
*
* @param {string} [customPostCssPath ]
* @returns
*/ | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/tooling/tailwind-config/node_modules/tailwindcss/src/oxide/cli/build/plugin.ts#L27-L75 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | parseChanges | async function parseChanges(changes) {
return Promise.all(
changes.map(async (change) => ({
content: await change.content(),
extension: change.extension,
}))
)
} | /**
* @param {{file: string, content(): Promise<string>, extension: string}[]} changes
*/ | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/tooling/tailwind-config/node_modules/tailwindcss/src/oxide/cli/build/plugin.ts#L397-L404 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | rebuildAndContinue | async function rebuildAndContinue() {
let changes = changedContent.splice(0)
// There are no changes to rebuild so we can just do nothing
if (changes.length === 0) {
return Promise.resolve()
}
// Clear all pending rebuilds for the about-to-be-built files
changes.forEach((change) => pendingRebuilds.delete(change.file))
// Resolve the promise even when the rebuild fails
return rebuild(changes).then(
() => {},
() => {}
)
} | /**
* Rebuilds the changed files and resolves when the rebuild is
* complete regardless of whether it was successful or not
*/ | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/tooling/tailwind-config/node_modules/tailwindcss/src/oxide/cli/build/watching.ts#L76-L92 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
stackwise | github_2023 | stackwiseai | typescript | recordChangedFile | function recordChangedFile(file, content = null, skipPendingCheck = false) {
file = path.resolve(file)
// Applications like Vim/Neovim fire both rename and change events in succession for atomic writes
// In that case rebuild has already been queued by rename, so can be skipped in change
if (pendingRebuilds.has(file) && !skipPendingCheck) {
return Promise.resolve()
}
// Mark that a rebuild of this file is going to happen
// It MUST happen synchronously before the rebuild is queued for this to be effective
pendingRebuilds.add(file)
changedContent.push({
file,
content: content ?? (() => fs.promises.readFile(file, 'utf8')),
extension: path.extname(file).slice(1),
})
if (_timer) {
clearTimeout(_timer)
_reject()
}
// If a rebuild is already in progress we don't want to start another one until the 10ms timer has expired
chain = chain.then(
() =>
new Promise((resolve, reject) => {
_timer = setTimeout(resolve, 10)
_reject = reject
})
)
// Resolves once this file has been rebuilt (or the rebuild for this file has failed)
// This queues as many rebuilds as there are changed files
// But those rebuilds happen after some delay
// And will immediately resolve if there are no changes
chain = chain.then(rebuildAndContinue, rebuildAndContinue)
return chain
} | /**
*
* @param {*} file
* @param {(() => Promise<string>) | null} content
* @param {boolean} skipPendingCheck
* @returns {Promise<void>}
*/ | https://github.com/stackwiseai/stackwise/blob/c49a192df253bea4d6c8889049816cbcbb57cce1/tooling/tailwind-config/node_modules/tailwindcss/src/oxide/cli/build/watching.ts#L101-L141 | c49a192df253bea4d6c8889049816cbcbb57cce1 |
obsidian-pomodoro-timer | github_2023 | eatgrass | typescript | DefaultTaskSerializer.parsePriority | protected parsePriority(p: string): Priority {
const { prioritySymbols } = this.symbols
switch (p) {
case prioritySymbols.Lowest:
return Priority.Lowest
case prioritySymbols.Low:
return Priority.Low
case prioritySymbols.Medium:
return Priority.Medium
case prioritySymbols.High:
return Priority.High
case prioritySymbols.Highest:
return Priority.Highest
default:
return Priority.None
}
} | /**
* Given the string captured in the first capture group of
* {@link DefaultTaskSerializerSymbols.TaskFormatRegularExpressions.priorityRegex},
* returns the corresponding Priority level.
*
* @param p String captured by priorityRegex
* @returns Corresponding priority if parsing was successful, otherwise {@link Priority.None}
*/ | https://github.com/eatgrass/obsidian-pomodoro-timer/blob/f56bcc3cb4d719ce5504c76bbca54432d49ade6b/src/serializer/DefaultTaskSerializer.ts#L92-L108 | f56bcc3cb4d719ce5504c76bbca54432d49ade6b |
obsidian-pomodoro-timer | github_2023 | eatgrass | typescript | DefaultTaskSerializer.deserialize | public deserialize(line: string): TaskDetails {
const { TaskFormatRegularExpressions } = this.symbols
// Keep matching and removing special strings from the end of the
// description in any order. The loop should only run once if the
// strings are in the expected order after the description.
// NEW_TASK_FIELD_EDIT_REQUIRED
let matched: boolean
let priority: Priority = Priority.None
let startDate: Moment | null = null
let scheduledDate: Moment | null = null
let dueDate: Moment | null = null
let doneDate: Moment | null = null
let cancelledDate: Moment | null = null
let createdDate: Moment | null = null
let recurrenceRule: string = ''
let pomodoros: string = ''
// Tags that are removed from the end while parsing, but we want to add them back for being part of the description.
// In the original task description they are possibly mixed with other components
// (e.g. #tag1 <due date> #tag2), they do not have to all trail all task components,
// but eventually we want to paste them back to the task description at the end
let trailingTags = ''
// Add a "max runs" failsafe to never end in an endless loop:
const maxRuns = 20
let runs = 0
do {
// NEW_TASK_FIELD_EDIT_REQUIRED
matched = false
const pomodorosMatch = line.match(
TaskFormatRegularExpressions.pomodorosRegex,
)
if (pomodorosMatch !== null) {
pomodoros = pomodorosMatch[1]
line = line
.replace(TaskFormatRegularExpressions.pomodorosRegex, '')
.trim()
matched = true
}
const priorityMatch = line.match(
TaskFormatRegularExpressions.priorityRegex,
)
if (priorityMatch !== null) {
priority = this.parsePriority(priorityMatch[1])
line = line
.replace(TaskFormatRegularExpressions.priorityRegex, '')
.trim()
matched = true
}
const doneDateMatch = line.match(
TaskFormatRegularExpressions.doneDateRegex,
)
if (doneDateMatch !== null) {
doneDate = window.moment(
doneDateMatch[1],
TaskRegularExpressions.dateFormat,
)
line = line
.replace(TaskFormatRegularExpressions.doneDateRegex, '')
.trim()
matched = true
}
const cancelledDateMatch = line.match(
TaskFormatRegularExpressions.cancelledDateRegex,
)
if (cancelledDateMatch !== null) {
cancelledDate = window.moment(
cancelledDateMatch[1],
TaskRegularExpressions.dateFormat,
)
line = line
.replace(
TaskFormatRegularExpressions.cancelledDateRegex,
'',
)
.trim()
matched = true
}
const dueDateMatch = line.match(
TaskFormatRegularExpressions.dueDateRegex,
)
if (dueDateMatch !== null) {
dueDate = window.moment(
dueDateMatch[1],
TaskRegularExpressions.dateFormat,
)
line = line
.replace(TaskFormatRegularExpressions.dueDateRegex, '')
.trim()
matched = true
}
const scheduledDateMatch = line.match(
TaskFormatRegularExpressions.scheduledDateRegex,
)
if (scheduledDateMatch !== null) {
scheduledDate = window.moment(
scheduledDateMatch[1],
TaskRegularExpressions.dateFormat,
)
line = line
.replace(
TaskFormatRegularExpressions.scheduledDateRegex,
'',
)
.trim()
matched = true
}
const startDateMatch = line.match(
TaskFormatRegularExpressions.startDateRegex,
)
if (startDateMatch !== null) {
startDate = window.moment(
startDateMatch[1],
TaskRegularExpressions.dateFormat,
)
line = line
.replace(TaskFormatRegularExpressions.startDateRegex, '')
.trim()
matched = true
}
const createdDateMatch = line.match(
TaskFormatRegularExpressions.createdDateRegex,
)
if (createdDateMatch !== null) {
createdDate = window.moment(
createdDateMatch[1],
TaskRegularExpressions.dateFormat,
)
line = line
.replace(TaskFormatRegularExpressions.createdDateRegex, '')
.trim()
matched = true
}
const recurrenceMatch = line.match(
TaskFormatRegularExpressions.recurrenceRegex,
)
if (recurrenceMatch !== null) {
// Save the recurrence rule, but *do not parse it yet*.
// Creating the Recurrence object requires a reference date (e.g. a due date),
// and it might appear in the next (earlier in the line) tokens to parse
recurrenceRule = recurrenceMatch[1].trim()
line = line
.replace(TaskFormatRegularExpressions.recurrenceRegex, '')
.trim()
matched = true
}
// Match tags from the end to allow users to mix the various task components with
// tags. These tags will be added back to the description below
const tagsMatch = line.match(TaskRegularExpressions.hashTagsFromEnd)
if (tagsMatch != null) {
line = line
.replace(TaskRegularExpressions.hashTagsFromEnd, '')
.trim()
matched = true
const tagName = tagsMatch[0].trim()
// Adding to the left because the matching is done right-to-left
trailingTags =
trailingTags.length > 0
? [tagName, trailingTags].join(' ')
: tagName
}
runs++
} while (matched && runs <= maxRuns)
// Add back any trailing tags to the description. We removed them so we can parse the rest of the
// components but now we want them back.
// The goal is for a task of them form 'Do something #tag1 (due) tomorrow #tag2 (start) today'
// to actually have the description 'Do something #tag1 #tag2'
if (trailingTags.length > 0) line += ' ' + trailingTags
// NEW_TASK_FIELD_EDIT_REQUIRED
return {
description: line,
priority,
startDate,
createdDate,
scheduledDate,
dueDate,
doneDate,
cancelledDate,
recurrenceRule,
pomodoros,
tags: extractHashtags(line),
}
} | /* Parse TaskDetails from the textual description of a {@link Task}
*
* @param line The string to parse
*
* @return {TaskDetails}
*/ | https://github.com/eatgrass/obsidian-pomodoro-timer/blob/f56bcc3cb4d719ce5504c76bbca54432d49ade6b/src/serializer/DefaultTaskSerializer.ts#L116-L310 | f56bcc3cb4d719ce5504c76bbca54432d49ade6b |
codemirror-copilot | github_2023 | asadm | typescript | wrapUserFetcher | function wrapUserFetcher(onSuggestionRequest: SuggestionRequestCallback) {
return async function fetchSuggestion(state: EditorState) {
const { from, to } = state.selection.ranges[0];
const text = state.doc.toString();
const prefix = text.slice(0, to);
const suffix = text.slice(from);
// If we have a local suggestion cache, use it
const key = `${prefix}<:|:>${suffix}`;
const localSuggestion = localSuggestionsCache[key];
if (localSuggestion) {
return localSuggestion;
}
const prediction = await onSuggestionRequest(prefix, suffix);
localSuggestionsCache[key] = prediction;
return prediction;
};
} | /**
* Wraps a user-provided fetch method so that users
* don't have to interact directly with the EditorState
* object, and connects it to the local result cache.
*/ | https://github.com/asadm/codemirror-copilot/blob/09e737a3da8449d5d7f0b5cd8266688afaf3baa5/packages/codemirror-copilot/src/copilot.ts#L21-L39 | 09e737a3da8449d5d7f0b5cd8266688afaf3baa5 |
codemirror-copilot | github_2023 | asadm | typescript | inlineSuggestionDecoration | function inlineSuggestionDecoration(view: EditorView, suggestionText: string) {
const pos = view.state.selection.main.head;
const widgets = [];
const w = Decoration.widget({
widget: new InlineSuggestionWidget(suggestionText),
side: 1,
});
widgets.push(w.range(pos));
return Decoration.set(widgets);
} | /**
* Rendered by `renderInlineSuggestionPlugin`,
* this creates possibly multiple lines of ghostly
* text to show what would be inserted if you accept
* the AI suggestion.
*/ | https://github.com/asadm/codemirror-copilot/blob/09e737a3da8449d5d7f0b5cd8266688afaf3baa5/packages/codemirror-copilot/src/inline-suggestion.ts#L66-L75 | 09e737a3da8449d5d7f0b5cd8266688afaf3baa5 |
codemirror-copilot | github_2023 | asadm | typescript | InlineSuggestionWidget.constructor | constructor(suggestion: string) {
super();
this.suggestion = suggestion;
} | /**
* Create a new suggestion widget.
*/ | https://github.com/asadm/codemirror-copilot/blob/09e737a3da8449d5d7f0b5cd8266688afaf3baa5/packages/codemirror-copilot/src/inline-suggestion.ts#L99-L102 | 09e737a3da8449d5d7f0b5cd8266688afaf3baa5 |
Solana-raydium-sniper-bot | github_2023 | hudesdev | typescript | loadSnipeList | function loadSnipeList() {
if (!USE_SNIPE_LIST) {
return;
}
const count = snipeList.length;
const data = fs.readFileSync(path.join(__dirname, 'snipe-list.txt'), 'utf-8');
snipeList = data
.split('\n')
.map((a) => a.trim())
.filter((a) => a);
if (snipeList.length != count) {
logger.info(`Loaded snipe list: ${snipeList.length}`);
}
} | // async function getMarkPrice(connection: Connection, baseMint: PublicKey, quoteMint?: PublicKey): Promise<number> { | https://github.com/hudesdev/Solana-raydium-sniper-bot/blob/1851088920c8386db25fc58b7383e5118d9dd515/start.ts#L437-L452 | 1851088920c8386db25fc58b7383e5118d9dd515 |
open-saas | github_2023 | wasp-lang | typescript | CookieConsentBanner | const CookieConsentBanner = () => {
useEffect(() => {
CookieConsent.run(getConfig());
}, []);
return <div id='cookieconsent'></div>;
}; | /**
* NOTE: if you do not want to use the cookie consent banner, you should
* run `npm uninstall vanilla-cookieconsent`, and delete this component, its config file,
* as well as its import in src/client/App.tsx .
*/ | https://github.com/wasp-lang/open-saas/blob/8fdee109e451a1d629dd116222b67298edb02737/template/app/src/client/components/cookie-consent/Banner.tsx#L11-L17 | 8fdee109e451a1d629dd116222b67298edb02737 |
open-saas | github_2023 | wasp-lang | typescript | handleOrderCreated | async function handleOrderCreated(data: Order, userId: string, prismaUserDelegate: PrismaClient['user']) {
const { customer_id, status, first_order_item, order_number } = data.data.attributes;
const lemonSqueezyId = customer_id.toString();
const planId = getPlanIdByVariantId(first_order_item.variant_id.toString());
const plan = paymentPlans[planId];
const lemonSqueezyCustomerPortalUrl = await fetchUserCustomerPortalUrl({ lemonSqueezyId });
let numOfCreditsPurchased: number | undefined = undefined;
let datePaid: Date | undefined = undefined;
if (status === 'paid' && plan.effect.kind === 'credits') {
numOfCreditsPurchased = plan.effect.amount;
datePaid = new Date();
}
await updateUserLemonSqueezyPaymentDetails(
{ lemonSqueezyId, userId, lemonSqueezyCustomerPortalUrl, numOfCreditsPurchased, datePaid },
prismaUserDelegate
);
console.log(`Order ${order_number} created for user ${lemonSqueezyId}`);
} | // This will fire for one-time payment orders AND subscriptions. But subscriptions will ALSO send a follow-up | https://github.com/wasp-lang/open-saas/blob/8fdee109e451a1d629dd116222b67298edb02737/template/app/src/payment/lemonSqueezy/webhook.ts#L73-L95 | 8fdee109e451a1d629dd116222b67298edb02737 |
open-saas | github_2023 | wasp-lang | typescript | handleSubscriptionUpdated | async function handleSubscriptionUpdated(data: Subscription, userId: string, prismaUserDelegate: PrismaClient['user']) {
const { customer_id, status, variant_id } = data.data.attributes;
const lemonSqueezyId = customer_id.toString();
const planId = getPlanIdByVariantId(variant_id.toString());
// We ignore other statuses like 'paused' and 'unpaid' for now, because we block user usage if their status is NOT active.
// Note that a status changes to 'past_due' on a failed payment retry, then after 4 unsuccesful payment retries status
// becomes 'unpaid' and finally 'expired' (i.e. 'deleted').
// NOTE: ability to pause or trial a subscription is something that has to be additionally configured in the lemon squeezy dashboard.
// If you do enable these features, make sure to handle these statuses here.
if (status === 'past_due' || status === 'active') {
await updateUserLemonSqueezyPaymentDetails(
{
lemonSqueezyId,
userId,
subscriptionPlan: planId,
subscriptionStatus: status,
...(status === 'active' && { datePaid: new Date() }),
},
prismaUserDelegate
);
console.log(`Subscription updated for user ${lemonSqueezyId}`);
}
} | // NOTE: LemonSqueezy's 'subscription_updated' event is sent as a catch-all and fires even after 'subscription_created' & 'order_created'. | https://github.com/wasp-lang/open-saas/blob/8fdee109e451a1d629dd116222b67298edb02737/template/app/src/payment/lemonSqueezy/webhook.ts#L123-L147 | 8fdee109e451a1d629dd116222b67298edb02737 |
shadcn-ui-expansions | github_2023 | hsuanyi-chou | typescript | AdBase | const AdBase = ({ id, slot, layout, format = 'auto', className }: AdBaseProps) => {
return (
<>
<script
async
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-5359135355025668"
crossOrigin="anonymous"
></script>
<ins
className={cn('adsbygoogle', className)}
style={{ display: 'block' }}
data-ad-client="ca-pub-5359135355025668"
data-ad-slot={slot}
data-ad-layout={layout}
data-ad-format={format}
data-full-width-responsive="true"
data-ad-channel="shadcnui-expansions"
></ins>
<Script id={id} strategy="afterInteractive">{`
(adsbygoogle = window.adsbygoogle || []).push({});
`}</Script>
</>
);
}; | /**
* reference: https://support.google.com/adsense/answer/9183363?visit_id=638147466252817641-3093829945&rd=1
*/ | https://github.com/hsuanyi-chou/shadcn-ui-expansions/blob/4240453967eb55ca7e3321aa34e6373c6dbd117c/components/ad/ad-base.tsx#L18-L41 | 4240453967eb55ca7e3321aa34e6373c6dbd117c |
shadcn-ui-expansions | github_2023 | hsuanyi-chou | typescript | handleSelect | const handleSelect = (newDay: Date | undefined) => {
if (!newDay) {
return;
}
if (!defaultPopupValue) {
newDay.setHours(month?.getHours() ?? 0, month?.getMinutes() ?? 0, month?.getSeconds() ?? 0);
onChange?.(newDay);
setMonth(newDay);
return;
}
const diff = newDay.getTime() - defaultPopupValue.getTime();
const diffInDays = diff / (1000 * 60 * 60 * 24);
const newDateFull = add(defaultPopupValue, { days: Math.ceil(diffInDays) });
newDateFull.setHours(
month?.getHours() ?? 0,
month?.getMinutes() ?? 0,
month?.getSeconds() ?? 0,
);
onChange?.(newDateFull);
setMonth(newDateFull);
}; | /**
* carry over the current time when a user clicks a new day
* instead of resetting to 00:00
*/ | https://github.com/hsuanyi-chou/shadcn-ui-expansions/blob/4240453967eb55ca7e3321aa34e6373c6dbd117c/components/ui/datetime-picker.tsx#L701-L721 | 4240453967eb55ca7e3321aa34e6373c6dbd117c |
shadcn-ui-expansions | github_2023 | hsuanyi-chou | typescript | doSearchSync | const doSearchSync = () => {
const res = onSearchSync?.(debouncedSearchTerm);
setOptions(transToGroupOption(res || [], groupBy));
}; | /** sync search */ | https://github.com/hsuanyi-chou/shadcn-ui-expansions/blob/4240453967eb55ca7e3321aa34e6373c6dbd117c/components/ui/multiple-selector.tsx#L300-L303 | 4240453967eb55ca7e3321aa34e6373c6dbd117c |
shadcn-ui-expansions | github_2023 | hsuanyi-chou | typescript | doSearch | const doSearch = async () => {
setIsLoading(true);
const res = await onSearch?.(debouncedSearchTerm);
setOptions(transToGroupOption(res || [], groupBy));
setIsLoading(false);
}; | /** async search */ | https://github.com/hsuanyi-chou/shadcn-ui-expansions/blob/4240453967eb55ca7e3321aa34e6373c6dbd117c/components/ui/multiple-selector.tsx#L324-L329 | 4240453967eb55ca7e3321aa34e6373c6dbd117c |
comfyui-workspace-manager | github_2023 | 11cafe | typescript | sanitizeNodeName | function sanitizeNodeName(string: string): string {
const entityMap: Record<string, string> = {
"&": "",
"<": "",
">": "",
'"': "",
"'": "",
"`": "",
"=": "",
};
return String(string).replace(/[&<>"'`=]/g, function fromEntityMap(s) {
return entityMap[s];
});
} | // copied from app.js | https://github.com/11cafe/comfyui-workspace-manager/blob/338b9b85e69bd73a2bf56df345910680dc0871d0/ui/src/utils.tsx#L10-L23 | 338b9b85e69bd73a2bf56df345910680dc0871d0 |
comfyui-workspace-manager | github_2023 | 11cafe | typescript | openDatabase | function openDatabase(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open("WorkspaceDB", 3);
request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
// Create an object store if it doesn't exist
if (!db.objectStoreNames.contains(WORKSPACE_TABLE)) {
db.createObjectStore(WORKSPACE_TABLE, { keyPath: "id" });
}
};
request.onsuccess = (event) => {
resolve((event.target as IDBOpenDBRequest).result);
};
request.onerror = (event) => {
reject((event.target as IDBOpenDBRequest).error);
};
});
} | // Function to open a database | https://github.com/11cafe/comfyui-workspace-manager/blob/338b9b85e69bd73a2bf56df345910680dc0871d0/ui/src/db-tables/IndexDBUtils.ts#L7-L27 | 338b9b85e69bd73a2bf56df345910680dc0871d0 |
comfyui-workspace-manager | github_2023 | 11cafe | typescript | writeWorkspaceTable | async function writeWorkspaceTable(data: string): Promise<void> {
try {
if (indexDB == null) indexDB = await openDatabase();
return new Promise((resolve, reject) => {
if (indexDB == null) return reject("indexDB is null");
const transaction = indexDB.transaction([WORKSPACE_TABLE], "readwrite");
const store = transaction.objectStore(WORKSPACE_TABLE);
const request = store.put({ id: WORKSPACE_KEY, value: data });
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
});
} catch (error) {
console.error("Error while opening database:", error);
}
} | // Function to write data to the database | https://github.com/11cafe/comfyui-workspace-manager/blob/338b9b85e69bd73a2bf56df345910680dc0871d0/ui/src/db-tables/IndexDBUtils.ts#L30-L46 | 338b9b85e69bd73a2bf56df345910680dc0871d0 |
comfyui-workspace-manager | github_2023 | 11cafe | typescript | readDataFromDatabase | async function readDataFromDatabase(): Promise<string | undefined> {
try {
if (indexDB == null) indexDB = await openDatabase();
return new Promise((resolve, reject) => {
if (indexDB == null) return reject("indexDB is null");
const transaction = indexDB.transaction([WORKSPACE_TABLE], "readonly");
const store = transaction.objectStore(WORKSPACE_TABLE);
const request = store.get(WORKSPACE_KEY);
request.onsuccess = () => {
if (request.result) {
resolve(request.result.value);
} else {
resolve(undefined); // Key not found
}
};
request.onerror = () => reject(request.error);
});
} catch (error) {
console.error("Error while reading from database:", error);
}
} | // Function to read data from the database | https://github.com/11cafe/comfyui-workspace-manager/blob/338b9b85e69bd73a2bf56df345910680dc0871d0/ui/src/db-tables/IndexDBUtils.ts#L49-L72 | 338b9b85e69bd73a2bf56df345910680dc0871d0 |
comfyui-workspace-manager | github_2023 | 11cafe | typescript | WorkflowsTable.latestVersionCheck | public async latestVersionCheck() {
if (this._curWorkflow) {
const curFlowInDB = await indexdb.workflows.get(this._curWorkflow.id);
if (curFlowInDB) {
return curFlowInDB?.updateTime === this._curWorkflow.updateTime;
}
return true;
}
return true;
} | /**
* Check whether the currently opened workflow is the latest version and is consistent with the DB
*/ | https://github.com/11cafe/comfyui-workspace-manager/blob/338b9b85e69bd73a2bf56df345910680dc0871d0/ui/src/db-tables/WorkflowsTable.ts#L52-L61 | 338b9b85e69bd73a2bf56df345910680dc0871d0 |
comfyui-workspace-manager | github_2023 | 11cafe | typescript | WorkflowsTable.update | async update(
_id: string,
_change: Partial<Workflow>,
): Promise<Workflow | null> {
throw new Error("Method not allowed.");
} | // disallow TableBase.update() | https://github.com/11cafe/comfyui-workspace-manager/blob/338b9b85e69bd73a2bf56df345910680dc0871d0/ui/src/db-tables/WorkflowsTable.ts#L144-L149 | 338b9b85e69bd73a2bf56df345910680dc0871d0 |
comfyui-workspace-manager | github_2023 | 11cafe | typescript | WorkflowsTable.batchCreateFlows | public async batchCreateFlows(
flowList: ImportWorkflow[] = [],
isOverwriteExistingFile: boolean = false,
parentFolderID?: string,
) {
const newWorkflows: Workflow[] = [];
for (const flow of flowList) {
const newFlowName =
flow.name && isOverwriteExistingFile
? flow.name
: await this.generateUniqueName(flow.name, parentFolderID);
const uuid = nanoid();
const time = Date.now();
const newWorkflow: Workflow = {
id: uuid,
name: newFlowName,
json: flow.json,
parentFolderID: parentFolderID,
updateTime: time,
createTime: time,
tags: [],
};
newWorkflows.push(newWorkflow);
const twoWaySyncEnabled =
await userSettingsTable?.getSetting("twoWaySync");
if (twoWaySyncEnabled) {
try {
const jsonObj = JSON.parse(flow.json);
const existingWorkflowID =
jsonObj?.extra?.[COMFYSPACE_TRACKING_FIELD_NAME]?.id;
if (existingWorkflowID) {
const existingWorkflow = await this.get(existingWorkflowID);
if (!existingWorkflow) {
newWorkflow.id = existingWorkflowID;
}
}
TwowaySyncAPI.createWorkflow(newWorkflow);
} catch (e) {
console.error("batchCreateFlows error", e);
}
}
}
try {
await indexdb.workflows.bulkAdd(newWorkflows);
} catch (e) {
console.error("batchCreateFlows error", e);
}
} | /**
* Add flows in batches
* @param flowList Need to add a new flow list
* @param isOverwriteExistingFile By automatically scanning the newly added flow on the local disk,
* when synchronizing the DB, the flow on the local disk needs to be rewritten
* because extra.comfyspace_tracking.id needs to be appended to json.
* @param parentFolderID If you are adding batches to the specified files, provide the folder id.
* @returns
*/ | https://github.com/11cafe/comfyui-workspace-manager/blob/338b9b85e69bd73a2bf56df345910680dc0871d0/ui/src/db-tables/WorkflowsTable.ts#L233-L280 | 338b9b85e69bd73a2bf56df345910680dc0871d0 |
comfyui-workspace-manager | github_2023 | 11cafe | typescript | readInt | function readInt(
offset: number,
isLittleEndian: boolean | undefined,
length: number,
) {
const arr = exifData.slice(offset, offset + length);
if (length === 2) {
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).getUint16(
0,
isLittleEndian,
);
} else if (length === 4) {
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength).getUint32(
0,
isLittleEndian,
);
}
} | // Function to read 16-bit and 32-bit integers from binary data | https://github.com/11cafe/comfyui-workspace-manager/blob/338b9b85e69bd73a2bf56df345910680dc0871d0/ui/src/utils/mediaMetadataUtils.ts#L62-L79 | 338b9b85e69bd73a2bf56df345910680dc0871d0 |
comfyui-workspace-manager | github_2023 | 11cafe | typescript | removeModal | const removeModal = (event: MouseEvent) => {
if (event.target === modal) {
modal.removeEventListener("click", removeModal);
document.body.removeChild(modal);
}
}; | // Function to remove the modal when clicked outside | https://github.com/11cafe/comfyui-workspace-manager/blob/338b9b85e69bd73a2bf56df345910680dc0871d0/ui/src/utils/showAlert.ts#L28-L33 | 338b9b85e69bd73a2bf56df345910680dc0871d0 |
kun-galgame-nuxt3 | github_2023 | KUN1007 | typescript | isEditUpdateTopicData | const isEditUpdateTopicData = (data: any): data is EditUpdateTopicRequestData =>
typeof data.tid !== 'undefined' | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/KUN1007/kun-galgame-nuxt3/blob/9f9050f662b45569d2c5c5f51737f64c5a500d38/components/edit/utils/checkTopicPublish.ts#L7-L8 | 9f9050f662b45569d2c5c5f51737f64c5a500d38 |
kun-galgame-nuxt3 | github_2023 | KUN1007 | typescript | flattenHelper | function flattenHelper(prefix: string, value: any) {
if (typeof value === 'object' && value !== null) {
for (const key in value) {
if (Object.prototype.hasOwnProperty.call(value, key)) {
flattenHelper(prefix ? `${prefix}.${key}` : key, value[key])
}
}
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
;(flattened as any)[prefix] = value
}
} | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/KUN1007/kun-galgame-nuxt3/blob/9f9050f662b45569d2c5c5f51737f64c5a500d38/composables/useFlatten.ts#L13-L24 | 9f9050f662b45569d2c5c5f51737f64c5a500d38 |
kun-galgame-nuxt3 | github_2023 | KUN1007 | typescript | isObject | const isObject = (obj: any) => obj && typeof obj === 'object' | // eslint-disable-next-line @typescript-eslint/no-explicit-any | https://github.com/KUN1007/kun-galgame-nuxt3/blob/9f9050f662b45569d2c5c5f51737f64c5a500d38/server/utils/merge.ts#L8-L8 | 9f9050f662b45569d2c5c5f51737f64c5a500d38 |
rsdoctor | github_2023 | web-infra-dev | typescript | replacePaths | function replacePaths(
manifestPath: fs.PathOrFileDescriptor,
oldPath: string,
newPath: string,
) {
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
const replaceInObject = (obj: { [x: string]: any }) => {
for (const key in obj) {
if (typeof obj[key] === 'string') {
obj[key] = obj[key].replace(oldPath, newPath);
} else if (Array.isArray(obj[key])) {
obj[key] = obj[key].map((item) =>
typeof item === 'string' ? item.replace(oldPath, newPath) : item,
);
} else if (typeof obj[key] === 'object') {
replaceInObject(obj[key]);
}
}
};
replaceInObject(manifest);
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2), 'utf-8');
} | // Function to replace paths in manifest.json | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/e2e/cases/doctor-rspack/bundle-diff.test.ts#L17-L41 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | rspackBuild | function rspackBuild(config: rspack.Configuration) {
return new Promise<void>((resolve) => {
rspack.rspack(config, (err, stats) => {
if (err) {
throw err;
}
console.log();
if (stats) {
console.log(
stats.toString({
chunks: false,
chunkModules: false,
colors: true,
modules: false,
children: false,
}),
);
}
resolve();
});
});
} | // console.log(config) | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/examples/rspack-layers-minimal/build.ts#L9-L33 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | rspackBuild | function rspackBuild(config: rspack.Configuration) {
return new Promise<void>((resolve) => {
rspack.rspack(config, (err, stats) => {
if (err) {
throw err;
}
console.log();
if (stats) {
console.log(
stats.toString({
chunks: false,
chunkModules: false,
colors: true,
modules: false,
children: false,
}),
);
}
resolve();
});
});
} | // console.log(config) | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/examples/rspack-minimal/build.ts#L9-L33 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | applyFix | const applyFix = () => {
axios.post(SDK.ServerAPI.API.ApplyErrorFix, { id }).then(() => {
setIsFixed(true);
});
}; | // const [isFixed, setIsFixed] = useState(file.isFixed ?? false); | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/components/Alert/change.tsx#L21-L25 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.isEmpty | isEmpty() {
return Range.isEmpty(this);
} | /**
* Test if this range is empty.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L40-L42 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.isEmpty | static isEmpty(range: Range) {
return (
range.startLineNumber === range.endLineNumber &&
range.startColumn === range.endColumn
);
} | /**
* Test if `range` is empty.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L46-L51 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.containsPosition | containsPosition(position: any) {
return Range.containsPosition(this, position);
} | /**
* Test if position is in this range. If the position is at the edges, will return true.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L55-L57 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.containsPosition | static containsPosition(
range: Range,
position: {
lineNumber: number;
column: number;
},
) {
if (
position.lineNumber < range.startLineNumber ||
position.lineNumber > range.endLineNumber
) {
return false;
}
if (
position.lineNumber === range.startLineNumber &&
position.column < range.startColumn
) {
return false;
}
if (
position.lineNumber === range.endLineNumber &&
position.column > range.endColumn
) {
return false;
}
return true;
} | /**
* Test if `position` is in `range`. If the position is at the edges, will return true.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L61-L87 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.strictContainsPosition | static strictContainsPosition(
range: Range,
position: {
lineNumber: number;
column: number;
},
) {
if (
position.lineNumber < range.startLineNumber ||
position.lineNumber > range.endLineNumber
) {
return false;
}
if (
position.lineNumber === range.startLineNumber &&
position.column <= range.startColumn
) {
return false;
}
if (
position.lineNumber === range.endLineNumber &&
position.column >= range.endColumn
) {
return false;
}
return true;
} | /**
* Test if `position` is in `range`. If the position is at the edges, will return false.
* @internal
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L92-L118 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.containsRange | containsRange(range: Range) {
return Range.containsRange(this, range);
} | /**
* Test if range is in this range. If the range is equal to this range, will return true.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L122-L124 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.containsRange | static containsRange(
range: Range,
otherRange: {
startLineNumber: number;
endLineNumber: number;
startColumn: number;
endColumn: number;
},
) {
if (
otherRange.startLineNumber < range.startLineNumber ||
otherRange.endLineNumber < range.startLineNumber
) {
return false;
}
if (
otherRange.startLineNumber > range.endLineNumber ||
otherRange.endLineNumber > range.endLineNumber
) {
return false;
}
if (
otherRange.startLineNumber === range.startLineNumber &&
otherRange.startColumn < range.startColumn
) {
return false;
}
if (
otherRange.endLineNumber === range.endLineNumber &&
otherRange.endColumn > range.endColumn
) {
return false;
}
return true;
} | /**
* Test if `otherRange` is in `range`. If the ranges are equal, will return true.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L128-L162 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.strictContainsRange | strictContainsRange(range: Range) {
return Range.strictContainsRange(this, range);
} | /**
* Test if `range` is strictly in this range. `range` must start after and end before this range for the result to be true.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L166-L168 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.strictContainsRange | static strictContainsRange(
range: Range,
otherRange: {
startLineNumber: number;
endLineNumber: number;
startColumn: number;
endColumn: number;
},
) {
if (
otherRange.startLineNumber < range.startLineNumber ||
otherRange.endLineNumber < range.startLineNumber
) {
return false;
}
if (
otherRange.startLineNumber > range.endLineNumber ||
otherRange.endLineNumber > range.endLineNumber
) {
return false;
}
if (
otherRange.startLineNumber === range.startLineNumber &&
otherRange.startColumn <= range.startColumn
) {
return false;
}
if (
otherRange.endLineNumber === range.endLineNumber &&
otherRange.endColumn >= range.endColumn
) {
return false;
}
return true;
} | /**
* Test if `otherRange` is strictly in `range` (must start after, and end before). If the ranges are equal, will return false.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L172-L206 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.plusRange | plusRange(range: Range) {
return Range.plusRange(this, range);
} | /**
* A reunion of the two ranges.
* The smallest position will be used as the start point, and the largest one as the end point.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L211-L213 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.plusRange | static plusRange(a: Range, b: Range) {
let startLineNumber;
let startColumn;
let endLineNumber;
let endColumn;
if (b.startLineNumber < a.startLineNumber) {
startLineNumber = b.startLineNumber;
startColumn = b.startColumn;
} else if (b.startLineNumber === a.startLineNumber) {
startLineNumber = b.startLineNumber;
startColumn = Math.min(b.startColumn, a.startColumn);
} else {
startLineNumber = a.startLineNumber;
startColumn = a.startColumn;
}
if (b.endLineNumber > a.endLineNumber) {
endLineNumber = b.endLineNumber;
endColumn = b.endColumn;
} else if (b.endLineNumber === a.endLineNumber) {
endLineNumber = b.endLineNumber;
endColumn = Math.max(b.endColumn, a.endColumn);
} else {
endLineNumber = a.endLineNumber;
endColumn = a.endColumn;
}
return new Range(startLineNumber, startColumn, endLineNumber, endColumn);
} | /**
* A reunion of the two ranges.
* The smallest position will be used as the start point, and the largest one as the end point.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L218-L244 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.intersectRanges | intersectRanges(range: Range) {
return Range.intersectRanges(this, range);
} | /**
* A intersection of the two ranges.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L248-L250 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.intersectRanges | static intersectRanges(a: Range, b: Range) {
let resultStartLineNumber = a.startLineNumber;
let resultStartColumn = a.startColumn;
let resultEndLineNumber = a.endLineNumber;
let resultEndColumn = a.endColumn;
const otherStartLineNumber = b.startLineNumber;
const otherStartColumn = b.startColumn;
const otherEndLineNumber = b.endLineNumber;
const otherEndColumn = b.endColumn;
if (resultStartLineNumber < otherStartLineNumber) {
resultStartLineNumber = otherStartLineNumber;
resultStartColumn = otherStartColumn;
} else if (resultStartLineNumber === otherStartLineNumber) {
resultStartColumn = Math.max(resultStartColumn, otherStartColumn);
}
if (resultEndLineNumber > otherEndLineNumber) {
resultEndLineNumber = otherEndLineNumber;
resultEndColumn = otherEndColumn;
} else if (resultEndLineNumber === otherEndLineNumber) {
resultEndColumn = Math.min(resultEndColumn, otherEndColumn);
}
// Check if selection is now empty
if (resultStartLineNumber > resultEndLineNumber) {
return null;
}
if (
resultStartLineNumber === resultEndLineNumber &&
resultStartColumn > resultEndColumn
) {
return null;
}
return new Range(
resultStartLineNumber,
resultStartColumn,
resultEndLineNumber,
resultEndColumn,
);
} | /**
* A intersection of the two ranges.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L254-L291 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.equalsRange | equalsRange(other: Range) {
return Range.equalsRange(this, other);
} | /**
* Test if this range equals other.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L295-L297 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.equalsRange | static equalsRange(a: Range, b: Range) {
if (!a && !b) {
return true;
}
return (
!!a &&
!!b &&
a.startLineNumber === b.startLineNumber &&
a.startColumn === b.startColumn &&
a.endLineNumber === b.endLineNumber &&
a.endColumn === b.endColumn
);
} | /**
* Test if range `a` equals `b`.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L301-L313 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.getEndPosition | getEndPosition() {
return Range.getEndPosition(this);
} | /**
* Return the end position (which will be after or equal to the start position)
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L317-L319 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.getEndPosition | static getEndPosition(range: Range) {
return new Position(range.endLineNumber, range.endColumn);
} | /**
* Return the end position (which will be after or equal to the start position)
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L323-L325 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.getStartPosition | getStartPosition() {
return Range.getStartPosition(this);
} | /**
* Return the start position (which will be before or equal to the end position)
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L329-L331 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.getStartPosition | static getStartPosition(range: Range) {
return new Position(range.startLineNumber, range.startColumn);
} | /**
* Return the start position (which will be before or equal to the end position)
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L335-L337 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.toString | toString() {
return `[${this.startLineNumber},${this.startColumn} -> ${this.endLineNumber},${this.endColumn}]`;
} | /**
* Transform to a user presentable string representation.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L341-L343 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
rsdoctor | github_2023 | web-infra-dev | typescript | Range.setEndPosition | setEndPosition(endLineNumber: number, endColumn: number) {
return new Range(
this.startLineNumber,
this.startColumn,
endLineNumber,
endColumn,
);
} | /**
* Create a new range using this range's start position, and using endLineNumber and endColumn as the end position.
*/ | https://github.com/web-infra-dev/rsdoctor/blob/7a588b4569adc6d13ddf6294f48b84c07d587784/packages/components/src/pages/TreeShaking/range.ts#L347-L354 | 7a588b4569adc6d13ddf6294f48b84c07d587784 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.