repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
homebridge-appletv-enhanced | github_2023 | maxileith | typescript | AppleTVEnhancedPlatform.discoverDevices | private async discoverDevices(): Promise<void> {
this.log.debug('Starting device discovery ...');
let scanResults: NodePyATVDevice[] = [];
// multicast discovery
if (
this.config.discover?.multicast === undefined ||
this.config.discover.multicast === true
... | /**
* This is an example method showing how to register discovered accessories.
* Accessories must only be registered once, previously created accessories
* must not be registered again to prevent "duplicate UUID" errors.
*/ | https://github.com/maxileith/homebridge-appletv-enhanced/blob/94633e9bd19b47d6fb9cdc419d5465e7c6382a0a/src/appleTVEnhancedPlatform.ts#L105-L224 | 94633e9bd19b47d6fb9cdc419d5465e7c6382a0a |
icloud-passwords-firefox | github_2023 | au2001 | typescript | SRPSession.constructor | private constructor(
username: Buffer,
clientPrivateKey: bigint,
shouldUseBase64 = false,
) {
this.clientPrivateKey = clientPrivateKey;
this.shouldUseBase64 = shouldUseBase64;
this.username = this.serialize(username);
} | // x | https://github.com/au2001/icloud-passwords-firefox/blob/d41739a4b3fe89faa395cd9dbc788dfe2c84a514/src/utils/srp.ts#L45-L54 | d41739a4b3fe89faa395cd9dbc788dfe2c84a514 |
icloud-passwords-firefox | github_2023 | au2001 | typescript | SRPSession.clientPublicKey | get clientPublicKey() {
return powermod(GROUP_GENERATOR, this.clientPrivateKey, GROUP_PRIME);
} | // A | https://github.com/au2001/icloud-passwords-firefox/blob/d41739a4b3fe89faa395cd9dbc788dfe2c84a514/src/utils/srp.ts#L66-L68 | d41739a4b3fe89faa395cd9dbc788dfe2c84a514 |
LLM-RGB | github_2023 | babelcloud | typescript | getAggregatedScores | function getAggregatedScores(scores: TestScore[], tests) {
var context_length = 0;
var reasoning_depth = 0;
var instruction_compliance = 0;
for (const score of scores) {
const diffculties = findDifficulties(score.test_name, tests);
context_length = context_length + score.assertion_score ... | /**
* Calculate the aggregated scores of a given llm's test scores.
*/ | https://github.com/babelcloud/LLM-RGB/blob/e6befa35de28640f0f5bdb5176a385f2784bfae7/utils/generateEvalScore.ts#L160-L175 | e6befa35de28640f0f5bdb5176a385f2784bfae7 |
LLM-RGB | github_2023 | babelcloud | typescript | findDifficulties | function findDifficulties(name: string, tests) {
for (const test of tests) {
if (test.name == name) {
return test.difficulties;
}
}
return null;
} | /**
* Return the difficulties values of given test
*/ | https://github.com/babelcloud/LLM-RGB/blob/e6befa35de28640f0f5bdb5176a385f2784bfae7/utils/generateEvalScore.ts#L181-L188 | e6befa35de28640f0f5bdb5176a385f2784bfae7 |
LLM-RGB | github_2023 | babelcloud | typescript | getLLMScores | function getLLMScores(llm_id: string, results, tests) {
var scoreMap = new Map<string, TestScore[]>();
for (const result of results) {
if (result.provider.id == llm_id) {
const test_difficulties = findDifficulties(result.vars.name, tests);
const test_score = result.score.toFixed(... | /**
* Find all results of provided llm and extract the scores
*/ | https://github.com/babelcloud/LLM-RGB/blob/e6befa35de28640f0f5bdb5176a385f2784bfae7/utils/generateEvalScore.ts#L194-L228 | e6befa35de28640f0f5bdb5176a385f2784bfae7 |
directus-schema-sync | github_2023 | bcc-code | typescript | CollectionExporter.sortbyIfLinked | protected async sortbyIfLinked(items: Array<Item>) {
const { getPrimary, linkedFields } = await this.settings();
if (!linkedFields.length) return false;
const itemsMap = items.reduce((map, o) => {
o.__dependents = [];
map[getPrimary(o)] = o;
return map;
}, {} as Record<PrimaryKey, Item>);
items.for... | /**
* Orders items so that items that are linked are inserted after the items they reference
* Only works with items that have a primary key
* Assumes items not in given items list are already in the database
* @param items
* @returns
*/ | https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/collectionExporter.ts#L230-L253 | f73c15c196f2e897d27c7b8f272e94fc68afbf46 |
directus-schema-sync | github_2023 | bcc-code | typescript | CollectionExporter.countDependents | private countDependents(o: any): number {
if (!o.__dependents.length) return 0;
return (o.__dependents as Array<Item>).reduce((acc, o) => acc + this.countDependents(o), o.__dependents.length);
} | // Recursively count dependents | https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/collectionExporter.ts#L255-L258 | f73c15c196f2e897d27c7b8f272e94fc68afbf46 |
directus-schema-sync | github_2023 | bcc-code | typescript | CollectionExporter.loadGroupedItems | public async loadGroupedItems(config: PARTIAL_CONFIG, merge = false) {
const loadedItems = [];
let found = 0;
const files = await glob(this.groupedFilesPath('*'));
for (const file of files) {
const groupJson = await readFile(file, { encoding: 'utf8' });
const items = JSON.parse(groupJson) as Array<Item>;... | /**
* Fetches the items from grouped files and then subsequently loads the items
*
* @param config
* @param merge {see loadItems}
* @returns
*/ | https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/collectionExporter.ts#L267-L295 | f73c15c196f2e897d27c7b8f272e94fc68afbf46 |
directus-schema-sync | github_2023 | bcc-code | typescript | CollectionExporter.loadItems | public async loadItems(loadedItems: Array<Item>, merge = false) {
if (merge && !loadedItems.length) return null;
const itemsSvc = await this._getService();
const { getKey, getPrimary, queryWithPrimary } = await this.settings();
const items = await itemsSvc.readByQuery(queryWithPrimary);
const itemsMap = ne... | /**
* Loads the items and updates the database
*
* @param loadedItems An array of loaded items to sync with the database
* @param merge boolean indicating whether to merge the items or replace them, ie. delete all items not in the JSON
* @returns
*/ | https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/collectionExporter.ts#L304-L397 | f73c15c196f2e897d27c7b8f272e94fc68afbf46 |
directus-schema-sync | github_2023 | bcc-code | typescript | ExportManager.addExporter | public addExporter(exporterConfig: IExporterConfig) {
this.exporters.push(exporterConfig);
} | // FIRST: Add exporters | https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/exportManager.ts#L12-L14 | f73c15c196f2e897d27c7b8f272e94fc68afbf46 |
directus-schema-sync | github_2023 | bcc-code | typescript | ExportManager.loadAll | public async loadAll(merge = false) {
await this._loadNextExporter(0, merge);
} | // SECOND: Import if needed | https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/exportManager.ts#L27-L29 | f73c15c196f2e897d27c7b8f272e94fc68afbf46 |
directus-schema-sync | github_2023 | bcc-code | typescript | ExportManager.attachAllWatchers | public attachAllWatchers(action: (event: string, handler: ActionHandler) => void, updateMeta: () => Promise<void>) {
// EXPORT SCHEMAS & COLLECTIONS ON CHANGE //
const actions = ['create', 'update', 'delete'];
this.exporters.forEach(({ watch, exporter }) => {
watch.forEach(col => {
actions.forEach(evt => {... | // THIRD: Start watching for changes | https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/exportManager.ts#L45-L58 | f73c15c196f2e897d27c7b8f272e94fc68afbf46 |
directus-schema-sync | github_2023 | bcc-code | typescript | SchemaExporter.constructor | constructor(
getSchemaService: () => any,
protected logger: ApiExtensionContext['logger'],
protected options = { split: true }
) {
this._getSchemaService = () => getSchemaService();
this._filePath = `${ExportHelper.dataDir}/schema.json`;
} | // Directus SchemaService, database and getSchema | https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/schemaExporter.ts#L17-L24 | f73c15c196f2e897d27c7b8f272e94fc68afbf46 |
directus-schema-sync | github_2023 | bcc-code | typescript | SchemaExporter.createAndSaveSnapshot | public load = async () => {
const svc = this._getSchemaService();
if (await ExportHelper.fileExists(this._filePath)) {
const json = await readFile(this._filePath, { encoding: 'utf8' });
if (json) {
const schemaParsed = JSON.parse(json);
// For older versions, the snapshot was stored under the key `sna... | /**
* Import the schema from file to the database
*/ | https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/schemaExporter.ts | f73c15c196f2e897d27c7b8f272e94fc68afbf46 |
directus-schema-sync | github_2023 | bcc-code | typescript | UpdateManager.lockForUpdates | public async lockForUpdates(newHash: string, isoTS: string) {
if (this._locked || this._locking) return false;
this._locking = true;
// Don't lock if schema sync is not installed yet
const isInstalled = await this.db.schema.hasColumn(this.tableName, 'mv_hash');
if (!isInstalled) {
this._locking = false;
... | /**
* Acquire the lock to make updates
* @param newHash - New hash value of latest changes
* @param isoTS - ISO timestamp
* @returns
*/ | https://github.com/bcc-code/directus-schema-sync/blob/f73c15c196f2e897d27c7b8f272e94fc68afbf46/src/updateManager.ts#L27-L67 | f73c15c196f2e897d27c7b8f272e94fc68afbf46 |
materialite | github_2023 | vlcn-io | typescript | IssueModal | function IssueModal({ isOpen, onDismiss }: Props) {
const ref = useRef<HTMLInputElement>(null);
const [title, setTitle] = useState("");
const [description, setDescription] = useState<string>();
const [priority, setPriority] = useState<PriorityType>(Priority.NONE);
const [status, setStatus] = useState<StatusTy... | // eslint-disable-next-line react-refresh/only-export-components | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/demos/linearite/src/components/IssueModal.tsx#L26-L173 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | IssueCollection.getSortedSource | getSortedSource(
order: Order
): Omit<MutableSetSource<Issue>, "add" | "delete"> {
let index = this.#orderedIndices.get(order);
if (!index) {
index = m.newSortedSet<Issue>(issueComparators[order]);
const newIndex = index;
m.tx(() => {
for (const issue of this.#base.value.values()... | // the developer should mutate `issueCollection` which keeps all the indices in sync. | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/demos/linearite/src/domain/db.ts#L74-L89 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | IssueItem | const IssueItem = ({ issue, style, isDragging, provided }: IssueProps) => {
const navigate = useNavigate();
const priorityIcon = (
<span className="inline-block m-0.5 rounded-sm border border-gray-100 hover:border-gray-200 p-0.5">
<PriorityIcon priority={issue.priority} />
</span>
);
const update... | // eslint-disable-next-line react-refresh/only-export-components | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/demos/linearite/src/pages/Board/IssueItem.tsx#L34-L82 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | VirtualTableBase | function VirtualTableBase<T>({
rowRenderer,
width,
height,
rowHeight,
rows,
totalRows,
startIndex,
onNextPage,
onPrevPage,
hasNextPage,
hasPrevPage,
loading,
className,
}: {
className?: string;
width: string | number;
height: number;
rowHeight: number;
rows: readonly T[];
totalRows... | /**
* A virtual table which uses a cursor to paginate the data.
*
* onNextPage and onPrevPage are called when the user scrolls to the bottom or top of the table.
*
* Note: `onNextPage` and `onPrevPage` should pass the cursor of the item that starts the page.
* The caller was doing this: https://github.com/vlcn-io... | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/demos/linearite/src/pages/List/VirtualTable-Cursored.tsx#L24-L215 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | VirtualTableBase | function VirtualTableBase<T>({
rowRenderer,
width,
height,
rowHeight,
rows,
totalRows,
startIndex,
onPage,
loading,
className,
}: {
className?: string;
width: string | number;
height: number;
rowHeight: number;
rows: PersistentTreap<T>;
totalRows: number;
startIndex: number;
onPage: ... | /**
* Same as `VirtualTable` but uses offset pagination.
*
* Offset pagination isn't terribly efficient for SQLite but there are ways around this:
* 1. Creating a temp table to index the offsets
* 2. Using cursor as a hint to find the offset?
* See: https://github.com/vlcn-io/js/issues/27#issuecomment-1751333337
... | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/demos/linearite/src/pages/List/VirtualTable-Offset.tsx#L25-L192 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | VirtualTableBase | function VirtualTableBase<T>({
rowRenderer,
width,
height,
rowHeight,
rows,
totalRows,
startIndex,
onPage,
hasNextPage,
hasPrevPage,
loading,
className,
}: {
className?: string;
width: string | number;
height: number;
rowHeight: number;
rows: readonly T[];
totalRows: number;
startI... | /**
* Same as `VirtualTable` but uses offset pagination.
*
* Offset pagination isn't terribly efficient for SQLite but there are ways around this:
* 1. Creating a temp table to index the offsets
* 2. Using cursor as a hint to find the offset?
*
* Offset pagination works fine in Materialite since our treap knows ... | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/demos/react/src/virtualized/OffsetVirtualTable.tsx#L23-L192 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | PersistentTreap.findIndexByPredicate | findIndexByPredicate(pred: (x: T) => boolean): number {
let index = 0;
for (const value of inOrderTraversal(this.#root)) {
if (pred(value)) {
return index;
}
index += 1;
}
return -1;
} | // TODO: we can do better here. We can `findIndex` based on a provided value in O(logn) | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/ds-and-algos/src/trees-v2/persistent-treap.ts#L97-L108 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | PersistentTreap.findIndexByPredicate | findIndexByPredicate(pred: (x: T) => boolean): number {
let index = 0;
for (const value of inOrderTraversal(this.root)) {
if (pred(value)) {
return index;
}
index += 1;
}
return -1;
} | // TODO: we can do better here. We can `findIndex` based on a provided value in O(logn) | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/ds-and-algos/src/trees/PersistentTreap.ts#L121-L132 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | TreeIterator.prev | prev() {
if (this.cursor === null) {
const root = this.#tree.root;
if (root !== null) {
this.#maxNode(root);
}
} else {
if (this.cursor.left === null) {
let save: INode<V> | null;
do {
save = this.cursor;
if (this.ancestors.length) {
... | // otherwise, returns previous node | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/ds-and-algos/src/trees/TreeBase.ts#L214-L238 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | depth | function depth<T>(node: Node<T> | null): number {
if (!node) return 0;
return 1 + Math.max(depth(node.left), depth(node.right));
} | // Assuming your treap class is imported as: | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/ds-and-algos/src/trees/__tests__/TreapFastCheck.test.ts#L12-L15 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | Materialite.newStatelessSet | newStatelessSet<T>() {
const ret = new SetSource<T>(this.#internal);
return ret;
} | /**
* A source that does not retain and values and
* only sends them down the stream.
* @returns
*/ | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/materialite.ts#L44-L47 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | Materialite.newImmutableSortedSet | newImmutableSortedSet<T>(comparator: Comparator<T>) {
const ret = new ImmutableSetSource<T>(this.#internal, comparator);
return ret;
} | /**
* A source that retains values in a versioned, immutable, and sorted data structure.
*
* 1. The retaining of values allows for late pipeline additions to receive all data they may have missed.
* 2. The versioning allows for late pipeline additions to receive data from a specific point in time.
* 3. B... | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/materialite.ts#L65-L68 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | Materialite.newSortedSet | newSortedSet<T>(comparator: Comparator<T>) {
const ret = new MutableSetSource<T>(this.#internal, comparator);
return ret;
} | /**
* A source that retains values in a mutable, sorted data structure.
*
* 1. The retaining of values allows for late pipeline additions to receive all data they may have missed.
* 2. Being sorted allows cheaper construction of the final materialized view on pipeline modification if the
* order of the... | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/materialite.ts#L77-L80 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | Materialite.newUnorderedSet | newUnorderedSet<K, V>(getKey: KeyFn<V, K>) {
const ret = new MutableMapSource<K, V>(this.#internal, getKey);
return ret;
} | /**
* A source that retains values in a mutable, unordered data structure.
*
* 1. The retaining of values allows for late pipeline additions to receive all data they may have missed.
*
* The fact that the source is unsorted means that we can build it faster than a sorted source. This is
* useful where... | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/materialite.ts#L98-L101 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | Materialite.compute | compute<T extends any[], TRet>(
f: (...args: { [K in keyof T]: T[K] }) => TRet,
...s: { [K in keyof T]: ISignal<T[K]> }
): Thunk<T, TRet> {
return new Thunk(f, ...s) as any;
} | /**
*
* @param f
* @param signals
*/ | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/materialite.ts#L108-L113 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | Materialite.tx | tx(fn: () => void) {
if (this.#currentTx === null) {
this.#currentTx = this.#version + 1;
} else {
// nested transaction
// just run the function as we're already inside the
// scope of a transaction that will handle rollback and commit.
fn();
return;
}
try {
f... | /**
* Run the provided lambda in a transaciton.
* Will be committed when the lambda exits
* and all incremental computations that depend on modified inputs
* will be run.
*
* An exception to this is in the case of nested transactions.
* No incremental computation will run until the outermost transa... | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/materialite.ts#L133-L153 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | Index.compact | compact(keys: K[] = []) {
function consolidateValues(values: Entry<V>[]): [V, number][] {
const consolidated = new TuplableMap<V, number>();
for (const [value, multiplicity] of values) {
if (multiplicity === 0) {
continue;
}
const existing = consolidated.get(value);
... | // each tuple will have a unique identity according to `Map`. | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/core/index.ts#L66-L102 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | Multiset.consolidate | consolidate(): Multiset<T> {
return new Multiset([...this.#toNormalizedMap()], this.eventMetadata);
} | // aka normalize | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/core/multiset.ts#L57-L59 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | Multiset._extend | _extend(other: Multiset<T>) {
if (!Array.isArray(this.#entries)) {
this.#entries = [...this.#entries];
}
for (const e of other.entries) {
(this.#entries as Entry<T>[]).push(e);
}
} | // TODO: faster way to extend without converting to an array? | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/core/multiset.ts#L131-L138 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | inner | const inner = (version: Version) => {
for (const collection of this.inputAMessages(version)) {
const deltaA = new Index<K, V1>();
for (const [value, mult] of collection.entries) {
deltaA.add(getKeyA(value), [value, mult]);
}
this.#inputAPending.push(deltaA);
}
... | // TODO: how to deal with full re-compute messages | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/core/graph/ops/JoinOperator.ts#L31-L64 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | Operator.pull | pull(msg: Hoisted) {
for (const input of this.inputs) {
input.pull(msg);
}
} | /**
* If an operator is pulled, it sends the pull
* up the stream to its inputs.
* @param msg
* @returns
*/ | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/core/graph/ops/Operator.ts#L57-L61 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | subtractValues | const subtractValues = (first: Entry<O>[], second: Entry<O>[]) => {
const result = new TuplableMap<O, number>();
for (const [v1, m1] of first) {
const sum = (result.get(v1) || 0) + m1;
if (sum === 0) {
result.delete(v1);
} else {
result.set(v1, sum);
}
... | // TODO: deal with full recompute messages | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/core/graph/ops/ReduceOperator.ts#L20-L40 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | Thunk.off | off(
fn: (value: TRet, version: Version) => void,
options: { autoCleanup?: boolean } = { autoCleanup: true }
): void {
this.listeners.delete(fn);
this.#maybeCleanup(options.autoCleanup || false);
} | /**
* If there are 0 listeners left after removing the given listener,
* the signal is destroyed.
*
* To opt out of this behavior, pass `autoCleanup: false`
* @param listener
*/ | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/signal/Thunk.ts#L133-L139 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | MutableMapSource.on | on(fn: (value: Map<K, T>, version: number) => void): () => void {
return this.onChange(fn as any);
} | // TODO: implement these correctly. | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/sources/MutableMapSource.ts#L135-L137 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | SetSource.add | add(value: T): this {
this.#pending.push([value, 1]);
this.#materialite.addDirtySource(this.#internal);
return this;
} | // making delete problematic? | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/sources/StatelessSetSource.ts#L80-L84 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | SetSource.delete | delete(value: T): void {
this.#pending.push([value, -1]);
this.#materialite.addDirtySource(this.#internal);
} | // } | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/sources/StatelessSetSource.ts#L92-L95 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | PersistentTreeView.rematerialize | rematerialize(newLimit: number) {
const newView = new PersistentTreeView(
this.materialite,
this.stream,
this.comparator,
newLimit
);
newView.#min = this.#min;
newView.#max = this.#max;
newView.#data = this.#data;
if (this.#max !== undefined) {
this.materialite.tx(... | /**
* Re-materialize the view but with a new limit.
* All other params remain the same.
* Returns a new view.
* The view will ask the upstream for data _after_ the current view's max
*/ | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/views/PersistentTreeView.ts#L53-L86 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
materialite | github_2023 | vlcn-io | typescript | PersistentTreeView.run | protected run(version: Version) {
const collections = this.reader.drain(version);
let changed = false;
let newData = this.#data;
for (const c of collections) {
if (c.eventMetadata?.cause === "full_recompute") {
newData = new PersistentTreap<T>(this.comparator);
changed = true;
... | // TODO: notify on empty? | https://github.com/vlcn-io/materialite/blob/e08c1fa176883a51296d7c2c3a86c539c0e72eab/packages/materialite/src/views/PersistentTreeView.ts#L93-L109 | e08c1fa176883a51296d7c2c3a86c539c0e72eab |
azure-openai-rag-workshop | github_2023 | Azure-Samples | typescript | MessageBuilder.constructor | constructor(systemContent: string, chatgptModel: string) {
this.model = chatgptModel;
this.messages = [{ role: 'system', content: systemContent }];
this.tokens = this.getTokenCountFromMessages(this.messages[this.messages.length - 1], this.model);
} | /**
* A class for building and managing messages in a chat conversation.
* @param {string} systemContent The initial system message content.
* @param {string} chatgptModel The name of the ChatGPT model.
*/ | https://github.com/Azure-Samples/azure-openai-rag-workshop/blob/039f3f8bd106f3766f0dc1408f67289d0c1f8121/src/backend/src/lib/message-builder.ts#L15-L19 | 039f3f8bd106f3766f0dc1408f67289d0c1f8121 |
azure-openai-rag-workshop | github_2023 | Azure-Samples | typescript | MessageBuilder.appendMessage | appendMessage(role: AIChatRole, content: string, index = 1) {
this.messages.splice(index, 0, { role, content });
this.tokens += this.getTokenCountFromMessages(this.messages[index], this.model);
} | /**
* Append a new message to the conversation.
* @param {AIChatRole} role The role of the message sender.
* @param {string} content The content of the message.
* @param {number} index The index at which to insert the message.
*/ | https://github.com/Azure-Samples/azure-openai-rag-workshop/blob/039f3f8bd106f3766f0dc1408f67289d0c1f8121/src/backend/src/lib/message-builder.ts#L27-L30 | 039f3f8bd106f3766f0dc1408f67289d0c1f8121 |
azure-openai-rag-workshop | github_2023 | Azure-Samples | typescript | MessageBuilder.popMessage | popMessage(): AIChatMessage | undefined {
const message = this.messages.pop();
if (message) {
this.tokens -= this.getTokenCountFromMessages(message, this.model);
}
return message;
} | /**
* Get and remove the last message from the conversation.
* @returns {AIChatMessage} The removed message.
*/ | https://github.com/Azure-Samples/azure-openai-rag-workshop/blob/039f3f8bd106f3766f0dc1408f67289d0c1f8121/src/backend/src/lib/message-builder.ts#L36-L42 | 039f3f8bd106f3766f0dc1408f67289d0c1f8121 |
azure-openai-rag-workshop | github_2023 | Azure-Samples | typescript | MessageBuilder.getMessages | getMessages(): BaseMessage[] {
return this.messages.map((message) => {
if (message.role === 'system') {
return new SystemMessage(message.content);
} else if (message.role === 'assistant') {
return new AIMessage(message.content);
} else {
return new HumanMessage(message.cont... | /**
* Get the messages in the conversation in LangChain format.
* @returns {BaseMessage[]} The messages.
*/ | https://github.com/Azure-Samples/azure-openai-rag-workshop/blob/039f3f8bd106f3766f0dc1408f67289d0c1f8121/src/backend/src/lib/message-builder.ts#L48-L58 | 039f3f8bd106f3766f0dc1408f67289d0c1f8121 |
azure-openai-rag-workshop | github_2023 | Azure-Samples | typescript | MessageBuilder.getTokenCountFromMessages | private getTokenCountFromMessages(message: AIChatMessage, model: string): number {
// GPT3.5 tiktoken model name is slightly different than Azure OpenAI model name
const tiktokenModel = model.replace('gpt-35', 'gpt-3.5') as TiktokenModel;
const encoder = encoding_for_model(tiktokenModel);
let tokens = 2... | /**
* Calculate the number of tokens required to encode a message.
* @param {AIChatMessage} message The message to encode.
* @param {string} model The name of the model to use for encoding.
* @returns {number} The total number of tokens required to encode the message.
* @example
* const message = { ro... | https://github.com/Azure-Samples/azure-openai-rag-workshop/blob/039f3f8bd106f3766f0dc1408f67289d0c1f8121/src/backend/src/lib/message-builder.ts#L71-L81 | 039f3f8bd106f3766f0dc1408f67289d0c1f8121 |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | FastAndSlowPointers.hasCycleHashSetApproach | hasCycleHashSetApproach(head: ListNode | null): boolean {
const visited = new Set<ListNode>();
let current = head;
while (current) {
if (visited.has(current)) {
return true;
}
visited.add(current);
current = current.next;
}
... | // LeetCode 141 - Linked List Cycle (HashSet Approach) | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/fastAndSlowPointers.ts#L11-L22 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | FastAndSlowPointers.hasCycleFastAndSlowPointersApproach | hasCycleFastAndSlowPointersApproach(head: ListNode | null): boolean {
if (!head || !head.next) return false;
let slow: ListNode | null = head;
let fast: ListNode | null = head;
while (fast && fast.next) {
slow = slow!.next;
fast = fast.next.next;
if (s... | // LeetCode 141 - Linked List Cycle (Fast and Slow Pointer Approach) | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/fastAndSlowPointers.ts#L25-L35 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | FastAndSlowPointers.middleNodeCountingApproach | middleNodeCountingApproach(head: ListNode | null): ListNode | null {
let count = 0;
let current = head;
while (current) {
count++;
current = current.next;
}
current = head;
for (let i = 0; i < Math.floor(count / 2); i++) {
current = cur... | // LeetCode 876 - Middle of the Linked List (Counting Approach) | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/fastAndSlowPointers.ts#L38-L50 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | FastAndSlowPointers.middleNodeFastAndSlowPointerApproach | middleNodeFastAndSlowPointerApproach(head: ListNode | null): ListNode | null {
let slow = head, fast = head;
while (fast && fast.next) {
slow = slow!.next;
fast = fast.next.next;
}
return slow;
} | // LeetCode 876 - Middle of the Linked List (Fast and Slow Pointer Approach) | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/fastAndSlowPointers.ts#L53-L60 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | FastAndSlowPointers.getSumOfSquares | getSumOfSquares(n: number): number {
return String(n).split('').reduce((sum, digit) => sum + Number(digit) ** 2, 0);
} | // LeetCode 202 - Happy Number (HashSet Approach) | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/fastAndSlowPointers.ts#L63-L65 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | FastAndSlowPointers.isHappyFastAndSlowPointersApproach | isHappyFastAndSlowPointersApproach(n: number): boolean {
let slow = n;
let fast = this.getSumOfSquares(n);
while (fast !== 1 && slow !== fast) {
slow = this.getSumOfSquares(slow);
fast = this.getSumOfSquares(this.getSumOfSquares(fast));
}
return fast === 1... | // LeetCode 202 - Happy Number (Fast and Slow Pointer Approach) | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/fastAndSlowPointers.ts#L77-L85 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | SlidingWindow.findMaxAverageBruteForce | findMaxAverageBruteForce(nums: number[], k: number): number {
let maxAvg = -Infinity;
for (let i = 0; i <= nums.length - k; i++) {
let sum = 0;
for (let j = i; j < i + k; j++) {
sum += nums[j];
}
maxAvg = Math.max(maxAvg, sum / k);
... | // Brute Force Approach - O(n * k) | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/slidingWindow.ts#L3-L14 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | SlidingWindow.findMaxAverageSlidingWindow | findMaxAverageSlidingWindow(nums: number[], k: number): number {
let sum = nums.slice(0, k).reduce((a, b) => a + b, 0);
let maxSum = sum;
for (let i = k; i < nums.length; i++) {
sum += nums[i] - nums[i - k];
maxSum = Math.max(maxSum, sum);
}
return maxSu... | // Sliding Window Approach - O(n) | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/slidingWindow.ts#L17-L27 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | SlidingWindow.lengthOfLongestSubstringSlidingWindow | lengthOfLongestSubstringSlidingWindow(s: string): number {
let seen = new Set<string>();
let maxLength = 0, left = 0;
for (let right = 0; right < s.length; right++) {
while (seen.has(s[right])) {
seen.delete(s[left]);
left++;
}
... | // Sliding Window for Longest Substring Without Repeating Characters | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/slidingWindow.ts#L30-L43 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | SlidingWindow.lengthOfLongestSubstringSlidingWindowFrequencyArray | lengthOfLongestSubstringSlidingWindowFrequencyArray(s: string): number {
let freq = new Array(128).fill(0);
let maxLength = 0, left = 0;
for (let right = 0; right < s.length; right++) {
freq[s.charCodeAt(right)]++;
while (freq[s.charCodeAt(right)] > 1) {
... | // Sliding Window using Frequency Array | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/slidingWindow.ts#L46-L61 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | TopKElements.kLargestElementsSortingApproach | kLargestElementsSortingApproach(nums: number[], k: number): number[] {
nums.sort((a, b) => b - a);
return nums.slice(0, k);
} | // K Largest Elements using Sorting | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/topKElements.ts#L4-L7 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | TopKElements.kLargestElementsMaxHeapApproach | kLargestElementsMaxHeapApproach(nums: number[], k: number): number[] {
const maxHeap = new MaxPriorityQueue({ priority: (x: number) => x });
for (const num of nums) {
maxHeap.enqueue(num);
}
const result: number[] = [];
for (let i = 0; i < k; i++) {
result... | // K Largest Elements using Max Heap | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/topKElements.ts#L10-L20 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | TopKElements.kLargestElementsMinHeapApproach | kLargestElementsMinHeapApproach(nums: number[], k: number): number[] {
const minHeap = new MinPriorityQueue({ priority: (x: number) => x });
for (let i = 0; i < k; i++) {
minHeap.enqueue(nums[i]);
}
for (let i = k; i < nums.length; i++) {
minHeap.enqueue(nums[i]);... | // K Largest Elements using Min Heap | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/topKElements.ts#L23-L39 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | TopKElements.topKFrequentElementsSortingApproach | topKFrequentElementsSortingApproach(nums: number[], k: number): number[] {
const frequencyMap = new Map<number, number>();
nums.forEach(num => frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1));
return Array.from(frequencyMap)
.sort((a, b) => b[1] - a[1])
.slice(0, ... | // Top K Frequent Elements using Sorting | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/topKElements.ts#L42-L49 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | TopKElements.topKFrequentElementsMinHeapApproach | topKFrequentElementsMinHeapApproach(nums: number[], k: number): number[] {
const frequencyMap = new Map<number, number>();
nums.forEach(num => frequencyMap.set(num, (frequencyMap.get(num) || 0) + 1));
const minHeap = new MinPriorityQueue({ priority: (x: [number, number]) => x[1] });
freq... | // Top K Frequent Elements using Min Heap | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/topKElements.ts#L52-L67 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | TopKElements.getDistance | getDistance(point: number[]): number {
return point[0] ** 2 + point[1] ** 2;
} | // K Closest Points to Origin using Max Heap | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/topKElements.ts#L70-L72 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | TwoPointers.moveZeroesTwoPointers | moveZeroesTwoPointers(nums: number[]): void {
let left = 0; // Pointer for placing non-zero elements
// Iterate with right pointer
for (let right = 0; right < nums.length; right++) {
if (nums[right] !== 0) {
// Swap elements if right pointer finds a non-zero
... | // Move Zeroes using Two Pointers | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/twoPointers.ts#L3-L14 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | TwoPointers.maxAreaBruteForce | maxAreaBruteForce(height: number[]): number {
let maxArea = 0;
let n = height.length;
// Check all pairs (i, j)
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
// Compute the minimum height and width
let minHeight = Math.min(he... | // Brute Force approach for Container with Most Water | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/twoPointers.ts#L17-L33 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
awesome-leetcode-resources | github_2023 | ashishps1 | typescript | TwoPointers.maxAreaTwoPointers | maxAreaTwoPointers(height: number[]): number {
let left = 0, right = height.length - 1;
let maxArea = 0;
// Move pointers toward each other
while (left < right) {
let width = right - left; // Distance between lines
let minHeight = Math.min(height[left], height[ri... | // Two Pointers approach for Container with Most Water | https://github.com/ashishps1/awesome-leetcode-resources/blob/c4a4f662ee6e41ae2be1c1c638e76152d6f3751e/patterns/typescript/twoPointers.ts#L36-L56 | c4a4f662ee6e41ae2be1c1c638e76152d6f3751e |
openapi-devtools | github_2023 | AndrewWalsh | typescript | pruneRouter | const pruneRouter = (
node: RadixNode<RouteData>,
parts: Array<string>
): void => {
if (!parts.length || !node.children.size) return;
const isLast = parts.length === 1;
const part = parts[0];
const matchAny = isParameter(part);
if (!matchAny && !node.children.has(part)) return;
if (!isLast) {
if (ma... | /**
* When you remove an item in radix3, it only removes the data
* We need to remove the node itself so that lookups won't match with it
*/ | https://github.com/AndrewWalsh/openapi-devtools/blob/e26c20b3a9b8e2fa1f2d6e4d525e04f4d1ed0e27/src/lib/store-helpers/prune-router.ts#L9-L36 | e26c20b3a9b8e2fa1f2d6e4d525e04f4d1ed0e27 |
openapi-devtools | github_2023 | AndrewWalsh | typescript | remove | function remove(ctx: RadixRouterContext, path: string) {
let success = false;
const sections = path.split("/");
let node = ctx.rootNode;
for (const section of sections) {
// @ts-expect-error tempfile
node = node.children.get(section);
if (!node) {
return success;
}
}
if (node.data)... | // This can be removed when https://github.com/unjs/radix3/pull/73 is fixed | https://github.com/AndrewWalsh/openapi-devtools/blob/e26c20b3a9b8e2fa1f2d6e4d525e04f4d1ed0e27/src/lib/store-helpers/remove.ts#L5-L34 | e26c20b3a9b8e2fa1f2d6e4d525e04f4d1ed0e27 |
LLOneBot | github_2023 | LLOneBot | typescript | RequestUtil.HttpsGetCookies | static async HttpsGetCookies(url: string): Promise<{ [key: string]: string }> {
const client = url.startsWith('https') ? https : http
return new Promise((resolve, reject) => {
client.get(url, (res) => {
let cookies: { [key: string]: string } = {}
const handleRedirect = (res: http.IncomingM... | // 适用于获取服务器下发cookies时获取,仅GET | https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/common/utils/request.ts#L7-L48 | 17e8b69a1df7c569cb245d6dc5ad2881e9db1b16 |
LLOneBot | github_2023 | LLOneBot | typescript | RequestUtil.HttpGetJson | static async HttpGetJson<T>(url: string, method: string = 'GET', data?: unknown, headers: Record<string, string> = {}, isJsonRet: boolean = true, isArgJson: boolean = true): Promise<T> {
const option = new URL(url)
const protocol = url.startsWith('https://') ? https : http
const options = {
hostname: ... | // 请求和回复都是JSON data传原始内容 自动编码json | https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/common/utils/request.ts#L51-L98 | 17e8b69a1df7c569cb245d6dc5ad2881e9db1b16 |
LLOneBot | github_2023 | LLOneBot | typescript | RequestUtil.HttpGetText | static async HttpGetText(url: string, method: string = 'GET', data?: unknown, headers: Record<string, string> = {}) {
return this.HttpGetJson<string>(url, method, data, headers, false, false)
} | // 请求返回都是原始内容 | https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/common/utils/request.ts#L101-L103 | 17e8b69a1df7c569cb245d6dc5ad2881e9db1b16 |
LLOneBot | github_2023 | LLOneBot | typescript | LimitedHashTable.getHeads | getHeads(size: number): { key: K, value: V }[] | undefined {
const keyList = this.getKeyList()
if (keyList.length === 0) {
return undefined
}
const result: { key: K; value: V }[] = []
const listSize = Math.min(size, keyList.length)
for (let i = 0; i < listSize; i++) {
const key = key... | //获取最近刚写入的几个值 | https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/common/utils/table.ts#L58-L70 | 17e8b69a1df7c569cb245d6dc5ad2881e9db1b16 |
LLOneBot | github_2023 | LLOneBot | typescript | onLoad | function onLoad() {
if (!existsSync(DATA_DIR)) {
mkdirSync(DATA_DIR, { recursive: true })
}
if (!existsSync(LOG_DIR)) {
mkdirSync(LOG_DIR)
}
if (!existsSync(TEMP_DIR)) {
mkdirSync(TEMP_DIR)
}
const dbDir = path.join(DATA_DIR, 'database')
if (!existsSync(dbDir)) {
mkdirSync(dbDir)
}
... | // 加载插件时触发 | https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/main/main.ts#L48-L227 | 17e8b69a1df7c569cb245d6dc5ad2881e9db1b16 |
LLOneBot | github_2023 | LLOneBot | typescript | onBrowserWindowCreated | function onBrowserWindowCreated(window: BrowserWindow) {
if (window.id === 2) {
mainWindow = window
}
} | // 创建窗口时触发 | https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/main/main.ts#L230-L234 | 17e8b69a1df7c569cb245d6dc5ad2881e9db1b16 |
LLOneBot | github_2023 | LLOneBot | typescript | secondCallback | const secondCallback = () => {
eventId = registerReceiveHook<R>(options.cbCmd!, (payload) => {
if (options.cmdCB) {
if (!options.cmdCB(payload, result)) {
return
}
}
removeReceiveHook(eventId)
clearTimeout(timeoutId)
resolve... | // 这里的callback比较特殊,QQ后端先返回是否调用成功,再返回一条结果数据 | https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/ntqqapi/ntcall.ts#L169-L180 | 17e8b69a1df7c569cb245d6dc5ad2881e9db1b16 |
LLOneBot | github_2023 | LLOneBot | typescript | NTQQFileApi.uploadFile | async uploadFile(filePath: string, elementType = ElementType.Pic, elementSubType = 0) {
const fileMd5 = await calculateFileMD5(filePath)
let fileName = path.basename(filePath)
if (!fileName.includes('.')) {
const ext = (await this.getFileType(filePath))?.ext
fileName += ext ? '.' + ext : ''
... | /** 上传文件到 QQ 的文件夹 */ | https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/ntqqapi/api/file.ts#L67-L94 | 17e8b69a1df7c569cb245d6dc5ad2881e9db1b16 |
LLOneBot | github_2023 | LLOneBot | typescript | NTQQFriendApi.getFriends | async getFriends() {
const res = await invoke<{
data: {
categoryId: number
categroyName: string
categroyMbCount: number
buddyList: Friend[]
}[]
}>('getBuddyList', [], {
className: NTClass.NODE_STORE_API,
cbCmd: ReceiveCmdS.FRIENDS,
afterFirstCmd: fal... | /** 大于或等于 26702 应使用 getBuddyV2 */ | https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/ntqqapi/api/friend.ts#L18-L32 | 17e8b69a1df7c569cb245d6dc5ad2881e9db1b16 |
LLOneBot | github_2023 | LLOneBot | typescript | NTQQFriendApi.getBuddyIdMap | async getBuddyIdMap(refresh = false): Promise<Map<string, string>> {
const retMap: Map<string, string> = new Map()
const data = await invoke<{
buddyCategory: CategoryFriend[]
userSimpleInfos: Record<string, SimpleInfo>
}>(
'getBuddyList',
[refresh],
{
className: NTClass... | /** uid -> uin */ | https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/ntqqapi/api/friend.ts#L62-L83 | 17e8b69a1df7c569cb245d6dc5ad2881e9db1b16 |
LLOneBot | github_2023 | LLOneBot | typescript | NTQQGroupApi.banMember | async banMember(groupCode: string, memList: Array<{ uid: string, timeStamp: number }>) {
return await invoke(NTMethod.MUTE_MEMBER, [{ groupCode, memList }])
} | /** timeStamp为秒数, 0为解除禁言 */ | https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/ntqqapi/api/group.ts#L134-L136 | 17e8b69a1df7c569cb245d6dc5ad2881e9db1b16 |
LLOneBot | github_2023 | LLOneBot | typescript | SendForwardMsg.handleForwardNode | private async handleForwardNode(destPeer: Peer, messageNodes: OB11MessageNode[]): Promise<Response> {
const selfPeer = {
chatType: ChatType.C2C,
peerUid: selfInfo.uid,
}
const nodeMsgIds: { msgId: string, peer: Peer }[] = []
// 先判断一遍是不是id和自定义混用
for (const messageNode of messageNodes) {
... | // 返回一个合并转发的消息id | https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/onebot11/action/go-cqhttp/SendForwardMsg.ts#L157-L256 | 17e8b69a1df7c569cb245d6dc5ad2881e9db1b16 |
LLOneBot | github_2023 | LLOneBot | typescript | buildHostListItem | const buildHostListItem = (type: HostsType, host: string, index: number, inputAttrs = {}) => {
const dom = {
container: document.createElement('setting-item'),
input: document.createElement('input'),
inputContainer: document.createElement('div'),
deleteBtn: document.createElement('setting-bu... | // 生成反向地址列表 | https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/renderer/index.ts#L279-L310 | 17e8b69a1df7c569cb245d6dc5ad2881e9db1b16 |
LLOneBot | github_2023 | LLOneBot | typescript | checkVersionFunc | async function checkVersionFunc(info: CheckVersion) {
const titleDom = view.querySelector<HTMLSpanElement>('#llonebot-update-title')!
const buttonDom = view.querySelector<HTMLButtonElement>('#llonebot-update-button')!
if (info.version === '') {
titleDom.innerHTML = `当前版本为 v${version},检查更新失败`
bu... | // 更新逻辑 | https://github.com/LLOneBot/LLOneBot/blob/17e8b69a1df7c569cb245d6dc5ad2881e9db1b16/src/renderer/index.ts#L435-L467 | 17e8b69a1df7c569cb245d6dc5ad2881e9db1b16 |
Sistema-Anti-Fraude-Electoral | github_2023 | Las-Fuerzas-Del-Cielo | typescript | validarFiscalGeneral | async function validarFiscalGeneral(fiscalId: string): Promise<boolean> {
// Lógica para verificar en la base de datos si el fiscal es general
// Ejemplo:
// const fiscal = await FiscalModel.findById(fiscalId);
// return fiscal && fiscal.tipo === 'general';
return true; // Simulación, reemplazar con la lógica... | // Aquí irían las implementaciones de las funciones auxiliares | https://github.com/Las-Fuerzas-Del-Cielo/Sistema-Anti-Fraude-Electoral/blob/051da907b8ae468060a754a163cda1b0372f8211/api/src/controllers/voting-tables.ts#L89-L95 | 051da907b8ae468060a754a163cda1b0372f8211 |
Sistema-Anti-Fraude-Electoral | github_2023 | Las-Fuerzas-Del-Cielo | typescript | listener | const listener: typeof handler = (event) => savedHandler.current(event); | // Create event listener that calls handler function stored in ref | https://github.com/Las-Fuerzas-Del-Cielo/Sistema-Anti-Fraude-Electoral/blob/051da907b8ae468060a754a163cda1b0372f8211/frontend/src/hooks/utils/use-event-listener.tsx#L65-L65 | 051da907b8ae468060a754a163cda1b0372f8211 |
DevToolboxWeb | github_2023 | YourAverageTechBro | typescript | encodeBase64 | const encodeBase64 = (inputString: string) =>
// Use the btoa function to encode the string to Base64
btoa(inputString); | // Encode a string to Base64 | https://github.com/YourAverageTechBro/DevToolboxWeb/blob/d5e14628db174c0dc1a9a4249efe85536be79067/src/app/tools/base64encoder/Base64EncoderClientComponent.tsx#L53-L55 | d5e14628db174c0dc1a9a4249efe85536be79067 |
DevToolboxWeb | github_2023 | YourAverageTechBro | typescript | decodeBase64 | const decodeBase64 = (base64String: string) =>
// Use the atob function to decode the Base64 string
atob(base64String); | // Decode a Base64 string to its original form | https://github.com/YourAverageTechBro/DevToolboxWeb/blob/d5e14628db174c0dc1a9a4249efe85536be79067/src/app/tools/base64encoder/Base64EncoderClientComponent.tsx#L58-L60 | d5e14628db174c0dc1a9a4249efe85536be79067 |
DevToolboxWeb | github_2023 | YourAverageTechBro | typescript | toHex | const toHex = (value: number) => {
const hex = value.toString(16);
return hex.length === 1 ? `0${hex}` : hex;
}; | // Convert the RGB values to hexadecimal and pad with zeros if needed | https://github.com/YourAverageTechBro/DevToolboxWeb/blob/d5e14628db174c0dc1a9a4249efe85536be79067/src/app/tools/color-converter/ColorConverterComponent.tsx#L68-L71 | d5e14628db174c0dc1a9a4249efe85536be79067 |
velite | github_2023 | zce | typescript | timestamp | const timestamp = () =>
s
.custom<string | undefined>(i => i === undefined || typeof i === 'string')
.transform<string>(async (value, { meta, addIssue }) => {
if (value != null) {
addIssue({ fatal: false, code: 'custom', message: '`s.timestamp()` schema will resolve the value from `git log -1 --... | // refer to https://velite.js.org/guide/last-modified#based-on-git-timestamp for more details | https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/examples/nextjs/velite.config.ts#L26-L35 | cfb639a8fa0452168c1be3962a1022cdb947d8d3 |
velite | github_2023 | zce | typescript | load | const load = async (config: Config, path: string, schema: Schema, changed?: string): Promise<VeliteFile> => {
path = normalize(path)
if (changed != null && path !== changed) {
const exists = VeliteFile.get(path)
// skip file if changed file not match
if (exists) return exists
}
const file = await ... | /**
* Load file and parse data with given schema
* @param config resolved config
* @param path file path
* @param schema data schema
* @param changed changed file path (relative to content root)
*/ | https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/build.ts#L32-L85 | cfb639a8fa0452168c1be3962a1022cdb947d8d3 |
velite | github_2023 | zce | typescript | resolve | const resolve = async (config: Config, changed?: string): Promise<Record<string, unknown>> => {
const { root, output, collections, prepare, complete } = config
const begin = performance.now()
logger.log(`resolving collections from '${root}'`)
const entries = await Promise.all(
Object.entries(collections).... | /**
* Resolve collections from content root
* @param config resolved config
* @param changed changed file path (relative to content root)
* @returns resolved result
*/ | https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/build.ts#L93-L167 | cfb639a8fa0452168c1be3962a1022cdb947d8d3 |
velite | github_2023 | zce | typescript | watch | const watch = async (config: Config) => {
const { watch } = await import('chokidar')
const { root, collections, configImports } = config
logger.info(`watching for changes in '${root}'`)
const patterns = Object.values(collections).flatMap(({ pattern }) => pattern)
const watcher = watch(['.', ...configImport... | /**
* Watch files and rebuild on changes
* @param config resolved config
*/ | https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/build.ts#L173-L214 | cfb639a8fa0452168c1be3962a1022cdb947d8d3 |
velite | github_2023 | zce | typescript | searchFiles | const searchFiles = async (files: string[], cwd: string = process.cwd(), depth: number = 3): Promise<string | undefined> => {
for (const file of files) {
try {
const path = resolve(cwd, file)
await access(path) // check file exists
return path
} catch {
continue
}
}
if (depth >... | /**
* recursive 3-level search files in cwd and its parent directories
* @param files filenames (relative or absolute)
* @param cwd start directory
* @param depth search depth
* @returns filename first searched
*/ | https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/config.ts#L19-L32 | cfb639a8fa0452168c1be3962a1022cdb947d8d3 |
velite | github_2023 | zce | typescript | loadConfig | const loadConfig = async (path: string): Promise<[UserConfig, string[]]> => {
// TODO: import js (mjs, cjs) config file directly without esbuild?
if (!/\.(js|mjs|cjs|ts|mts|cts)$/.test(path)) {
const ext = path.split('.').pop()
throw new Error(`not supported config file with '${ext}' extension`)
}
cons... | /**
* bundle and load user config file
* @param path config file path
* @returns user config object and dependencies
*/ | https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/config.ts#L39-L67 | cfb639a8fa0452168c1be3962a1022cdb947d8d3 |
velite | github_2023 | zce | typescript | VeliteFile.records | get records(): unknown {
return this.data.data
} | /**
* Get parsed records from file
*/ | https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/file.ts#L29-L31 | cfb639a8fa0452168c1be3962a1022cdb947d8d3 |
velite | github_2023 | zce | typescript | VeliteFile.content | get content(): string | undefined {
return this.data.content
} | /**
* Get content of file
*/ | https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/file.ts#L36-L38 | cfb639a8fa0452168c1be3962a1022cdb947d8d3 |
velite | github_2023 | zce | typescript | VeliteFile.mdast | get mdast(): Root | undefined {
if (this._mdast != null) return this._mdast
if (this.content == null) return undefined
this._mdast = Object.freeze(fromMarkdown(this.content))
return this._mdast
} | /**
* Get mdast object from cache
*/ | https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/file.ts#L43-L48 | cfb639a8fa0452168c1be3962a1022cdb947d8d3 |
velite | github_2023 | zce | typescript | VeliteFile.hast | get hast(): Nodes | undefined {
if (this._hast != null) return this._hast
if (this.mdast == null) return undefined
this._hast = Object.freeze(raw(toHast(this.mdast, { allowDangerousHtml: true })))
return this._hast
} | /**
* Get hast object from cache
*/ | https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/file.ts#L53-L58 | cfb639a8fa0452168c1be3962a1022cdb947d8d3 |
velite | github_2023 | zce | typescript | VeliteFile.plain | get plain(): string | undefined {
if (this._plain != null) return this._plain
if (this.hast == null) return undefined
this._plain = toString(this.hast)
return this._plain
} | /**
* Get plain text of content from cache
*/ | https://github.com/zce/velite/blob/cfb639a8fa0452168c1be3962a1022cdb947d8d3/src/file.ts#L63-L68 | cfb639a8fa0452168c1be3962a1022cdb947d8d3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.