max_stars_repo_path
stringlengths
4
384
max_stars_repo_name
stringlengths
5
120
max_stars_count
int64
0
208k
id
stringlengths
1
8
content
stringlengths
1
1.05M
score
float64
-1.05
3.83
int_score
int64
0
4
src/Interface/proyects.interface.ts
LMANMAI/Portfolio-APIRest
0
800
import { Document } from 'mongoose'; export interface IProyects extends Document { readonly name: String; readonly link: String; readonly linkGitHub: String; readonly technologies: Array<String>; readonly image: String; readonly height: Number; readonly proyectType: String; }
0.691406
1
src/Rendering/babylon.renderingGroup.ts
BitOneInc/Babylon.js
0
808
module BABYLON { export class RenderingGroup { private _scene: Scene; private _opaqueSubMeshes = new SmartArray<SubMesh>(256); private _transparentSubMeshes = new SmartArray<SubMesh>(256); private _alphaTestSubMeshes = new SmartArray<SubMesh>(256); private _depthOnlySubMeshes = new SmartArray<SubMesh>(256); private _particleSystems = new SmartArray<IParticleSystem>(256); private _spriteManagers = new SmartArray<SpriteManager>(256); private _opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number>; private _alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number>; private _transparentSortCompareFn: (a: SubMesh, b: SubMesh) => number; private _renderOpaque: (subMeshes: SmartArray<SubMesh>) => void; private _renderAlphaTest: (subMeshes: SmartArray<SubMesh>) => void; private _renderTransparent: (subMeshes: SmartArray<SubMesh>) => void; private _edgesRenderers = new SmartArray<EdgesRenderer>(16); public onBeforeTransparentRendering: () => void; /** * Set the opaque sort comparison function. * If null the sub meshes will be render in the order they were created */ public set opaqueSortCompareFn(value: Nullable<(a: SubMesh, b: SubMesh) => number>) { this._opaqueSortCompareFn = value; if (value) { this._renderOpaque = this.renderOpaqueSorted; } else { this._renderOpaque = RenderingGroup.renderUnsorted; } } /** * Set the alpha test sort comparison function. * If null the sub meshes will be render in the order they were created */ public set alphaTestSortCompareFn(value: Nullable<(a: SubMesh, b: SubMesh) => number>) { this._alphaTestSortCompareFn = value; if (value) { this._renderAlphaTest = this.renderAlphaTestSorted; } else { this._renderAlphaTest = RenderingGroup.renderUnsorted; } } /** * Set the transparent sort comparison function. * If null the sub meshes will be render in the order they were created */ public set transparentSortCompareFn(value: Nullable<(a: SubMesh, b: SubMesh) => number>) { if (value) { this._transparentSortCompareFn = value; } else { this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare; } this._renderTransparent = this.renderTransparentSorted; } /** * Creates a new rendering group. * @param index The rendering group index * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied */ constructor(public index: number, scene: Scene, opaqueSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null, alphaTestSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null, transparentSortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number> = null) { this._scene = scene; this.opaqueSortCompareFn = opaqueSortCompareFn; this.alphaTestSortCompareFn = alphaTestSortCompareFn; this.transparentSortCompareFn = transparentSortCompareFn; } /** * Render all the sub meshes contained in the group. * @param customRenderFunction Used to override the default render behaviour of the group. * @returns true if rendered some submeshes. */ public render(customRenderFunction: Nullable<(opaqueSubMeshes: SmartArray<SubMesh>, transparentSubMeshes: SmartArray<SubMesh>, alphaTestSubMeshes: SmartArray<SubMesh>, depthOnlySubMeshes: SmartArray<SubMesh>) => void>, renderSprites: boolean, renderParticles: boolean, activeMeshes: Nullable<AbstractMesh[]>): void { if (customRenderFunction) { customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes); return; } var engine = this._scene.getEngine(); // Depth only if (this._depthOnlySubMeshes.length !== 0) { engine.setColorWrite(false); this._renderAlphaTest(this._depthOnlySubMeshes); engine.setColorWrite(true); } // Opaque if (this._opaqueSubMeshes.length !== 0) { this._renderOpaque(this._opaqueSubMeshes); } // Alpha test if (this._alphaTestSubMeshes.length !== 0) { this._renderAlphaTest(this._alphaTestSubMeshes); } var stencilState = engine.getStencilBuffer(); engine.setStencilBuffer(false); // Sprites if (renderSprites) { this._renderSprites(); } // Particles if (renderParticles) { this._renderParticles(activeMeshes); } if (this.onBeforeTransparentRendering) { this.onBeforeTransparentRendering(); } // Transparent if (this._transparentSubMeshes.length !== 0) { this._renderTransparent(this._transparentSubMeshes); engine.setAlphaMode(Engine.ALPHA_DISABLE); } // Set back stencil to false in case it changes before the edge renderer. engine.setStencilBuffer(false); // Edges for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) { this._edgesRenderers.data[edgesRendererIndex].render(); } // Restore Stencil state. engine.setStencilBuffer(stencilState); } /** * Renders the opaque submeshes in the order from the opaqueSortCompareFn. * @param subMeshes The submeshes to render */ private renderOpaqueSorted(subMeshes: SmartArray<SubMesh>): void { return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false); } /** * Renders the opaque submeshes in the order from the alphatestSortCompareFn. * @param subMeshes The submeshes to render */ private renderAlphaTestSorted(subMeshes: SmartArray<SubMesh>): void { return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false); } /** * Renders the opaque submeshes in the order from the transparentSortCompareFn. * @param subMeshes The submeshes to render */ private renderTransparentSorted(subMeshes: SmartArray<SubMesh>): void { return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true); } /** * Renders the submeshes in a specified order. * @param subMeshes The submeshes to sort before render * @param sortCompareFn The comparison function use to sort * @param cameraPosition The camera position use to preprocess the submeshes to help sorting * @param transparent Specifies to activate blending if true */ private static renderSorted(subMeshes: SmartArray<SubMesh>, sortCompareFn: Nullable<(a: SubMesh, b: SubMesh) => number>, camera: Nullable<Camera>, transparent: boolean): void { let subIndex = 0; let subMesh: SubMesh; let cameraPosition = camera ? camera.globalPosition : Vector3.Zero(); for (; subIndex < subMeshes.length; subIndex++) { subMesh = subMeshes.data[subIndex]; subMesh._alphaIndex = subMesh.getMesh().alphaIndex; subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length(); } let sortedArray = subMeshes.data.slice(0, subMeshes.length); if (sortCompareFn) { sortedArray.sort(sortCompareFn); } for (subIndex = 0; subIndex < sortedArray.length; subIndex++) { subMesh = sortedArray[subIndex]; if (transparent) { let material = subMesh.getMaterial(); if (material && material.needDepthPrePass) { let engine = material.getScene().getEngine(); engine.setColorWrite(false); engine.setAlphaMode(Engine.ALPHA_DISABLE); subMesh.render(false); engine.setColorWrite(true); } } subMesh.render(transparent); } } /** * Renders the submeshes in the order they were dispatched (no sort applied). * @param subMeshes The submeshes to render */ private static renderUnsorted(subMeshes: SmartArray<SubMesh>): void { for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) { let submesh = subMeshes.data[subIndex]; submesh.render(false); } } /** * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) * are rendered back to front if in the same alpha index. * * @param a The first submesh * @param b The second submesh * @returns The result of the comparison */ public static defaultTransparentSortCompare(a: SubMesh, b: SubMesh): number { // Alpha index first if (a._alphaIndex > b._alphaIndex) { return 1; } if (a._alphaIndex < b._alphaIndex) { return -1; } // Then distance to camera return RenderingGroup.backToFrontSortCompare(a, b); } /** * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) * are rendered back to front. * * @param a The first submesh * @param b The second submesh * @returns The result of the comparison */ public static backToFrontSortCompare(a: SubMesh, b: SubMesh): number { // Then distance to camera if (a._distanceToCamera < b._distanceToCamera) { return 1; } if (a._distanceToCamera > b._distanceToCamera) { return -1; } return 0; } /** * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent) * are rendered front to back (prevent overdraw). * * @param a The first submesh * @param b The second submesh * @returns The result of the comparison */ public static frontToBackSortCompare(a: SubMesh, b: SubMesh): number { // Then distance to camera if (a._distanceToCamera < b._distanceToCamera) { return -1; } if (a._distanceToCamera > b._distanceToCamera) { return 1; } return 0; } /** * Resets the different lists of submeshes to prepare a new frame. */ public prepare(): void { this._opaqueSubMeshes.reset(); this._transparentSubMeshes.reset(); this._alphaTestSubMeshes.reset(); this._depthOnlySubMeshes.reset(); this._particleSystems.reset(); this._spriteManagers.reset(); this._edgesRenderers.reset(); } public dispose(): void { this._opaqueSubMeshes.dispose(); this._transparentSubMeshes.dispose(); this._alphaTestSubMeshes.dispose(); this._depthOnlySubMeshes.dispose(); this._particleSystems.dispose(); this._spriteManagers.dispose(); this._edgesRenderers.dispose(); } /** * Inserts the submesh in its correct queue depending on its material. * @param subMesh The submesh to dispatch * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance. */ public dispatch(subMesh: SubMesh, mesh?: AbstractMesh, material?: Nullable<Material>): void { // Get mesh and materials if not provided if (mesh === undefined) { mesh = subMesh.getMesh(); } if (material === undefined) { material = subMesh.getMaterial(); } if (material === null || material === undefined) { return; } if (material.needAlphaBlendingForMesh(mesh)) { // Transparent this._transparentSubMeshes.push(subMesh); } else if (material.needAlphaTesting()) { // Alpha test if (material.needDepthPrePass) { this._depthOnlySubMeshes.push(subMesh); } this._alphaTestSubMeshes.push(subMesh); } else { if (material.needDepthPrePass) { this._depthOnlySubMeshes.push(subMesh); } this._opaqueSubMeshes.push(subMesh); // Opaque } if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) { this._edgesRenderers.push(mesh._edgesRenderer); } } public dispatchSprites(spriteManager: SpriteManager) { this._spriteManagers.push(spriteManager); } public dispatchParticles(particleSystem: IParticleSystem) { this._particleSystems.push(particleSystem); } private _renderParticles(activeMeshes: Nullable<AbstractMesh[]>): void { if (this._particleSystems.length === 0) { return; } // Particles var activeCamera = this._scene.activeCamera; this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene); for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) { var particleSystem = this._particleSystems.data[particleIndex]; if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) { continue; } let emitter: any = particleSystem.emitter; if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) { this._scene._activeParticles.addCount(particleSystem.render(), false); } } this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene); } private _renderSprites(): void { if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) { return; } // Sprites var activeCamera = this._scene.activeCamera; this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene); for (var id = 0; id < this._spriteManagers.length; id++) { var spriteManager = this._spriteManagers.data[id]; if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) { spriteManager.render(); } } this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene); } } }
1.703125
2
src/builder.spec.ts
danielpza/typescript-infer-types
1
816
import { resolve } from "path"; import * as ts from "typescript"; import { Builder } from "./builder"; import { readFileSync } from "fs"; test("builder", () => { const program = ts.createProgram([resolve(__dirname, "__fixtures/base.ts")], { allowJs: true, target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.CommonJS }); const builder = new Builder(program); builder.analyze(); const actual = builder.print(); const expected = readFileSync( resolve(__dirname, "__fixtures/expected.d.ts"), "utf8" ).toString(); expect(actual).toBe(expected); });
1.132813
1
test/loader/error-test/src/index.ts
solsson/webpack-cli
2,495
824
const foobar = "foobar"; // eslint-disable-next-line no-const-assign foobar = "barbaz"; // Error! console.log(foobar);
0.933594
1
src/components/core/link/index.ts
vitus-labs/docs
0
832
import element from '../element' import withLink, { Props } from './withLink' export default element .config({ name: 'core/link', }) .compose({ withLink, }) .attrs<Props & { onClick?: MouseEvent | (() => void) }>( ({ href, onClick }) => ({ tag: href ? 'a' : onClick ? 'button' : 'span', }) ) .theme((t) => ({ transition: t.transition.base, border: 'none', // backgroundColor: t.color.transparent, textDecoration: 'none', outline: 'none', padding: 0, margin: 0, userSelect: 'none', }))
1.023438
1
src/vs/base/common/iterator.ts
Semperia/vscode
133
840
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ export namespace Iterable { export function is<T = any>(thing: any): thing is IterableIterator<T> { return thing && typeof thing === 'object' && typeof thing[Symbol.iterator] === 'function'; } const _empty: Iterable<any> = Object.freeze([]); export function empty<T = any>(): Iterable<T> { return _empty; } export function* single<T>(element: T): Iterable<T> { yield element; } export function from<T>(iterable: Iterable<T> | undefined | null): Iterable<T> { return iterable || _empty; } export function isEmpty<T>(iterable: Iterable<T> | undefined | null): boolean { return !iterable || iterable[Symbol.iterator]().next().done === true; } export function first<T>(iterable: Iterable<T>): T | undefined { return iterable[Symbol.iterator]().next().value; } export function some<T>(iterable: Iterable<T>, predicate: (t: T) => boolean): boolean { for (const element of iterable) { if (predicate(element)) { return true; } } return false; } export function find<T, R extends T>(iterable: Iterable<T>, predicate: (t: T) => t is R): T | undefined; export function find<T>(iterable: Iterable<T>, predicate: (t: T) => boolean): T | undefined; export function find<T>(iterable: Iterable<T>, predicate: (t: T) => boolean): T | undefined { for (const element of iterable) { if (predicate(element)) { return element; } } return undefined; } export function filter<T, R extends T>(iterable: Iterable<T>, predicate: (t: T) => t is R): Iterable<R>; export function filter<T>(iterable: Iterable<T>, predicate: (t: T) => boolean): Iterable<T>; export function* filter<T>(iterable: Iterable<T>, predicate: (t: T) => boolean): Iterable<T> { for (const element of iterable) { if (predicate(element)) { yield element; } } } export function* map<T, R>(iterable: Iterable<T>, fn: (t: T, index: number) => R): Iterable<R> { let index = 0; for (const element of iterable) { yield fn(element, index++); } } export function* concat<T>(...iterables: Iterable<T>[]): Iterable<T> { for (const iterable of iterables) { for (const element of iterable) { yield element; } } } export function* concatNested<T>(iterables: Iterable<Iterable<T>>): Iterable<T> { for (const iterable of iterables) { for (const element of iterable) { yield element; } } } export function reduce<T, R>(iterable: Iterable<T>, reducer: (previousValue: R, currentValue: T) => R, initialValue: R): R { let value = initialValue; for (const element of iterable) { value = reducer(value, element); } return value; } /** * Returns an iterable slice of the array, with the same semantics as `array.slice()`. */ export function* slice<T>(arr: ReadonlyArray<T>, from: number, to = arr.length): Iterable<T> { if (from < 0) { from += arr.length; } if (to < 0) { to += arr.length; } else if (to > arr.length) { to = arr.length; } for (; from < to; from++) { yield arr[from]; } } /** * Consumes `atMost` elements from iterable and returns the consumed elements, * and an iterable for the rest of the elements. */ export function consume<T>(iterable: Iterable<T>, atMost: number = Number.POSITIVE_INFINITY): [T[], Iterable<T>] { const consumed: T[] = []; if (atMost === 0) { return [consumed, iterable]; } const iterator = iterable[Symbol.iterator](); for (let i = 0; i < atMost; i++) { const next = iterator.next(); if (next.done) { return [consumed, Iterable.empty()]; } consumed.push(next.value); } return [consumed, { [Symbol.iterator]() { return iterator; } }]; } /** * Returns whether the iterables are the same length and all items are * equal using the comparator function. */ export function equals<T>(a: Iterable<T>, b: Iterable<T>, comparator = (at: T, bt: T) => at === bt) { const ai = a[Symbol.iterator](); const bi = b[Symbol.iterator](); while (true) { const an = ai.next(); const bn = bi.next(); if (an.done !== bn.done) { return false; } else if (an.done) { return true; } else if (!comparator(an.value, bn.value)) { return false; } } } }
1.90625
2
src/app/service/project/query/expense-ticket-query.model.ts
newmann/front-ta-admin
0
848
/** * @Description: list界面查询条件 * @Author: <EMAIL> * @Date: Created in 2018-03-25 9:03 **/ export class BylExpenseTicketQuery { billNo: string; projectId: string; status: Array<number> = [1,2, 10,20]; modifyDateBegin: number = 0; modifyDateEnd: number = 0; }
0.640625
1
libs/withdraws/src/lib/withdraw-dialog.tsx
vegaprotocol/frontend-monorepo
1
856
import { Link, Dialog, Icon, Intent, Loader } from '@vegaprotocol/ui-toolkit'; import { useEnvironment } from '@vegaprotocol/network-switcher'; import type { VegaTxState } from '@vegaprotocol/wallet'; import { VegaTxStatus } from '@vegaprotocol/wallet'; import type { ReactNode } from 'react'; import type { EthTxState } from '@vegaprotocol/web3'; import { EthTxStatus } from '@vegaprotocol/web3'; import { t } from '@vegaprotocol/react-helpers'; import type { Erc20Approval_erc20WithdrawalApproval } from './__generated__/Erc20Approval'; export interface WithdrawDialogProps { vegaTx: VegaTxState; ethTx: EthTxState; approval: Erc20Approval_erc20WithdrawalApproval | null; dialogOpen: boolean; onDialogChange: (isOpen: boolean) => void; } export const WithdrawDialog = ({ vegaTx, ethTx, approval, dialogOpen, onDialogChange, }: WithdrawDialogProps) => { const { ETHERSCAN_URL } = useEnvironment(); const { intent, ...props } = getProps(approval, vegaTx, ethTx, ETHERSCAN_URL); return ( <Dialog open={dialogOpen} intent={intent} onChange={onDialogChange}> <DialogWrapper {...props} /> </Dialog> ); }; interface DialogWrapperProps { children: ReactNode; icon: ReactNode; title: string; } export const DialogWrapper = ({ children, icon, title, }: DialogWrapperProps) => { return ( <div className="flex gap-12 max-w-full text-ui"> <div className="pt-8 fill-current">{icon}</div> <div className="flex-1"> <h1 data-testid="dialog-title" className="text-h4 text-black dark:text-white capitalize mb-12" > {title} </h1> {children} </div> </div> ); }; interface StepProps { children: ReactNode; } const Step = ({ children }: StepProps) => { return ( <p data-testid="dialog-text" className="flex justify-between"> {children} </p> ); }; interface DialogProps { title: string; icon: ReactNode; children: ReactNode; intent?: Intent; } const getProps = ( approval: Erc20Approval_erc20WithdrawalApproval | null, vegaTx: VegaTxState, ethTx: EthTxState, ethUrl: string ) => { const vegaTxPropsMap: Record<VegaTxStatus, DialogProps> = { [VegaTxStatus.Default]: { title: '', icon: null, intent: undefined, children: null, }, [VegaTxStatus.Error]: { title: t('Withdrawal transaction failed'), icon: <Icon name="warning-sign" size={20} />, intent: Intent.Danger, children: ( <Step> {vegaTx.error && ( <pre className="text-ui break-all whitespace-pre-wrap"> {JSON.stringify(vegaTx.error, null, 2)} </pre> )} </Step> ), }, [VegaTxStatus.Requested]: { title: t('Confirm withdrawal'), icon: <Icon name="hand-up" size={20} />, intent: Intent.Warning, children: <Step>Confirm withdrawal in Vega wallet</Step>, }, [VegaTxStatus.Pending]: { title: t('Withdrawal transaction pending'), icon: <Loader size="small" />, intent: Intent.None, children: <Step>Awaiting transaction</Step>, }, }; const ethTxPropsMap: Record<EthTxStatus, DialogProps> = { [EthTxStatus.Default]: { title: '', icon: null, intent: undefined, children: null, }, [EthTxStatus.Error]: { title: t('Ethereum transaction failed'), icon: <Icon name="warning-sign" size={20} />, intent: Intent.Danger, children: ( <Step> {ethTx.error ? ethTx.error.message : t('Something went wrong')} </Step> ), }, [EthTxStatus.Requested]: { title: t('Confirm transaction'), icon: <Icon name="hand-up" size={20} />, intent: Intent.Warning, children: <Step>{t('Confirm transaction in wallet')}</Step>, }, [EthTxStatus.Pending]: { title: t('Ethereum transaction pending'), icon: <Loader size="small" />, intent: Intent.None, children: ( <Step> <span> {t( `Awaiting Ethereum transaction ${ethTx.confirmations}/1 confirmations...` )} </span> <Link href={`${ethUrl}/tx/${ethTx.txHash}`} title={t('View transaction on Etherscan')} className="text-vega-pink dark:text-vega-yellow" > {t('View on Etherscan')} </Link> </Step> ), }, [EthTxStatus.Complete]: { title: t('Withdrawal complete'), icon: <Icon name="tick" />, intent: Intent.Success, children: ( <Step> <span>{t('Ethereum transaction complete')}</span> <Link href={`${ethUrl}/tx/${ethTx.txHash}`} title={t('View transaction on Etherscan')} className="text-vega-pink dark:text-vega-yellow" > {t('View on Etherscan')} </Link> </Step> ), }, }; return approval ? ethTxPropsMap[ethTx.status] : vegaTxPropsMap[vegaTx.status]; };
1.203125
1
node_modules/@vuepress/core/lib/app/setupAppPlugins.d.ts
JintaoYang18/JintaoYang-LearningPython
1
864
import type { App } from '../types'; /** * Setup plugins for vuepress app */ export declare const setupAppPlugins: (app: App) => void;
0.566406
1
lib/main.ts
rayyreall/Bot-Whatsapp
6
872
import Logger from "./log"; import {config} from "dotenv"; import Config from "./database/config"; import MongoDB from "./database/mongodb"; import path from "path"; import createWA from "./core/main"; import {Events} from "./events"; import chalk from "chalk"; import type {ProcessModel, ConfigGlobal } from "./types"; config(); export const start = async () => { let proses: Array<ProcessModel | string> = process.argv .slice(2) .filter((p) => p.startsWith("--")) .map((p) => p.replace("--", "")); if (proses.some((p) => p === "dev")) { process.env.mode = "dev"; } else { process.env.mode = "client"; } const configure: Config<Partial<ConfigGlobal>> = Config.create(); configure.readJSON(path.join(path.resolve("./"), "config.json")); configure.Set({ mode: process.env.mode, loggerConfig: { mode: process.env.mode, }, status: false, user: [], memory: "low" }); const color = (text: string, color: string) => { return !color ? chalk.green(text) : chalk.keyword(color)(text); }; console.clear(); console.log(color("..............", "red")); console.log(color(" ..,;:ccc,.", "red")); console.log(color(" ......''';lxO.", "red")); console.log(color(".....''''..........,:ld;", "red")); console.log(color(" .';;;:::;,,.x,", "red")); console.log(color(" ..'''. 0Xxoc:,. ...", "red")); console.log(color(" .... ,ONkc;,;cokOdc',.", "red")); console.log(color(" . OMo ':ddo.", "red")); console.log(color(" dMc :OO;", "red")); console.log(color(" 0M. .:o.", "red")); console.log(color(" ;Wd", "red")); console.log(color(" ;XO,", "red")); console.log(color(" ,d0Odlc;,..", "red")); console.log(color(" ..',;:cdOOd::,.", "red")); console.log(color(" .:d;.':;.", "red")); console.log(color(" 'd, .'", "red")); console.log(color(" ;l ..", "red")); console.log(color(" .o", "red")); console.log( color(` [=] Bot: ${configure.config.botName} [=] `, "cyan"), color("c", "red"), ); console.log( color( ` [=] Number : ${configure.config.ownerNumber[0]} [=] `, "cyan", ), color(".'", "red"), ); console.log( color(" ", "cyan"), color(".'", "red"), ); console.log(""); console.log(""); const Log: Logger = new Logger(configure.config.loggerConfig!); const ev: Events = Events.getEvents(); ev.setLocFolder(path.join(__dirname, "./command")); ev.setLog(Log); await ev.load(); const db: MongoDB = MongoDB.createDB(configure.config.mongoURL, createWA, { sessions: path.join( path.resolve("./"), "./lib/database/sessions/sessions.json", ), logger: Log, }); db.Utility(Log); await db.connect(proses.some((p) => p == "resetdb") ? path.join(path.resolve("./"),"./lib/database/sessions/sessions.json",) : undefined); }; start();
1.492188
1
src/entity/mail.entity.ts
GBernardo10/api-service-mail
0
880
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, OneToMany, } from 'typeorm'; import { Field, ObjectType } from '@nestjs/graphql'; import MailStatus from './mail-status.entity'; @Entity({ name: 'mails_store' }) @ObjectType() export default class Mail { @Field() @PrimaryGeneratedColumn({ type: 'uuid' }) @Column({ name: 'mail_id', primary: true }) id: string; @Column() @Field() to: string; @Column() @Field() from: string; @Column() @Field() subject: string; @Column() @Field() body: string; @CreateDateColumn({ name: 'created_at' }) createdAt: Date; @UpdateDateColumn({ name: 'updated_at' }) updateAt: Date; @OneToMany( () => MailStatus, mailStatus => mailStatus.mailConnection, ) mailConnection: Promise<MailStatus>[]; }
1.054688
1
types/controllers/index.d.ts
danmana/Chart.js
0
888
import { Chart, DatasetController } from '../core'; import { IChartArea, IChartComponent, ScriptableAndArrayOptions, ScriptableOptions } from '../core/interfaces'; import { IArcHoverOptions, IArcOptions, ICommonHoverOptions, IPointHoverOptions, ILineHoverOptions, ILineOptions, IPointOptions, IPointPrefixedHoverOptions, IPointPrefixedOptions, IBarOptions, } from '../elements'; export interface IControllerDatasetOptions { /** * How to clip relative to chartArea. Positive value allows overflow, negative value clips that many pixels inside chartArea. 0 = clip at chartArea. Clipping can also be configured per side: clip: {left: 5, top: false, right: -2, bottom: 0} */ clip: number | IChartArea; /** * The label for the dataset which appears in the legend and tooltips. */ label: string; /** * The drawing order of dataset. Also affects order for stacking, tooltip and legend. */ order: number; } export interface IBarControllerDatasetOptions extends IControllerDatasetOptions, ScriptableAndArrayOptions<IBarOptions>, ScriptableAndArrayOptions<ICommonHoverOptions> { /** * The base axis of the dataset. 'x' for vertical bars and 'y' for horizontal bars. * @default 'x' */ indexAxis: 'x' | 'y'; /** * The ID of the x axis to plot this dataset on. */ xAxisID: string; /** * The ID of the y axis to plot this dataset on. */ yAxisID: string; /** * Percent (0-1) of the available width each bar should be within the category width. 1.0 will take the whole category width and put the bars right next to each other. * @default 0.9 */ barPercentage: number; /** * Percent (0-1) of the available width each category should be within the sample width. * @default 0.8 */ categoryPercentage: number; /** * Manually set width of each bar in pixels. If set to 'flex', it computes "optimal" sample widths that globally arrange bars side by side. If not set (default), bars are equally sized based on the smallest interval. */ barThickness: number | 'flex'; /** * Set this to ensure that bars are not sized thicker than this. */ maxBarThickness: number; /** * Set this to ensure that bars have a minimum length in pixels. */ minBarLength: number; /** * The ID of the group to which this dataset belongs to (when stacked, each group will be a separate stack). */ stack: string; } export interface IBarControllerChartOptions { /** * Should null or undefined values be omitted from drawing */ skipNull?: boolean; } export interface BarController extends DatasetController {} export const BarController: IChartComponent & { prototype: BarController; new (chart: Chart, datasetIndex: number): BarController; }; export interface IBubbleControllerDatasetOptions extends IControllerDatasetOptions, ScriptableAndArrayOptions<IPointOptions>, ScriptableAndArrayOptions<IPointHoverOptions> {} export interface IBubbleDataPoint { /** * X Value */ x: number; /** * Y Value */ y: number; /** * Bubble radius in pixels (not scaled). */ r: number; } export interface BubbleController extends DatasetController {} export const BubbleController: IChartComponent & { prototype: BubbleController; new (chart: Chart, datasetIndex: number): BubbleController; }; export interface ILineControllerDatasetOptions extends IControllerDatasetOptions, ScriptableAndArrayOptions<IPointPrefixedOptions>, ScriptableAndArrayOptions<IPointPrefixedHoverOptions>, ScriptableOptions<ILineOptions>, ScriptableOptions<ILineHoverOptions> { /** * The ID of the x axis to plot this dataset on. */ xAxisID: string; /** * The ID of the y axis to plot this dataset on. */ yAxisID: string; /** * If true, lines will be drawn between points with no or null data. If false, points with NaN data will create a break in the line. Can also be a number specifying the maximum gap length to span. The unit of the value depends on the scale used. * @default false */ spanGaps: boolean | number; showLine: boolean; } export interface ILineControllerChartOptions { /** * If true, lines will be drawn between points with no or null data. If false, points with NaN data will create a break in the line. Can also be a number specifying the maximum gap length to span. The unit of the value depends on the scale used. * @default false */ spanGaps: boolean | number; /** * If false, the lines between points are not drawn. * @default true */ showLine: boolean; } export interface LineController extends DatasetController {} export const LineController: IChartComponent & { prototype: LineController; new (chart: Chart, datasetIndex: number): LineController; }; export type IScatterControllerDatasetOptions = ILineControllerDatasetOptions; export interface IScatterDataPoint { x: number; y: number; } export type IScatterControllerChartOptions = ILineControllerChartOptions; export interface ScatterController extends LineController {} export const ScatterController: IChartComponent & { prototype: ScatterController; new (chart: Chart, datasetIndex: number): ScatterController; }; export interface IDoughnutControllerDatasetOptions extends IControllerDatasetOptions, ScriptableAndArrayOptions<IArcOptions>, ScriptableAndArrayOptions<IArcHoverOptions> { /** * Sweep to allow arcs to cover. * @default 2 * Math.PI */ circumference: number; /** * Starting angle to draw this dataset from. * @default -0.5 * Math.PI */ rotation: number; /** * The relative thickness of the dataset. Providing a value for weight will cause the pie or doughnut dataset to be drawn with a thickness relative to the sum of all the dataset weight values. * @default 1 */ weight: number; } export interface IDoughnutAnimationOptions { /** * If true, the chart will animate in with a rotation animation. This property is in the options.animation object. * @default true */ animateRotate: boolean; /** * If true, will animate scaling the chart from the center outwards. * @default false */ animateScale: boolean; } export interface IDoughnutControllerChartOptions { /** * The percentage of the chart that is cut out of the middle. (50 - for doughnut, 0 - for pie) * @default 50 */ cutoutPercentage: number; /** * Starting angle to draw arcs from. * @default -0.5 * Math.PI */ rotation: number; /** * Sweep to allow arcs to cover. * @default 2 * Math.PI */ circumference: number; animation: IDoughnutAnimationOptions; } export type IDoughnutDataPoint = number; export interface DoughnutController extends DatasetController { readonly innerRadius: number; readonly outerRadius: number; readonly offsetX: number; readonly offsetY: number; getRingIndex(datasetIndex: number): number; calculateTotal(): number; calculateCircumference(value: number): number; } export const DoughnutController: IChartComponent & { prototype: DoughnutController; new (chart: Chart, datasetIndex: number): DoughnutController; }; export type IPieControllerDatasetOptions = IDoughnutControllerDatasetOptions; export type IPieControllerChartOptions = IDoughnutControllerChartOptions; export type IPieAnimationOptions = IDoughnutAnimationOptions; export type IPieDataPoint = IDoughnutDataPoint; export interface PieController extends DoughnutController {} export const PieController: IChartComponent & { prototype: PieController; new (chart: Chart, datasetIndex: number): PieController; }; export interface IPolarAreaControllerDatasetOptions extends IDoughnutControllerDatasetOptions { /** * Arc angle to cover. - for polar only * @default circumference / (arc count) */ angle: number; } export type IPolarAreaAnimationOptions = IDoughnutAnimationOptions; export interface IPolarAreaControllerChartOptions { /** * Starting angle to draw arcs for the first item in a dataset. In degrees, 0 is at top. * @default 0 */ startAngle: number; animation: IPolarAreaAnimationOptions; } export interface PolarAreaController extends DoughnutController { countVisibleElements(): number; } export const PolarAreaController: IChartComponent & { prototype: PolarAreaController; new (chart: Chart, datasetIndex: number): PolarAreaController; }; export interface IRadarControllerDatasetOptions extends IControllerDatasetOptions, ScriptableOptions<IPointPrefixedOptions>, ScriptableOptions<IPointPrefixedHoverOptions>, ScriptableOptions<ILineOptions>, ScriptableOptions<ILineHoverOptions> { /** * The ID of the x axis to plot this dataset on. */ xAxisID: string; /** * The ID of the y axis to plot this dataset on. */ yAxisID: string; /** * If true, lines will be drawn between points with no or null data. If false, points with NaN data will create a break in the line. Can also be a number specifying the maximum gap length to span. The unit of the value depends on the scale used. */ spanGaps: boolean | number; /** * If false, the line is not drawn for this dataset. */ showLine: boolean; } export type IRadarControllerChartOptions = ILineControllerChartOptions; export interface RadarController extends DatasetController {} export const RadarController: IChartComponent & { prototype: RadarController; new (chart: Chart, datasetIndex: number): RadarController; };
1.414063
1
src/util_fs.ts
elarivie/css-ts
0
896
import * as fs from "fs"; import {Promised} from "./util"; /* * Get entry element status. */ export async function stats(aPath: Promised<string>): Promise<fs.Stats | null> { return Promise.all([aPath]).then(([aPath]) => { try { return fs.statSync(aPath); } catch (e) { if (e.code == 'ENOTDIR') { // The path to the entry does not exist return null; } if (e.code == 'ENOENT') { // no such file or directory. File does not exist return null; } throw e; // something went wrong… } }); } /* * Read a utf-8 encoded text file on disk or read from stdin if path is 0 */ export async function readTextFile(filePath: Promised<string | 0>): Promise<string> { return new Promise<string>((resolve: (value?: string | PromiseLike<string> | undefined) => void, reject: (reason?: any)=> void) => { Promise.all([filePath]).then(([filePath]) => { fs.readFile(filePath, {encoding: "utf-8", flag: "r"}, (err, data) => { if (err) { reject(err); } resolve(data); }); }); }); } /* * Write a utf-8 encoded text file on disk or to stdout/stderr if filePath is a file number */ export async function writeTextFile(filePath: Promised<string | 1 | 2>, data: Promised<string>, encoding: Promised<"utf-8"> = "utf-8"): Promise<void> { return new Promise<void>((resolve: (value?: void | PromiseLike<void> | undefined) => void, reject: (reason?: any) => void) => { Promise.all([filePath, data]).then(([filePath, data]) => { fs.writeFile((1 == filePath) ? 1 : filePath, data, {encoding: "utf-8", flag: "w"}, (err) => { if (err) { reject(err); } resolve(); }); }); }); }
1.570313
2
src/index.ts
TimMikeladze/super-yt-mp3
0
904
export * from './SuperYT'
-0.326172
0
packages/sil-governance/src/routes/dashboard/components/Proposal/VotingPanel/index.tsx
webmaster128/ponferrada
6
912
import { ProposalResult, VoteOption } from "@iov/bns"; import { Block, Typography } from "medulas-react-components"; import React from "react"; import { voteToString } from "ui-logic"; import { Tally } from "../../../../../store/proposals"; import Buttons from "./Buttons"; import ParticipationData from "./ParticipationData"; import ResultFlair from "./ResultFlair"; interface Props { readonly result: ProposalResult; readonly vote: VoteOption | undefined; readonly id: number; readonly quorum: number; readonly threshold: number; readonly tally: Tally; readonly hasStarted: boolean; readonly hasEnded: boolean; } const VotingPanel = ({ result, vote, id, quorum, threshold, tally, hasStarted, hasEnded, }: Props): JSX.Element => { const voteText = voteToString(vote); return ( <Block minWidth="160px" margin={2} display="flex" flexDirection="column"> {hasEnded && <ResultFlair result={result} />} {hasStarted && <Typography variant="body2">Your vote: {voteText}</Typography>} {hasStarted && !hasEnded && <Buttons id={id} vote={vote} />} <ParticipationData quorum={quorum} threshold={threshold} tally={tally} /> </Block> ); }; export default VotingPanel;
1.414063
1
projects/demo/src/app/examples/check-list/check-list-item/check-list-item.component.ts
chongqiangchen/slate-ng
4
920
import { AfterContentChecked, ChangeDetectionStrategy, ChangeDetectorRef, Component, ElementRef, Inject, OnInit } from "@angular/core"; import { AngularEditor, BaseElementComponent, NsEditorService, Key, KEY_TOKEN, NsDepsService } from "slate-ng"; import { Element as SlateElement, Transforms } from "slate"; @Component({ selector: "div[check-list-item]", templateUrl: "./check-list-item.component.html", styleUrls: ["./check-list-item.component.less"], changeDetection: ChangeDetectionStrategy.OnPush }) export class CheckListItemComponent extends BaseElementComponent implements OnInit { static type = 'check-list-item'; constructor( @Inject(KEY_TOKEN) readonly key: Key, public deps: NsDepsService, public editorService: NsEditorService, public elementRef: ElementRef, public cdr: ChangeDetectorRef, ) { super(key, deps, editorService, elementRef, cdr); } ngOnInit(): void { this.init(); this.watchDeps(); } handleCheckboxChange($event: any) { const path = AngularEditor.findPath(this.editorService.editor, this.cNode); const newProperties: Partial<SlateElement & {checked: boolean}> = { checked: $event.target?.checked }; Transforms.setNodes(this.editorService.editor, newProperties, { at: path }); } }
1.296875
1
src/index.ts
thegecko/vscode-test-web
0
928
#!/usr/bin/env node /* eslint-disable header/header */ /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import { IConfig, runServer, Static, Sources } from './server/main'; import { downloadAndUnzipVSCode, directoryExists, fileExists } from './server/download'; import * as playwright from 'playwright'; import * as minimist from 'minimist'; import * as path from 'path'; export type BrowserType = 'chromium' | 'firefox' | 'webkit' | 'none'; export type VSCodeQuality = 'insiders' | 'stable'; export type GalleryExtension = { readonly id: string; readonly preRelease?: boolean; } export interface Options { /** * Browser to open: 'chromium' | 'firefox' | 'webkit' | 'none'. */ browserType: BrowserType; /** * Absolute path to folder that contains one or more extensions (in subfolders). * Extension folders include a `package.json` extension manifest. */ extensionDevelopmentPath?: string; /** * Absolute path to the extension tests runner module. * Can be either a file path or a directory path that contains an `index.js`. * The module is expected to have a `run` function of the following signature: * * ```ts * function run(): Promise<void>; * ``` * * When running the extension test, the Extension Development Host will call this function * that runs the test suite. This function should throws an error if any test fails. */ extensionTestsPath?: string; /** * The quality of the VS Code to use. Supported qualities are: * - `'stable'` : The latest stable build will be used * - `'insiders'` : The latest insiders build will be used * * Currently defaults to `insiders`, which is latest stable insiders. * * The setting is ignored when a vsCodeDevPath is provided. */ quality?: VSCodeQuality; /** * @deprecated. Use `quality` or `vsCodeDevPath` instead. */ version?: string; /** * Open the dev tools. */ devTools?: boolean; /** * Do not show the browser. Defaults to `true` if a `extensionTestsPath` is provided, `false` otherwise. */ headless?: boolean; /** * @deprecated. Use `printServerLog` instead. */ hideServerLog?: boolean; /** * If set, the server access log is printed to the console. Defaults to `false`. */ printServerLog?: boolean; /** * Expose browser debugging on this port number, and wait for the debugger to attach before running tests. */ waitForDebugger?: number; /** * A local path to open VSCode on. VS Code for the browser will open an a virtual * file system ('vscode-test-web://mount') where the files of the local folder will served. * The file system is read/write, but modifications are stored in memory and not written back to disk. */ folderPath?: string; /** * The folder URI to open VSCode on. If 'folderPath' is set this will be ignored and 'vscode-test-web://mount' * is used as folder URI instead. */ folderUri?: string; /** * Permissions granted to the opened browser. An list of permissions can be found at * https://playwright.dev/docs/api/class-browsercontext#browser-context-grant-permissions * Example: [ 'clipboard-read', 'clipboard-write' ] */ permissions?: string[]; /** * Absolute paths pointing to built-in extensions to include. */ extensionPaths?: string[]; /** * List of extensions to include. The id format is ${publisher}.${name}. */ extensionIds?: GalleryExtension[]; /** * Absolute path pointing to VS Code sources to use. */ vsCodeDevPath?: string; /** * Print out more information while the server is running, e.g. the console output in the browser */ verbose?: boolean; /** * The port to start the server on. Defaults to `3000`. */ port?: number; /** * The host name to start the server on. Defaults to `localhost` */ host?: string; } export interface Disposable { dispose(): void; } /** * Runs the tests in a browser. * * @param options The options defining browser type, extension and test location. */ export async function runTests(options: Options & { extensionTestsPath: string }): Promise<void> { const config: IConfig = { extensionDevelopmentPath: options.extensionDevelopmentPath, extensionTestsPath: options.extensionTestsPath, build: await getBuild(options), folderUri: options.folderUri, folderMountPath: options.folderPath, printServerLog: options.printServerLog ?? options.hideServerLog === false, extensionPaths: options.extensionPaths, extensionIds: options.extensionIds }; const host = options.host ?? 'localhost'; const port = options.port ?? 3000; const server = await runServer(host, port, config); return new Promise(async (s, e) => { const endpoint = `http://${host}:${port}`; const context = await openBrowser(endpoint, options); if (context) { context.once('close', () => server.close()); await context.exposeFunction('codeAutomationLog', (type: 'warn' | 'error' | 'info', args: unknown[]) => { console[type](...args); }); await context.exposeFunction('codeAutomationExit', async (code: number) => { try { await context.browser()?.close(); } catch (error) { console.error(`Error when closing browser: ${error}`); } server.close(); if (code === 0) { s(); } else { e(new Error('Test failed')); } }); } else { server.close(); e(new Error('Can not run test as opening of browser failed.')); } }); } async function getBuild(options: Options): Promise<Static | Sources> { if (options.vsCodeDevPath) { return { type: 'sources', location: options.vsCodeDevPath }; } const quality = options.quality || options.version; return await downloadAndUnzipVSCode(quality === 'stable' ? 'stable' : 'insider'); } export async function open(options: Options): Promise<Disposable> { const config: IConfig = { extensionDevelopmentPath: options.extensionDevelopmentPath, extensionTestsPath: options.extensionTestsPath, build: await getBuild(options), folderUri: options.folderUri, folderMountPath: options.folderPath, printServerLog: options.printServerLog ?? options.hideServerLog === false, extensionPaths: options.extensionPaths, extensionIds: options.extensionIds }; const host = options.host ?? 'localhost'; const port = options.port ?? 3000; const server = await runServer(host, port, config); const endpoint = `http://${host}:${port}`; const context = await openBrowser(endpoint, options); context?.once('close', () => server.close()); return { dispose: () => { server.close(); context?.browser()?.close(); } } } async function openBrowser(endpoint: string, options: Options): Promise<playwright.BrowserContext | undefined> { if (options.browserType === 'none') { return undefined; } const browserType = await playwright[options.browserType]; if (!browserType) { console.error(`Can not open browser type: ${options.browserType}`); return undefined; } const args: string[] = [] if (process.platform === 'linux' && options.browserType === 'chromium') { args.push('--no-sandbox'); } if (options.waitForDebugger) { args.push(`--remote-debugging-port=${options.waitForDebugger}`); } const headless = options.headless ?? options.extensionTestsPath !== undefined; const browser = await browserType.launch({ headless, args, devtools: options.devTools }); const context = await browser.newContext({ viewport: null }); if (options.permissions) { context.grantPermissions(options.permissions); } // forcefully close browser if last page is closed. workaround for https://github.com/microsoft/playwright/issues/2946 let openPages = 0; context.on('page', page => { openPages++; page.once('close', () => { openPages--; if (openPages === 0) { browser.close(); } }) }); const page = context.pages()[0] ?? await context.newPage(); if (options.waitForDebugger) { await page.waitForFunction(() => '__jsDebugIsReady' in globalThis); } if (options.verbose) { page.on('console', (message) => { console.log(message.text()); }) } await page.goto(endpoint); return context; } function validateStringOrUndefined(options: CommandLineOptions, name: keyof CommandLineOptions): string | undefined { const value = options[name]; if (value === undefined || (typeof value === 'string')) { return value; } console.log(`'${name}' needs to be a string value.`); showHelp(); process.exit(-1); } async function validatePathOrUndefined(options: CommandLineOptions, name: keyof CommandLineOptions, isFile?: boolean): Promise<string | undefined> { const loc = validateStringOrUndefined(options, name); return loc && validatePath(loc, isFile); } function validateBooleanOrUndefined(options: CommandLineOptions, name: keyof CommandLineOptions): boolean | undefined { const value = options[name]; if (value === undefined || (typeof value === 'boolean')) { return value; } console.log(`'${name}' needs to be a boolean value.`); showHelp(); process.exit(-1); } function validatePrintServerLog(options: CommandLineOptions): boolean { const printServerLog = validateBooleanOrUndefined(options, 'printServerLog'); if (printServerLog !== undefined) { return printServerLog; } const hideServerLog = validateBooleanOrUndefined(options, 'hideServerLog'); if (hideServerLog !== undefined) { return !hideServerLog; } return false; } function valdiateBrowserType(options: CommandLineOptions): BrowserType { const browserType = options.browser || options.browserType; if (browserType === undefined) { return 'chromium'; } if (options.browserType && options.browser) { console.log(`Ignoring browserType option '${options.browserType}' as browser option '${options.browser}' is set.`); } if ((typeof browserType === 'string') && ['chromium', 'firefox', 'webkit', 'none'].includes(browserType)) { return browserType as BrowserType; } console.log(`Invalid browser option ${browserType}.`); showHelp(); process.exit(-1); } function valdiatePermissions(permissions: unknown): string[] | undefined { if (permissions === undefined) { return undefined } function isValidPermission(p: unknown): p is string { return typeof p === 'string'; } if (isValidPermission(permissions)) { return [permissions]; } if (Array.isArray(permissions) && permissions.every(isValidPermission)) { return permissions; } console.log(`Invalid permission`); showHelp(); process.exit(-1); } async function valdiateExtensionPaths(extensionPaths: unknown): Promise<string[] | undefined> { if (extensionPaths === undefined) { return undefined } if (!Array.isArray(extensionPaths)) { extensionPaths = [extensionPaths]; } if (Array.isArray(extensionPaths)) { const res: string[] = []; for (const extensionPath of extensionPaths) { if (typeof extensionPath === 'string') { res.push(await validatePath(extensionPath)); } else { break; } } return res; } console.log(`Invalid extensionPath`); showHelp(); process.exit(-1); } const EXTENSION_IDENTIFIER_PATTERN = /^([a-z0-9A-Z][a-z0-9-A-Z]*\.[a-z0-9A-Z][a-z0-9-A-Z]*)(@prerelease)?$/; async function valdiateExtensionIds(extensionIds: unknown): Promise<GalleryExtension[] | undefined> { if (extensionIds === undefined) { return undefined } if (!Array.isArray(extensionIds)) { extensionIds = [extensionIds]; } if (Array.isArray(extensionIds)) { const res: GalleryExtension[] = []; for (const extensionId of extensionIds) { const m = (typeof extensionId === 'string' && extensionId.match(EXTENSION_IDENTIFIER_PATTERN)); if (m) { if (m[2]) { res.push({ id: m[1], preRelease: true }); } else { res.push({ id: m[1] }); } } else { console.log(`Invalid extension id: ${extensionId}. Format is publisher.name[@prerelease].`); break; } } return res; } else { console.log(`Invalid extensionId`); } showHelp(); process.exit(-1); } async function validatePath(loc: string, isFile?: boolean): Promise<string> { loc = path.resolve(loc); if (isFile) { if (!await fileExists(loc)) { console.log(`'${loc}' must be an existing file.`); process.exit(-1); } } else { if (!await directoryExists(loc)) { console.log(`'${loc}' must be an existing folder.`); process.exit(-1); } } return loc; } function validateQuality(quality: unknown, version: unknown, vsCodeDevPath: string | undefined): VSCodeQuality | undefined { if (version) { console.log(`--version has been replaced by --quality`); quality = quality || version; } if (vsCodeDevPath && quality) { console.log(`Sources folder is provided as input, quality is ignored.`); return undefined; } if (quality === undefined || ((typeof quality === 'string') && ['insiders', 'stable'].includes(quality))) { return quality as VSCodeQuality; } if (version === 'sources') { console.log(`Instead of version=sources use 'sourcesPath' with the location of the VS Code repository.`); } else { console.log(`Invalid quality.`); } showHelp(); process.exit(-1); } function validatePortNumber(port: unknown): number | undefined { if (typeof port === 'string') { const number = Number.parseInt(port); if (!Number.isNaN(number) && number >= 0) { return number; } } return undefined; } interface CommandLineOptions { browser?: string; browserType?: string; extensionDevelopmentPath?: string; extensionTestsPath?: string; quality?: string; sourcesPath?: string; 'open-devtools'?: boolean; headless?: boolean; hideServerLog?: boolean; printServerLog?: boolean; permission?: string | string[]; 'folder-uri'?: string; extensionPath?: string | string[]; extensionId?: string | string[]; host?: string; port?: string; verbose?: boolean; help?: boolean; } function showHelp() { console.log('Usage:'); console.log(` --browser 'chromium' | 'firefox' | 'webkit' | 'none': The browser to launch. [Optional, defaults to 'chromium']`) console.log(` --extensionDevelopmentPath path: A path pointing to an extension under development to include. [Optional]`); console.log(` --extensionTestsPath path: A path to a test module to run. [Optional]`); console.log(` --quality 'insiders' | 'stable' [Optional, default 'insiders', ignored when running from sources]`); console.log(` --sourcesPath path: If provided, running from VS Code sources at the given location. [Optional]`); console.log(` --open-devtools: If set, opens the dev tools. [Optional]`); console.log(` --headless: Whether to hide the browser. Defaults to true when an extensionTestsPath is provided, otherwise false. [Optional]`); console.log(` --permission: Permission granted in the opened browser: e.g. 'clipboard-read', 'clipboard-write'. [Optional, Multiple]`); console.log(` --folder-uri: workspace to open VS Code on. Ignored when folderPath is provided. [Optional]`); console.log(` --extensionPath: A path pointing to a folder containing additional extensions to include [Optional, Multiple]`); console.log(` --extensionId: The id of an extension include. The format is '\${publisher}.\${name}'. Append '@prerelease' to use a prerelease version [Optional, Multiple]`); console.log(` --host: The host name the server is opened on. [Optional, defaults to localhost]`); console.log(` --port: The port the server is opened on. [Optional, defaults to 3000]`); console.log(` --open-devtools: If set, opens the dev tools. [Optional]`); console.log(` --verbose: If set, prints out more information when running the server. [Optional]`); console.log(` --printServerLog: If set, prints the server access log. [Optional]`); console.log(` folderPath. A local folder to open VS Code on. The folder content will be available as a virtual file system. [Optional]`); } async function cliMain(): Promise<void> { // eslint-disable-next-line @typescript-eslint/no-var-requires const manifest = require('../package.json'); console.log(`${manifest.name}: ${manifest.version}`); const options: minimist.Opts = { string: ['extensionDevelopmentPath', 'extensionTestsPath', 'browser', 'browserType', 'quality', 'version', 'waitForDebugger', 'folder-uri', 'permission', 'extensionPath', 'extensionId', 'sourcesPath', 'host', 'port'], boolean: ['open-devtools', 'headless', 'hideServerLog', 'printServerLog', 'help', 'verbose'], unknown: arg => { if (arg.startsWith('-')) { console.log(`Unknown argument ${arg}`); showHelp(); process.exit(); } return true; } }; const args = minimist<CommandLineOptions>(process.argv.slice(2), options); if (args.help) { showHelp(); process.exit(); } const browserType = valdiateBrowserType(args); const extensionTestsPath = await validatePathOrUndefined(args, 'extensionTestsPath', true); const extensionDevelopmentPath = await validatePathOrUndefined(args, 'extensionDevelopmentPath'); const extensionPaths = await valdiateExtensionPaths(args.extensionPath); const extensionIds = await valdiateExtensionIds(args.extensionId); const vsCodeDevPath = await validatePathOrUndefined(args, 'sourcesPath'); const quality = validateQuality(args.quality, args.version, vsCodeDevPath); const devTools = validateBooleanOrUndefined(args, 'open-devtools'); const headless = validateBooleanOrUndefined(args, 'headless'); const permissions = valdiatePermissions(args.permission); const printServerLog = validatePrintServerLog(args); const verbose = validateBooleanOrUndefined(args, 'verbose'); const port = validatePortNumber(args.port); const host = validateStringOrUndefined(args, 'host'); const waitForDebugger = validatePortNumber(args.waitForDebugger); let folderUri = validateStringOrUndefined(args, 'folder-uri'); let folderPath: string | undefined; const inputs = args._; if (inputs.length) { const input = await validatePath(inputs[0]); if (input) { folderPath = input; if (folderUri) { console.log(`Local folder provided as input, ignoring 'folder-uri'`); folderUri = undefined; } } } if (extensionTestsPath) { runTests({ extensionTestsPath, extensionDevelopmentPath, browserType, quality, devTools, waitForDebugger, folderUri, folderPath, headless, printServerLog: printServerLog, permissions, extensionPaths, extensionIds, vsCodeDevPath, verbose, host, port }).catch(e => { console.log(e.message); process.exit(1); }) } else { open({ extensionDevelopmentPath, browserType, quality, devTools, waitForDebugger, folderUri, folderPath, headless, printServerLog: printServerLog, permissions, extensionPaths, extensionIds, vsCodeDevPath, verbose, host, port }) } } if (require.main === module) { cliMain(); }
1.25
1
.exclude/examples/platform-express/src/cats/cats.configure.ts
marcus-sa/one
6
936
import { MiddlewareConfigure } from '@nest/server'; // @TODO: Rename interface? // Seems inconvenient to call it that when it can configure routes as well export class CatsConfigure implements MiddlewareConfigure { configure() {} }
0.808594
1
tests/example_server.ts
Amatsagu/Promethium
1
944
import { App } from "../src/app.ts"; const app = new App({port: 8080}); const users = new Set<string>(); app.listen("GET", "/", () => new Response("Hello world")); app.listen("GET", "/key/:val", (_req, params) => { const res = new Response(JSON.stringify({ key: params["val"] })); res.headers.set("Content-Type", "application/json"); return res; }); app.listen("POST", "/users", async (req, _params) => { const payload = await req.text(); let content if (payload && payload.length !== 0) { try { content = JSON.parse(payload); } catch { const res = new Response(JSON.stringify({ error: "Invalid body" }), { status: 400 }); res.headers.set("Content-Type", "application/json"); return res; } } else { const res = new Response(JSON.stringify({ error: "Invalid body" }), { status: 400 }); res.headers.set("Content-Type", "application/json"); return res; } if (content.id) { if (users.has(content.id)) { const res = new Response(JSON.stringify({ error: "You're already added to users list." }), { status: 400 }); res.headers.set("Content-Type", "application/json"); return res; } else { users.add(content.id); const res = new Response(JSON.stringify({ data: "Success." }), { status: 200 }); res.headers.set("Content-Type", "application/json"); return res; } } else { const res = new Response(JSON.stringify({ error: "Invalid body" }), { status: 400 }); res.headers.set("Content-Type", "application/json"); return res; } }); app.listen("GET", "/users/:id", (_req, params) => { if (users.has(params["id"])) { const res = new Response(JSON.stringify({ data: "There is such user." })); res.headers.set("Content-Type", "application/json"); return res; } else { const res = new Response(JSON.stringify({ key: "Unknown user." })); res.headers.set("Content-Type", "application/json"); return res; } });
1.71875
2
src/app/services/places/places.actions.ts
Kauabunga/whitecloud
0
952
import { Action } from '@ngrx/store'; import { Coords } from '../map/map.model'; export const SEARCH = '[Places] Search'; export const SEARCH_SUCCESS = '[Places] Search Success'; export const SEARCH_FAILURE = '[Places] Search Failure'; export const LOOKUP = '[Places] Lookup place'; export const LOOKUP_SUCCESS = '[Places] Lookup place Success'; export const LOOKUP_FAILURE = '[Places] Lookup place Failure'; export class SearchAction implements Action { readonly type = SEARCH; constructor(public payload: string | Coords) { } } export class SearchSuccessAction implements Action { readonly type = SEARCH_SUCCESS; constructor(public payload: { query: string, results: string[] }) { } } export class SearchFailureAction implements Action { readonly type = SEARCH_FAILURE; constructor(public payload: { error: string }) { } } export class LookupAction implements Action { readonly type = LOOKUP; constructor(public payload: string) { } } export class LookupSuccessAction implements Action { readonly type = LOOKUP_SUCCESS; constructor(public payload: { query: string, results: string[] }) { } } export class LookupFailureAction implements Action { readonly type = LOOKUP_FAILURE; constructor(public payload: { error: string }) { } } export type Actions = SearchAction | SearchSuccessAction | SearchFailureAction | LookupAction | LookupSuccessAction | LookupFailureAction;
1.320313
1
src/passes/visitNode/visitTCsv.ts
ninmonkey/powerquery-formatter
1
960
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. import * as PQP from "@microsoft/powerquery-parser"; import { SerializeParameter, SerializeParameterState, SerializeWriteKind } from "../types"; import { getWorkspace, propagateWriteKind, setWorkspace } from "./visitNodeUtils"; export function visitTCsv(state: SerializeParameterState, node: PQP.Language.Ast.TCsv): void { const workspace: SerializeParameter = getWorkspace(state, node); const maybeWriteKind: SerializeWriteKind | undefined = workspace.maybeWriteKind; propagateWriteKind(state, node, node.node); if (node.maybeCommaConstant && maybeWriteKind !== SerializeWriteKind.Indented) { const commaConstant: PQP.Language.Ast.IConstant<PQP.Language.Constant.MiscConstantKind.Comma> = node.maybeCommaConstant; setWorkspace(state, commaConstant, { maybeWriteKind: SerializeWriteKind.PaddedRight }); } }
0.941406
1
apps/admin-web/src/admin-web.module.ts
xsharing/x-serverless-voting-system
0
968
import { AppConfigModule } from '@app/app-config'; import { Module } from '@nestjs/common'; import { RenderModule } from 'nest-next'; import Next from 'next'; import { resolve } from 'path'; import { AdminWebController } from './admin-web.controller'; import { AdminWebService } from './admin-web.service'; const dev = process.env.NODE_ENV !== 'production'; const nextDir = (function () { switch (process.env.NODE_ENV) { case 'test': return resolve(__dirname, 'ui'); default: return resolve(__dirname, 'ui'); } })(); @Module({ imports: [ RenderModule.forRootAsync( Next({ dev, dir: nextDir, }), { dev, }, ), AppConfigModule, ], controllers: [AdminWebController], providers: [AdminWebService], }) export class AdminWebModule {}
0.953125
1
out/separate/dojox.grid.enhanced.plugins.filter.ServerSideFilterLayer.d.ts
stopyoukid/DojoToTypescriptConverter
2
976
/// <reference path="Object.d.ts" /> /// <reference path="dojox.grid.enhanced.plugins._ServerSideLayer.d.ts" /> /// <reference path="dojox.grid.enhanced.plugins.filter._FilterLayerMixin.d.ts" /> module dojox.grid.enhanced.plugins.filter{ export class ServerSideFilterLayer extends dojox.grid.enhanced.plugins._ServerSideLayer { _filter : any; filterDef (filter?:any) : any; onFilterDefined (filter:any) : any; onFiltered (filteredSize:number,totalSize:number) : any; _filteredSize : Object; } }
0.882813
1
src/rest-handlers/users/show.ts
MissKernel/Misskey-API
6
984
import {IApplication, IUser} from '../../db/interfaces'; import show from '../../endpoints/users/show'; export default function( app: IApplication, user: IUser, req: any, res: any ): void { show( user, req.payload['user-id'], req.payload['screen-name'] ).then(showee => { res(showee); }, (err: any) => { res({error: err}).code(500); }); }
1.164063
1
dist/esm/models/contract-call-results.d.ts
daryledesilva/ethereum-multicall
0
992
import { ContractCallReturnContext } from './contract-call-return-context'; export interface ContractCallResults { results: { [key: string]: ContractCallReturnContext; }; blockNumber: number; }
0.664063
1
x-pack/plugins/uptime/public/components/functional/monitor_list.tsx
igoristic/kibana
0
1000
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import { EuiHealth, // @ts-ignore missing type definition EuiHistogramSeries, EuiIcon, // @ts-ignore missing type definition EuiInMemoryTable, EuiLink, EuiPanel, // @ts-ignore missing type definition EuiSeriesChart, // @ts-ignore missing type definition EuiSeriesChartUtils, EuiSpacer, EuiText, EuiTitle, } from '@elastic/eui'; import { i18n } from '@kbn/i18n'; import { FormattedMessage } from '@kbn/i18n/react'; import { get } from 'lodash'; import moment from 'moment'; import React from 'react'; import { Link } from 'react-router-dom'; import { LatestMonitor, MonitorSeriesPoint } from '../../../common/graphql/types'; import { UptimeGraphQLQueryProps, withUptimeGraphQL } from '../higher_order'; import { monitorListQuery } from '../../queries'; import { MonitorSparkline } from './monitor_sparkline'; interface MonitorListQueryResult { // TODO: clean up this ugly result data shape, there should be no nesting monitorStatus?: { monitors: LatestMonitor[]; }; } interface MonitorListProps { dangerColor: string; linkParameters?: string; } type Props = UptimeGraphQLQueryProps<MonitorListQueryResult> & MonitorListProps; const MONITOR_LIST_DEFAULT_PAGINATION = 10; const monitorListPagination = { initialPageSize: MONITOR_LIST_DEFAULT_PAGINATION, pageSizeOptions: [5, 10, 20, 50], }; export const MonitorListComponent = ({ dangerColor, data, linkParameters, loading }: Props) => ( <EuiPanel paddingSize="s"> <EuiTitle size="xs"> <h5> <FormattedMessage id="xpack.uptime.monitorList.monitoringStatusTitle" defaultMessage="Monitor status" /> </h5> </EuiTitle> <EuiSpacer size="s" /> <EuiInMemoryTable columns={[ { field: 'ping.monitor.status', width: '150px', name: i18n.translate('xpack.uptime.monitorList.statusColumnLabel', { defaultMessage: 'Status', }), render: (status: string, monitor: LatestMonitor) => ( <div> <EuiHealth color={status === 'up' ? 'success' : 'danger'} style={{ display: 'block' }} > {status === 'up' ? i18n.translate('xpack.uptime.monitorList.statusColumn.upLabel', { defaultMessage: 'Up', }) : i18n.translate('xpack.uptime.monitorList.statusColumn.downLabel', { defaultMessage: 'Down', })} </EuiHealth> <EuiText size="xs" color="subdued"> {moment(get(monitor, 'ping.monitor.timestamp', undefined)).fromNow()} </EuiText> </div> ), }, { field: 'ping.monitor.id', name: i18n.translate('xpack.uptime.monitorList.idColumnLabel', { defaultMessage: 'ID', }), render: (id: string, monitor: LatestMonitor) => ( <EuiLink> <Link data-test-subj={`monitor-page-link-${id}`} to={`/monitor/${id}${linkParameters}`} > {monitor.ping && monitor.ping.monitor && monitor.ping.monitor.name ? monitor.ping.monitor.name : id} </Link> </EuiLink> ), }, { field: 'ping.url.full', name: i18n.translate('xpack.uptime.monitorList.urlColumnLabel', { defaultMessage: 'URL', }), render: (url: string, monitor: LatestMonitor) => ( <div> <EuiLink href={url} target="_blank" color="text"> {url} <EuiIcon size="s" type="popout" color="subdued" /> </EuiLink> {monitor.ping && monitor.ping.monitor && monitor.ping.monitor.ip ? ( <EuiText size="xs" color="subdued"> {monitor.ping.monitor.ip} </EuiText> ) : null} </div> ), }, { field: 'upSeries', width: '180px', align: 'right', name: i18n.translate('xpack.uptime.monitorList.monitorHistoryColumnLabel', { defaultMessage: 'Downtime history', }), render: (downSeries: MonitorSeriesPoint, monitor: LatestMonitor) => ( <MonitorSparkline dangerColor={dangerColor} monitor={monitor} /> ), }, ]} loading={loading} items={(data && data.monitorStatus && data.monitorStatus.monitors) || undefined} pagination={monitorListPagination} /> </EuiPanel> ); export const MonitorList = withUptimeGraphQL<MonitorListQueryResult, MonitorListProps>( MonitorListComponent, monitorListQuery );
1.359375
1
src/utils/index.ts
simplicy-io/bitcoincomputer-contracts
1
1008
export * from './Context'; export * from './shared.utils';
-0.217773
0
clients/node/client-swf-node/types/RespondActivityTaskCanceledExceptionsUnion.ts
pravgupt/aws-sdk-js-v3
0
1016
import { UnknownResourceFault } from "./UnknownResourceFault"; import { OperationNotPermittedFault } from "./OperationNotPermittedFault"; export type RespondActivityTaskCanceledExceptionsUnion = | UnknownResourceFault | OperationNotPermittedFault;
0.414063
0
front/src/app/models/day.view.model.ts
sebferrer/healthy-day
2
1024
import { IDay } from './day.model'; import { getSortOrder } from '../util/array.utils'; import { DayOverviewViewModel } from 'src/app/models/day.overview.view.model'; import { ISymptomLog, ISymptom } from './symptom.model'; export class DayViewModel extends DayOverviewViewModel { public readonly wakeUp: string; public readonly goToBed: string; public readonly content: Array<any>; public readonly symptoms: Array<ISymptom>; public removable: boolean; constructor(day: IDay) { super(day); this.wakeUp = day.wakeUp; this.goToBed = day.goToBed; this.content = [...day.logs]; this.symptoms = [...day.symptoms]; for (const symptom of day.symptoms) { this.content.push(...symptom.logs); } this.content.push(...day.meds); this.content.push(...day.meals); this.content.sort(getSortOrder('time')); this.removable = false; } }
1.28125
1
src/utils.ts
OlaoluwaM/codename-foo
0
1032
import fs from 'fs/promises'; import path from 'path'; import { chalk } from 'zx'; import { oraPromise } from 'ora'; import { AnyObject, FilePath, Primitive } from './compiler/types'; import { ErrorHook, ERROR_HOOK, DEFAULT_LEFT_PADDING_SIZE } from './constants'; export function info(msg: string, leftPaddingSize = DEFAULT_LEFT_PADDING_SIZE) { console.info(addSpacesToString(chalk.whiteBright.bold(msg), leftPaddingSize)); } export function success(msg: string) { console.log(addSpacesToString(chalk.greenBright.bold(msg), DEFAULT_LEFT_PADDING_SIZE)); } export function error(msg: string, shouldThrow = false) { console.error(addSpacesToString(chalk.red.bold(msg), DEFAULT_LEFT_PADDING_SIZE)); if (shouldThrow) throw new Error(msg); } export function pipe(...fns: readonly ((...args: any[]) => any)[]) { return (initialValue?: unknown) => fns.reduce((accumulatedValue, fnToRun) => fnToRun(accumulatedValue), initialValue); } export function includedInCollection<T extends U, U>( collection: readonly T[], itemToCheck: U ): itemToCheck is T { return collection.includes(itemToCheck as T); } export function doesObjectHaveProperty(obj: AnyObject, property: Primitive): boolean { return Object.prototype.hasOwnProperty.call(obj, property); } type MultiLineString = string & { _type: 'multiLine' }; export function toMultiLineString(arr: string[]): MultiLineString { return arr.map(elem => `${elem}\n`).join('\n') as MultiLineString; } export function isSubset<PSubS extends PSupS, PSupS>( potentialSuperset: PSupS[], potentialSubset: PSubS[] ): boolean { return potentialSubset.some(potentialSubsetElem => potentialSuperset.includes(potentialSubsetElem) ); } export function isObjSubset<PSubS extends AnyObject, PSupS extends AnyObject>( potentialSupersetObj: PSupS, potentialSubsetObj: PSubS ): boolean { const potentialSubset = Object.entries(potentialSubsetObj); return potentialSubset.some(([key, value]) => { const propertyInSuperset = potentialSupersetObj[key]; const propertyMatchesInSuperset = rawTypeOf(value) === rawTypeOf(propertyInSuperset); return !!propertyInSuperset && propertyMatchesInSuperset; }); } export function filterOutPaths(arr: string[]): string[] { const pathRegex = /\.\.?\/[^\n"?:*<>|]+\.[A-z0-9]+/; return arr.filter(elem => !pathRegex.test(elem)); } export function addException<P extends unknown[], R extends unknown>( callback: (...args: P) => R ) { return async (...args: P) => { const value = (await callback(...args)) as Awaited<R>; if (value === ERROR_HOOK || !value) throw new Error('An Error occurred'); return value as Exclude<Awaited<R>, ErrorHook>; }; } type TrueOnNullish<T> = T extends undefined | null ? true : T; export function addExceptionHook<P extends unknown[], R extends unknown>( successCallback: (...args: P[]) => R, errorCallback = defaultErrorCallback ): () => Promise<TrueOnNullish<R> | ErrorHook> { return async () => { try { const returnValue = await successCallback(); return (returnValue || true) as TrueOnNullish<R>; } catch (err) { errorCallback(err as Error | string); return ERROR_HOOK; } }; } function defaultErrorCallback(err: Error | string) { if (typeof err === 'object') { error(err.message); } else error(err); } export function extractSetFromCollection<ArrA, ArrB>( collectionOne: ArrA[], collectionTwo: (ArrA | ArrB)[], excludeSubset = false ) { return collectionOne.filter(elem => { const elemIsInSubset = collectionTwo.includes(elem); return excludeSubset ? !elemIsInSubset : elemIsInSubset; }); } export function pickObjPropsToAnotherObj<O extends {}, P extends keyof O>( initialObject: O, targetProperties: P[], excludeProperties: true ): Omit<O, P>; export function pickObjPropsToAnotherObj<O extends {}, P extends keyof O>( initialObject: O, targetProperties: P[], excludeProperties: false ): Pick<O, P>; export function pickObjPropsToAnotherObj<O extends {}, P extends keyof O>( initialObject: O, targetProperties: P[] ): Pick<O, P>; export function pickObjPropsToAnotherObj<O extends {}, P extends keyof O>( initialObject: O, targetProperties: P[], excludeProperties?: boolean ) { const desiredPropertyKeys = extractSetFromCollection( Object.keys(initialObject), targetProperties, excludeProperties ) as P[]; const objWithDesiredProperties = desiredPropertyKeys.reduce((filteredObj, propName) => { /* eslint no-param-reassign: ["error", { "props": false }] */ filteredObj[propName] = initialObject[propName]; return filteredObj; }, {} as O); return objWithDesiredProperties; } type RawTypes = Lowercase< 'Function' | 'Object' | 'Array' | 'Null' | 'Undefined' | 'String' | 'Number' | 'Boolean' >; export function rawTypeOf(value: unknown): RawTypes { return Object.prototype.toString .call(value) .replace(/\[|\]|object|\s/g, '') .toLocaleLowerCase() as RawTypes; } export const valueIs = { aString(val: unknown): val is string { return rawTypeOf(val) === 'string'; }, anArray(val: unknown): val is unknown[] { return rawTypeOf(val) === 'array'; }, anObject(val: unknown): val is AnyObject { return rawTypeOf(val) === 'object'; }, aNumber(val: unknown): val is number { return rawTypeOf(val) === 'number'; }, true(val: unknown): val is true { return val === true; }, async aFile(val: string): Promise<(value: string) => asserts value is FilePath> { let errMsg: string | undefined; try { const status = await fs.stat(val); if (!status.isFile()) throw new TypeError(`${val} is not a file`); } catch (err) { errMsg = err instanceof TypeError ? err.message : (err as string); } return (value: string) => { const thereWasAValidationError = !!errMsg; let innerErrMsg: string | undefined; if (value !== val) { innerErrMsg = "The returned function's argument must equal the argument passed into the initial async function call"; } else if (thereWasAValidationError) { innerErrMsg = errMsg; } if (innerErrMsg) throw new TypeError(innerErrMsg); }; }, }; export type FileAssertionFn = Awaited<ReturnType<typeof valueIs.aFile>>; export const isEmpty = { obj(possiblyEmptyObj: AnyObject): boolean { const hasNoProperties = Object.keys(possiblyEmptyObj).length === 0; return hasNoProperties; }, array(possiblyEmptyArr: unknown[]): boolean { return possiblyEmptyArr.length === 0; }, string(possiblyEmptyString: string): boolean { const EMPTY_STRING = '' as const; return possiblyEmptyString === EMPTY_STRING; }, }; export function extractBasenameFromPath(filepath: string): string { return path.basename(filepath); } export function normalizeArrForSentence(arrOfWords: string[]): string { switch (arrOfWords.length) { case 0: case 1: return arrOfWords[0] ?? ''; case 2: return `${arrOfWords[0]} and ${arrOfWords[1]}`; default: return createGrammaticalSentence(arrOfWords); } } function createGrammaticalSentence(arrOfWords: string[]): string { const arrCopy = [...arrOfWords]; const lastSentenceElement = `and ${arrCopy.pop()}`; arrCopy.push(lastSentenceElement); const sentenceList = arrCopy.join(', '); return sentenceList; } interface AsyncProcessSpinnerOptions { initialText: string; onSuccessText: string; onFailText: string; } type IdleAsyncSpinnerProcess<PromiseType> = () => Promise<PromiseType>; export class AsyncProcessSpinner<PromiseType> { #defaultSpinnerOptions = { initialText: 'Loading...', onSuccessText: 'Success!', onFailText: 'Error!', }; #spinnerOptions: AsyncProcessSpinnerOptions; #asyncSpinnerProcess: IdleAsyncSpinnerProcess<PromiseType>; constructor( promise: Promise<PromiseType>, options: Partial<AsyncProcessSpinnerOptions> ) { this.#spinnerOptions = { ...this.#defaultSpinnerOptions, ...options }; const oraCompatibleOptions = this.#mapPublicOptionsToImplementationOptions(); this.#asyncSpinnerProcess = oraPromise.bind( null, promise, oraCompatibleOptions ) as IdleAsyncSpinnerProcess<PromiseType>; } #mapPublicOptionsToImplementationOptions(): { text: string; successText: string; failText: string; } { const { onSuccessText, onFailText, initialText } = this.#spinnerOptions; return { text: initialText, successText: onSuccessText, failText: onFailText, }; } async startAsyncSpinnerWithPromise() { return this.#asyncSpinnerProcess(); } } export function addSpacesToString(text: string, numberOfSpaces: number): string { const SPACE_CHAR = ' '; const spaces = SPACE_CHAR.repeat(numberOfSpaces); const spacesWithText = spaces.concat(text); return spacesWithText; } export function isSemverString(possibleSemVerString: string): boolean { // Gotten From https://github.com/sindresorhus/semver-regex/blob/main/index.js const SEMVER_REGEX = /(?:(?<=^v?|\sv?)(?:(?:0|[1-9]\d{0,9})\.){2}(?:0|[1-9]\d{0,9})(?:-(?:0|[1-9]\d*?|[\da-z-]*?[a-z-][\da-z-]*?){0,100}(?:\.(?:0|[1-9]\d*?|[\da-z-]*?[a-z-][\da-z-]*?))*?){0,100}(?:\+[\da-z-]+?(?:\.[\da-z-]+?)*?){0,100}\b){1,200}|latest/; return SEMVER_REGEX.test(possibleSemVerString); } // NOTE: Copy on write ops export function objSet< Obj extends AnyObject, Prop extends string | number, NewValue extends Obj[Prop] >(obj: Obj, property: Prop, value: NewValue) { return { ...obj, ...{ [property]: value }, } as { [Key in keyof Obj | Prop]: Key extends Prop ? NewValue : Obj[Key] }; }
1.640625
2
src/context/AuthContext.tsx
LuisManuelGlz/social-kitchen
0
1040
import React, { createContext, Dispatch, ReactNode, SetStateAction, useState, } from 'react'; import firebase from 'firebase'; import { auth, firestore } from '../firebase/config'; type AuthContextType = { user: firebase.User | null; setUser: Dispatch<SetStateAction<firebase.User | null>>; googleSignIn: () => void; signOut: () => void; }; interface Props { children: ReactNode; } export const AuthContext = createContext({} as AuthContextType); const AuthProvider = ({ children }: Props) => { const [user, setUser] = useState<firebase.User | null>(null); const googleSignIn = async () => { try { const provider = new firebase.auth.GoogleAuthProvider(); const { user } = await auth.signInWithPopup(provider); const doc = await firestore.collection('users').doc(user?.uid).get(); if (!doc.exists) { const { uid: id, displayName, photoURL } = user!; await firestore .collection('users') .doc(user?.uid) .set({ id, displayName, photoURL }); } } catch (error) { console.log(error); } }; const signOut = async () => { try { await auth.signOut(); } catch (error) { console.log(error); } }; return ( <AuthContext.Provider value={{ user, setUser, googleSignIn, signOut, }} > {children} </AuthContext.Provider> ); }; export default AuthProvider;
1.554688
2
src/util/directive-name.ts
PierreFritsch/fundamental-vue
0
1048
export const directiveName = (plain: string) => plain;
0.15918
0
src/decorator/current-user.decorator.ts
rohitsingh-fp/nestjs-graphql-mongoose
0
1056
import { createParamDecorator, ExecutionContext } from '@nestjs/common'; import { GqlExecutionContext } from '@nestjs/graphql'; import * as jwt from "jsonwebtoken" export const CurrentUser = createParamDecorator( async (data: Object, context: ExecutionContext) => { let accessTokenSecret = process.env.JWT_ACCESS_TOKEN_SECRET; let ctx, token; if(context.getType() === 'http'){ let auth = context.switchToHttp().getRequest().headers.authorization if(!auth) { return { status: 401, message : "User is not authorized" } } token = auth.split(" ")[1]; await jwt.verify(token, accessTokenSecret, (err, decoded) => { if(err) return new Error("User not authorized") data = decoded }) return data; }else{ ctx = GqlExecutionContext.create(context); token = ctx.getContext().req.headers.authorization.split(" ")[1] await jwt.verify(token, accessTokenSecret, (err, decoded) => { if(err) throw new Error("User not authorized") data = decoded }) return data; } }, );
1.351563
1
src/ui_ng/lib/src/index.ts
sufuf3/k8s-harbor
1
1064
export * from './harbor-library.module'; export * from './service.config'; export * from './service/index'; export * from './error-handler/index'; //export * from './utils'; export * from './log/index'; export * from './filter/index'; export * from './endpoint/index'; export * from './repository/index'; export * from './create-edit-endpoint/index'; export * from './repository-stackview/index'; export * from './tag/index'; export * from './list-replication-rule/index'; export * from './replication/index'; export * from './vulnerability-scanning/index'; export * from './i18n/index'; export * from './push-image/index'; export * from './third-party/index'; export * from './config/index'; export * from './job-log-viewer/index'; export * from './channel/index'; export * from './project-policy-config/index';
0.291016
0
projects/layout/src/modules/page/page.component.ts
Blackbaud-SpencerMurphy/skyux-layout
0
1072
import { Component, OnDestroy, OnInit } from '@angular/core'; import { SkyPageThemeAdapterService } from './page-theme-adapter.service'; /** * Resets the SPA's background to white and adds the `sky-theme-default` CSS class to the host * element to let consumers override CSS styling. Consumers can override any element by writing * CSS selectors like this: `:host-context(.sky-theme-default) .my-class {}`. */ @Component({ selector: 'sky-page', templateUrl: './page.component.html', providers: [SkyPageThemeAdapterService] }) export class SkyPageComponent implements OnInit, OnDestroy { constructor(private themeAdapter: SkyPageThemeAdapterService) { } public ngOnInit(): void { this.themeAdapter.addTheme(); } public ngOnDestroy(): void { this.themeAdapter.removeTheme(); } }
1.164063
1
site/src/pages/index.tsx
iiroj/iiro.fi
8
1080
import Head from 'next/head' import type { VFC } from 'react' import React, { memo } from 'react' import LinkButton from '../components/LinkButton' import Main from '../components/Main' import Text from '../components/Text' import Ul from '../components/Ul' import microdata from '../constants/microdata.json' const Root: VFC = () => ( <Main> <Head> <title><NAME></title> <meta content="Senior Web Engineer at SOK" name="description" /> <script type="application/ld+json">{JSON.stringify(microdata)}</script> </Head> <Text.H1><NAME></Text.H1> <Text.H2>Senior Web Engineer at SOK</Text.H2> <Text.P>I build web experiences, develop tooling, and maintain open-source libraries.</Text.P> <footer> <nav> <Ul> <li> <LinkButton href="https://github.com/iiroj" rel="author"> GitHub </LinkButton> </li> <li> <LinkButton href="https://linkedin.com/in/iiroj" rel="author"> LinkedIn </LinkButton> </li> </Ul> </nav> </footer> </Main> ) Root.displayName = 'Root' export default memo(Root)
1.125
1
src/reducers/__tests__/stats-test.ts
tdilauro/circulation-web
0
1088
import { expect } from "chai"; import reducer, { StatsState } from "../stats"; import { StatsData } from "../../interfaces"; import ActionCreator from "../../actions"; describe("stats reducer", () => { const statsData: StatsData = { NYPL: { patrons: { total: 3456, with_active_loans: 55, with_active_loans_or_holds: 1234, loans: 100, holds: 2000, }, inventory: { titles: 54321, licenses: 123456, available_licenses: 100000, }, collections: { Overdrive: { licensed_titles: 500, open_access_titles: 10, licenses: 350, available_licenses: 100, }, Bibliotheca: { licensed_titles: 400, open_access_titles: 0, licenses: 300, available_licenses: 170, }, "Axis 360": { licensed_titles: 300, open_access_titles: 0, licenses: 280, available_licenses: 260, }, "Open Bookshelf": { licensed_titles: 0, open_access_titles: 1200, licenses: 0, available_licenses: 0, }, }, }, }; const initState: StatsState = { data: null, isFetching: false, fetchError: null, isLoaded: false, }; const errorState: StatsState = { data: null, isFetching: false, fetchError: { status: 401, response: "test error", url: "test url" }, isLoaded: true, }; it("returns initial state for unrecognized action", () => { expect(reducer(undefined, {})).to.deep.equal(initState); }); it("handles STATS_REQUEST", () => { const action = { type: ActionCreator.STATS_REQUEST, url: "test url" }; // start with empty state let newState = Object.assign({}, initState, { isFetching: true, }); expect(reducer(initState, action)).to.deep.equal(newState); // start with error state newState = Object.assign({}, errorState, { isFetching: true, fetchError: null, }); expect(reducer(errorState, action)).to.deep.equal(newState); }); it("handles STATS_FAILURE", () => { const action = { type: ActionCreator.STATS_FAILURE, error: "test error" }; const oldState = Object.assign({}, initState, { isFetching: true }); const newState = Object.assign({}, oldState, { fetchError: "test error", isFetching: false, isLoaded: true, }); expect(reducer(oldState, action)).to.deep.equal(newState); }); it("handles STATS_LOAD", () => { const action = { type: ActionCreator.STATS_LOAD, data: statsData }; const newState = Object.assign({}, initState, { data: statsData, isFetching: false, isLoaded: true, }); expect(reducer(initState, action)).to.deep.equal(newState); }); });
1.609375
2
clients/node/client-fms-node/commands/GetProtectionStatusCommand.ts
pravgupt/aws-sdk-js-v3
0
1096
import * as __aws_sdk_middleware_stack from "@aws-sdk/middleware-stack"; import * as __aws_sdk_types from "@aws-sdk/types"; import * as _stream from "stream"; import { GetProtectionStatus } from "../model/operations/GetProtectionStatus"; import { InputTypesUnion } from "../types/InputTypesUnion"; import { OutputTypesUnion } from "../types/OutputTypesUnion"; import { GetProtectionStatusInput } from "../types/GetProtectionStatusInput"; import { GetProtectionStatusOutput } from "../types/GetProtectionStatusOutput"; import { FMSResolvedConfiguration } from "../FMSConfiguration"; export * from "../types/GetProtectionStatusInput"; export * from "../types/GetProtectionStatusOutput"; export * from "../types/GetProtectionStatusExceptionsUnion"; export class GetProtectionStatusCommand implements __aws_sdk_types.Command< InputTypesUnion, GetProtectionStatusInput, OutputTypesUnion, GetProtectionStatusOutput, FMSResolvedConfiguration, _stream.Readable > { readonly model = GetProtectionStatus; readonly middlewareStack = new __aws_sdk_middleware_stack.MiddlewareStack< GetProtectionStatusInput, GetProtectionStatusOutput, _stream.Readable >(); constructor(readonly input: GetProtectionStatusInput) {} resolveMiddleware( clientStack: __aws_sdk_middleware_stack.MiddlewareStack< InputTypesUnion, OutputTypesUnion, _stream.Readable >, configuration: FMSResolvedConfiguration ): __aws_sdk_types.Handler< GetProtectionStatusInput, GetProtectionStatusOutput > { const { handler } = configuration; const stack = clientStack.concat(this.middlewareStack); const handlerExecutionContext: __aws_sdk_types.HandlerExecutionContext = { logger: {} as any, model: this.model }; return stack.resolve( handler<GetProtectionStatusInput, GetProtectionStatusOutput>( handlerExecutionContext ), handlerExecutionContext ); } }
1.171875
1
src/models/base.d.ts
advanced-rest-client/arc-types
0
1104
/** * @deprecated This module has been moved to `@advanced-rest-client/events` */ export declare interface Entity { /** * Pouch DB datastore `_id` */ _id?: string; /** * Pouch DB datastore `_rev` as a revision of the object */ _rev?: string; /** * Special flag used by PouchDB to delete an object. */ _deleted?: boolean; } /** * @deprecated This module has been moved to `@advanced-rest-client/events` */ export declare interface DeletedEntity { /** * Pouch DB datastore `_id` */ id: string; /** * Pouch DB datastore revision of the deleted object */ rev: string; } /** * An entity change record base definition * @deprecated This module has been moved to `@advanced-rest-client/events` */ export declare interface ARCEntityChangeRecord<T> { /** * The ID of the changed entity */ id: string; /** * The revision of the updated entity. * It is not set when old revision is unavailable (new entity is created). */ oldRev?: string; /** * New revision id of updated entity */ rev: string; /** * The updated entity. */ item?: T; } /** * Event detail object for data store query result object. * @deprecated This module has been moved to `@advanced-rest-client/events` */ export declare interface ARCModelListResultDetail<T> { result: Promise<ARCModelListResult<T>>; } /** * Base query options for the data store. * @deprecated This module has been moved to `@advanced-rest-client/events` */ export declare interface ARCModelListOptions { /** * The number of results per the page. */ limit?: number; /** * A string that should be used with pagination. */ nextPageToken?: string; } /** * Data store query result object. * @deprecated This module has been moved to `@advanced-rest-client/events` */ export declare interface ARCModelListResult<T> { /** * Next page token to be used with pagination. * It is not set when the query has not returned any results. */ nextPageToken?: string; /** * The list of items in the response. * May be empty array when there was no more results. */ items: T[]; }
1.171875
1
example/src/MultipleStores.tsx
simonghales/leva
0
1112
import React, { useEffect } from 'react' import { folder, Leva, useControls, LevaPanel, usePanel, button } from 'leva' import { useDrag, addV } from 'react-use-gesture' function Box({ index, selected, setSelect }) { const [{ position, size, fill, color, width }, store, set] = usePanel({ position: { value: [window.innerWidth / 2 - 150, window.innerHeight / 2], step: 1 }, size: { value: { width: 100, height: 100 }, min: 10 }, fill: '#cfcfcf', stroke: folder({ color: '#555555', width: { value: 1, min: 0, max: 10 } }), }) const bind = useDrag( ({ first, movement: [x, y], args: [control, mod], memo = { p: position, s: Object.values(size) } }) => { if (first) setSelect([index, store]) let v switch (control) { case 'position': v = { position: addV(memo.p, [x, y]) } break case 'width': v = { size: [memo.s[0] + x * mod, memo.s[1]] } if (mod === -1) v.position = [memo.p[0] + x, memo.p[1]] break case 'height': v = { size: [memo.s[0], memo.s[1] + y * mod] } if (mod === -1) v.position = [memo.p[0], memo.p[1] + y] break } set(v) return memo } ) useEffect(() => { setSelect([index, store]) }, []) return ( <div tabIndex={index} className={`box ${selected ? 'selected' : ''}`} style={{ background: fill, width: size.width, height: size.height, border: `${width}px solid ${color}`, transform: `translate(${position[0]}px, ${position[1]}px)`, }}> <span className="handle top" {...bind('height', -1)} /> <span className="handle right" {...bind('width', 1)} /> <span className="handle bottom" {...bind('height', 1)} /> <span className="handle left" {...bind('width', -1)} /> <span className="handle position" {...bind('position')} /> </div> ) } export default function App() { const [boxes, setBoxes] = React.useState<number[]>([]) const [[selection, store], setSelection] = React.useState([-1, null]) React.useEffect(() => { function deleteSelection(e) { if (e.key === 'Backspace' && selection > -1) { setBoxes((b) => { const _b = [...b] _b.splice(selection, 1) return _b }) setSelection([-1, null]) } } window.addEventListener('keydown', deleteSelection) return () => window.removeEventListener('keydown', deleteSelection) }, [selection]) const unSelect = (e) => { if (e.target === e.currentTarget) { setSelection([-1, null]) } } const addBox = () => { setBoxes((b) => [...b, Date.now()]) } useControls({ 'New Box': button(addBox) }) return ( <div className="wrapper"> <div className="canvas" onClick={unSelect}> {boxes.map((v, i) => ( <Box key={v} selected={selection === i} index={i} setSelect={setSelection} /> ))} </div> <div className="panel"> <Leva detached={false} hideTitleBar /> <LevaPanel store={store} /> </div> </div> ) }
1.625
2
src/features/category/index.ts
martin-nderitu/react-redux-inventory-manager
3
1120
export {CategoriesList} from "./CategoriesList"; export {AddCategoryForm} from "./AddCategoryForm"; export {EditCategoryForm} from "./EditCategoryForm";
0.04541
0
typings.d.ts
emino07/sharder
0
1128
declare module 'discord-hybrid-sharding' { import { EventEmitter } from 'events'; import { ChildProcess } from 'child_process'; export class Cluster extends EventEmitter { constructor(manager: Manager, id: number); private _evals: Map<string, Promise<any>>; private _exitListener: (...args: any[]) => void; private _fetches: Map<string, Promise<any>>; private _handleExit(respawn?: boolean): void; private _handleMessage(message: any): void; public args: string[]; public execArgv: string[]; public env: object; public id: number; public manager: Manager; public process: ChildProcess | null; public ready: boolean; public worker: any | null; public eval(script: string): Promise<any>; public eval<T>(fn: (client: client) => T): Promise<T[]>; public fetchClientValue(prop: string): Promise<any>; public kill(): void; public respawn(delay?: number, spawnTimeout?: number): Promise<ChildProcess>; public send(message: any): Promise<Cluster>; public spawn(spawnTimeout?: number): Promise<ChildProcess>; public on(event: 'spawn' | 'death', listener: (child: ChildProcess) => void): this; public on(event: 'disconnect' | 'ready' | 'reconnecting', listener: () => void): this; public on(event: 'error', listener: (error: Error) => void): this; public on(event: 'message', listener: (message: any) => void): this; public on(event: string, listener: (...args: any[]) => void): this; public once(event: 'spawn' | 'death', listener: (child: ChildProcess) => void): this; public once(event: 'disconnect' | 'ready' | 'reconnecting', listener: () => void): this; public once(event: 'error', listener: (error: Error) => void): this; public once(event: 'message', listener: (message: any) => void): this; public once(event: string, listener: (...args: any[]) => void): this; } export class Client { constructor(client: client, mode: ClusterManagerMode); private _handleMessage(message: any): void; private _respond(type: string, message: any): void; public client: client; public readonly count: number; public readonly ids: number[]; public mode: ClusterManagerMode; public parentPort: any | null; public broadcastEval(script: string): Promise<any[]>; public broadcastEval(script: string, cluster: number): Promise<any>; public broadcastEval<T>(fn: (client: client) => T): Promise<T[]>; public broadcastEval<T>(fn: (client: client) => T, cluster: number): Promise<T>; public fetchClientValues(prop: string): Promise<any[]>; public fetchClientValues(prop: string, cluster: number): Promise<any>; public respawnAll(clusterDelay?: number, respawnDelay?: number, spawnTimeout?: number): Promise<void>; public send(message: any): Promise<void>; public static singleton(client: client, mode: ClusterManagerMode): client; } export class Manager extends EventEmitter { constructor( file: string, options?: { totalShards?: number | 'auto'; totalClusters?: number | 'auto'; shardList?: number[] | 'auto'; mode?: ClusterManagerMode; respawn?: boolean; shardArgs?: string[]; token?: string; execArgv?: string[]; }, ); private _performOnShards(method: string, args: any[]): Promise<any[]>; private _performOnShards(method: string, args: any[], cluster: number): Promise<any>; public file: string; public respawn: boolean; public shardArgs: string[]; public clusters: Map<number, Cluster>; public token: string | null; public totalClusters: number | 'auto'; public totalShards: number | 'auto'; public shardList: number[] | 'auto'; public broadcast(message: any): Promise<Cluster[]>; public broadcastEval(script: string): Promise<any[]>; public broadcastEval(script: string, cluster: number): Promise<any>; public createCluster(id: number, clusterstospawn: number[], totalshards: number): Cluster; public fetchClientValues(prop: string): Promise<any[]>; public fetchClientValues(prop: string, cluster: number): Promise<any>; public respawnAll( clusterDelay?: number, respawnDelay?: number, spawnTimeout?: number, ): Promise<Map<number, Cluster>>; public spawn(amount?: number | 'auto', delay?: number, spawnTimeout?: number): Promise<Map<number, Cluster>>; public on(event: 'clusterCreate', listener: (cluster: Cluster) => void): this; public once(event: 'clusterCreate', listener: (cluster: Cluster) => void): this; } type ClusterManagerMode = 'process' | 'worker'; type client = 'client'; }
1.296875
1
server/src/app/controllers/index.ts
cnwhy/ghChat
1
1136
/* * Generated by cli, don't modify manually */ export * from './githubOAuth.controller'; export * from './login.controller'; export * from './register.controller';
-0.092285
0
src/scrapper/flip.ts
lbenie/flip-scrapper
0
1144
import axios from 'axios' import { ResultSet } from '../models/resultSet' import { FlipResponse } from '../models/flip' import { from, EMPTY, timer } from 'rxjs' import { mergeMap, scan, tap, catchError } from 'rxjs/operators' import { stores } from './search.json' import { getConnection } from '../data/database' import { config } from 'dotenv' import { MongoClient } from 'mongodb' config() class FlipScrapper { private client?: MongoClient private async getItems( query: string, postalCode = 'G1G2A1', locale = 'fr-ca', ) { const { data } = await axios.get<FlipResponse>( `https://backflipp.wishabi.com/flipp/items/search`, { params: { locale, // eslint-disable-next-line @typescript-eslint/camelcase postal_code: postalCode, q: query, }, }, ) return data } run(postalCode = 'G1G2A1', locale = 'fr-ca') { const oneWeek = 1000 * 60 * 60 * 24 * 7 return timer(0, oneWeek).pipe( mergeMap(() => from(stores)), mergeMap( async query => ({ query, ...(await this.getItems(query, postalCode, locale)), } as ResultSet), ), scan((acc, value) => [...acc, { ...value }], [] as ResultSet[]), tap(async results => { this.client = await getConnection() const db = this.client?.db(process.env.MONGO_DATABASE) const itemCollection = db.collection( process.env.MONGO_DATABASE_COLLECTION_ITEMS, ) results.forEach(async ({ items, query }) => { await itemCollection.insertMany( items.map(item => ({ ...item, query })), ) }) }), catchError(err => { console.error(err) return EMPTY }), ) } async close() { await this.client?.close() } } export default new FlipScrapper()
1.703125
2
src/people-body/hands/Hands19.tsx
react-pakistan/react-emoji-collection
1
1152
import * as React from "react"; import { IEmojiProps } from "../../styled"; const SvgHands19 = (props: IEmojiProps) => ( <svg viewBox="0 0 72 72" width="1em" height="1em" {...props}> <path transform="matrix(1.187 0 0 1.188 -8.324 -10.3)" fill="#fcea2b" stroke="#fcea2b" strokeLinecap="round" strokeWidth={1.532} d="M33.59 59.58c1.617 1.699 4.094-3.063 4.809-4.103 2.298 1.695 8.481 3.023 7.537-1.592 1.225.448 5.037.661 3.849-3.45 3.047 1.486 5.646-.84 5.245-3.457 2.698.488 4.347-1.715 3.588-4.344 4.063-5.1 3.828-11.69 3.595-14.66-.778-9.896-14.08-6.154-20.2-10.02l-12.99.052c-2.202 3.942-3.569 1.824-7.728 2.337-6.072.889-11.08 16.24-9.519 16.94l7.732 8.23c.14 1.526-3.91 4.042-.357 5.882 6.126 2.159 10.32 5.064 14.45 8.183z" /> <g fill="none" stroke="#000" strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} > <path d="M15.05 43.95s-7.133-5.822-8.537-8.259c-4.392-7.595.949-19.79 10.44-21.82M38.71 42.99l12.89 7.021M33.87 47.79l13 6.498M58.18 45.72l-5.1-4.358-8.279-4.335" /> <path d="M37.49 56.29c8.574 5.466 10.79-.295 9.387-1.994 2.734 1.625 6.209-.517 4.731-4.283 3.844 1.847 7.022-1.034 6.579-4.283 3.326.591 5.395-2.142 4.435-5.392 6.721-4.585 5.041-19.03-.099-25.36-9.287-1.459-11-2.362-20.98-3.943l-13.53-.619a3.993 3.993 0 00-4.779 2.533c-.752 2.816-1.677 4.971-3.599 8.378a3.539 3.539 0 001.872 4.588c1.908.477 2.78-.386 4.46-1.686 2.195-2.102 2.628-2.996 3.805-4.575l13.64 6.204 12.72 7.164c2.514 1.698 5.012 5.844 6.51 7.321" /> <path d="M31.51 54.15c1.109-1.477 2.666-1.713 4.144-.9 1.405.812 2.439 2.362 1.478 4.063l-1.774 3.1c-1.109 1.478-3.178 1.699-4.582.665-1.234-.924-1.592-2.518-1.076-3.836l1.81-3.094zM25.84 50.98c1.109-1.477 2.666-1.713 4.144-.9 1.405.812 2.439 2.362 1.478 4.063l-1.774 3.1c-1.109 1.478-3.178 1.699-4.582.665-1.234-.924-1.592-2.518-1.076-3.836l1.81-3.094z" /> <path d="M20.18 47.82c1.109-1.477 2.666-1.713 4.144-.9 1.405.812 2.439 2.362 1.478 4.063l-1.774 3.1c-1.109 1.478-3.178 1.699-4.582.665-1.234-.924-1.592-2.518-1.076-3.836l1.81-3.094z" /> <path d="M14.53 44.65c1.109-1.477 2.666-1.713 4.144-.9 1.405.812 2.439 2.362 1.478 4.063l-1.774 3.1c-1.109 1.478-3.178 1.699-4.582.665-1.234-.924-1.592-2.518-1.076-3.836l1.81-3.094z" /> </g> </svg> ); export default SvgHands19;
1.132813
1
src/Cookie.ts
dbpkgs/cookie
7
1160
interface Options { expires?: Date; path?: string; domain?: string; secure?: boolean; } export const encode = global?.window?.encodeURIComponent; export const decode = global?.window?.decodeURIComponent; export default class Cookie { private doc: Partial<Document> | undefined | string; constructor(domDocument?: Partial<Document & { cookie: string }> | string) { this.doc = domDocument; if (typeof domDocument === 'object') { this.doc = domDocument; } if (!this.doc) this.doc = {}; if (typeof this.doc !== 'object') this.doc = { cookie: '' }; if (typeof this.doc.cookie !== 'string') this.doc.cookie = ''; } /** * This method will get your cookies from the browser with the specified key * * @param {string} key - The cookie string used to uniquely identify the cookie in the browser * * @returns {string | null} - The return value of the found cookie with the specified key provided * * @example * cookie.get("session_value") * */ get = (key: string): string | null => { if (typeof this.doc === 'object' && this.doc.cookie) { const splittedCookie = this.doc.cookie.split(/;\cookieString*/); for (let cookieIndex = 0; cookieIndex < splittedCookie.length; cookieIndex++) { const cookieKeyValues = splittedCookie[0]?.split(';').map((a) => a.trim()); if (!cookieKeyValues) return null; for (let keyIndex = 0; keyIndex <= cookieKeyValues.length; keyIndex++) { const cookieKeyValue = cookieKeyValues[keyIndex]?.split('='); const cookieKey = decode(cookieKeyValue?.[0] ?? ''); if (cookieKey === key) return decode(cookieKeyValue?.[1] ?? ''); } } return null; } return null; }; /** * This method will set your cookies to the browser the specified key and value provided. * If options are provided the value option values will also be set in the cookie storage in the browser * * @param {string} key - The cookie string used to uniquely identify the cookie in the browser * * @param {string} value - The value of the cookie you need to set * * @param {Options} options - The optional parameters to pass when setting the cookie * * @returns {string | undefined} - The return value of the set cookie * * @example * cookie.set('session_value', 'Uxc70_67gGuHHvAmTy10a', { * expires: new Date(2022, 03, 13), * path: '', * secure: true * }) * */ set = (key: string, value: string, options?: Options): string | undefined => { let opts: Options | undefined = options; if (!opts) opts = {}; let cookieString = encode(key) + '=' + encode(value); if (opts.expires) cookieString += '; expires=' + opts.expires; if (opts.path) cookieString += '; path=' + encode(opts.path); if (opts.domain) cookieString += '; domain=' + encode(opts.domain); if (opts.secure) cookieString += '; secure'; if (typeof this.doc === 'object') { this.doc.cookie = cookieString; } return cookieString; }; /** * This method will remove your cookie from the browser with the specified key * * @param {string} key - The cookie string used to uniquely identify the cookie in the browser * * @example * cookie.remove("session_value") */ remove = (key: string): void => { let cookieString = encode(key) + '='; cookieString += '; expires=' + new Date(0); if (typeof this.doc === 'object') { this.doc.cookie = cookieString; } }; } // const cookie = new Cookie(global?.window?.document); // export const Cookies = Cookie; // export default cookie;
2.046875
2
src/app/i18n/languagePacks/de.ts
DorianGrey/react-ts-playground
1
1168
import deLocale from "date-fns/locale/de"; import translationsDe from "../../../generated/translations-de"; import type { LanguagePack } from "./languagePack"; const deLanguagePack: LanguagePack = { translations: translationsDe, locale: "de", dateLocale: deLocale, }; export default deLanguagePack;
0.447266
0
src/constants/colors.ts
iwanwang-0/sushiswap-lite
1
1176
export const Colors = { common: { white: "#ffffff", transparent: "#ffffff00", primary: "#FA52A0", secondary: "#27B0E6", green: "#32CD32", red: "#FF0000", twitter: "#1da1f2", facebook: "#3B5998" }, light: { accent: "#FA52A0", header: "#ffffff", submenu: "#ffffff80", background: "#ffffff", backgroundLight: "#f0f0f0", border: "#e5e5e5", borderDark: "#cccccc", textDark: "#1d1d1f", textMedium: "#222222", textLight: "#000000", disabled: "#b4b4b4", shadow: "#444444", placeholder: "#666666", overlay: "#ffffffc0" }, dark: { accent: "#27B0E6", header: "#0D0E20", submenu: "#00000020", background: "#101216", backgroundLight: "#0D0E20", border: "#ffffff33", borderDark: "#666666", textDark: "#d5d1cc", textMedium: "#cccccc", textLight: "#FFFFFF", disabled: "#aaaaaa80", shadow: "#03080c", placeholder: "#666666", overlay: "#000000c0" } };
0.765625
1
text-adventure-sama/src/models/other/text-input-type.enum.ts
musti645/text-adventure-sama
0
1184
export enum TextInputType { UserInput = 'input', Output = 'output' }
0.279297
0
lib/suku-buttons/suku-secondary-button/suku-secondary-button.component.d.ts
SukuLab/suku-web-components-library
0
1192
import { OnInit, EventEmitter } from '@angular/core'; export declare class SukuSecondaryButtonComponent implements OnInit { id: any; size: number; weight: any; color: any; customClass: any; action: EventEmitter<{}>; constructor(); ngOnInit(): void; }
0.9375
1
src/vs/workbench/parts/debug/electron-browser/debugHover.ts
SirHoneyBiscuit/vscode
1
1200
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as nls from 'vs/nls'; import * as lifecycle from 'vs/base/common/lifecycle'; import { TPromise } from 'vs/base/common/winjs.base'; import { KeyCode } from 'vs/base/common/keyCodes'; import { ScrollbarVisibility } from 'vs/base/common/scrollable'; import * as dom from 'vs/base/browser/dom'; import { ITree } from 'vs/base/parts/tree/browser/tree'; import { IKeyboardEvent } from 'vs/base/browser/keyboardEvent'; import { ICancelableEvent, OpenMode } from 'vs/base/parts/tree/browser/treeDefaults'; import { IConfigurationChangedEvent } from 'vs/editor/common/config/editorOptions'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { IContentWidget, ICodeEditor, IContentWidgetPosition, ContentWidgetPositionPreference } from 'vs/editor/browser/editorBrowser'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IDebugService, IExpression, IExpressionContainer } from 'vs/workbench/parts/debug/common/debug'; import { Expression } from 'vs/workbench/parts/debug/common/debugModel'; import { renderExpressionValue } from 'vs/workbench/parts/debug/browser/baseDebugView'; import { VariablesDataSource, VariablesRenderer } from 'vs/workbench/parts/debug/electron-browser/variablesView'; import { DomScrollableElement } from 'vs/base/browser/ui/scrollbar/scrollableElement'; import { attachStylerCallback } from 'vs/platform/theme/common/styler'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { editorHoverBackground, editorHoverBorder } from 'vs/platform/theme/common/colorRegistry'; import { WorkbenchTree, WorkbenchTreeController } from 'vs/platform/list/browser/listService'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; const $ = dom.$; const MAX_ELEMENTS_SHOWN = 18; export class DebugHoverWidget implements IContentWidget { public static readonly ID = 'debug.hoverWidget'; // editor.IContentWidget.allowEditorOverflow public allowEditorOverflow = true; private _isVisible: boolean; private domNode: HTMLElement; private tree: WorkbenchTree; private showAtPosition: Position; private highlightDecorations: string[]; private complexValueContainer: HTMLElement; private treeContainer: HTMLElement; private complexValueTitle: HTMLElement; private valueContainer: HTMLElement; private stoleFocus: boolean; private toDispose: lifecycle.IDisposable[]; private scrollbar: DomScrollableElement; constructor( private editor: ICodeEditor, private debugService: IDebugService, private instantiationService: IInstantiationService, private themeService: IThemeService ) { this.toDispose = []; this._isVisible = false; this.showAtPosition = null; this.highlightDecorations = []; } private create(): void { this.domNode = $('.debug-hover-widget'); this.complexValueContainer = dom.append(this.domNode, $('.complex-value')); this.complexValueTitle = dom.append(this.complexValueContainer, $('.title')); this.treeContainer = dom.append(this.complexValueContainer, $('.debug-hover-tree')); this.treeContainer.setAttribute('role', 'tree'); this.tree = this.instantiationService.createInstance(WorkbenchTree, this.treeContainer, { dataSource: new VariablesDataSource(), renderer: this.instantiationService.createInstance(VariablesHoverRenderer), controller: this.instantiationService.createInstance(DebugHoverController, this.editor) }, { indentPixels: 6, twistiePixels: 15, ariaLabel: nls.localize('treeAriaLabel', "Debug Hover") }); this.valueContainer = $('.value'); this.valueContainer.tabIndex = 0; this.valueContainer.setAttribute('role', 'tooltip'); this.scrollbar = new DomScrollableElement(this.valueContainer, { horizontal: ScrollbarVisibility.Hidden }); this.domNode.appendChild(this.scrollbar.getDomNode()); this.toDispose.push(this.scrollbar); this.editor.applyFontInfo(this.domNode); this.toDispose.push(attachStylerCallback(this.themeService, { editorHoverBackground, editorHoverBorder }, colors => { this.domNode.style.backgroundColor = colors.editorHoverBackground; if (colors.editorHoverBorder) { this.domNode.style.border = `1px solid ${colors.editorHoverBorder}`; } else { this.domNode.style.border = null; } })); this.registerListeners(); this.editor.addContentWidget(this); } private registerListeners(): void { this.toDispose.push(this.tree.onDidExpandItem(() => { this.layoutTree(); })); this.toDispose.push(this.tree.onDidCollapseItem(() => { this.layoutTree(); })); this.toDispose.push(dom.addStandardDisposableListener(this.domNode, 'keydown', (e: IKeyboardEvent) => { if (e.equals(KeyCode.Escape)) { this.hide(); } })); this.toDispose.push(this.editor.onDidChangeConfiguration((e: IConfigurationChangedEvent) => { if (e.fontInfo) { this.editor.applyFontInfo(this.domNode); } })); } public isVisible(): boolean { return this._isVisible; } public getId(): string { return DebugHoverWidget.ID; } public getDomNode(): HTMLElement { return this.domNode; } private getExactExpressionRange(lineContent: string, range: Range): Range { let matchingExpression: string = undefined; let startOffset = 0; // Some example supported expressions: myVar.prop, a.b.c.d, myVar?.prop, myVar->prop, MyClass::StaticProp, *myVar // Match any character except a set of characters which often break interesting sub-expressions let expression: RegExp = /([^()\[\]{}<>\s+\-/%~#^;=|,`!]|\->)+/g; let result: RegExpExecArray = undefined; // First find the full expression under the cursor while (result = expression.exec(lineContent)) { let start = result.index + 1; let end = start + result[0].length; if (start <= range.startColumn && end >= range.endColumn) { matchingExpression = result[0]; startOffset = start; break; } } // If there are non-word characters after the cursor, we want to truncate the expression then. // For example in expression 'a.b.c.d', if the focus was under 'b', 'a.b' would be evaluated. if (matchingExpression) { let subExpression: RegExp = /\w+/g; let subExpressionResult: RegExpExecArray = undefined; while (subExpressionResult = subExpression.exec(matchingExpression)) { let subEnd = subExpressionResult.index + 1 + startOffset + subExpressionResult[0].length; if (subEnd >= range.endColumn) { break; } } if (subExpressionResult) { matchingExpression = matchingExpression.substring(0, subExpression.lastIndex); } } return matchingExpression ? new Range(range.startLineNumber, startOffset, range.endLineNumber, startOffset + matchingExpression.length - 1) : new Range(range.startLineNumber, 0, range.endLineNumber, 0); } public showAt(range: Range, focus: boolean): TPromise<void> { const pos = range.getStartPosition(); const process = this.debugService.getViewModel().focusedProcess; const lineContent = this.editor.getModel().getLineContent(pos.lineNumber); const expressionRange = this.getExactExpressionRange(lineContent, range); // use regex to extract the sub-expression #9821 const matchingExpression = lineContent.substring(expressionRange.startColumn - 1, expressionRange.endColumn); if (!matchingExpression) { return TPromise.as(this.hide()); } let promise: TPromise<IExpression>; if (process.session.capabilities.supportsEvaluateForHovers) { const result = new Expression(matchingExpression); promise = result.evaluate(process, this.debugService.getViewModel().focusedStackFrame, 'hover').then(() => result); } else { promise = this.findExpressionInStackFrame(matchingExpression.split('.').map(word => word.trim()).filter(word => !!word), expressionRange); } return promise.then(expression => { if (!expression || (expression instanceof Expression && !expression.available)) { this.hide(); return undefined; } this.highlightDecorations = this.editor.deltaDecorations(this.highlightDecorations, [{ range: new Range(pos.lineNumber, expressionRange.startColumn, pos.lineNumber, expressionRange.startColumn + matchingExpression.length), options: { className: 'hoverHighlight' } }]); return this.doShow(pos, expression, focus); }); } private doFindExpression(container: IExpressionContainer, namesToFind: string[]): TPromise<IExpression> { if (!container) { return TPromise.as(null); } return container.getChildren().then(children => { // look for our variable in the list. First find the parents of the hovered variable if there are any. const filtered = children.filter(v => namesToFind[0] === v.name); if (filtered.length !== 1) { return null; } if (namesToFind.length === 1) { return filtered[0]; } else { return this.doFindExpression(filtered[0], namesToFind.slice(1)); } }); } private findExpressionInStackFrame(namesToFind: string[], expressionRange: Range): TPromise<IExpression> { return this.debugService.getViewModel().focusedStackFrame.getScopes() .then(scopes => scopes.filter(s => !s.expensive)) .then(scopes => TPromise.join(scopes.map(scope => this.doFindExpression(scope, namesToFind)))) .then(expressions => expressions.filter(exp => !!exp)) // only show if all expressions found have the same value .then(expressions => (expressions.length > 0 && expressions.every(e => e.value === expressions[0].value)) ? expressions[0] : null); } private doShow(position: Position, expression: IExpression, focus: boolean, forceValueHover = false): TPromise<void> { if (!this.domNode) { this.create(); } this.showAtPosition = position; this._isVisible = true; this.stoleFocus = focus; if (!expression.hasChildren || forceValueHover) { this.complexValueContainer.hidden = true; this.valueContainer.hidden = false; renderExpressionValue(expression, this.valueContainer, { showChanged: false, preserveWhitespace: true, colorize: true }); this.valueContainer.title = ''; this.editor.layoutContentWidget(this); this.scrollbar.scanDomNode(); if (focus) { this.editor.render(); this.valueContainer.focus(); } return TPromise.as(null); } this.valueContainer.hidden = true; this.complexValueContainer.hidden = false; return this.tree.setInput(expression).then(() => { this.complexValueTitle.textContent = expression.value; this.complexValueTitle.title = expression.value; this.layoutTree(); this.editor.layoutContentWidget(this); this.scrollbar.scanDomNode(); if (focus) { this.editor.render(); this.tree.DOMFocus(); } }); } private layoutTree(): void { const navigator = this.tree.getNavigator(); let visibleElementsCount = 0; while (navigator.next()) { visibleElementsCount++; } if (visibleElementsCount === 0) { this.doShow(this.showAtPosition, this.tree.getInput(), false, true); } else { const height = Math.min(visibleElementsCount, MAX_ELEMENTS_SHOWN) * 18; if (this.treeContainer.clientHeight !== height) { this.treeContainer.style.height = `${height}px`; this.tree.layout(); } } } public hide(): void { if (!this._isVisible) { return; } this._isVisible = false; this.editor.deltaDecorations(this.highlightDecorations, []); this.highlightDecorations = []; this.editor.layoutContentWidget(this); if (this.stoleFocus) { this.editor.focus(); } } public getPosition(): IContentWidgetPosition { return this._isVisible ? { position: this.showAtPosition, preference: [ ContentWidgetPositionPreference.ABOVE, ContentWidgetPositionPreference.BELOW ] } : null; } public dispose(): void { this.toDispose = lifecycle.dispose(this.toDispose); } } class DebugHoverController extends WorkbenchTreeController { constructor( private editor: ICodeEditor, @IConfigurationService configurationService: IConfigurationService ) { super({ openMode: OpenMode.SINGLE_CLICK }, configurationService); } protected onLeftClick(tree: ITree, element: any, eventish: ICancelableEvent, origin = 'mouse'): boolean { if (element.reference > 0) { super.onLeftClick(tree, element, eventish, origin); tree.clearFocus(); tree.deselect(element); this.editor.focus(); } return true; } } class VariablesHoverRenderer extends VariablesRenderer { public getHeight(tree: ITree, element: any): number { return 18; } }
1.0625
1
home/.vscode/extensions/aestheticintegration.iml-vscode-0.5.0/node_modules/imandra-language-server/bin/server/processes/merlin.d.ts
rdesmartin/dotfiles
0
1208
import * as LSP from "vscode-languageserver-protocol"; import { merlin } from "../../../lib"; import Session from "../session"; export default class Merlin implements LSP.Disposable { private readonly session; private readonly queue; private readonly readline; private process; constructor(session: Session); dispose(): void; initialize(): Promise<void>; query<I, O>({ query }: merlin.Query<I, O>, token: LSP.CancellationToken | null, id?: LSP.TextDocumentIdentifier, priority?: number): merlin.Response<O>; restart(): Promise<void>; sync<I, O>({ sync: query }: merlin.Sync<I, O>, id?: LSP.TextDocumentIdentifier): merlin.Response<O>; private establishProtocol; private logMessage; }
1.046875
1
src/serializers/commandmatch.ts
F7ASH/AR-APEX-ZONE
183
1216
import { CommandMatcher, Serializer, SerializerUpdateContext } from '#lib/database'; import { LanguageKeys } from '#lib/i18n/languageKeys'; import type { Awaitable } from '@sapphire/utilities'; export class UserSerializer extends Serializer<string> { public async parse(args: Serializer.Args) { const result = await args.pickResult('commandMatch'); return result.success ? this.ok(result.value) : this.errorFromArgument(args, result.error); } public isValid(value: string, { t, entry }: SerializerUpdateContext): Awaitable<boolean> { const command = CommandMatcher.resolve(value); if (!command) throw t(LanguageKeys.Serializers.InvalidCommand, { name: entry.name }); return true; } public stringify(value: string) { return (this.container.stores.get('commands').get(value) || { name: value }).name; } }
1.429688
1
src/modules/video/video.service.ts
huuthanhla/RankSong
0
1224
import { Injectable } from '@nestjs/common'; import { VideoLoader } from './video.loader'; import { VideoRepository } from './video.repository'; import { VideoHelper} from './video.helper'; @Injectable() export class VideoService { constructor( private videoLoader: VideoLoader, private videoRepository: VideoRepository ) {} async getVideo(id: string) { let video = await this.videoRepository.findVideo(id); video = await this.videoLoader.response(video.url); this.videoRepository.saveVideos(video.videos.map(({title, info}) => ({ name: title, url: info }))); this.videoRepository.saveVideos(video.singers); return { track: video.track, videos: video.videos.map(video => ({ id: video.key, name: video.title, singer: video.singer, avatar: video.image, time: video.time })), singers: VideoHelper.videos(video.singers) }; } }
1.289063
1
core/com/zoho/crm/api/layouts/properties.ts
zoho/zohocrm-typescript-sdk-2.0
0
1232
import {ToolTip} from "../fields/tool_tip"; import {Model} from "../../../../../../utils/util/model"; class Properties implements Model{ private reorderRows: boolean; private tooltip: ToolTip; private maximumRows: number; private keyModified: Map<string, number> = new Map<string, number>(); /** * The method to get the reorderRows * @returns A boolean representing the reorderRows */ public getReorderRows(): boolean { return this.reorderRows; } /** * The method to set the value to reorderRows * @param reorderRows A boolean representing the reorderRows */ public setReorderRows(reorderRows: boolean): void { this.reorderRows = reorderRows; this.keyModified.set("reorder_rows", 1); } /** * The method to get the tooltip * @returns An instance of ToolTip */ public getTooltip(): ToolTip { return this.tooltip; } /** * The method to set the value to tooltip * @param tooltip An instance of ToolTip */ public setTooltip(tooltip: ToolTip): void { this.tooltip = tooltip; this.keyModified.set("tooltip", 1); } /** * The method to get the maximumRows * @returns A number representing the maximumRows */ public getMaximumRows(): number { return this.maximumRows; } /** * The method to set the value to maximumRows * @param maximumRows A number representing the maximumRows */ public setMaximumRows(maximumRows: number): void { this.maximumRows = maximumRows; this.keyModified.set("maximum_rows", 1); } /** * The method to check if the user has modified the given key * @param key A string representing the key * @returns A number representing the modification */ public isKeyModified(key: string): number | null | undefined { if(this.keyModified.has(key)) { return this.keyModified.get(key); } return null; } /** * The method to mark the given key as modified * @param key A string representing the key * @param modification A number representing the modification */ public setKeyModified(key: string, modification: number): void { this.keyModified.set(key, modification); } } export { Properties as MasterModel, Properties as Properties }
1.429688
1
packages/stack/src/navigators/createStackNavigator.tsx
frankyjuang/react-navigation
3
1240
import * as React from 'react'; import { useNavigationBuilder, createNavigatorFactory, DefaultNavigatorOptions, EventArg, StackRouter, StackRouterOptions, StackNavigationState, StackActions, } from '@react-navigation/native'; import StackView from '../views/Stack/StackView'; import { StackNavigationConfig, StackNavigationOptions, StackNavigationEventMap, } from '../types'; type Props = DefaultNavigatorOptions<StackNavigationOptions> & StackRouterOptions & StackNavigationConfig; function StackNavigator({ initialRouteName, children, screenOptions, ...rest }: Props) { const { state, descriptors, navigation } = useNavigationBuilder< StackNavigationState, StackRouterOptions, StackNavigationOptions, StackNavigationEventMap >(StackRouter, { initialRouteName, children, screenOptions, }); React.useEffect( () => navigation.addListener && navigation.addListener('tabPress', (e) => { const isFocused = navigation.isFocused(); // Run the operation in the next frame so we're sure all listeners have been run // This is necessary to know if preventDefault() has been called requestAnimationFrame(() => { if ( state.index > 0 && isFocused && !(e as EventArg<'tabPress', true>).defaultPrevented ) { // When user taps on already focused tab and we're inside the tab, // reset the stack to replicate native behaviour navigation.dispatch({ ...StackActions.popToTop(), target: state.key, }); } }); }), [navigation, state.index, state.key] ); return ( <StackView {...rest} state={state} descriptors={descriptors} navigation={navigation} /> ); } export default createNavigatorFactory< StackNavigationState, StackNavigationOptions, StackNavigationEventMap, typeof StackNavigator >(StackNavigator);
1.484375
1
src/app.ts
nagytech/acid-banger
1
1248
import {Clock, pressToStart} from "./boilerplate"; import {Audio, AudioT, textNoteToNumber} from './audio'; import {NineOhGen, ThreeOhGen} from "./pattern"; import {UI} from "./ui"; import { DrumPattern, genericParameter, NineOhMachine, NoteGenerator, NumericParameter, parameter, Pattern, ProgramState, ThreeOhMachine, trigger, DelayUnit, ClockUnit, AutoPilotUnit } from "./interface"; import { IMidiChannel, IMidiController, IMidiControllerInput, IMidiControllerOutput, MidiAccess } from "./midi" function WanderingParameter(param: NumericParameter, scaleFactor = 1/400) { const [min,max] = param.bounds; let diff = 0.0; let scale = scaleFactor * (max - min); let touchCountdown = 0; let previousValue = (min + max) / 2 ; const step = () => { if (previousValue != param.value) { // Something else has touched this parameter diff = 0; previousValue = param.value; touchCountdown = 200 } else { if (touchCountdown > 0) { touchCountdown--; } if (touchCountdown < 100) { diff *= touchCountdown > 0 ? 0.8 : 0.98; diff += (Math.random() - 0.5) * scale; param.value += diff; previousValue = param.value if (param.value > min + 0.8 * (max - min)) { diff -= Math.random() * scale; } else if (param.value < min + 0.2 * (max - min)) { diff += Math.random() * scale; } } } } return { step } } function ThreeOhUnit(audio: AudioT, waveform: OscillatorType, output: AudioNode, gen: NoteGenerator, midi: IMidiChannel | undefined, patternLength: number=16): ThreeOhMachine { const synth = audio.ThreeOh(waveform, output); const pattern = genericParameter<Pattern>("Pattern", []); const newPattern = trigger("New Pattern Trigger", true); gen.newNotes.subscribe(newNotes => { if (newNotes == true) newPattern.value = true; }) function step(index: number) { if ((index === 0 && newPattern.value == true) || pattern.value.length == 0) { pattern.value = gen.createPattern(); newPattern.value = false; } const slot = pattern.value[index % patternLength]; if (slot.note != "-") { if (midi !== undefined) { midi.noteOn(textNoteToNumber(slot.note), 100); synth.noteOn(slot.note, slot.accent, slot.glide); midi.noteOff(textNoteToNumber(slot.note), 30); } } else { synth.noteOff(); } } const parameters = { cutoff: parameter("Cutoff", [30,700],400), resonance: parameter("Resonance", [1,30],15), envMod: parameter("Env Mod", [0,8000], 4000), decay: parameter("Decay", [0.1,0.9], 0.5) }; parameters.cutoff.subscribe(v => synth.params.cutoff.value = v); parameters.resonance.subscribe(v => synth.params.resonance.value = v); parameters.envMod.subscribe(v => synth.params.envMod.value = v); parameters.decay.subscribe(v => synth.params.decay.value = v); return { step, pattern, parameters, newPattern } } async function NineOhUnit(audio: AudioT, midi: IMidiController | undefined): Promise<NineOhMachine> { const drums = await audio.SamplerDrumMachine(["909BD.mp3","909OH.mp3","909CH.mp3","909SD.mp3"]) const pattern = genericParameter<DrumPattern>("Drum Pattern", []); const mutes = [ genericParameter("Mute BD", false), genericParameter("Mute OH", false), genericParameter("Mute CH", false), genericParameter("Mute SD", false) ]; const newPattern = trigger("New Pattern Trigger", true); const gen = NineOhGen(); function step(index: number) { if ((index == 0 && newPattern.value == true) || pattern.value.length == 0) { pattern.value = gen.createPatterns(true); newPattern.value = false; } // HACK: don't like how I've had to do this, perhaps the subscribe function above // can be refactored to relay midi in parallel? var x = 0; for (let i in pattern.value) { const entry = pattern.value[i][index % pattern.value[i].length]; if (entry && !mutes[i].value) { drums.triggers[i].play(midi, x, entry); } x++; } } return { step, pattern, mutes, newPattern } } function DelayUnit(audio: AudioT): DelayUnit { const dryWet = parameter("Dry/Wet", [0,0.5], 0.5); const feedback = parameter("Feedback", [0,0.9], 0.3); const delayTime = parameter("Time", [0,2], 0.3); const delay = audio.DelayInsert(delayTime.value, dryWet.value, feedback.value); dryWet.subscribe(w => delay.wet.value = w); feedback.subscribe(f => delay.feedback.value = f); delayTime.subscribe(t => delay.delayTime.value = t); return { dryWet, feedback, delayTime, inputNode: delay.in, } } function AutoPilot(state: ProgramState): AutoPilotUnit { const nextMeasure = parameter("upcomingMeasure", [0, Infinity],0); const currentMeasure = parameter("measure", [0, Infinity], 0); const patternEnabled = genericParameter("Alter Patterns", true); const dialsEnabled = genericParameter("Twiddle With Knobs", true); const mutesEnabled = genericParameter("Mute Drum Parts", true); state.clock.currentStep.subscribe(step => { if (step === 4) { nextMeasure.value = nextMeasure.value + 1; } else if (step === 15) { // slight hack to get mutes functioning as expected currentMeasure.value = currentMeasure.value + 1; } }); nextMeasure.subscribe(measure => { if (patternEnabled.value) { if (measure % 64 === 0) { if (Math.random() < 0.2) { state.gen.newNotes.value = true; } } if (measure % 16 === 0) { state.notes.forEach((n, i) => { if (Math.random() < 0.5) { n.newPattern.value = true; } }); if (Math.random() < 0.3) { state.drums.newPattern.value = true; } } } }) currentMeasure.subscribe(measure => { if (mutesEnabled.value) { if (measure % 8 == 0) { const drumMutes = [Math.random() < 0.2, Math.random() < 0.5, Math.random() < 0.5, Math.random() < 0.5]; state.drums.mutes[0].value = drumMutes[0]; state.drums.mutes[1].value = drumMutes[1]; state.drums.mutes[2].value = drumMutes[2]; state.drums.mutes[3].value = drumMutes[3]; } } }) const noteParams = state.notes.flatMap(x => Object.values(x.parameters)) const delayParams = [state.delay.feedback, state.delay.dryWet]; const wanderers = [...noteParams, ...delayParams].map(param => WanderingParameter(param)); window.setInterval(() => { if (dialsEnabled.value) wanderers.forEach(w => w.step());},100); return { switches: [ patternEnabled, dialsEnabled, mutesEnabled ] } } function ClockUnit(): ClockUnit { const bpm = parameter("BPM", [70,200],142); const currentStep = parameter("Current Step", [0,15],0); const clockImpl = Clock(bpm.value, 4, 0.0); bpm.subscribe(clockImpl.setBpm); clockImpl.bind((time, step) => { currentStep.value = step % 16; }) return { bpm, currentStep } } async function start(midiController: IMidiController | undefined) { const audio = Audio(); const clock = ClockUnit(); const delay = DelayUnit(audio); clock.bpm.subscribe(b => delay.delayTime.value = (3/4) * (60/b)); let channel_8 = midiController?.getChannel(8); let channel_9 = midiController?.getChannel(9); const gen = ThreeOhGen(); const programState: ProgramState = { notes: [ ThreeOhUnit(audio, "sawtooth", delay.inputNode, gen, channel_8), ThreeOhUnit(audio, "square", delay.inputNode, gen, channel_9) ], drums: await NineOhUnit(audio, midiController), gen, delay, clock } clock.currentStep.subscribe(step => [...programState.notes, programState.drums].forEach(d => d.step(step))); const autoPilot = AutoPilot(programState); const ui = UI(programState, autoPilot, audio.master.analyser); document.body.append(ui); } pressToStart(start, "The Endless Acid Banger v2");
2
2
src/content/state.ts
tongwentang/tongwentang-extension
66
1256
import { TARGET_NODE_ATTRIBUTES } from 'tongwen-core'; import { storage } from '../service/storage/storage'; import { ZhType } from '../service/tabs/tabs.constant'; import { getDetectLanguage } from './services'; const mutationOpt: MutationObserverInit = { childList: true, attributes: true, characterData: true, subtree: true, attributeFilter: TARGET_NODE_ATTRIBUTES as string[], }; export interface CtState { zhType: ZhType; debugMode: boolean; timeoutId: number | undefined; mutationOpt: MutationObserverInit; mutationObserver?: MutationObserver; mutations: MutationRecord[]; converting: Promise<any>; } const getDebugMode = () => storage.get('general').then(({ general }) => general.debugMode); export async function createCtState(): Promise<CtState> { return Promise.all([getDetectLanguage(), getDebugMode()]).then(([zhType, debugMode]) => ({ zhType, debugMode, timeoutId: undefined, mutationOpt, mutations: [], converting: Promise.resolve(null), })); }
1.109375
1
packages/app/src/screens/Home.tsx
wendelfreitas/4Fun-Fullstack
1
1264
import React from "react"; import { Text, View, FlatList } from "react-native"; import createQueryRenderer from "./../relay/createQueryRenderer"; import { graphql, createFragmentContainer } from "react-relay"; import { Home_planets } from "./__generated__/Home_planets.graphql"; import { withNavigation } from "react-navigation"; export const navigationOptionsHome = { title: "Home" }; type Props = { planets: Home_planets; }; const Home = () => { // const CardItem = ({ value }: any) => { // return ( // <View> // <Text>aqui</Text> // </View> // ); // }; return ( <View> {/* <FlatList data={planets} RenderItem={() => <CardItem />} keyExtractor={(v, i) => i.toString()} /> */} </View> ); }; const FragmentContainerHome = createFragmentContainer(Home, { planets: graphql` fragment Home_planets on Planets @relay(plural: true) { _id name description img } ` }); export default withNavigation( createQueryRenderer(FragmentContainerHome, Home, { query: graphql` query HomeQuery { planets { ...Home_planets } } ` }) );
1.390625
1
src/app/@ansyn/ansyn/modules/status-bar/components/tools/export-maps-popup/export-maps-popup.component.ts
AnSyn/ansyn
60
1272
import { Component, Inject, OnDestroy, OnInit } from '@angular/core'; import { AutoSubscription, AutoSubscriptions } from 'auto-subscriptions'; import { select, Store } from '@ngrx/store'; import { floationMenuClassNameForExport, imageryStatusClassNameForExport, selectActiveMapId, selectIsMinimalistViewMode, SetMinimalistViewModeAction, SetToastMessageAction } from '@ansyn/map-facade'; import { catchError, debounceTime, filter, finalize, mergeMap, tap, withLatestFrom } from 'rxjs/operators'; import { saveAs } from 'file-saver'; import { toBlob } from 'dom-to-image'; import { MatDialogRef } from '@angular/material/dialog'; import { DOCUMENT } from '@angular/common'; import { IToolsConfig, toolsConfig } from '../models/tools-config'; import { annotationsClassNameForExport } from '@ansyn/ol'; import { IExportMapData, IExportMapMetadata, ImageryCommunicatorService } from '@ansyn/imagery'; import { jsPDF } from 'jspdf'; import { TranslateService } from '@ngx-translate/core'; import { EMPTY, Observable, of } from 'rxjs'; import { HttpClient } from '@angular/common/http'; import { arrayBufferToBinaryString } from 'blob-util' import { measuresClassNameForExport } from '../../../../plugins/openlayers/plugins/visualizers/tools/measure-distance.visualizer'; import { LoggerService } from '../../../../core/services/logger.service'; import { IOverlay } from '../../../../overlays/models/overlay.model'; import { UpdateMeasureDataOptionsAction } from '../actions/tools.actions'; import { selectIsMeasureToolActive } from '../reducers/tools.reducer'; enum GraphicExportEnum { All = 'All', DrawsAndMeasures = 'Draws & Measurements', North = 'North point', Description = 'Description' } enum ExportMethodEnum { BASIC = 'Basic', ADVANCED = 'Advanced' } enum FormatEnum { JPG = 'JPG', PDF = 'PDF' } const LOGS = { request: 'Request to export maps', failed: 'Export maps failed', success: 'Export maps success', canceled: 'Export maps was canceled', unsupported: `can't export map,use basic export instead` }; const DEFAULT_QUALITY = 'normal'; const DEFAULT_PAGE_SIZE = 'a4'; const item2class = { [GraphicExportEnum.DrawsAndMeasures]: [annotationsClassNameForExport, measuresClassNameForExport], [GraphicExportEnum.North]: floationMenuClassNameForExport, [GraphicExportEnum.Description]: imageryStatusClassNameForExport }; @Component({ selector: 'ansyn-export-maps-popup', templateUrl: './export-maps-popup.component.html', styleUrls: ['./export-maps-popup.component.less'] }) @AutoSubscriptions() export class ExportMapsPopupComponent implements OnInit, OnDestroy { readonly advancedExport = ExportMethodEnum.ADVANCED; readonly pdfFormat = FormatEnum.PDF; readonly exportMethods = [ExportMethodEnum.BASIC, ExportMethodEnum.ADVANCED]; lastMeasureActiveStatus: boolean; title = 'Export'; description = 'keep in mind that the image may be protected'; selectedExportMethod: ExportMethodEnum = ExportMethodEnum.BASIC; pdfExportMapId: string; exporting: boolean; graphicExport = [GraphicExportEnum.All, GraphicExportEnum.DrawsAndMeasures, GraphicExportEnum.North, GraphicExportEnum.Description]; graphicexportMap = new Map(this.graphicExport.reduce((entries: Array<[string, boolean]>, e) => { entries.push([e, true]); return entries; }, [])); formats = [FormatEnum.JPG, FormatEnum.PDF]; format = this.formats[0]; quality = DEFAULT_QUALITY; @AutoSubscription onActiveMapChange$ = this.store$.pipe( select(selectActiveMapId), tap( (activeMapId: string) => this.pdfExportMapId = activeMapId) ); @AutoSubscription basicExport$ = this.store$.pipe( select(selectIsMinimalistViewMode), filter(Boolean), debounceTime(100), tap(this.basicExportMap.bind(this)) ); _pageSize = DEFAULT_PAGE_SIZE; get pageSize(): string { if (this.isPDF()) { return this._pageSize; } return 'Screenshot'; } set pageSize(value) { this._pageSize = value } _pageSizes = { a0: [1189, 841], a1: [841, 594], a2: [594, 420], a3: [420, 297], a4: [297, 210], a5: [210, 148] }; get pageSizes() { if (this.isPDF()) { return Object.keys(this._pageSizes); } return ['Screenshot'] } _qualities = { low: 72, normal: 150, high: 300 }; get qualities() { return Object.keys(this._qualities); } get config() { return this.toolsConfigData.exportMap; } constructor(protected store$: Store<any>, protected logger: LoggerService, protected dialogRef: MatDialogRef<ExportMapsPopupComponent>, protected imageryCommunicatorService: ImageryCommunicatorService, protected translateService: TranslateService, protected http: HttpClient, @Inject(DOCUMENT) protected document: any, @Inject(toolsConfig) public toolsConfigData: IToolsConfig) { this.logger.info(LOGS.request); } @AutoSubscription onOpenDialogDisableMeasureDraw$ = () => this.dialogRef.afterOpened().pipe( withLatestFrom(this.store$.select(selectIsMeasureToolActive), (_, isActive) => isActive), tap( (measureActive) => { this.lastMeasureActiveStatus = measureActive; this.updateMeasureStatus(); }) ); @AutoSubscription revertMeasureActiveStatusOnClose$ = () => this.dialogRef.beforeClosed().pipe( tap( () => { this.updateMeasureStatus(this.lastMeasureActiveStatus); }) ); getFont(): Observable<ArrayBuffer> { const pathToFontFile = 'assets/fonts/TTWPGOTT.ttf'; return this.http.get(pathToFontFile, {responseType: 'arraybuffer'}); } ngOnInit(): void { } ngOnDestroy(): void { } advancedExportMaps(exportMetadata: IExportMapMetadata) { const mapToBeExport = this.imageryCommunicatorService.provide(this.pdfExportMapId); if (!mapToBeExport) { throw new Error('No Such Map Error'); } mapToBeExport.exportMap(exportMetadata).pipe( mergeMap( (exportMapData) => { if (exportMetadata.extra.north) { return new Observable( obs => { const virtualNorth = mapToBeExport?.getVirtualNorth() || 0; const realNorth = mapToBeExport?.getRotation() || 0; const rotation = realNorth - virtualNorth; const northImage = new Image(); northImage.onload = function() { const { width, height } = northImage; northImage.style.transform = `rotate(${rotation}rad)`; const canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; const x = canvas.width / 2, y = canvas.height / 2; const ctx = canvas.getContext('2d'); ctx.translate(x, y); ctx.rotate(rotation); ctx.drawImage(northImage, -width / 2, -height / 2, width, height); ctx.rotate(-rotation); ctx.translate(-x, -y); obs.next({...exportMapData, compass: canvas}); obs.complete(); }; northImage.src = 'assets/icons/full-north.svg'; }) } return of(exportMapData); }), tap((exportMapData: IExportMapData) => { this.getFont().subscribe(res => { const font = arrayBufferToBinaryString(res); const {size, extra} = exportMetadata; const doc = new jsPDF('landscape', undefined, this.pageSize); doc.addImage(exportMapData.canvas.toDataURL('image/jpeg'), 'JPEG', 0, 0, exportMetadata.size[0], exportMetadata.size[1]); if (extra.descriptions) { doc.rect(0, 0, size[0], 5, 'F'); doc.setTextColor(255, 255, 255); doc.addFileToVFS('TTWPGOTT.ttf', font); doc.addFont('TTWPGOTT.ttf', 'TTWPGOTT', 'normal'); doc.setFont('TTWPGOTT'); doc.setFontSize(11); const loadOverlay = mapToBeExport.mapSettings.data.overlay; const isInOverlay: boolean = Boolean(loadOverlay); const desc = isInOverlay ? this.getDescriptionFromOverlay(loadOverlay) : this.translateService.instant('Base Map'); doc.setR2L(!isInOverlay); doc.text(desc, size[0] / 2, 5, {align: 'center', baseline: 'bottom'}); } if (exportMapData.compass) { doc.addImage(exportMapData.compass.toDataURL('image/png'), 'PNG', 0, 0, 25, 25); // we use png for transparent compass } doc.save('map.pdf'); this.logger.info(LOGS.success); }); }), catchError( (err) => { console.error(err); this.logger.error(LOGS.failed); this.store$.dispatch(new SetToastMessageAction({toastText: LOGS.unsupported})); return EMPTY; }), finalize( () => this.dialogRef.close()) ).subscribe(); } basicExportMap() { toBlob(document.querySelector(this.config.target), { filter: this.filterExcludeClass(), }).then(blob => { this.logger.info(LOGS.success); this.store$.dispatch(new SetMinimalistViewModeAction(false)); saveAs(blob, 'map.jpg'); }).catch(err => { this.logger.error(LOGS.failed); }).finally(() => { this.dialogRef.close() }); } graphicExportChange(ge: string, forceState = false) { const newState = forceState || !this.graphicexportMap.get(ge); if (ge !== GraphicExportEnum.All) { this.graphicexportMap.set(ge, newState); let notAllCheck = !newState; this.graphicexportMap.forEach((g, key) => { notAllCheck = notAllCheck || (key !== GraphicExportEnum.All && !g) }); this.graphicexportMap.set(GraphicExportEnum.All, !notAllCheck); } else { this.graphicexportMap.forEach((_, key, map) => map.set(key, newState)) } } reset() { this.graphicExportChange(GraphicExportEnum.All, true); this.format = this.formats[0]; this.quality = DEFAULT_QUALITY; this._pageSize = DEFAULT_PAGE_SIZE; } export() { this.exporting = true; const exportMetadata: IExportMapMetadata = this.getExportMetadata(); if (this.selectedExportMethod === ExportMethodEnum.BASIC || !this.isPDF()) { this.store$.dispatch(new SetMinimalistViewModeAction(true)); } else { this.advancedExportMaps(exportMetadata); } } private getExportMetadata(): IExportMapMetadata { const annotations = this.graphicexportMap.get(GraphicExportEnum.DrawsAndMeasures) ? item2class[GraphicExportEnum.DrawsAndMeasures].map( (layerName) => `.${layerName} canvas`).join(',') : false; const resolution = this._qualities[this.quality]; return { size: this._pageSizes[this._pageSize], resolution: this._pageSize === 'a0' ? Math.min(250, resolution) : resolution, // export a0 with 300 dpi cause some problem. extra: { north: this.graphicexportMap.get(GraphicExportEnum.North), annotations, descriptions: this.graphicexportMap.get(GraphicExportEnum.Description) } } } private isPDF() { return this.format === FormatEnum.PDF; } private filterExcludeClass() { const excludeClasses = [...this.config.excludeClasses]; if (this.selectedExportMethod === ExportMethodEnum.ADVANCED && !this.isPDF()) { this.graphicexportMap.forEach((show, key) => { if (!show && item2class[key]) { let excludeClass = item2class[key]; if (!Array.isArray(excludeClass)) { excludeClass = [excludeClass]; } excludeClasses.push(...excludeClass); } }) } return function(element) { if (element.tagName === 'CANVAS') { return element.width > 0; } return !(element.classList && excludeClasses.some(excludeClass => element.classList.contains(excludeClass))); } } private getDescriptionFromOverlay(overlay: IOverlay) { const time = overlay.date; const sensorName = this.translateService.instant(overlay.sensorName); return `${time.toLocaleString()} ${sensorName}`; } private updateMeasureStatus(active: boolean = false) { this.store$.dispatch(new UpdateMeasureDataOptionsAction({ mapId: this.pdfExportMapId, options: { isToolActive: active } })); } close() { this.logger.info(LOGS.canceled); } }
0.929688
1
packages/manager/src/features/StackScripts/SelectStackScriptPanel/SelectStackScriptsSection.tsx
RULCSoft/manager
0
1280
import { Image } from '@linode/api-v4/lib/images'; import { StackScript } from '@linode/api-v4/lib/stackscripts'; import * as React from 'react'; import CircleProgress from 'src/components/CircleProgress'; import { createStyles, Theme, withStyles, WithStyles } from 'src/components/core/styles'; import TableBody from 'src/components/core/TableBody'; import TableCell from 'src/components/core/TableCell'; import TableRow from 'src/components/core/TableRow'; import { formatDate } from 'src/utilities/format-date-iso8601'; import stripImageName from 'src/utilities/stripImageName'; import truncateText from 'src/utilities/truncateText'; import StackScriptSelectionRow from './StackScriptSelectionRow'; type ClassNames = 'root' | 'loadingWrapper'; const styles = (theme: Theme) => createStyles({ root: {}, loadingWrapper: { border: 0, paddingTop: 100 } }); export interface Props { onSelect: (s: StackScript) => void; selectedId?: number; data: StackScript[]; isSorting: boolean; publicImages: Record<string, Image>; currentUser: string; disabled?: boolean; } type CombinedProps = Props & WithStyles<ClassNames>; const SelectStackScriptsSection: React.FC<CombinedProps> = props => { const { onSelect, selectedId, data, isSorting, classes, disabled } = props; const selectStackScript = (s: StackScript) => ( <StackScriptSelectionRow key={s.id} label={s.label} stackScriptUsername={s.username} description={truncateText(s.description, 100)} images={stripImageName(s.images)} deploymentsActive={s.deployments_active} updated={formatDate(s.updated, false)} onSelect={() => onSelect(s)} checked={selectedId === s.id} updateFor={[selectedId === s.id, classes]} stackScriptID={s.id} disabled={disabled} /> ); return ( <TableBody> {!isSorting ? ( data && data.map(selectStackScript) ) : ( <TableRow> <TableCell colSpan={5} className={classes.loadingWrapper}> <CircleProgress noTopMargin /> </TableCell> </TableRow> )} </TableBody> ); }; const styled = withStyles(styles); export default styled(SelectStackScriptsSection) as React.FC<Props>;
1.546875
2
src/root/components/DropdownMenuItem/index.tsx
IFRCGo/go-frontend
18
1288
import React from 'react'; import { _cs, isValidUrl, } from '@togglecorp/fujs'; import { Link } from 'react-router-dom'; import RawButton, { Props as RawButtonProps, } from '#components/RawButton'; import styles from './styles.module.scss'; interface BaseProps { className?: string; icon?: React.ReactNode; label?: React.ReactNode; } type Props<N extends string | number> = BaseProps & ({ name?: N; onClick: RawButtonProps<N>['onClick']; href?: never; } | { href: string; onClick?: never; name?: never; }) function DropdownMenuItem<N extends string | number>(props: Props<N>) { const { className: classNameFromProps, icon, label, } = props; const isExternalLink = React.useMemo(() => ( props.href && typeof props.href === 'string' && (isValidUrl(props.href) || props.href.startsWith('mailto:')) ), [props.href]); const className = _cs(styles.dropdownMenuItem, classNameFromProps); const children = ( <> <div className={styles.iconContainer}> {icon} </div> <div className={styles.label}> {label} </div> </> ); if (props.href) { if (isExternalLink) { return ( <a className={className} href={props.href} target="_blank" > {children} </a> ); } return ( <Link className={className} to={props.href} > {children} </Link> ); } if (props.name) { return ( <RawButton className={className} name={props.name} onClick={props.onClick} > {children} </RawButton> ); } return ( <RawButton<undefined> name={undefined} className={className} onClick={props.onClick as RawButtonProps<undefined>['onClick']} > {children} </RawButton> ); } export default DropdownMenuItem;
1.59375
2
assets/test/short_answer/short_answer_delivery_test.tsx
chrislawson/oli-torus
45
1296
import { render, fireEvent, screen } from '@testing-library/react'; import React from 'react'; import { defaultDeliveryElementProps } from '../utils/activity_mocks'; import { act } from 'react-dom/test-utils'; import '@testing-library/jest-dom'; import { defaultModel } from 'components/activities/short_answer/utils'; import { ShortAnswerComponent } from 'components/activities/short_answer/ShortAnswerDelivery'; import { makeHint } from 'components/activities/types'; import { configureStore } from 'state/store'; import { activityDeliverySlice } from 'data/activities/DeliveryState'; import { Provider } from 'react-redux'; import { DeliveryElementProvider } from 'components/activities/DeliveryElement'; import { defaultActivityState } from 'data/activities/utils'; describe('multiple choice delivery', () => { it('renders ungraded activities correctly', async () => { const model = defaultModel(); model.authoring.parts[0].hints.push(makeHint('Hint 1')); const props = { model, activitySlug: 'activity-slug', state: Object.assign(defaultActivityState(model), { hasMoreHints: false }), graded: false, preview: false, }; const { onSaveActivity, onSubmitActivity } = defaultDeliveryElementProps; const store = configureStore({}, activityDeliverySlice.reducer); render( <Provider store={store}> <DeliveryElementProvider {...defaultDeliveryElementProps} {...props}> <ShortAnswerComponent /> </DeliveryElementProvider> </Provider>, ); // expect no hints displayed expect(screen.queryAllByLabelText(/hint [0-9]/)).toHaveLength(0); // expect hints button const requestHintButton = screen.getByLabelText('request hint'); expect(requestHintButton).toBeTruthy(); // expect clicking request hint to display a hint act(() => { fireEvent.click(requestHintButton); }); expect(await screen.findAllByLabelText(/hint [0-9]/)).toHaveLength(1); // enter an input, expect it to save act(() => { fireEvent.change(screen.getByLabelText('answer submission textbox'), { target: { value: 'answer' }, }); }); expect(onSaveActivity).toHaveBeenCalledTimes(1); // expect a submit button const submitButton = screen.getByLabelText('submit'); expect(submitButton).toBeTruthy(); // submit and expect a submission act(() => { fireEvent.click(submitButton); }); expect(onSubmitActivity).toHaveBeenCalledTimes(1); expect(onSubmitActivity).toHaveBeenCalledWith(props.state.attemptGuid, [ { attemptGuid: '1', response: { input: 'answer' }, }, ]); // expect results to be displayed after submission expect(await screen.findAllByLabelText('result')).toHaveLength(1); expect(screen.getByLabelText('score')).toHaveTextContent('1'); expect(screen.getByLabelText('out of')).toHaveTextContent('1'); }); });
1.539063
2
src/components/FormElements/Field/Field.tsx
ArmandPhilippot/apcom
0
1304
import { ChangeEvent, ForwardedRef, forwardRef, ReactElement, SetStateAction, } from 'react'; import styles from './Field.module.scss'; type FieldType = 'email' | 'number' | 'search' | 'select' | 'text' | 'textarea'; type SelectOptions = { id: string; name: string; value: string; }; const Field = ( { id, name, value, setValue, required = false, kind = 'text', label, options, }: { id: string; name: string; value: string; setValue: (value: SetStateAction<string>) => void; required?: boolean; kind?: FieldType; label?: ReactElement; options?: SelectOptions[]; }, ref: ForwardedRef<HTMLInputElement | HTMLTextAreaElement> ) => { const updateValue = ( e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement> ) => { setValue(e.target.value); }; const getOptions = () => { return options ? options.map((option) => ( <option key={option.id} value={option.value}> {option.name} </option> )) : ''; }; const getField = () => { switch (kind) { case 'select': return ( <select name={name} id={id} value={value} onChange={updateValue} required={required} className={`${styles.field} ${styles.select}`} > {getOptions()} </select> ); case 'textarea': return ( <textarea ref={ref as ForwardedRef<HTMLTextAreaElement>} id={id} name={name} value={value} required={required} onChange={updateValue} className={`${styles.field} ${styles.textarea}`} /> ); default: return ( <input ref={ref as ForwardedRef<HTMLInputElement>} type={kind} id={id} name={name} value={value} required={required} onChange={updateValue} className={styles.field} /> ); } }; return ( <> {label} {getField()} </> ); }; export default forwardRef(Field);
1.648438
2
sc-client/src/redux/selectors/product.selector.ts
shubham43MP/ps-shop-assigmnet-react
0
1312
import { createSelector } from 'reselect'; import { ReducerType } from 'redux/types/rootStateType'; const selectSelf = (state: ReducerType) => state.productReducer export const selectProducts = createSelector( selectSelf, state => state.products ) export const selectProdLoading = createSelector( selectSelf, state => state.loading )
1.015625
1
finalProject/src/app/zimmer/zimmer-list/zimmer-list.component.ts
TalRandi/FinalProject
0
1320
import { Component, OnDestroy, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { stat } from 'fs'; import { Subscription } from 'rxjs'; import { finalize } from 'rxjs/operators'; import { AuthenticationService } from 'src/app/authentication/authentication.service'; import { Client } from 'src/app/shared-data/client.model'; import { DataStorageService } from 'src/app/shared-data/data-storage.service'; import { EmailService } from 'src/app/shared-data/email.service'; import { Hut } from 'src/app/shared-data/hut.model'; import { InnerDataService } from 'src/app/shared-data/inner-data.service'; import { Zimmer } from 'src/app/shared-data/zimmer.model'; interface Sort { value: string; viewValue: string; } @Component({ selector: 'app-zimmer-list', templateUrl: './zimmer-list.component.html', styleUrls: ['./zimmer-list.component.css'] }) export class ZimmerListComponent implements OnInit, OnDestroy { sorts: Sort[] = [ {value: 'all', viewValue: '-'}, {value: 'weekend', viewValue: 'מחיר - סופ"ש'}, {value: 'midweek', viewValue: 'מחיר - אמצ"ש'}, {value: 'huts_number', viewValue: 'מספר בקתות'}, {value: 'total_capacity', viewValue: 'מקסימום אורחים'}, {value: 'rating', viewValue: 'דירוג'}, ]; currentRate = 8; client: Client; isLoading = false; sort_direction = true; number_of_guests: number; private data: Subscription; hut: Hut[] = [] all_zimmers:Zimmer[] = [] disabled_zimmers:Zimmer[] = [] zimmers_to_display:Zimmer[] = [] dictionary = new Map<string, string>(); general_filter: string[] = [] region_filter: string[] = [] huts_number_filter: string = ""; sort_parameter: string = "all"; constructor(private storage: DataStorageService, public innerData: InnerDataService, private router: Router, public authService: AuthenticationService, private emailService: EmailService) { } private removeElement(array: string[], element: string){ const index = array.indexOf(element); if (index > -1) array.splice(index, 1); } private removeZimmer(array: Zimmer[], zimmer: Zimmer){ const index = array.indexOf(zimmer); if (index > -1) array.splice(index, 1); } getByValue(map: Map<string, string>, searchValue: string) { for (let [key, value] of map.entries()) { if (value === searchValue) return key; } return undefined } sortBy(event: any): void{ this.isLoading = true this.sort_parameter = event.value setTimeout(() => { switch (this.sort_parameter) { case 'weekend': this.zimmers_to_display.sort((a,b) => (a.min_price_weekend > b.min_price_weekend) ? 1 : ((b.min_price_weekend > a.min_price_weekend) ? -1 : 0)) break; case 'midweek': this.zimmers_to_display.sort((a,b) => (a.min_price_regular > b.min_price_regular) ? 1 : ((b.min_price_regular > a.min_price_regular) ? -1 : 0)) break; case 'huts_number': this.zimmers_to_display.sort((a,b) => (a.huts.length > b.huts.length) ? 1 : ((b.huts.length > a.huts.length) ? -1 : 0)) break; case 'total_capacity': this.zimmers_to_display.sort((a,b) => (a.total_capacity > b.total_capacity) ? 1 : ((b.total_capacity > a.total_capacity) ? -1 : 0)) break; case 'rating': this.zimmers_to_display.sort((a,b) => (a.rate > b.rate) ? 1 : ((b.rate > a.rate) ? -1 : 0)) break; default: break; } this.isLoading = false }, 200); } sortDirection(): void{ if(this.sort_parameter == "all") return this.isLoading = true setTimeout(() => { this.zimmers_to_display.reverse(); this.sort_direction = !this.sort_direction this.isLoading = false }, 200); } zimmer_clicked(zimmer: Zimmer): void{ const url = this.router.serializeUrl( this.router.createUrlTree([`/home/${zimmer.zimmer_id}`]) ); window.open(url, '_blank'); } ngOnInit(): void { this.number_of_guests = this.innerData.number_of_guests this.isLoading = true; if(localStorage.getItem('userData')){ var userData = JSON.parse(localStorage.getItem('userData')!.toString()); if(userData.zimmer == 'client' && userData.admin == false){ this.storage.getClient(userData.email).subscribe(client => { this.client = client; if(!this.client.favorites){ this.client.favorites = []; } }) } } this.storage.fetchAcceptedZimmers().pipe(finalize(() => this.isLoading = false)).subscribe(zimmers => { this.all_zimmers = zimmers.filter(zimmer => zimmer.status != 'disabled'); this.zimmers_to_display = [...this.all_zimmers] this.dictionary.set("בריכה", "pool") this.dictionary.set("בריכה מחוממת", "heated_pool") this.dictionary.set("בריכה מקורה", "indoor_pool") this.dictionary.set("ג'קוזי", "jacuzzi") this.dictionary.set("WiFi", "wifi") this.dictionary.set("סאונה", "sauna") this.dictionary.set("מזגן", "air_conditioner") this.dictionary.set("חניה", "parking") this.innerData.regions_map.forEach((value, region) => { if(value) this.region_filter.push(region) }) this.innerData.filters_map.forEach((value, filter) => { if(value) this.general_filter.push(this.dictionary.get(filter)!) }) this.innerData.huts_map.forEach((value, hut_number) => { if(value) this.huts_number_filter = hut_number }) this.applyFilters() this.data = this.innerData.string_subject.subscribe(zimmer_to_search => { this.zimmers_to_display = [...this.all_zimmers] if(zimmer_to_search == '') return this.isLoading = true; setTimeout(() => { for (let index_zimmer = 0; index_zimmer < this.zimmers_to_display.length; index_zimmer++) { if(this.zimmers_to_display[index_zimmer] == undefined) break if(this.zimmers_to_display[index_zimmer].zimmerName != zimmer_to_search){ this.removeZimmer(this.zimmers_to_display, this.zimmers_to_display[index_zimmer]) index_zimmer-- } } this.isLoading = false; }, 500) }) this.data = this.innerData.number_subject.subscribe(number_of_guests => { this.number_of_guests = number_of_guests this.isLoading = true; setTimeout(() => { this.applyFilters() this.isLoading = false; }, 500) }) this.data = this.innerData.subject.subscribe(filters => { this.isLoading = true; if(filters.has("בריכה")){ // Update the general_filter array filters.forEach((checked: boolean, filter: string) => { if(checked && !this.general_filter.includes(this.dictionary.get(filter)!)) this.general_filter.push(this.dictionary.get(filter)!) else if(!checked && this.general_filter.includes(this.dictionary.get(filter)!)) this.removeElement(this.general_filter, this.dictionary.get(filter)!) }); } else if(filters.has("צפון")){ // Update the region_filter array filters.forEach((checked: boolean, filter: string) => { if(checked && !this.region_filter.includes(filter)) this.region_filter.push(filter) else if(!checked && this.region_filter.includes(filter)) this.removeElement(this.region_filter, filter) }); } else if(filters.has("1")){ // Update the huts_number array filters.forEach((checked: boolean, filter: string) => { if(checked && this.huts_number_filter != filter) this.huts_number_filter = filter }); } this.applyFilters() this.isLoading = false; }); }) } applyFilters(): void { this.zimmers_to_display = [...this.all_zimmers] for (let index_zimmer = 0; index_zimmer < this.zimmers_to_display.length; index_zimmer++) { if(this.zimmers_to_display[index_zimmer].features == undefined && this.general_filter.length != 0){ this.removeZimmer(this.zimmers_to_display, this.zimmers_to_display[index_zimmer]) index_zimmer-- continue } if(this.huts_number_filter != ""){ if(this.huts_number_filter == "הכל"){ this.huts_number_filter = ""; console.log(this.zimmers_to_display); } else if(this.zimmers_to_display[index_zimmer].huts.length+'' != this.huts_number_filter){ this.removeZimmer(this.zimmers_to_display, this.zimmers_to_display[index_zimmer]) index_zimmer-- continue } else if(this.huts_number_filter == "6+" && this.zimmers_to_display[index_zimmer].huts.length < 6){ this.removeZimmer(this.zimmers_to_display, this.zimmers_to_display[index_zimmer]) index_zimmer-- continue } } if(this.number_of_guests){ if(this.zimmers_to_display[index_zimmer] == undefined) break if(this.zimmers_to_display[index_zimmer].total_capacity < this.number_of_guests){ this.removeZimmer(this.zimmers_to_display, this.zimmers_to_display[index_zimmer]) index_zimmer-- continue } } for (let index_filter = 0; index_filter < this.general_filter.length; index_filter++) { if (!this.zimmers_to_display[index_zimmer].features.includes(this.general_filter[index_filter])) { this.removeZimmer(this.zimmers_to_display, this.zimmers_to_display[index_zimmer]) index_zimmer-- break } } for (let index_region = 0; index_region < this.region_filter.length; index_region++) { if(this.zimmers_to_display[index_zimmer] == undefined) break if(!this.region_filter.includes(this.zimmers_to_display[index_zimmer].region)){ this.removeZimmer(this.zimmers_to_display, this.zimmers_to_display[index_zimmer]) index_zimmer-- break } } } } isFavorite(zimmer_id: string){ return this.client.favorites.map(zimmer => zimmer.zimmer_id).includes(zimmer_id) } favoriteClicked(favoriteZimmer: Zimmer, status: string){ const index = this.zimmers_to_display.indexOf(favoriteZimmer); if (index > -1) this.zimmers_to_display.splice(index, 1); if(status == "addFavorite") this.client.favorites.push(favoriteZimmer) else if(status == "removeFavorite") this.client.favorites = this.client.favorites.filter(zimmer => zimmer.zimmer_id != favoriteZimmer.zimmer_id) this.zimmers_to_display.splice(index, 0, favoriteZimmer); this.storage.updateClient(this.client).subscribe(); } disableZimmer(zimmer: Zimmer, index: number){ this.isLoading = true; zimmer.status = "disabled" this.zimmers_to_display.splice(index, 1); let header = zimmer.ownerName + ", שלום רב " let message = "זוהי הודעה על חסימת הצימר - " + zimmer.zimmerName this.emailService.sendEmail(header, zimmer.email, message, "GoEasy") this.storage.updateZimmer(zimmer).pipe(finalize(() => this.isLoading = false)).subscribe() } ngOnDestroy(): void { if(this.data) this.data.unsubscribe(); } }
1.28125
1
src/dashboard/components/Footer.tsx
barzanimatin/ghost
0
1328
import { useRouter } from "next/router"; import { useTranslation } from "react-i18next"; import * as React from "react"; const Footer: React.FC = () => { const [locale, setLocale] = React.useState(""); const router = useRouter(); const { t } = useTranslation("footer"); React.useEffect(() => { setLocale(window.localStorage.getItem("bot_locale") || "en"); }, []); function handleChange(e: React.ChangeEvent<HTMLSelectElement>) { const locale = e.target.value; if (router.locale === locale) return; window.localStorage.setItem("bot_locale", locale); router.push(router.pathname, router.asPath, { locale: e.target.value }); } return ( <footer className="footer"> <p> {t("created")} <a href="https://caspertheghost.me/">CasperTheGhost</a> |{" "} {t("not_affiliated")} </p> <select value={locale} onChange={handleChange} className="select-language"> <option value="en">English</option> <option value="ru">Russian</option> <option value="nl">Dutch</option> </select> </footer> ); }; export default Footer;
1.507813
2
projects/fsastorefrontlib/src/core/my-account/store/effects/index.ts
divna-p/fsa-spa-test
1
1336
import { ClaimPoliciesEffects } from './claim-policies.effect'; import { ClaimEffects } from './claim.effect'; import { PolicyEffects } from './policy.effect'; import { QuoteEffects } from './quote.effect'; export const effects: any[] = [ QuoteEffects, PolicyEffects, ClaimEffects, ClaimPoliciesEffects, ]; export * from './claim-policies.effect'; export * from './claim.effect'; export * from './policy.effect'; export * from './quote.effect';
0.462891
0
src/app/organizations/organization/organization-stargazers/organization-stargazers.component.ts
david4096/dockstore-ui2
0
1344
/* * Copyright 2019 OICR * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { Component, OnInit } from '@angular/core'; import { takeUntil } from 'rxjs/operators'; import { Base } from '../../../shared/base'; import { StarOrganizationService } from '../../../shared/star-organization.service'; import { User } from '../../../shared/swagger'; import { UserService } from '../../../shared/user/user.service'; import { OrganizationStarringService } from '../organization-starring/organization-starring.service'; @Component({ selector: 'app-organization-stargazers', templateUrl: '../../../stargazers/stargazers.component.html' }) export class OrganizationStargazersComponent extends Base implements OnInit { starGazers: Array<User>; constructor( private organizationStarringService: OrganizationStarringService, private userService: UserService, private starOrganizationService: StarOrganizationService ) { super(); } ngOnInit() { this.starOrganizationService.starOrganization$.pipe(takeUntil(this.ngUnsubscribe)).subscribe(organization => { if (organization && organization.theOrganization) { this.organizationStarringService.getStarring(organization.theOrganization.id).subscribe((starring: Array<User>) => { this.starGazers = starring; this.starGazers.forEach((user: User) => { user.avatarUrl = this.userService.gravatarUrl(null, user.avatarUrl); }); }); } }); } }
1.375
1
src/question_expression.ts
jeremykenedy/survey-library
0
1352
import { HashTable, Helpers } from "./helpers"; import { Question } from "./question"; import { JsonObject } from "./jsonobject"; import { QuestionFactory } from "./questionfactory"; import { LocalizableString } from "./localizablestring"; import { ExpressionRunner } from "./conditions"; /** * A Model for expression question. It is a read-only question. It calculates value based on epxression property. */ export class QuestionExpressionModel extends Question { private expressionIsRunning: boolean; private expressionRunner: ExpressionRunner; constructor(public name: string) { super(name); this.createLocalizableString("format", this); var self = this; this.registerFunctionOnPropertyValueChanged("expression", function() { if (self.expressionRunner) { self.expressionRunner = new ExpressionRunner(self.expression); } }); } public getType(): string { return "expression"; } /** * Use this property to display the value in your own format. Make sure you have "{0}" substring in your string, to display the actual value. */ public get format(): string { return this.getLocalizableStringText("format", ""); } public set format(val: string) { this.setLocalizableStringText("format", val); } get locFormat(): LocalizableString { return this.getLocalizableString("format"); } /** * The Expression that used to calculate the question value. You may use standard operators like +, -, * and /, squares (). Here is the example of accessing the question value {questionname}. * <br/>Example: "({quantity} * {price}) * (100 - {discount}) / 100" */ public get expression(): string { return this.getPropertyValue("expression", ""); } public set expression(val: string) { this.setPropertyValue("expression", val); } public locCalculation() { this.expressionIsRunning = true; } public unlocCalculation() { this.expressionIsRunning = false; } public runCondition(values: HashTable<any>, properties: HashTable<any>) { super.runCondition(values, properties); if (!this.expression || this.expressionIsRunning) return; this.locCalculation(); if (!this.expressionRunner) this.expressionRunner = new ExpressionRunner(this.expression); var newValue = this.expressionRunner.run(values, properties); if (!Helpers.isTwoValueEquals(newValue, this.value)) { this.value = newValue; } this.unlocCalculation(); } /** * The maximum number of fraction digits to use if displayStyle is not "none". Possible values are from 0 to 20. The default value is -1 and it means that this property is not used. */ public get maximumFractionDigits(): number { return this.getPropertyValue("maximumFractionDigits", -1); } public set maximumFractionDigits(val: number) { if (val < -1 || val > 20) return; this.setPropertyValue("maximumFractionDigits", val); } /** * The minimum number of fraction digits to use if displayStyle is not "none". Possible values are from 0 to 20. The default value is -1 and it means that this property is not used. */ public get minimumFractionDigits(): number { return this.getPropertyValue("minimumFractionDigits", -1); } public set minimumFractionDigits(val: number) { if (val < -1 || val > 20) return; this.setPropertyValue("minimumFractionDigits", val); } protected getDisplayValueCore(keysAsText: boolean): any { var val = this.isValueEmpty(this.value) ? this.defaultValue : this.value; if (this.isValueEmpty(val)) return ""; var str = this.getValueAsStr(val); if (!this.format) return str; return (<any>this.format)["format"](str); } /** * You may set this property to "decimal", "currency" or "percent". If you set it to "currency", you may use the currency property to display the value in currency different from USD. * @see currency */ public get displayStyle(): string { return this.getPropertyValue("displayStyle", "none"); } public set displayStyle(val: string) { this.setPropertyValue("displayStyle", val); } /** * Use it to display the value in the currency differen from USD. The displayStype should be set to "currency". * @see displayStyle */ public get currency(): string { return this.getPropertyValue("currency", "USD"); } public set currency(val: string) { if (getCurrecyCodes().indexOf(val) < 0) return; this.setPropertyValue("currency", val); } public get useGrouping(): boolean { return this.getPropertyValue("useGrouping", true); } public set useGrouping(val: boolean) { this.setPropertyValue("useGrouping", val); } protected getValueAsStr(val: any): string { if ( this.displayStyle != "none" && !isNaN(parseFloat(val)) && isFinite(val) ) { var locale = this.getLocale(); if (!locale) locale = "en"; var options = { style: this.displayStyle, currency: this.currency, useGrouping: this.useGrouping }; if (this.maximumFractionDigits > -1) { (<any>options)["maximumFractionDigits"] = this.maximumFractionDigits; } if (this.minimumFractionDigits > -1) { (<any>options)["minimumFractionDigits"] = this.minimumFractionDigits; } return val.toLocaleString(locale, options); } return val.toString(); } } export function getCurrecyCodes(): Array<string> { return [ "AED", "AFN", "ALL", "AMD", "ANG", "AOA", "ARS", "AUD", "AWG", "AZN", "BAM", "BBD", "BDT", "BGN", "BHD", "BIF", "BMD", "BND", "BOB", "BOV", "BRL", "BSD", "BTN", "BWP", "BYN", "BZD", "CAD", "CDF", "CHE", "CHF", "CHW", "CLF", "CLP", "CNY", "COP", "COU", "CRC", "CUC", "CUP", "CVE", "CZK", "DJF", "DKK", "DOP", "DZD", "EGP", "ERN", "ETB", "EUR", "FJD", "FKP", "GBP", "GEL", "GHS", "GIP", "GMD", "GNF", "GTQ", "GYD", "HKD", "HNL", "HRK", "HTG", "HUF", "IDR", "ILS", "INR", "IQD", "IRR", "ISK", "JMD", "JOD", "JPY", "KES", "KGS", "KHR", "KMF", "KPW", "KRW", "KWD", "KYD", "KZT", "LAK", "LBP", "LKR", "LRD", "LSL", "LYD", "MAD", "MDL", "MGA", "MKD", "MMK", "MNT", "MOP", "MRO", "MUR", "MVR", "MWK", "MXN", "MXV", "MYR", "MZN", "NAD", "NGN", "NIO", "NOK", "NPR", "NZD", "OMR", "PAB", "PEN", "PGK", "PHP", "PKR", "PLN", "PYG", "QAR", "RON", "RSD", "RUB", "RWF", "SAR", "SBD", "SCR", "SDG", "SEK", "SGD", "SHP", "SLL", "SOS", "SRD", "SSP", "STD", "SVC", "SYP", "SZL", "THB", "TJS", "TMT", "TND", "TOP", "TRY", "TTD", "TWD", "TZS", "UAH", "UGX", "USD", "USN", "UYI", "UYU", "UZS", "VEF", "VND", "VUV", "WST", "XAF", "XAG", "XAU", "XBA", "XBB", "XBC", "XBD", "XCD", "XDR", "XOF", "XPD", "XPF", "XPT", "XSU", "XTS", "XUA", "XXX", "YER", "ZAR", "ZAR", "ZMW", "ZWL" ]; } JsonObject.metaData.addClass( "expression", [ "expression:expression", { name: "format", serializationProperty: "locFormat" }, { name: "displayStyle", default: "none", choices: ["none", "decimal", "currency", "percent"] }, { name: "currency", choices: () => { return getCurrecyCodes(); }, default: "USD" }, { name: "maximumFractionDigits:number", default: -1 }, { name: "minimumFractionDigits:number", default: -1 }, { name: "useGrouping:boolean", default: true }, { name: "commentText", visible: false }, { name: "enableIf", visible: false }, { name: "isRequired", visible: false }, { name: "readOnly", visible: false }, { name: "requiredErrorText", visible: false }, { name: "validators", visible: false } ], function() { return new QuestionExpressionModel(""); }, "question" ); QuestionFactory.Instance.registerQuestion("expression", name => { return new QuestionExpressionModel(name); });
1.953125
2
src/school/school.service.ts
parthchauhan-solutelabs/School
0
1360
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { UsersService } from 'src/users/users.service'; import { Repository } from 'typeorm'; import { CreateSchoolInput } from './dto/create-school.input'; import { UpdateSchoolInput } from './dto/update-school.input'; import { School } from './entities/school.entity'; @Injectable() export class SchoolService { constructor(@InjectRepository(School) private schoolRepository: Repository<School>) {} create(createSchoolInput: CreateSchoolInput) { return 'This action adds a new school'; } findAll() { return `This action returns all school`; } findOne(id: number) { return `This action returns a #${id} school`; } update(id: number, updateSchoolInput: UpdateSchoolInput) { return `This action updates a #${id} school`; } remove(id: number) { return `This action removes a #${id} school`; } }
1.179688
1
WhatYouGotUI/src/app/review-list/review-list.component.ts
200106-UTA-PRS-NET/P2-WhatYouGot
0
1368
import { Component, OnInit } from '@angular/core'; import { ReviewService } from '../Services/fridgethingsServices/review.service'; import { Review } from '../Models/fridgethingsModels/review'; import { ReviewComponent } from '../review/review.component'; import { RecipeService } from '../Services/fridgethingsServices/recipe.service'; import { AccountService } from '../Services/fridgethingsServices/account.service'; @Component({ selector: 'app-review-list', templateUrl: './review-list.component.html', styleUrls: ['./review-list.component.css'] }) export class ReviewListComponent implements OnInit { recipeId = +localStorage.getItem('recipeId'); recipeTitle: string; reviews: Review[] = null; constructor(private reviewService: ReviewService, private recipeService: RecipeService, private accountService: AccountService) { } ngOnInit(): void { this.getReviewsByRecipeId(); this.getRecipeTitle(); } getReviewsByRecipeId(): void { this.reviewService.getReviewsByRecipeId(this.recipeId) .then(reviews => this.reviews = reviews); // getReviews() should be an observable (or maybe not) } deleteReview(id: number): void { this.reviewService.deleteReview(id); } getRecipeTitle(): void { this.recipeService.getRecipeById(this.recipeId) .then(recipe => this.recipeTitle = recipe.title); } }
1.359375
1
store/base.ts
envoylabs/whoami-ui
4
1376
import create, { GetState, SetState } from 'zustand' import { persist, StoreApiWithPersist, devtools } from 'zustand/middleware' import { SigningCosmWasmClient, CosmWasmClient, } from '@cosmjs/cosmwasm-stargate' import { Metadata } from 'util/types/messages' import { OptionString } from 'util/types/base' import * as R from 'ramda' type SCWClientOrNull = SigningCosmWasmClient | null type CWClientOrNull = CosmWasmClient | null interface State { // fields signingClient: SCWClientOrNull nonSigningClient: CWClientOrNull primaryAlias: OptionString walletAddress: OptionString token: Metadata | null tokenIds: string[] tokens: Metadata[] pathIds: string[] paths: Metadata[] // functions setSigningClient: (c: SCWClientOrNull) => void setNonSigningClient: (c: CWClientOrNull) => void setPrimaryAlias: (alias: OptionString) => void setWalletAddress: (address: string) => void setToken: (t: Metadata | null) => void appendTokenId: (tid: string) => void setTokenIds: (tids: string[]) => void appendToken: (t: Metadata) => void setTokens: (ts: Metadata[]) => void appendPathId: (pid: string) => void setPathIds: (pids: string[]) => void appendPath: (p: Metadata) => void setPaths: (ps: Metadata[]) => void } const useStore = create< State, SetState<State>, GetState<State>, StoreApiWithPersist<State> >( devtools( // persist( (set) => ({ signingClient: null, setSigningClient: (client: SCWClientOrNull) => set((state) => ({ signingClient: client })), nonSigningClient: null, setNonSigningClient: (client: CWClientOrNull) => set((state) => ({ nonSigningClient: client })), primaryAlias: null, setPrimaryAlias: (alias: OptionString) => set((state) => ({ primaryAlias: alias })), walletAddress: null, setWalletAddress: (address: OptionString) => set((state) => ({ walletAddress: address })), token: null, setToken: (token: Metadata | null) => set((state) => ({ token: token })), tokenIds: [], appendTokenId: (tokenId: string) => set((state) => ({ tokenIds: R.append(tokenId, state.tokenIds) })), setTokenIds: (tokenIds: string[]) => set((state) => ({ tokenIds: tokenIds })), tokens: [], appendToken: (token: Metadata) => set((state) => ({ tokens: R.append(token, state.tokens) })), setTokens: (tokens: Metadata[]) => set((state) => ({ tokens: tokens })), pathIds: [], appendPathId: (pathId: string) => set((state) => ({ pathIds: R.append(pathId, state.pathIds) })), setPathIds: (pathIds: string[]) => set((state) => ({ pathIds: pathIds })), paths: [], appendPath: (path: Metadata) => set((state) => ({ paths: R.append(path, state.paths) })), setPaths: (paths: Metadata[]) => set((state) => ({ paths: paths })), } as State) //, // { // name: 'dens-storage', // getStorage: () => localStorage, // } // ) ) ) export { useStore }
1.25
1
src/app/@theme/components/index.ts
cloudtrust/mockspital-front
0
1384
export * from './header/header.component'; export * from './footer/footer.component'; export * from './search-input/search-input.component'; export * from './theme-settings/theme-settings.component'; export * from './theme-switcher/theme-switcher.component'; export * from './switcher/switcher.component'; export * from './layout-direction-switcher/layout-direction-switcher.component' export * from './tables/departments-table.component' export * from './tables/doctors-table.component' export * from './tables/files-table.component' export * from './tables/hospitals-table.component' export * from './tables/patients-table.component'
-0.088379
0
src/store/tests/test-data/cat-c/vehicle-checks/vehicle-checks.cat-c.reducer.ts
andrewsetterfield/des-mobile-app
0
1392
import { CatCUniqueTypes } from '@dvsa/mes-test-schema/categories/C'; import { createReducer, on } from '@ngrx/store'; import { dropRight } from 'lodash'; import * as vehicleChecksCatCActionTypes from './vehicle-checks.cat-c.action'; const initialState: CatCUniqueTypes.VehicleChecks = { tellMeQuestions: Array(1).fill({}), showMeQuestions: Array(1).fill({}), vehicleChecksCompleted: null, fullLicenceHeld: null, }; export const generateInitialState = (): CatCUniqueTypes.VehicleChecks => ({ tellMeQuestions: Array(2).fill({}), showMeQuestions: Array(3).fill({}), vehicleChecksCompleted: null, fullLicenceHeld: null, }); export const vehicleChecksCatCReducer = createReducer( initialState, on(vehicleChecksCatCActionTypes.InitialiseVehicleChecks, (): CatCUniqueTypes.VehicleChecks => ({ ...generateInitialState(), })), on(vehicleChecksCatCActionTypes.ShowMeQuestionSelected, (state, { showMeQuestion, index, }): CatCUniqueTypes.VehicleChecks => ({ ...state, showMeQuestions: state.showMeQuestions.map((item, i) => (i === index ? showMeQuestion : item)), })), on(vehicleChecksCatCActionTypes.ShowMeQuestionOutcomeChanged, (state, { showMeQuestionOutcome, index, }): CatCUniqueTypes.VehicleChecks => ({ ...state, showMeQuestions: state.showMeQuestions.map((item, i) => (i === index ? { ...item, outcome: showMeQuestionOutcome, } : item)), })), on(vehicleChecksCatCActionTypes.TellMeQuestionSelected, (state, { tellMeQuestion, index, }): CatCUniqueTypes.VehicleChecks => ({ ...state, tellMeQuestions: state.tellMeQuestions.map((item, i) => (i === index ? tellMeQuestion : item)), })), on(vehicleChecksCatCActionTypes.TellMeQuestionOutcomeChanged, (state, { tellMeQuestionOutcome, index, }): CatCUniqueTypes.VehicleChecks => ({ ...state, tellMeQuestions: state.tellMeQuestions.map((item, i) => (i === index ? { ...item, outcome: tellMeQuestionOutcome, } : item)), })), on(vehicleChecksCatCActionTypes.AddShowMeTellMeComment, (state, { comment, }): CatCUniqueTypes.VehicleChecks => ({ ...state, showMeTellMeComments: comment, })), on(vehicleChecksCatCActionTypes.VehicleChecksCompletedToggled, (state, { toggled, }): CatCUniqueTypes.VehicleChecks => ({ ...state, vehicleChecksCompleted: toggled, })), on(vehicleChecksCatCActionTypes.VehicleChecksDrivingFaultsNumberChanged, (state, { payload, }): CatCUniqueTypes.VehicleChecks => ({ ...state, showMeQuestions: [...payload], })), on(vehicleChecksCatCActionTypes.DropExtraVehicleChecks, (state): CatCUniqueTypes.VehicleChecks => ({ ...state, showMeQuestions: dropRight(state.showMeQuestions, state.showMeQuestions.length - 1), tellMeQuestions: dropRight(state.tellMeQuestions, state.tellMeQuestions.length - 1), })), on(vehicleChecksCatCActionTypes.DropExtraVehicleChecksDelegated, (state): CatCUniqueTypes.VehicleChecks => { const showMeQuestion1 = state.showMeQuestions.shift(); return { ...state, tellMeQuestions: showMeQuestion1 ? [showMeQuestion1] : [], showMeQuestions: state.showMeQuestions || [], }; }), on(vehicleChecksCatCActionTypes.SetFullLicenceHeld, (state, { fullLicenceHeld }): CatCUniqueTypes.VehicleChecks => ({ ...state, fullLicenceHeld, })), );
1.507813
2
ui/src/app/business/user/user-create/user-create.component.ts
Allen-12345/KubeOperator
1
1400
import {Component, EventEmitter, OnInit, Output, ViewChild} from '@angular/core'; import {User, UserCreateRequest} from '../user'; import {BaseModelDirective} from '../../../shared/class/BaseModelDirective'; import {UserService} from '../user.service'; import {NgForm} from '@angular/forms'; import {AlertLevels} from '../../../layout/common-alert/alert'; import {ModalAlertService} from '../../../shared/common-component/modal-alert/modal-alert.service'; import {NamePattern, PasswordPattern} from '../../../constant/pattern'; import {CommonAlertService} from '../../../layout/common-alert/common-alert.service'; import {TranslateService} from '@ngx-translate/core'; @Component({ selector: 'app-user-create', templateUrl: './user-create.component.html', styleUrls: ['./user-create.component.css'] }) export class UserCreateComponent extends BaseModelDirective<User> implements OnInit { opened = false; isSubmitGoing = false; item: UserCreateRequest = new UserCreateRequest(); passwordPattern = PasswordPattern; namePattern = NamePattern; @ViewChild('userForm') userForm: NgForm; @Output() created = new EventEmitter(); private validationStateMap: any = { password: true, rePassword: true, namePwd: true, rePwdCheck: true, }; constructor(private userService: UserService, private modalAlertService: ModalAlertService, private commonAlertService: CommonAlertService, private translateService: TranslateService) { super(userService); } ngOnInit(): void { } public get isValid(): boolean { if (this.userForm && this.userForm.form.get('password')) { return this.userForm.valid && (this.userForm.form.get('password').value === this.userForm.form.get('rePassword').value); } return false; } open() { this.opened = true; this.item = new UserCreateRequest(); this.userForm.resetForm(); } onCancel() { this.opened = false; } getValidationState(key: string): boolean { return this.validationStateMap[key]; } handleValidation(key) { const cont = this.userForm.controls[key]; if (cont && cont.invalid && !cont.hasError) { this.validationStateMap[key] = false; return; } this.validationStateMap[key] = true; if (this.userForm.form.get('password').value === this.userForm.form.get('name').value) { this.userForm.controls['password'].setErrors({namePwdError: false}); this.validationStateMap['namePwd'] = false; return; } else { this.validationStateMap['namePwd'] = true; } const r = /^(?=.*\d)(?=.*[a-zA-Z])[\da-zA-Z~!@#$%^&*]{6,30}$/g; r.lastIndex = 0; if (!r.test(this.userForm.form.get('password').value)) { this.userForm.controls['password'].setErrors({passwordError: false}); this.validationStateMap['password'] = false; return; } else { this.validationStateMap['password'] = true; } if (this.userForm.form.get('rePassword').value !== null && this.userForm.form.get('password').value !== this.userForm.form.get('rePassword').value) { this.userForm.controls[key].setErrors({rePwdError: false}); this.validationStateMap['rePwdCheck'] = false; } else { this.validationStateMap['rePwdCheck'] = true; this.userForm.controls['password'].setErrors(null); this.userForm.controls['rePassword'].setErrors(null); } } onSubmit() { if (this.item.name === this.item.password) { this.modalAlertService.showAlert(this.translateService.instant('USERNAME_PWD_INVALID'), AlertLevels.ERROR); return; } this.isSubmitGoing = true; this.userService.create(this.item).subscribe(data => { this.opened = false; this.isSubmitGoing = false; this.created.emit(); this.commonAlertService.showAlert(this.translateService.instant('APP_ADD_SUCCESS'), AlertLevels.SUCCESS); }, error => { this.isSubmitGoing = false; this.modalAlertService.showAlert(error.error.msg, AlertLevels.ERROR); }); } }
1.40625
1
packages/hedgehog-lab/src/components/YourCode/UploadButton.tsx
Hedgehog-Computing/hedgehog-lab
523
1408
import React, {ChangeEvent} from 'react'; import {IconButton, Tooltip} from "@mui/material"; import {CloudUploadOutlined} from "@mui/icons-material"; interface UploadButtonProps { handleLoadFile: (str: string) => void; } const UploadButton: React.FC<UploadButtonProps> = (props: UploadButtonProps) => { const {handleLoadFile} = props; const handleFileChange = (e: ChangeEvent<HTMLInputElement>) => { const files = e.target.files; if (!files) return; const resultFile = files[0]; const reader = new FileReader(); reader.readAsText(resultFile, 'UTF-8'); reader.onload = function (e) { if (!e.target) return; const fileContent = e.target.result; const reg = /(.md)$/g; if (!fileContent) return; if (reg.test(resultFile.name)) { handleLoadFile(`markdown(\`\n${fileContent as string}\n\`)`); } else { handleLoadFile(fileContent as string); } }; }; return ( <React.Fragment> <input accept=".js,.md" id="contained-button-file" multiple={false} type="file" onChange={handleFileChange} style={{display: "none"}} /> <Tooltip title={'Upload'}> <label htmlFor="contained-button-file"> <IconButton component="span"> <CloudUploadOutlined/> </IconButton> </label> </Tooltip> </React.Fragment> ); }; export default UploadButton;
1.578125
2
facturador-java/src/app/main/reportes/components/historial-cliente/historial-cliente.component.ts
dPanibra0/Facturador-JAVA
0
1416
import { Component, OnInit, Inject } from "@angular/core"; import { MatDialogRef, MAT_DIALOG_DATA } from "@angular/material/dialog"; @Component({ selector: "app-historial-cliente", templateUrl: "./historial-cliente.component.html", styleUrls: ["./historial-cliente.component.scss"], }) export class HistorialClienteComponent implements OnInit { constructor( public dialogRef: MatDialogRef<HistorialClienteComponent>, public deleteElement: MatDialogRef<HistorialClienteComponent>, @Inject(MAT_DIALOG_DATA) public data: any ) {} ngOnInit(): void {} }
0.949219
1
packages/react/src/components/Checkbox/Checkbox.styles.ts
tomkiel/natds-js
3
1424
/* eslint-disable max-len */ /* eslint-disable max-lines-per-function */ import { createUseStyles } from 'react-jss' import { Theme } from '@naturacosmeticos/natds-themes' import { CheckboxProps } from './Checkbox.props' type CheckboxStyleProps = Required<Pick<CheckboxProps, 'indeterminate' | 'disabled'>> const styles = createUseStyles((theme: Theme) => ({ container: { display: 'flex', alignItems: 'center' }, wrapper: { height: theme.size.semiX, width: theme.size.semiX, display: 'flex', alignItems: 'center', justifyContent: 'center' }, checkbox: { appearance: 'none', border: `2px solid ${theme.color.mediumEmphasis}`, borderRadius: theme.checkbox.borderRadius, cursor: 'pointer', display: 'inline-block', height: 18, margin: 0, position: 'relative', width: 18, '&:focus': { outline: 'none' }, '&:disabled': { border: `2px solid ${theme.color.lowEmphasis}`, cursor: 'default' }, '&:checked': { backgroundColor: theme.color.primary, border: `2px solid ${theme.color.primary}`, color: theme.color.surface, '&:after': { content: ({ indeterminate }: CheckboxStyleProps) => (indeterminate ? '"\uea5d"' : '"\uea3c"'), display: 'block', fontFamily: 'natds-icons', fontSize: 18, left: '50%', position: 'absolute', textAlign: 'center', top: '50%', transform: 'translate(-50%, -50%)' }, '&:disabled': { backgroundColor: theme.color.lowEmphasis, border: `2px solid ${theme.color.lowEmphasis}` } } }, labelText: { color: ({ disabled }: CheckboxStyleProps) => (disabled ? theme.color.lowEmphasis : theme.color.highEmphasis), fontFamily: [theme.checkbox.label.primary.fontFamily, theme.checkbox.label.fallback.fontFamily], fontSize: theme.checkbox.label.fontSize, fontWeight: theme.checkbox.label.primary.fontWeight, letterSpacing: theme.checkbox.label.letterSpacing, lineHeight: theme.checkbox.label.lineHeight } })) export default styles
1.5
2
src/medium-collection/trees-and-graphs/kth-smallest-element/test.spec.ts
mkryuk/top-interview-questions
0
1432
import { arrayToTreeNode } from "../../../easy-collection/trees/common"; import { kthSmallest } from "./solution"; it("kthSmallest should return 1 for root = [3,1,4,null,2], k = 1", () => { const root = [3, 1, 4, null, 2], k = 1; const rootTreeNode = arrayToTreeNode(root); const result = kthSmallest(rootTreeNode, k); expect(result).toBe(1); }); it("kthSmallest should return 3 for root = [5,3,6,2,4,null,null,1], k = 3", () => { const root = [5, 3, 6, 2, 4, null, null, 1], k = 3; const rootTreeNode = arrayToTreeNode(root); const result = kthSmallest(rootTreeNode, k); expect(result).toBe(3); }); it("kthSmallest should return 5 for root = [4,2,6,1,3,5,7], k = 5", () => { const root = [4, 2, 6, 1, 3, 5, 7], k = 5; const rootTreeNode = arrayToTreeNode(root); const result = kthSmallest(rootTreeNode, k); expect(result).toBe(5); });
1.28125
1
packages/karrotframe/src/navigator/helpers/getNavigatorParams.ts
daadaadaah/karrotframe
0
1440
export const NavigatorParamKeys = { screenInstanceId: '_si', present: '_present', } export type NavigatorParams = { screenInstanceId: string | null present: boolean } export function getNavigatorParams( searchParams: URLSearchParams ): NavigatorParams { return { screenInstanceId: searchParams.get(NavigatorParamKeys.screenInstanceId), present: searchParams.get(NavigatorParamKeys.present) === 'true', } }
0.964844
1
src/triangle.ts
eduinlight/my-wife-star
0
1448
import Point2D from './point' export default class Triangle { b: Point2D a: Point2D c: Point2D constructor (a: Point2D, b: Point2D, c: Point2D) { this.a = a this.b = b this.c = c } }
0.824219
1
leetcode/00900-00999/00954_array-of-doubled-pairs/Solution.ts
geekhall/algorithms
0
1456
/** * ID: 00954 * Title: Array of Doubled Pairs * Difficulty: Medium * Description: Given an integer array of even length arr, return true if it is possible to reorder arr such that arr[2 * i + 1] = 2 * arr[2 * i] for every 0 <= i < len(arr) / 2, or false otherwise. * * Example 1: * * Input: arr = [3,1,3,6] Output: false * * Example 2: * * Input: arr = [2,1,2,6] Output: false * * Example 3: * * Input: arr = [4,-2,2,-4] Output: true Explanation: We can take two groups, [-2,-4] and [2,4] to form [-2,-4,2,4] or [2,4,-2,-4]. * * Constraints: * * 2 <= arr.length <= 3 * 10 4 * arr.length is even. * -10 5 <= arr[i] <= 10 5 */ function solution() { } function test_00954() { } test_00954()
2.75
3
packages/graphql-playground-react/src/components/Playground/DocExplorer/SearchResults.tsx
danielrearden/graphql-playground
0
1464
import * as React from 'react' import { styled } from '../../../styled' import TypeLink from './TypeLink' export interface Props { schema: any withinType?: any searchValue: string level: number sessionId: string } export default class SearchResults extends React.Component<Props, {}> { shouldComponentUpdate(nextProps) { return ( this.props.schema !== nextProps.schema || this.props.searchValue !== nextProps.searchValue ) } render() { const { level } = this.props const searchValue = this.props.searchValue const withinType = this.props.withinType const schema = this.props.schema const matchedWithin: any[] = [] const matchedTypes: any[] = [] const matchedFields: any[] = [] const typeMap = schema.getTypeMap() let typeNames = Object.keys(typeMap) // Move the within type name to be the first searched. if (withinType) { typeNames = typeNames.filter(n => n !== withinType.name) typeNames.unshift(withinType.name) } let count = 0 for (const typeName of typeNames) { if ( matchedWithin.length + matchedTypes.length + matchedFields.length >= 100 ) { break } const type = typeMap[typeName] if (withinType !== type && (isMatch(typeName, searchValue) || isMatch(type.description, searchValue))) { matchedTypes.push( <div className="doc-category-item" key={typeName}> <TypeLink type={type} x={level} y={count++} lastActive={false} /> </div>, ) } if (type.getFields) { const fields = type.getFields() Object.keys(fields).forEach(fieldName => { const field = fields[fieldName] field.parent = type let matchingArgs if (!isMatch(fieldName, searchValue) && !isMatch(field.description, searchValue)) { if (field.args && field.args.length) { matchingArgs = field.args.filter(arg => isMatch(arg.name, searchValue), ) if (matchingArgs.length === 0) { return } } else { return } } const match = ( <div className="doc-category-item" key={typeName + '.' + fieldName}> <TypeLink key="type" type={field} x={level} y={count++} showParentName={true} lastActive={false} /> </div> ) if (withinType === type) { matchedWithin.push(match) } else { matchedFields.push(match) } }) } } if ( matchedWithin.length + matchedTypes.length + matchedFields.length === 0 ) { return <NoResult>No results found.</NoResult> } if (withinType && matchedTypes.length + matchedFields.length > 0) { return ( <div> {matchedWithin} <div className="doc-category"> <div className="doc-category-title">{'other results'}</div> {matchedTypes} {matchedFields} </div> </div> ) } return ( <div> {matchedWithin} {matchedTypes} {matchedFields} </div> ) } } function isMatch(sourceText, searchValue) { try { const escaped = searchValue.replace(/[^_0-9A-Za-z]/g, ch => '\\' + ch) return sourceText.search(new RegExp(escaped, 'i')) !== -1 } catch (e) { return sourceText.toLowerCase().indexOf(searchValue.toLowerCase()) !== -1 } } const NoResult = styled.span` display: block; margin-top: 16px; margin-left: 16px; `
1.65625
2
frontend/node_modules/@popperjs/core/lib/modifiers/arrow.d.ts
lubitelpospat/CFM-source
5
1472
import { Modifier, Padding } from "../types"; declare type Options = { element: HTMLElement | string; padding: Padding; }; declare const _default: Modifier<Options>; export default _default;
0.414063
0
util/mxMouseEvent.d.ts
vuongddang/mxgraph-type-definitions
23
1480
declare class mxMouseEvent { constructor(evt: Event, state?: mxCellState); /** * Variable: consumed * * Holds the consumed state of this event. */ consumed: boolean; /** * Variable: evt * * Holds the inner event object. */ evt: Event; /** * Variable: graphX * * Holds the x-coordinate of the event in the graph. This value is set in * <mxGraph.fireMouseEvent>. */ graphX: number; /** * Variable: graphY * * Holds the y-coordinate of the event in the graph. This value is set in * <mxGraph.fireMouseEvent>. */ graphY: number; /** * Variable: state * * Holds the optional <mxCellState> associated with this event. */ state: mxCellState; /** * Variable: sourceState * * Holds the <mxCellState> that was passed to the constructor. This can be * different from <state> depending on the result of <mxGraph.getEventState>. */ sourceState: mxCellState; /** * Function: getEvent * * Returns <evt>. */ getEvent(): MouseEvent; /** * Function: getSource * * Returns the target DOM element using <mxEvent.getSource> for <evt>. */ getSource(): Element; /** * Function: isSource * * Returns true if the given <mxShape> is the source of <evt>. */ isSource(shape: mxShape): boolean; /** * Function: getX * * Returns <evt.clientX>. */ getX(): number; /** * Function: getY * * Returns <evt.clientY>. */ getY(): number; /** * Function: getGraphX * * Returns <graphX>. */ getGraphX(): number; /** * Function: getGraphY * * Returns <graphY>. */ getGraphY(): number; /** * Function: getState * * Returns <state>. */ getState(): mxCellState; /** * Function: getCell * * Returns the <mxCell> in <state> is not null. */ getCell(): mxCell; /** * Function: isPopupTrigger * * Returns true if the event is a popup trigger. */ isPopupTrigger(): boolean; /** * Function: isConsumed * * Returns <consumed>. */ isConsumed(): boolean; /** * Function: consume * * Sets <consumed> to true and invokes preventDefault on the native event * if such a method is defined. This is used mainly to avoid the cursor from * being changed to a text cursor in Webkit. You can use the preventDefault * flag to disable this functionality. * * Parameters: * * preventDefault - Specifies if the native event should be canceled. Default * is true. */ consume(preventDefault?: boolean): void; }
1.96875
2
pages/post/[slug].tsx
ConnieML/rtc.admin
0
1488
import { GetStaticPathsResult, GetStaticPropsContext } from 'next'; import React from 'react'; import { fetchGraphQL, gql } from '../../utils'; import { DocumentRenderer } from '../../schema/fields/content/renderers'; import { Container, HomeLink } from '../../components/ui/layout'; import { Link } from '../../components/ui/link'; import { H1 } from '../../components/ui/typography'; export default function Post({ post }: { post: any }) { return ( <Container> <HomeLink /> <article> <H1>{post.title}</H1> {post.author?.name && ( <p> By <span className="font-bold">{post.author.name}</span> </p> )} {post.content?.document && ( <DocumentRenderer document={post.content.document} /> )} </article> </Container> ); } export async function getStaticPaths(): Promise<GetStaticPathsResult> { const data = await fetchGraphQL( gql` query { allPosts { slug } } ` ); return { paths: data.allPosts.map((post: any) => ({ params: { slug: post.slug } })), fallback: 'blocking', }; } export async function getStaticProps({ params }: GetStaticPropsContext) { const data = await fetchGraphQL( gql` query ($slug: String!) { Post(where: { slug: $slug }) { title content { document(hydrateRelationships: true) } publishedDate author { id name } } } `, { slug: params!.slug } ); return { props: { post: data.Post }, revalidate: 60 }; }
1.476563
1
packages/webpack-aspects/__tests__/utils/ensureRules.test.ts
demiazz/react-dev-env
0
1496
import { Configuration, RuleSetRule } from "webpack"; import { ensureRules } from "../../src/utils"; describe("utils", () => { describe("ensureRules", () => { describe('when configuration have no "module" property', () => { let configuration: Configuration; beforeEach(() => { configuration = {}; }); it("adds property", () => { ensureRules(configuration); expect(configuration.module?.rules).toEqual([]); }); it("returns property", () => { const rules = ensureRules(configuration); expect(rules).toBe(configuration.module?.rules); }); }); describe('when configuration have "module" property, but have no "module.rules" property', () => { let configuration: Configuration; beforeEach(() => { configuration = { module: {} } as Configuration; }); it("adds property", () => { ensureRules(configuration); expect(configuration.module?.rules).toEqual([]); }); it("returns property", () => { const rules = ensureRules(configuration); expect(rules).toBe(configuration.module?.rules); }); }); describe('when configuration have "module.rules" property', () => { let configuration: Configuration; let rules: RuleSetRule[]; beforeEach(() => { rules = [ { test: /\.js$/, use: "babel-loader" } ]; configuration = { module: { rules } }; }); it("don't change property", () => { ensureRules(configuration); expect(configuration.module?.rules).toEqual(rules); }); it("returns property", () => { const rules = ensureRules(configuration); expect(rules).toBe(configuration.module?.rules); }); }); }); });
1.3125
1
src/legacy/connect/endpoints.ts
Antondj5/mbed-cloud-sdk-javascript
10
1504
/* * Pelion Device Management JavaScript SDK * Copyright Arm Limited 2017 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { ConfigOptions } from "../../common/config"; import { DeviceRequestsApi, EndpointsApi, NotificationsApi, ResourcesApi, SubscriptionsApi } from "../_api/mds"; import { AccountApi, StatisticsApi } from "../_api/statistics"; import { EndpointsBase } from "../common/endpointsBase"; export class Endpoints extends EndpointsBase { public endpoints: EndpointsApi; public deviceRequests: DeviceRequestsApi; public notifications: NotificationsApi; public resources: ResourcesApi; public subscriptions: SubscriptionsApi; public account: AccountApi; public statistics: StatisticsApi; constructor(options?: ConfigOptions) { super(); this.endpoints = new EndpointsApi(options, this.responseHandler.bind(this)); this.deviceRequests = new DeviceRequestsApi(options, this.responseHandler.bind(this)); this.notifications = new NotificationsApi(options, this.responseHandler.bind(this)); this.resources = new ResourcesApi(options, this.responseHandler.bind(this)); this.subscriptions = new SubscriptionsApi(options, this.responseHandler.bind(this)); this.account = new AccountApi(options, this.responseHandler.bind(this)); this.statistics = new StatisticsApi(options, this.responseHandler.bind(this)); } }
1.132813
1
server/git-service/src/utils/repoInfo.ts
oda404/gity-fullstack
0
1512
export interface RepoInfo { owner: string; name: string; }
0.294922
0
types/d3-scale/v1/d3-scale-tests.ts
fes300/DefinitelyTyped
35,620
1520
/** * Typescript definition tests for d3/d3-scale module * * Note: These tests are intended to test the definitions only * in the sense of typing and call signature consistency. They * are not intended as functional tests. */ import * as d3Scale from 'd3-scale'; import { interpolateCubehelix } from 'd3-interpolate'; import { timeHour } from 'd3-time'; import { schemePuRd } from 'd3-scale-chromatic'; // ------------------------------------------------------------------------------- // Preparatory Steps // ------------------------------------------------------------------------------- class NumCoercible { a: number; constructor(a: number) { this.a = a; } valueOf() { return this.a; } } class StringCoercible { txt: string; constructor(txt: string) { this.txt = txt; } toString() { return this.txt; } } let num: number; let date: Date; let clampFlag: boolean; let outputNumber: number; let outputString: string; let domainNumbers: number[] = [1, 100]; const domainNumeric: NumCoercible[] = [new NumCoercible(0), new NumCoercible(100)]; let domainStrings: string[]; let domainDates: Date[] = [new Date(2016, 0, 15), new Date(2016, 5, 15)]; let ticksNumbers: number[]; let ticksDates: Date[]; let tickFormatNumberFn: ((d: number | { valueOf(): number }) => string); let tickFormatDateFn: ((d: Date) => string); let rangeNumbers: number[] = [2, 200]; let rangeStrings: string[] = ['2px', '200px']; let numExtent: [number, number]; let numOrUndefinedExtent: [number | undefined, number | undefined]; let outputNumberMaybe: number | undefined; // ------------------------------------------------------------------------------- // Linear Scale Factory // ------------------------------------------------------------------------------- // scaleLinear() ----------------------------------------------------------------- let linearScaleNumber: d3Scale.ScaleLinear<number, number>; let linearScaleString: d3Scale.ScaleLinear<string, string>; let linearScaleNumString: d3Scale.ScaleLinear<number, string>; linearScaleNumber = d3Scale.scaleLinear(); linearScaleString = d3Scale.scaleLinear<string>(); linearScaleNumString = d3Scale.scaleLinear<number, string>(); // ScaleLinear Interface ======================================================== // domain(...) ----------------------------------------------------------------- linearScaleNumber = linearScaleNumber.domain(domainNumeric); linearScaleNumber = linearScaleNumber.domain(domainNumbers); domainNumbers = linearScaleNumber.domain(); linearScaleString = linearScaleString.domain(domainNumeric); linearScaleString = linearScaleString.domain([10, 100]); domainNumbers = linearScaleString.domain(); linearScaleNumString = linearScaleNumString.domain(domainNumeric); linearScaleNumString = linearScaleNumString.domain(domainNumbers); domainNumbers = linearScaleNumString.domain(); // range(...) ----------------------------------------------------------------- linearScaleNumber = linearScaleNumber.range(rangeNumbers); rangeNumbers = linearScaleNumber.range(); linearScaleString = linearScaleString.range(['steelblue', 'brown']); rangeStrings = linearScaleString.range(); linearScaleNumString = linearScaleNumString.range(rangeNumbers); rangeNumbers = linearScaleNumString.range(); // invert(...) ----------------------------------------------------------------- num = linearScaleNumber.invert(500); // has number range, so inversion is possible num = linearScaleNumber.invert(new NumCoercible(500)); // has number range, so inversion is possible num = linearScaleNumString.invert(500); // has number range, so inversion is possible num = linearScaleNumString.invert(new NumCoercible(500)); // has number range, so inversion is possible // rangeRound(...) ----------------------------------------------------------------- linearScaleNumber = linearScaleNumber.rangeRound(rangeNumbers); // clamp(...) ----------------------------------------------------------------- linearScaleNumber = linearScaleNumber.clamp(true); clampFlag = linearScaleNumber.clamp(); // interpolate(...) ----------------------------------------------------------------- linearScaleString = linearScaleString.interpolate(interpolateCubehelix.gamma(3)); linearScaleNumString = linearScaleNumString.interpolate((a, b) => { // take two numbers return (t: number) => (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type }); // Changes scale output type (inferred generic) linearScaleNumString = linearScaleNumber.interpolate((a, b) => { // take two numbers return (t: number) => (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type }); // nice(...) ----------------------------------------------------------------------- // chainable linearScaleNumber = linearScaleNumber.nice(); linearScaleNumber = linearScaleNumber.nice(5); // ticks(...) ----------------------------------------------------------------- ticksNumbers = linearScaleNumber.ticks(); ticksNumbers = linearScaleNumber.ticks(5); // tickFormat(...) ----------------------------------------------------------------- tickFormatNumberFn = linearScaleNumber.tickFormat(); tickFormatNumberFn = linearScaleNumber.tickFormat(5); tickFormatNumberFn = linearScaleNumber.tickFormat(5, '+%'); // (...) value mapping from domain to output ----------------------------------- outputNumber = linearScaleNumber(10); outputString = linearScaleString(10); outputString = linearScaleNumString(10); // copy(...) ----------------------------------------------------------------- const copiedLinearScale: d3Scale.ScaleLinear<number, string> = linearScaleNumString.copy(); // ------------------------------------------------------------------------------- // Power Scale Factories // ------------------------------------------------------------------------------- // scalePow() and scaleSqrt() ---------------------------------------------------- let powerScaleNumber: d3Scale.ScalePower<number, number>; let powerScaleString: d3Scale.ScalePower<string, string>; let powerScaleNumString: d3Scale.ScalePower<number, string>; powerScaleNumber = d3Scale.scalePow(); powerScaleString = d3Scale.scalePow<string>(); powerScaleNumString = d3Scale.scalePow<number, string>(); let squarerootScaleNumber: d3Scale.ScalePower<number, number>; let squarerootScaleString: d3Scale.ScalePower<string, string>; let squarerootScaleNumString: d3Scale.ScalePower<number, string>; squarerootScaleNumber = d3Scale.scaleSqrt(); squarerootScaleString = d3Scale.scaleSqrt<string>(); squarerootScaleNumString = d3Scale.scaleSqrt<number, string>(); // ScalePower Interface ======================================================== // exponent -------------------------------------------------------------------- const exponent: number = squarerootScaleNumber.exponent(); powerScaleNumber = powerScaleNumber.exponent(5); // domain(...) ----------------------------------------------------------------- powerScaleNumber = powerScaleNumber.domain(domainNumeric); powerScaleNumber = powerScaleNumber.domain(domainNumbers); domainNumbers = powerScaleNumber.domain(); powerScaleString = powerScaleString.domain(domainNumeric); powerScaleString = powerScaleString.domain([10, 100]); domainNumbers = powerScaleString.domain(); powerScaleNumString = powerScaleNumString.domain(domainNumeric); powerScaleNumString = powerScaleNumString.domain(domainNumbers); domainNumbers = powerScaleNumString.domain(); // range(...) ----------------------------------------------------------------- powerScaleNumber = powerScaleNumber.range(rangeNumbers); rangeNumbers = powerScaleNumber.range(); powerScaleString = powerScaleString.range(['steelblue', 'brown']); rangeStrings = powerScaleString.range(); powerScaleNumString = powerScaleNumString.range(rangeNumbers); rangeNumbers = powerScaleNumString.range(); // invert(...) ----------------------------------------------------------------- num = powerScaleNumber.invert(500); // has number range, so inversion is possible num = powerScaleNumber.invert(new NumCoercible(500)); // has number range, so inversion is possible num = powerScaleNumString.invert(500); // has number range, so inversion is possible num = powerScaleNumString.invert(new NumCoercible(500)); // has number range, so inversion is possible // rangeRound(...) ----------------------------------------------------------------- powerScaleNumber = powerScaleNumber.rangeRound(rangeNumbers); // clamp(...) ----------------------------------------------------------------- powerScaleNumber = powerScaleNumber.clamp(true); clampFlag = powerScaleNumber.clamp(); // interpolate(...) ----------------------------------------------------------------- powerScaleString = powerScaleString.interpolate(interpolateCubehelix.gamma(3)); powerScaleNumString = powerScaleNumString.interpolate((a, b) => { // take two numbers return (t: number) => (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type }); // nice(...) ----------------------------------------------------------------------- // chainable powerScaleNumber = powerScaleNumber.nice(); powerScaleNumber = powerScaleNumber.nice(5); // ticks(...) ----------------------------------------------------------------- ticksNumbers = powerScaleNumber.ticks(); ticksNumbers = powerScaleNumber.ticks(5); // tickFormat(...) ----------------------------------------------------------------- tickFormatNumberFn = powerScaleNumber.tickFormat(); tickFormatNumberFn = powerScaleNumber.tickFormat(5); tickFormatNumberFn = powerScaleNumber.tickFormat(5, '+%'); // (...) value mapping from domain to output ----------------------------------- outputNumber = powerScaleNumber(10); outputString = powerScaleString(10); outputString = powerScaleNumString(10); // copy(...) ----------------------------------------------------------------- const copiedPowerScale: d3Scale.ScalePower<number, string> = powerScaleNumString.copy(); // ------------------------------------------------------------------------------- // Logarithmic Scale Factory // ------------------------------------------------------------------------------- // scaleLog() --------------------------------------------------------------------- let logScaleNumber: d3Scale.ScaleLogarithmic<number, number>; let logScaleString: d3Scale.ScaleLogarithmic<string, string>; let logScaleNumString: d3Scale.ScaleLogarithmic<number, string>; logScaleNumber = d3Scale.scaleLog(); logScaleString = d3Scale.scaleLog<string>(); logScaleNumString = d3Scale.scaleLog<number, string>(); // ScaleLogarithmic Interface ======================================================== // base -------------------------------------------------------------------- const base: number = logScaleNumber.base(); logScaleNumber = logScaleNumber.base(42); // domain(...) ----------------------------------------------------------------- logScaleNumber = logScaleNumber.domain(domainNumeric); logScaleNumber = logScaleNumber.domain(domainNumbers); domainNumbers = logScaleNumber.domain(); logScaleString = logScaleString.domain(domainNumeric); logScaleString = logScaleString.domain([10, 100]); domainNumbers = logScaleString.domain(); logScaleNumString = logScaleNumString.domain(domainNumeric); logScaleNumString = logScaleNumString.domain(domainNumbers); domainNumbers = logScaleNumString.domain(); // range(...) ----------------------------------------------------------------- logScaleNumber = logScaleNumber.range(rangeNumbers); rangeNumbers = logScaleNumber.range(); logScaleString = logScaleString.range(['steelblue', 'brown']); rangeStrings = logScaleString.range(); logScaleNumString = logScaleNumString.range(rangeNumbers); rangeNumbers = logScaleNumString.range(); // invert(...) ----------------------------------------------------------------- num = logScaleNumber.invert(500); // has number range, so inversion is possible num = logScaleNumber.invert(new NumCoercible(500)); // has number range, so inversion is possible num = logScaleNumString.invert(500); // has number range, so inversion is possible num = logScaleNumString.invert(new NumCoercible(500)); // has number range, so inversion is possible // rangeRound(...) ----------------------------------------------------------------- logScaleNumber = logScaleNumber.rangeRound(rangeNumbers); // clamp(...) ----------------------------------------------------------------- logScaleNumber = logScaleNumber.clamp(true); clampFlag = logScaleNumber.clamp(); // interpolate(...) ----------------------------------------------------------------- logScaleString = logScaleString.interpolate(interpolateCubehelix.gamma(3)); logScaleNumString = logScaleNumString.interpolate((a, b) => { // take two numbers return (t: number) => (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type }); // nice(...) ----------------------------------------------------------------------- // chainable logScaleNumber = logScaleNumber.nice(); // logScaleNumber = logScaleNumber.nice(5); // fails, logarithmic scale does not support count parameter. // ticks(...) ----------------------------------------------------------------- ticksNumbers = logScaleNumber.ticks(); ticksNumbers = logScaleNumber.ticks(5); // tickFormat(...) ----------------------------------------------------------------- tickFormatNumberFn = logScaleNumber.tickFormat(); tickFormatNumberFn = logScaleNumber.tickFormat(5); tickFormatNumberFn = logScaleNumber.tickFormat(5, '+%'); // (...) value mapping from domain to output ----------------------------------- outputNumber = logScaleNumber(10); outputString = logScaleString(10); outputString = logScaleNumString(10); // copy(...) ----------------------------------------------------------------- const copiedLogScale: d3Scale.ScaleLogarithmic<number, string> = logScaleNumString.copy(); // ------------------------------------------------------------------------------- // Identity Scale Factory // ------------------------------------------------------------------------------- // scaleIdentity ----------------------------------------------------------------- let identityScale: d3Scale.ScaleIdentity; identityScale = d3Scale.scaleIdentity(); // ScaleIdentity Interface ======================================================== // domain(...) ----------------------------------------------------------------- identityScale = identityScale.domain(domainNumeric); identityScale = identityScale.domain(domainNumbers); domainNumbers = identityScale.domain(); // range(...) ----------------------------------------------------------------- identityScale = identityScale.range(rangeNumbers); rangeNumbers = identityScale.range(); // invert(...) ----------------------------------------------------------------- num = identityScale.invert(500); // has number range, so inversion is possible num = identityScale.invert(new NumCoercible(500)); // has number range, so inversion is possible // nice(...) ----------------------------------------------------------------------- // chainable identityScale = identityScale.nice(); identityScale = identityScale.nice(5); // ticks(...) ----------------------------------------------------------------- ticksNumbers = identityScale.ticks(); ticksNumbers = identityScale.ticks(5); // tickFormat(...) ----------------------------------------------------------------- tickFormatNumberFn = identityScale.tickFormat(); tickFormatNumberFn = identityScale.tickFormat(5); tickFormatNumberFn = identityScale.tickFormat(5, '+%'); // (...) value mapping from domain to output ----------------------------------- outputNumber = identityScale(10); // copy(...) ----------------------------------------------------------------- const copiedIdentityScale: d3Scale.ScaleIdentity = identityScale.copy(); // ------------------------------------------------------------------------------- // Time Scale Factories // ------------------------------------------------------------------------------- // scaleTime() and scaleUtc() ---------------------------------------------------- let localTimeScaleNumber: d3Scale.ScaleTime<number, number>; let localTimeScaleString: d3Scale.ScaleTime<string, string>; let localTimeScaleNumString: d3Scale.ScaleTime<number, string>; localTimeScaleNumber = d3Scale.scaleTime(); localTimeScaleString = d3Scale.scaleTime<string>(); localTimeScaleNumString = d3Scale.scaleTime<number, string>(); let utcScaleNumber: d3Scale.ScaleTime<number, number>; let utcScaleString: d3Scale.ScaleTime<string, string>; let utcScaleNumString: d3Scale.ScaleTime<number, string>; utcScaleNumber = d3Scale.scaleUtc(); utcScaleString = d3Scale.scaleUtc<string>(); utcScaleNumString = d3Scale.scaleUtc<number, string>(); // domain(...) ----------------------------------------------------------------- localTimeScaleNumber = localTimeScaleNumber.domain(domainDates); domainDates = localTimeScaleNumber.domain(); localTimeScaleString = localTimeScaleString.domain([new Date(2016, 6, 1), Date.now()]); domainDates = localTimeScaleString.domain(); localTimeScaleNumString = localTimeScaleNumString.domain(domainDates); domainDates = localTimeScaleNumString.domain(); // range(...) ----------------------------------------------------------------- localTimeScaleNumber = localTimeScaleNumber.range(rangeNumbers); rangeNumbers = localTimeScaleNumber.range(); localTimeScaleString = localTimeScaleString.range(['steelblue', 'brown']); rangeStrings = localTimeScaleString.range(); localTimeScaleNumString = localTimeScaleNumString.range(rangeNumbers); rangeNumbers = localTimeScaleNumString.range(); // invert(...) ----------------------------------------------------------------- date = localTimeScaleNumber.invert(500); // has number range, so inversion is possible date = localTimeScaleNumber.invert(new NumCoercible(500)); // has number range, so inversion is possible date = localTimeScaleNumString.invert(500); // has number range, so inversion is possible date = localTimeScaleNumString.invert(new NumCoercible(500)); // has number range, so inversion is possible // rangeRound(...) ----------------------------------------------------------------- localTimeScaleNumber = localTimeScaleNumber.rangeRound(rangeNumbers); // clamp(...) ----------------------------------------------------------------- localTimeScaleNumber = localTimeScaleNumber.clamp(true); clampFlag = localTimeScaleNumber.clamp(); // interpolate(...) ----------------------------------------------------------------- localTimeScaleString = localTimeScaleString.interpolate(interpolateCubehelix.gamma(3)); localTimeScaleNumString = localTimeScaleNumString.interpolate((a, b) => { // take two numbers return (t: number) => (a * (1 - t) + b * t) + 'px'; // a and b are numbers based on Range Type, return value of interpolator is string based on Output type }); // nice(...) ----------------------------------------------------------------------- // chainable localTimeScaleNumber = localTimeScaleNumber.nice(); localTimeScaleNumber = localTimeScaleNumber.nice(5); localTimeScaleNumber = localTimeScaleNumber.nice(timeHour); localTimeScaleNumber = localTimeScaleNumber.nice(timeHour, 5); // localTimeScaleNumber = localTimeScaleNumber.nice(timeHour.every(5)); // fails, requires CountableTimeInterval // ticks(...) ----------------------------------------------------------------- const timeInterval = timeHour.every(5); ticksDates = localTimeScaleNumber.ticks(); ticksDates = localTimeScaleNumber.ticks(50); if (timeInterval !== null) { ticksDates = localTimeScaleNumString.ticks(timeInterval); } // tickFormat(...) ----------------------------------------------------------------- tickFormatDateFn = localTimeScaleNumber.tickFormat(); tickFormatDateFn = localTimeScaleNumber.tickFormat(50, '%I %p'); if (timeInterval !== null) { tickFormatDateFn = localTimeScaleNumber.tickFormat(timeInterval, '%I %p'); } // (...) value mapping from domain to output ----------------------------------- outputNumber = localTimeScaleNumber(new Date(2016, 6, 4)); outputString = localTimeScaleString(new Date(2016, 6, 4)); outputString = localTimeScaleNumString(new Date(2016, 6, 4)); // copy(...) ----------------------------------------------------------------- const copiedTimeScale: d3Scale.ScaleTime<number, string> = localTimeScaleNumString.copy(); // ------------------------------------------------------------------------------- // Sequential Scale Factory // ------------------------------------------------------------------------------- // scaleSequential() ----------------------------------------------------------------- let sequentialScaleColorString: d3Scale.ScaleSequential<string>; sequentialScaleColorString = d3Scale.scaleSequential<string>(d3Scale.interpolateRainbow); sequentialScaleColorString = d3Scale.scaleSequential(d3Scale.interpolateCool); // inferred Output type string // ScaleSequential Interface ======================================================== // domain(...) ----------------------------------------------------------------- sequentialScaleColorString = sequentialScaleColorString.domain([0, 1]); sequentialScaleColorString = sequentialScaleColorString.domain([new NumCoercible(0), new NumCoercible(100)]); const domainSequential: [number, number] = sequentialScaleColorString.domain(); // clamp(...) ----------------------------------------------------------------- sequentialScaleColorString = sequentialScaleColorString.clamp(true); clampFlag = sequentialScaleColorString.clamp(); // interpolate(...) ----------------------------------------------------------------- sequentialScaleColorString = sequentialScaleColorString.interpolator(d3Scale.interpolateInferno); let sequentialInterpolator: (t: number) => string; sequentialInterpolator = sequentialScaleColorString.interpolator(); // (...) value mapping from domain to output ----------------------------------- outputString = sequentialScaleColorString(10); // copy(...) ----------------------------------------------------------------- const copiedSequentialScale: d3Scale.ScaleSequential<string> = sequentialScaleColorString.copy(); // ------------------------------------------------------------------------------- // Color Interpolators for Sequential Scale Factory // ------------------------------------------------------------------------------- let colorInterpolator: ((t: number) => string); colorInterpolator = d3Scale.interpolateViridis; colorInterpolator = d3Scale.interpolateMagma; colorInterpolator = d3Scale.interpolateInferno; colorInterpolator = d3Scale.interpolatePlasma; colorInterpolator = d3Scale.interpolateRainbow; colorInterpolator = d3Scale.interpolateWarm; colorInterpolator = d3Scale.interpolateCool; colorInterpolator = d3Scale.interpolateCubehelixDefault; // ------------------------------------------------------------------------------- // Quantize Scale Factory // ------------------------------------------------------------------------------- // scaleQuantize() ----------------------------------------------------------------- let quantizeScaleNumber: d3Scale.ScaleQuantize<number>; let quantizeScaleString: d3Scale.ScaleQuantize<string>; quantizeScaleNumber = d3Scale.scaleQuantize(); quantizeScaleString = d3Scale.scaleQuantize<string>(); // ScaleQuantize Interface ======================================================== // domain(...) ----------------------------------------------------------------- quantizeScaleNumber = quantizeScaleNumber.domain([0, 1]); quantizeScaleNumber = quantizeScaleNumber.domain([new NumCoercible(0), new NumCoercible(100)]); const domainQuantize: [number, number] = quantizeScaleNumber.domain(); // range(...) ----------------------------------------------------------------- quantizeScaleNumber = quantizeScaleNumber.range(rangeNumbers); rangeNumbers = quantizeScaleNumber.range(); quantizeScaleString = quantizeScaleString.range(['steelblue', 'brown']); rangeStrings = quantizeScaleString.range(); // invertExtent(...) ----------------------------------------------------------------- numExtent = quantizeScaleNumber.invertExtent(500); numExtent = quantizeScaleString.invertExtent('steelblue'); // nice(...) ----------------------------------------------------------------------- // chainable quantizeScaleNumber = quantizeScaleNumber.nice(); quantizeScaleNumber = quantizeScaleNumber.nice(5); // ticks(...) ----------------------------------------------------------------- ticksNumbers = quantizeScaleNumber.ticks(); ticksNumbers = quantizeScaleNumber.ticks(5); // tickFormat(...) ----------------------------------------------------------------- tickFormatNumberFn = quantizeScaleNumber.tickFormat(); tickFormatNumberFn = quantizeScaleNumber.tickFormat(5); tickFormatNumberFn = quantizeScaleNumber.tickFormat(5, '+%'); // (...) value mapping from domain to output ----------------------------------- outputNumber = quantizeScaleNumber(0.51); // copy(...) ----------------------------------------------------------------- const copiedQuantizeScale: d3Scale.ScaleQuantize<number> = quantizeScaleNumber.copy(); // ------------------------------------------------------------------------------- // Quantile Scale Factory // ------------------------------------------------------------------------------- // scaleQuantile() ----------------------------------------------------------------- let quantileScaleNumber: d3Scale.ScaleQuantile<number>; let quantileScaleString: d3Scale.ScaleQuantile<string>; quantileScaleNumber = d3Scale.scaleQuantile(); quantileScaleString = d3Scale.scaleQuantile<string>(); // ScaleQuantile Interface ======================================================== // domain(...) ----------------------------------------------------------------- quantileScaleNumber = quantileScaleNumber.domain(domainNumbers); domainNumbers = quantileScaleNumber.domain(); quantileScaleString = quantileScaleString.domain(domainNumeric); // range(...) ----------------------------------------------------------------- quantileScaleNumber = quantileScaleNumber.range([1, 2, 3, 4]); rangeNumbers = quantileScaleNumber.range(); quantileScaleString = quantileScaleString.range(['q25', 'q50', 'q75']); rangeStrings = quantileScaleString.range(); // invertExtent(...) ----------------------------------------------------------------- numExtent = quantileScaleNumber.invertExtent(2); numExtent = quantileScaleString.invertExtent('q50'); // quantile() ----------------------------------------------------------------------- const quantiles: number[] = quantileScaleNumber.quantiles(); // (...) value mapping from domain to output ----------------------------------- outputNumber = quantileScaleNumber(0.51); // copy(...) ----------------------------------------------------------------- const copiedQuantileScale: d3Scale.ScaleQuantile<number> = quantileScaleNumber.copy(); // ------------------------------------------------------------------------------- // Threshold Scale Factory // ------------------------------------------------------------------------------- // scaleThreshold() ----------------------------------------------------------------- let thresholdScaleNumberNumber: d3Scale.ScaleThreshold<number, number>; let thresholdScaleNumberString: d3Scale.ScaleThreshold<number, string>; thresholdScaleNumberNumber = d3Scale.scaleThreshold(); thresholdScaleNumberString = d3Scale.scaleThreshold<number, string>(); // ScaleThreshold Interface ======================================================== // domain(...) ----------------------------------------------------------------- thresholdScaleNumberNumber = thresholdScaleNumberNumber.domain([0.5]); domainNumbers = thresholdScaleNumberNumber.domain(); thresholdScaleNumberString = thresholdScaleNumberString.domain([0.2, 0.8]); // range(...) ----------------------------------------------------------------- thresholdScaleNumberNumber = thresholdScaleNumberNumber.range([100, 200]); rangeNumbers = thresholdScaleNumberNumber.range(); thresholdScaleNumberString = thresholdScaleNumberString.range(['steelblue', 'seagreen', 'brown']); rangeStrings = thresholdScaleNumberString.range(); // invertExtent(...) ----------------------------------------------------------------- numOrUndefinedExtent = thresholdScaleNumberNumber.invertExtent(100); numOrUndefinedExtent = thresholdScaleNumberString.invertExtent('seagreen'); // (...) value mapping from domain to output ----------------------------------- outputNumber = thresholdScaleNumberNumber(0.51); outputString = thresholdScaleNumberString(0.9); // copy(...) ----------------------------------------------------------------- const copiedThresholdScale: d3Scale.ScaleThreshold<number, string> = thresholdScaleNumberString.copy(); // ------------------------------------------------------------------------------- // Ordinal Scale Factory // ------------------------------------------------------------------------------- // scaleOrdinal() ----------------------------------------------------------------- let ordinalScaleStringString: d3Scale.ScaleOrdinal<string, string>; let ordinalScaleStringNumber: d3Scale.ScaleOrdinal<string, number>; ordinalScaleStringString = d3Scale.scaleOrdinal<string>(); ordinalScaleStringString = d3Scale.scaleOrdinal<string>(schemePuRd[3]); ordinalScaleStringNumber = d3Scale.scaleOrdinal<string, number>(); ordinalScaleStringString = d3Scale.scaleOrdinal<string, string>(schemePuRd[3]); // ScaleOrdinal Interface ======================================================== // domain(...) ----------------------------------------------------------------- ordinalScaleStringString = ordinalScaleStringString.domain(['negative', 'neutral', 'positive']); domainStrings = ordinalScaleStringString.domain(); ordinalScaleStringNumber = ordinalScaleStringNumber.domain(['negative', 'neutral', 'positive']); // range(...) ----------------------------------------------------------------- ordinalScaleStringString = ordinalScaleStringString.range(['crimson', 'midnightblue', 'seagreen']); ordinalScaleStringString = ordinalScaleStringString.range(schemePuRd[3]); rangeStrings = ordinalScaleStringString.range(); ordinalScaleStringNumber = ordinalScaleStringNumber.range([-1, 0, 1]); rangeNumbers = ordinalScaleStringNumber.range(); // unknown(...) and d3Scale.scaleImplicit -------------------------------------- const implicit: { name: 'implicit' } = d3Scale.scaleImplicit; ordinalScaleStringString = ordinalScaleStringString.unknown(d3Scale.scaleImplicit); ordinalScaleStringNumber = ordinalScaleStringNumber.unknown(0); const unknownValue: string | { name: 'implicit' } = ordinalScaleStringString.unknown(); if (typeof unknownValue === 'string') { console.log(unknownValue); } else { console.log(unknownValue.name); } // (...) value mapping from domain to output ----------------------------------- outputString = ordinalScaleStringString('neutral'); outputNumber = ordinalScaleStringNumber('negative'); // copy(...) ----------------------------------------------------------------- const copiedOrdinalScale: d3Scale.ScaleOrdinal<string, number> = ordinalScaleStringNumber.copy(); // ------------------------------------------------------------------------------- // Band Scale Factory // ------------------------------------------------------------------------------- // scaleBand() ----------------------------------------------------------------- let bandScaleString: d3Scale.ScaleBand<string>; let bandScaleCoercible: d3Scale.ScaleBand<StringCoercible>; bandScaleString = d3Scale.scaleBand(); bandScaleCoercible = d3Scale.scaleBand<StringCoercible>(); // ScaleBand Interface ======================================================== // domain(...) ----------------------------------------------------------------- bandScaleString = bandScaleString.domain(['negative', 'neutral', 'positive']); domainStrings = bandScaleString.domain(); bandScaleCoercible = bandScaleCoercible.domain([new StringCoercible('negative'), new StringCoercible('neutral'), new StringCoercible('positive')]); // range(...) ----------------------------------------------------------------- bandScaleString = bandScaleString.range([0, 300]); let rangeExtent: [number, number] = bandScaleString.range(); bandScaleCoercible = bandScaleCoercible.range([0, 300]); rangeExtent = bandScaleCoercible.range(); // rangeRound(...) ----------------------------------------------------------------- bandScaleString = bandScaleString.rangeRound([0, 300]); // round(...) ----------------------------------------------------------------- bandScaleCoercible = bandScaleCoercible.round(true); let roundingFlag: boolean = bandScaleCoercible.round(); // paddingInner(...) ----------------------------------------------------------------- bandScaleString = bandScaleString.paddingInner(0.1); num = bandScaleString.paddingInner(); // paddingOuter(...) ----------------------------------------------------------------- bandScaleString = bandScaleString.paddingOuter(0.1); num = bandScaleString.paddingOuter(); // padding(...) ----------------------------------------------------------------- bandScaleString = bandScaleString.padding(0.1); num = bandScaleString.padding(); // align(...) ----------------------------------------------------------------- bandScaleString = bandScaleString.align(0.5); num = bandScaleString.align(); // bandwidth(...) ----------------------------------------------------------------- num = bandScaleString.bandwidth(); // step(...) ----------------------------------------------------------------- num = bandScaleString.step(); // (...) value mapping from domain to output ----------------------------------- outputNumberMaybe = bandScaleString('neutral'); outputNumberMaybe = bandScaleCoercible(new StringCoercible('negative')); // copy(...) ----------------------------------------------------------------- const copiedBandScale: d3Scale.ScaleBand<StringCoercible> = bandScaleCoercible.copy(); // ------------------------------------------------------------------------------- // Point Scale Factory // ------------------------------------------------------------------------------- // scalePoint() ----------------------------------------------------------------- let pointScaleString: d3Scale.ScalePoint<string>; let pointScaleCoercible: d3Scale.ScalePoint<StringCoercible>; pointScaleString = d3Scale.scalePoint(); pointScaleCoercible = d3Scale.scalePoint<StringCoercible>(); // ScalePoint Interface ======================================================== // domain(...) ----------------------------------------------------------------- pointScaleString = pointScaleString.domain(['negative', 'neutral', 'positive']); domainStrings = pointScaleString.domain(); pointScaleCoercible = pointScaleCoercible.domain([new StringCoercible('negative'), new StringCoercible('neutral'), new StringCoercible('positive')]); // range(...) ----------------------------------------------------------------- pointScaleString = pointScaleString.range([0, 300]); rangeExtent = pointScaleString.range(); pointScaleCoercible = pointScaleCoercible.range([0, 300]); rangeExtent = pointScaleCoercible.range(); // rangeRound(...) ----------------------------------------------------------------- pointScaleString = pointScaleString.rangeRound([0, 300]); // round(...) ----------------------------------------------------------------- pointScaleCoercible = pointScaleCoercible.round(true); roundingFlag = pointScaleCoercible.round(); // padding(...) ----------------------------------------------------------------- pointScaleString = pointScaleString.padding(0.1); num = pointScaleString.padding(); // align(...) ----------------------------------------------------------------- pointScaleString = pointScaleString.align(0.5); num = pointScaleString.align(); // bandwidth(...) ----------------------------------------------------------------- num = pointScaleString.bandwidth(); // step(...) ----------------------------------------------------------------- num = pointScaleString.step(); // (...) value mapping from domain to output ----------------------------------- outputNumberMaybe = pointScaleString('neutral'); outputNumberMaybe = pointScaleCoercible(new StringCoercible('negative')); // copy(...) ----------------------------------------------------------------- const copiedPointScale: d3Scale.ScalePoint<StringCoercible> = pointScaleCoercible.copy(); // ------------------------------------------------------------------------------- // Categorical Color Schemas for Ordinal Scales // ------------------------------------------------------------------------------- let colorStrings: string[]; colorStrings = d3Scale.schemeCategory10; colorStrings = d3Scale.schemeCategory20; colorStrings = d3Scale.schemeCategory20b; colorStrings = d3Scale.schemeCategory20c;
2
2
packages/search/src/ago/helpers/filters/handle-filter.ts
andrewctate/hub.js
23
1528
import { buildFilter } from "./build-filter"; import { downloadableFilter } from "./downloadable"; import { hasApiFilter } from "./has-api"; import { groupIds } from "./group-ids"; import { collectionFilter } from "./collection"; // custom filter functions const customFilters: any = { downloadable: downloadableFilter, hasApi: hasApiFilter, groupIds, collection: collectionFilter }; function isCustomFilter(filter: any) { return !!customFilters[filter]; } /** * Convert filter object into AGO filter string * @param queryFilters filter object created by create-filters like { tags: { fn: 'all', terms: ['a'] } } */ export function handleFilter(queryFilters: any) { const catalogDefinition: any = []; const otherFilters: any = []; Object.keys(queryFilters).forEach(key => { let clause; if (isCustomFilter(key)) { clause = customFilters[key](queryFilters, key); } else { clause = buildFilter(queryFilters, key); } if (queryFilters[key].catalogDefinition) { catalogDefinition.push(clause); } else { otherFilters.push(clause); } }); if (catalogDefinition.length) { const catalogClause = `(${catalogDefinition.join(" OR ")})`; if (otherFilters.length) { return `${catalogClause} AND (${otherFilters.join(" AND ")})`; } else { return catalogClause; } } else if (otherFilters.length) { return otherFilters.join(" AND "); } else { return ""; } }
1.460938
1
packages/react-link/src/components/Link/Link.types.ts
GitHubMaxwell/office-ui-fabric-react
0
1536
/* eslint-disable @typescript-eslint/naming-convention */ import * as React from 'react'; import { IStyle, ITheme } from '@fluentui/style-utilities'; import { IRefObject, IStyleFunctionOrObject } from '@fluentui/utilities'; /** * {@docCategory Link} */ export interface ILink { /** Sets focus to the link. */ focus(): void; } /** * @deprecated No longer used. */ export interface ILinkHTMLAttributes<T> extends React.HTMLAttributes<T> { // Shared type?: string; // Anchor // eslint-disable-next-line @typescript-eslint/no-explicit-any download?: any; href?: string; hrefLang?: string; media?: string; rel?: string; target?: string; // Button autoFocus?: boolean; disabled?: boolean; form?: string; formAction?: string; formEncType?: string; formMethod?: string; formNoValidate?: boolean; formTarget?: string; name?: string; value?: string | string[] | number; /** Any other props for HTMLElements or a React component passed to `as` */ // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: any; } /** * Link component props. All built-in props for `<a>` and `<button>` are supported (including * various event handlers) even if not listed below. * {@docCategory Link} */ export interface ILinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement | HTMLButtonElement | HTMLElement>, Omit<React.ButtonHTMLAttributes<HTMLAnchorElement | HTMLButtonElement | HTMLElement>, 'type'>, React.RefAttributes<HTMLElement> { /** * Optional callback to access the ILink interface. Use this instead of ref for accessing * the public methods and properties of the component. */ componentRef?: IRefObject<ILink>; /** * URL the link points to. If not provided, the link renders as a button (unless that behavior is * overridden using `as`). */ href?: string; /** * Where to open the linked URL. Common values are `_blank` (a new tab or window), * `_self` (the current window/context), `_parent`, and `_top`. */ target?: string; /** * Relationship to the linked URL (can be a space-separated list). * Most common values are `noreferrer` and/or `noopener`. */ rel?: string; /** * Click handler for the link. */ onClick?: (event: React.MouseEvent<HTMLAnchorElement | HTMLButtonElement | HTMLElement>) => void; /** * Whether the link is disabled */ disabled?: boolean; /** * Call to provide customized styling that will layer on top of the variant rules. */ styles?: IStyleFunctionOrObject<ILinkStyleProps, ILinkStyles>; /** * Theme (provided through customization.) */ theme?: ITheme; /** * A component type or primitive that is rendered as the type of the root element. */ as?: React.ElementType; /** * Built-in HTML attribute with different behavior depending on how the link is rendered. * If rendered as `<a>`, hints at the MIME type. * If rendered as `<button>`, override the type of button (`button` is the default). */ type?: string; /** Any other props for elements or a React component passed to `as` */ // eslint-disable-next-line @typescript-eslint/no-explicit-any [key: string]: any; } /** * {@docCategory Link} */ export interface ILinkStyleProps { className?: string; isButton?: boolean; isDisabled?: boolean; theme: ITheme; } /** * {@docCategory Link} */ export interface ILinkStyles { root: IStyle; }
1.117188
1
packages/types/src/interfaces/system/definitions.ts
WoeOm/api
0
1544
// Copyright 2017-2021 @polkadot/types authors & contributors // SPDX-License-Identifier: Apache-2.0 // order important in structs... :) /* eslint-disable sort-keys */ import type { Definitions } from '../../types'; export default { rpc: { accountNextIndex: { alias: ['account_nextIndex'], description: 'Retrieves the next accountIndex as available on the node', params: [ { name: 'accountId', type: 'AccountId' } ], type: 'Index' }, dryRun: { alias: ['system_dryRunAt'], description: 'Dry run an extrinsic at a given block', params: [ { name: 'extrinsic', type: 'Bytes' }, { name: 'at', type: 'BlockHash', isHistoric: true, isOptional: true } ], type: 'ApplyExtrinsicResult' }, name: { description: 'Retrieves the node name', params: [], type: 'Text' }, version: { description: 'Retrieves the version of the node', params: [], type: 'Text' }, chain: { description: 'Retrieves the chain', params: [], type: 'Text' }, chainType: { description: 'Retrieves the chain type', params: [], type: 'ChainType' }, properties: { description: 'Get a custom set of properties as a JSON object, defined in the chain spec', params: [], type: 'ChainProperties' }, health: { description: 'Return health status of the node', params: [], type: 'Health' }, localPeerId: { description: 'Returns the base58-encoded PeerId of the node', params: [], type: 'Text' }, localListenAddresses: { description: 'The addresses include a trailing /p2p/ with the local PeerId, and are thus suitable to be passed to addReservedPeer or as a bootnode address for example', params: [], type: 'Vec<Text>' }, peers: { description: 'Returns the currently connected peers', params: [], type: 'Vec<PeerInfo>' }, networkState: { alias: ['system_unstable_networkState'], description: 'Returns current state of the network', params: [], type: 'NetworkState' }, addReservedPeer: { description: 'Adds a reserved peer', params: [ { name: 'peer', type: 'Text' } ], type: 'Text' }, removeReservedPeer: { description: 'Remove a reserved peer', params: [ { name: 'peerId', type: 'Text' } ], type: 'Text' }, reservedPeers: { description: 'Returns the list of reserved peers', params: [], type: 'Vec<Text>' }, nodeRoles: { description: 'Returns the roles the node is running as', params: [], type: 'Vec<NodeRole>' }, syncState: { description: 'Returns the state of the syncing of the node', params: [], type: 'SyncState' }, addLogFilter: { description: 'Adds the supplied directives to the current log filter', params: [ { name: 'directives', type: 'Text' } ], type: 'Null' }, resetLogFilter: { description: 'Resets the log filter to Substrate defaults', params: [], type: 'Null' } }, types: { AccountInfo: 'AccountInfoWithTripleRefCount', AccountInfoWithRefCount: { nonce: 'Index', refcount: 'RefCount', data: 'AccountData' }, AccountInfoWithDualRefCount: { nonce: 'Index', consumers: 'RefCount', providers: 'RefCount', data: 'AccountData' }, // original naming AccountInfoWithProviders: 'AccountInfoWithDualRefCount', AccountInfoWithTripleRefCount: { nonce: 'Index', consumers: 'RefCount', providers: 'RefCount', sufficients: 'RefCount', data: 'AccountData' }, ApplyExtrinsicResult: 'Result<DispatchOutcome, TransactionValidityError>', BlockLength: { max: 'PerDispatchClassU32' }, BlockWeights: { baseBlock: 'Weight', maxBlock: 'Weight', perClass: 'PerDispatchClassWeightsPerClass' }, ChainProperties: 'GenericChainProperties', ChainType: { _enum: { Development: 'Null', Local: 'Null', Live: 'Null', Custom: 'Text' } }, ConsumedWeight: 'PerDispatchClassWeight', DigestOf: 'Digest', DispatchClass: { _enum: ['Normal', 'Operational', 'Mandatory'] }, DispatchError: { _enum: { Other: 'Null', CannotLookup: 'Null', BadOrigin: 'Null', Module: 'DispatchErrorModule', ConsumerRemaining: 'Null', NoProviders: 'Null', Token: 'TokenError' } }, DispatchErrorModule: { index: 'u8', error: 'u8' }, DispatchErrorTo198: { module: 'Option<u8>', error: 'u8' }, DispatchInfo: { weight: 'Weight', class: 'DispatchClass', paysFee: 'Pays' }, DispatchInfoTo190: { weight: 'Weight', class: 'DispatchClass' }, DispatchInfoTo244: { weight: 'Weight', class: 'DispatchClass', paysFee: 'bool' }, DispatchOutcome: 'Result<(), DispatchError>', DispatchResult: 'Result<(), DispatchError>', DispatchResultOf: 'DispatchResult', DispatchResultTo198: 'Result<(), Text>', Event: 'GenericEvent', EventId: '[u8; 2]', EventIndex: 'u32', EventRecord: { phase: 'Phase', event: 'Event', topics: 'Vec<Hash>' }, Health: { peers: 'u64', isSyncing: 'bool', shouldHavePeers: 'bool' }, InvalidTransaction: { _enum: { Call: 'Null', Payment: 'Null', Future: 'Null', Stale: 'Null', BadProof: 'Null', AncientBirthBlock: 'Null', ExhaustsResources: 'Null', Custom: 'u8', BadMandatory: 'Null', MandatoryDispatch: 'Null' } }, Key: 'Bytes', LastRuntimeUpgradeInfo: { specVersion: 'Compact<u32>', specName: 'Text' }, NetworkState: { peerId: 'Text', listenedAddresses: 'Vec<Text>', externalAddresses: 'Vec<Text>', connectedPeers: 'HashMap<Text, Peer>', notConnectedPeers: 'HashMap<Text, NotConnectedPeer>', averageDownloadPerSec: 'u64', averageUploadPerSec: 'u64', peerset: 'NetworkStatePeerset' }, NetworkStatePeerset: { messageQueue: 'u64', nodes: 'HashMap<Text, NetworkStatePeersetInfo>' }, NetworkStatePeersetInfo: { connected: 'bool', reputation: 'i32' }, NodeRole: { _enum: { Full: 'Null', LightClient: 'Null', Authority: 'Null', UnknownRole: 'u8' } }, NotConnectedPeer: { knownAddresses: 'Vec<Text>', latestPingTime: 'Option<PeerPing>', versionString: 'Option<Text>' }, Peer: { enabled: 'bool', endpoint: 'PeerEndpoint', knownAddresses: 'Vec<Text>', latestPingTime: 'PeerPing', open: 'bool', versionString: 'Text' }, PeerEndpoint: { listening: 'PeerEndpointAddr' }, PeerEndpointAddr: { _alias: { localAddr: 'local_addr', sendBackAddr: 'send_back_addr' }, localAddr: 'Text', sendBackAddr: 'Text' }, PeerPing: { nanos: 'u64', secs: 'u64' }, PeerInfo: { peerId: 'Text', roles: 'Text', protocolVersion: 'u32', bestHash: 'Hash', bestNumber: 'BlockNumber' }, PerDispatchClassU32: { normal: 'u32', operational: 'u32', mandatory: 'u32' }, PerDispatchClassWeight: { normal: 'Weight', operational: 'Weight', mandatory: 'Weight' }, PerDispatchClassWeightsPerClass: { normal: 'WeightPerClass', operational: 'WeightPerClass', mandatory: 'WeightPerClass' }, Phase: { _enum: { ApplyExtrinsic: 'u32', Finalization: 'Null', Initialization: 'Null' } }, RawOrigin: { _enum: { Root: 'Null', Signed: 'AccountId', None: 'Null' } }, RefCount: 'u32', RefCountTo259: 'u8', SyncState: { startingBlock: 'BlockNumber', currentBlock: 'BlockNumber', highestBlock: 'Option<BlockNumber>' }, SystemOrigin: 'RawOrigin', TokenError: { _enum: [ 'NoFunds', 'WouldDie', 'BelowMinimum', 'CannotCreate', 'UnknownAsset', 'Frozen', 'Underflow', 'Overflow' ] }, TransactionValidityError: { _enum: { Invalid: 'InvalidTransaction', Unknown: 'UnknownTransaction' } }, UnknownTransaction: { _enum: { CannotLookup: 'Null', NoUnsignedValidator: 'Null', Custom: 'u8' } }, WeightPerClass: { baseExtrinsic: 'Weight', maxExtrinsic: 'Weight', maxTotal: 'Option<Weight>', reserved: 'Option<Weight>' } } } as Definitions;
1.398438
1
src/Element.scrollBy.ts
719media/seamless-scroll-polyfill
0
1552
import { IAnimationOptions, IScrollToOptions } from "./common.js"; import { elementScroll } from "./Element.scroll.js"; export const elementScrollBy = (elememt: Element, options: IScrollToOptions) => { const left = (options.left || 0) + elememt.scrollLeft; const top = (options.top || 0) + elememt.scrollTop; return elementScroll(elememt, { ...options, left, top }); }; export const polyfill = (options: IAnimationOptions) => { Element.prototype.scrollBy = function scrollBy() { const [arg0 = 0, arg1 = 0] = arguments; if (typeof arg0 === "number" && typeof arg1 === "number") { return elementScrollBy(this, { left: arg0, top: arg1 }); } if (Object(arg0) !== arg0) { throw new TypeError("Failed to execute 'scrollBy' on 'Element': parameter 1 ('options') is not an object."); } return elementScrollBy(this, { ...arg0, ...options }); }; };
1.015625
1
videos/c64ef54d-472e-48a9-ba08-da8a7810431d/360p_217.ts
Krystian19/cactus-fake-video-cdn-service
0
1560
version https://git-lfs.github.com/spec/v1 oid sha256:de7bbe7dafe4ce06d04162f5a530062042f6156edfc1de7227c2c177a7d3cda5 size 229360
-0.048584
0
packages/sdk/built/internal/connection/webSocket.d.ts
aRkker/mre-fork
0
1568
/*! * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import * as WS from 'ws'; import { EventedConnection } from './eventedConnection'; /** * An implementation of the Connection interface that wraps a WebSocket. */ export declare class WebSocket extends EventedConnection { private _ws; private _remoteAddress; get remoteAddress(): string; constructor(_ws: WS, _remoteAddress: string); /** @override */ close(): void; } //# sourceMappingURL=webSocket.d.ts.map
1.15625
1
src/fdf/Root.ts
ScrewTheTrees/tsFDFGenerator
1
1576
import {StringStream} from "../StringStream"; import {FrameBase} from "./FrameBase"; export type RootArgs = { Children?: FrameBase[], IncludeFiles?: string[] }; export class Root { public Children: FrameBase[] = []; public IncludeFiles: string[] = []; constructor(args?: RootArgs) { if (args) Object.assign(this, args); } public addChild(frame: FrameBase) { this.Children.push(frame); } compileFDFFile(): StringStream { const str: StringStream = new StringStream(); if (this.IncludeFiles.length > 0) { str.writeString("//--Includes--\n"); for (let file of this.IncludeFiles) { str.writeString(`IncludeFile "${file}",\n`); } str.writeString("\n"); } if (this.Children.length > 0) { str.writeString("//--Frames--\n"); for (let child of this.Children) { child.compileToStringStream(str); } } str.writeString("\n"); return str; } public compileUsableClass(fileName: string) { let theClass = new StringStream(); let theImports = new StringStream(); let theFields = new StringStream(); theClass.writeLine(`export class ${fileName} {`) theClass.pushIndent(); theFields.pushIndent(); theClass.writeIndentation().writeLine(`public frameContext: number;`); theClass.writeLine(""); theClass.writeIndentation().writeLine(`public constructor(context: number) {`); //Start constructor. theClass.pushIndent().writeIndentation() .writeLine(`this.frameContext = context;`) for (let i = 0; i < this.Children.length; i++) { let child = this.Children[i]; if (child.Name.length > 0) { //Write constructor theClass.writeIndentation() .writeString(`this.${child.Name} = new ${child.Name}(this.frameContext);`); //Write fields theFields.writeIndentation() .writeLine(`public ${child.Name}: ${child.Name};`); theImports.writeLine(`import {${child.Name}} from "./${child.Name}";`) } theClass.writeLine(`//Child ${i} ${child.constructor.name}`); } theClass.popIndent().writeIndentation().writeLine(`}`); //End Constructor. theClass.writeLine(theFields.data); theClass.popIndent(); theClass.writeLine(`}`); return theImports.data + "\n\n" + theClass.data; } compileClasses(fileName: string) { const classes: Map<string, string> = new Map(); classes.set(fileName, this.compileUsableClass(fileName)); function traverse(frame: FrameBase, depth: number = 0) { if (classes.has(frame.Name)) { console.error(`Duplicated frame: ${frame.Name}`); //FUCK } if (frame.Name.length > 0) { classes.set(frame.Name, frame.compileToClass(depth)); } for (let child of frame.Children) { //traverse(child, depth + 1); } } for (let child of this.Children) { traverse(child); } return classes; } }
1.734375
2
src/SidebarContents.tsx
wagnerjt/gatsby-antd-docs
0
1584
import React, { Component } from 'react' import { graphql, StaticQuery, Link } from 'gatsby' import { Affix, Menu } from 'antd' import 'antd/lib/menu/style/css' import { pathPrefix } from '../gatsby-config' const SubMenu = Menu.SubMenu /** * Returns the current browser's pathname * with the addition of the pathPrefix defiend in gatsby-config * @returns {string} Pathname */ const getPath = () => { let key = '/' // root as default if (typeof window !== 'undefined') key = pathPrefix !== '/' ? pathPrefix + window.location.pathname : window.location.pathname return key } const convertToTree = data => { const list = data.map(edge => { return { path: edge.node.fields.slug, key: edge.node.id, title: edge.node.frontmatter.title, parents: edge.node.frontmatter.parents, } }) return constructTree(list) } const constructTree = list => { let tree = [] let dir = [] list.forEach(item => { if (item.parents === [] || item.parents === null) tree.push(item) else { let subtree = tree for (let i = 0; i < item.parents.length; i++) { if ( subtree.filter( node => node.title === item.parents[i] && node.children ).length === 0 ) { const newNode = { key: item.path, title: item.parents[i], children: [], } subtree.push(newNode) dir.push(newNode) } subtree = subtree.find( node => node.title === item.parents[i] && node.children ).children } subtree.push(item) } }) return [tree, dir] } const sortTree = tree => { tree.sort((a, b) => { if ( ((a.children && b.children) || (!a.children && !b.children)) && a.title > b.title ) return 1 else if (a.children) return 1 return -1 }) } interface Props { root: any } export const SidebarContents = ({ root }: Props) => { return ( <StaticQuery query={graphql` query sidebarContentQuery { allMdx(sort: { order: ASC, fields: [fields___slug] }) { edges { node { fields { slug } id frontmatter { title parents } } } } } `} render={data => { const [tree, dir] = convertToTree( data.allMdx.edges.filter(node => node.node.fields.slug.startsWith(root) ) ) sortTree(tree) const loop = ({ data, activePath }) => data.map(item => { if (item.children) { sortTree(item.children) return ( <SubMenu key={item.key} title={<span style={{ fontWeight: 900 }}>{item.title}</span>} > {loop({ data: item.children, activePath })} </SubMenu> ) } return ( <Menu.Item key={item.path}> <Link to={item.path}> <div>{item.title}</div> </Link> </Menu.Item> ) }) const currentPath = getPath() const defaultOpenKeys = dir.map(item => item.key) return ( <Affix> <Menu mode="inline" style={{ minWidth: 180, height: '100%', borderRight: 0 }} defaultOpenKeys={defaultOpenKeys} selectedKeys={[currentPath]} > {loop({ data: tree, activePath: [currentPath] })} </Menu> </Affix> ) }} /> ) }
1.625
2
src/components/Icon/icon.tsx
sohucw/mo-ui
0
1592
import React from 'react' import classNames from 'classnames' import { FontAwesomeIcon, FontAwesomeIconProps } from '@fortawesome/react-fontawesome' export type ThemeProps = 'primary' | 'secondary' | 'success' | 'info' | 'warning' | 'danger' | 'light' | 'dark' export interface IconProps extends FontAwesomeIconProps { theme? : ThemeProps } const Icon: React.FC<IconProps> = (props) => { // icon-primary const { className, theme, ...restProps } = props const classes = classNames('mo-icon', className, { [`icon-${theme}`]: theme }) return ( <FontAwesomeIcon className={classes} {...restProps} /> ) } export default Icon
1.203125
1