Datasets:

blob_id
large_stringlengths
40
40
language
large_stringclasses
1 value
repo_name
large_stringlengths
5
119
path
large_stringlengths
4
271
score
float64
2.52
4.84
int_score
int64
3
5
text
stringlengths
26
4.09M
07f201a721761fbc51d2fc5877434ab49c92c1c2
TypeScript
josephdsbr/user-crud-backend
/src/repositories/implementations/PostgresUserRepository.ts
2.5625
3
import { Address, User } from "../../entities"; import { User as IUser, UserAttributes, UserModel } from "../../models/IUser"; import { IUpdateUserDTO } from "../../useCases/UpdateUser/UpdateUserDTO"; import { ComparePassword } from "../../utils/HashPasswordUtil"; import { IUserRepository } from "../IUserRepository"; export class PostgresUserRepository implements IUserRepository { existsByEmail(email: string): Promise<boolean> { return User.findAndCountAll({ where: { email } }).then(qty => !(qty.count === 0)); } async update(user: UserModel, data: IUpdateUserDTO): Promise<UserModel> { const serializedUser = Object.assign(user, data); return await serializedUser.save(); } findById(id: number): Promise<UserModel> { return User.findOne({ where: {id}, attributes: ['id', 'name', 'phone', 'email', 'createdAt', 'updatedAt'], include: [ { model: Address, attributes: ['id', 'street', 'number', 'complement', 'district', 'zipCode', 'city', 'state' ] } ] }); } findByEmailAndPassword(email: string, password: string): Promise<UserModel> { return User.findOne({ where: { email } }).then(user => { if (ComparePassword(user.password, password)) { return user; } else { throw new Error('Password is incorrect'); } }).catch(err => { console.error(err); throw new Error('User not found') }) } findByEmail (email: string): Promise<UserModel> { return User.findOne({ where: { email } }); } async save(user: UserAttributes): Promise<UserModel> { return await User.create(user, { include: [ { model: Address, as: 'address' } ],}); } }
9db8798a7da0b9cfd6d7c17b61080c32732f03a5
TypeScript
wartoshika/qhun-engine
/src/client/scene/LoadingScreenScene.ts
2.890625
3
/** * Copyright (c) 2017 Oliver Warrings <dev@qhun.de> * * This software is released under the MIT License. * https://opensource.org/licenses/MIT */ import { Scene } from '../scene/Scene'; import { Game } from '../Game'; /** * a basic loading screen scene */ export class LoadingScreenScene extends Scene { /** * creates the scene. the new scene starts only if the promise is resolved. * * @param game the current game holder instance */ public async create(game: Game): Promise<void> { console.log('scene create'); } /** * the update function called during game loop for the currently * active scene * * @param game the current game holder instance */ public update(game: Game): void { // console.log('scene update'); } /** * called if the scene changes. only if the promise is resolved, the * new scene will start * * @param game the current game holder instance */ public async destroy(game: Game): Promise<void> { console.log('scene destroy'); } }
c0b81a25805fe7539eec8f905d55659bec7f1303
TypeScript
SafireBlue/text-checker
/src/FindSpaces.ts
2.546875
3
import TextCheckResult from "./TextCheckResult"; import { UNonAsciiSpacesPattern, USpacesPattern } from "./Util/Spaces"; // tslint:disable-next-line:max-line-length export default async function(text: string, options: {excludesAsciiSpace: boolean} = {excludesAsciiSpace: false}): Promise<TextCheckResult[]> { const result = new Array<TextCheckResult>(); const regex = RegExp(options.excludesAsciiSpace ? UNonAsciiSpacesPattern : USpacesPattern, "mg"); let execResult: RegExpExecArray = regex.exec(text)!; while (execResult) { result.push({Name: "FindSpaces", StartIndex: execResult.index, Value: execResult[0]}); execResult = regex.exec(text)!; } return result; }
9acd38075ae75dd0056a537259b97780fb9e4db4
TypeScript
rheehot/Nuber-client
/src/modules/place.ts
2.75
3
import { createAction, createReducer, ActionType } from 'typesafe-actions'; const SET_BOTTOM_MODAL_PLACE_INFO = 'place/SET_BOTTOM_MODAL_PLACE_INFO'; export const actions = { setBottomModalInfo: createAction( SET_BOTTOM_MODAL_PLACE_INFO, (placeInfo: Address) => placeInfo, )(), }; export interface AddressInfo { address_name: string; main_address_no: string; mountain_yn: 'N' | 'Y'; region_1depth_name?: string; region_2depth_name?: string; region_3depth_name: string; sub_address_no?: string; } export interface RoadAddressInfo { address_name: string; building_name: string; main_building_no: string; region_1depth_name: string; region_2depth_name: string; region_3depth_name?: string; road_name: string; sub_building_no?: string; underground_yn: 'N' | 'Y'; zone_no: string; } export interface Address { address: AddressInfo; road_address: RoadAddressInfo; } type PlaceActions = ActionType<typeof actions>; interface PlaceState { address: Address | null; } const initialState: PlaceState = { address: null, }; const place = createReducer<PlaceState, PlaceActions>( initialState, ).handleAction([actions.setBottomModalInfo], (state, action) => { switch (action.type) { case SET_BOTTOM_MODAL_PLACE_INFO: return { ...state, address: action.payload, }; default: return state; } }); export default place;
c3a7784992b3f4687ce55ebd7739fac683cf8899
TypeScript
dom111/flow-free
/src/components/Grid.ts
2.75
3
import Element, { s } from './Element'; import Path, { Status } from '../lib/Path'; import Cell from './Cell'; import Colour from '../lib/Colour'; import PathFinder from '../lib/PathFinder'; import Point from './Point'; import TouchHighlight, { Status as HighlightStatus } from './TouchHighlight'; export class Grid extends Element { #cellMap: Map<HTMLElement, Cell> = new Map(); #currentPath: Path | null = null; #paths: Map<number, Path> = new Map(); #height: number; #touchHighlight: TouchHighlight; #width: number; constructor( height: number, width: number, cells: Cell[], touchHighlight: TouchHighlight ) { super(s('<div class="grid"></div>')); this.setSize(height, width); cells.forEach((cell) => { this.#cellMap.set(cell.element(), cell); this.append(cell); }); this.#touchHighlight = touchHighlight; this.bindEvents(); } private bindEvents(): void { this.on('pointerdown', (event) => { if (!event.isPrimary) { return; } event.preventDefault(); const cell = this.cellFromEvent(event); if (cell === null) { return; } const existingPath = this.pathFromCell(cell); if ( existingPath && existingPath.complete() && existingPath.last() === cell ) { this.#currentPath = existingPath; existingPath.setStatus(Status.DRAFT); existingPath.clear(); existingPath.push(cell); this.#touchHighlight.setColour(existingPath.colour()); return; } if (existingPath && existingPath.last() !== cell) { this.#currentPath = existingPath; existingPath.setStatus(Status.DRAFT); existingPath.breakAt(cell); this.#touchHighlight.setColour(existingPath.colour()); return; } if (existingPath && existingPath.last() === cell) { this.#currentPath = existingPath; existingPath.setStatus(Status.DRAFT); this.#touchHighlight.setColour(existingPath.colour()); return; } if (!(cell instanceof Point)) { return; } const path = new Path(cell.colour(), this); this.#currentPath = path; this.#touchHighlight.setColour(path.colour()); path.push(cell); this.#paths.set(path.colour(), path); }); this.on('pointermove', (event) => this.handleHighlight(event, this.cellFromEvent(event)) ); this.on('touchmove', (event) => { event.preventDefault(); const cell = this.cellFromEvent(event), currentPath = this.#currentPath; this.handleHighlight(event, cell); if ( cell === null || currentPath === null || (currentPath && currentPath.status() === Status.COMPLETE && !currentPath.includes(cell)) || currentPath.last() === cell ) { return; } this.handleAddCellToCurrentPath(cell); }); this.on( 'pointerenter', (event) => { if (!event.isPrimary) { return; } event.preventDefault(); const cell = this.cellFromEvent(event), currentPath = this.#currentPath; if ( cell === null || currentPath === null || (currentPath && currentPath.status() === Status.COMPLETE && !currentPath.includes(cell)) || currentPath.last() === cell ) { return; } this.handleAddCellToCurrentPath(cell); }, { capture: true, } ); this.on('pointerup', (event) => { if (this.#currentPath === null) { return; } event.preventDefault(); // TODO: break crossed paths this.#currentPath.setStatus(Status.FINAL); if (this.#currentPath.length() < 2) { this.#currentPath.clear(); this.#paths.delete(this.#currentPath.colour()); } this.#currentPath = null; this.#touchHighlight.setColour(Colour.NONE); }); } cells(): Cell[] { return Array.from(this.#cellMap.values()); } private cellFromEvent(event: PointerEvent | TouchEvent): Cell | null { return ( this.#cellMap.get( document.elementFromPoint( event instanceof TouchEvent ? event.touches[0].pageX : event.pageX, event instanceof TouchEvent ? event.touches[0].pageY : event.pageY ) as HTMLElement ) ?? null ); } private handleAddCellToCurrentPath(cell: Cell): void { const otherPath = this.pathFromCell(cell, this.#currentPath), currentPath = this.#currentPath; if (otherPath && otherPath !== currentPath && !(cell instanceof Point)) { otherPath.breakAt(cell); otherPath.pop(); } if (currentPath.includes(cell) && currentPath.last() !== cell) { currentPath.breakAt(cell); } if (currentPath.canAdd(cell)) { currentPath.push(cell); return; } const last = currentPath.last(); // TODO: instead of doing this check, this should never happen... if (!last) { return; } const pathFinder = new PathFinder(this, last, cell); if (pathFinder.isPathAvailable()) { pathFinder .shortestPath() .forEach((cell) => this.handleAddCellToCurrentPath(cell)); } } private handleHighlight( event: TouchEvent | PointerEvent | MouseEvent, cell: Cell ): void { this.#touchHighlight.move(event); if ( cell instanceof Point && this.#currentPath?.length() > 1 && this.#currentPath?.first() !== cell ) { this.#touchHighlight.setStatus(HighlightStatus.GOOD); } if ( cell instanceof Point && cell.colour() !== this.#currentPath?.colour() ) { this.#touchHighlight.setStatus(HighlightStatus.INVALID); } if (!(cell instanceof Point)) { this.#touchHighlight.setStatus(HighlightStatus.DEFAULT); } } height(): number { return this.#height; } private pathFromCell( cell: Cell, currentPath: Path | null = null ): Path | null { let path = null; this.#paths.forEach((existingPath) => { if (path) { return; } if (existingPath.includes(cell)) { path = existingPath; } }); if ( path === null && cell instanceof Point && this.#paths.has(cell.colour()) ) { path = this.#paths.get(cell.colour()); if (path !== currentPath && !path.canAdd(cell)) { path.clear(); } } return path; } private setSize(height: number, width: number): void { this.#height = height; this.#width = width; this.element().style.setProperty('--height', height.toString()); this.element().style.setProperty('--width', width.toString()); } width(): number { return this.#width; } } export default Grid;
85d73b1aa505eba5d3af7be23124da0af6802706
TypeScript
donggunn/angular2-typescript-shoping-cart
/app/cart/sum.pipe.spec.ts
2.59375
3
import {SumPipe} from './sum.pipe'; describe('Testing the sum pipe ',() => { it('shall return the correct sum for two posetive integers"', () => { let sumPipe = new SumPipe(); let transformedValue = sumPipe.transform(4,["3"]); expect(transformedValue).toEqual(12); }); })
5e3d22b07ae6754fc76a14513106bd8dc11c02f0
TypeScript
SocialGouv/cdtn-admin
/targets/alert-cli/src/diff/get-diff.ts
2.546875
3
import { GithubDiffFile } from "../APIs/api"; import { simpleGit } from "simple-git"; import { parsePatch } from "diff"; import fs from "fs"; export async function getDiff( project: string, fromTag: string, toTag: string ): Promise<GithubDiffFile[]> { const repoPath = `/tmp/${project}`; try { if (fs.existsSync(repoPath)) { // remove the repo if it already exists fs.rmSync(repoPath, { recursive: true }); } await simpleGit().clone(`https://github.com/${project}`, repoPath, { "--depth": 50, }); const diffString = await simpleGit(repoPath).diff([ `${fromTag}...${toTag}`, ]); const diffDetail = parsePatch(diffString); const result: GithubDiffFile[] = []; diffDetail.forEach(({ oldFileName, newFileName }) => { if (oldFileName === "/dev/null" && newFileName) { result.push({ filename: formatFileName(newFileName), status: "added", }); } else if (newFileName === "/dev/null" && oldFileName) { result.push({ filename: formatFileName(oldFileName), status: "removed", }); } else if (newFileName && oldFileName) { result.push({ filename: formatFileName(newFileName), status: "modified", }); } }); return result; } catch (error) { console.error(error); return []; } } export function formatFileName(filename: string): string { const parts = filename.split("/"); if (parts.length === 1) { return filename; } return parts.slice(1).join("/"); }
098e0164b53040b24aaf3b1f83ac0af7d976d83b
TypeScript
aadeshabichandani/Assignment3_ClickLabs
/src/app/private/profile/profile.component.ts
2.65625
3
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { GetDataService } from 'src/app/public/service/get-data.service'; import { dataFormat } from 'src/data-format/dataFormat'; import { PatchDataService } from '../services/patch-data.service'; @Component({ selector: 'app-profile', templateUrl: './profile.component.html', styleUrls: ['./profile.component.css'] }) export class ProfileComponent implements OnInit { //fetching stored data from localStorage public email: string = localStorage.getItem("user"); public uniqueId: string = localStorage.getItem("id"); // declaring some local variables public fetchedUserData: dataFormat; private profileForm: FormGroup; public fullName: string; constructor(private fBuilder: FormBuilder, private patchService: PatchDataService, private getService: GetDataService) { } ngOnInit() { //Creating profile form. this.profileForm = this.fBuilder.group({ first_name: [''], last_name: [''], full_name: ['', Validators.required], email: ['', [Validators.required, Validators.email]], phone_number: ['', Validators.required], address: ['', Validators.required], medical_history: [''] }); // fetching data using our service, and passing email as the parameter to identify unique user. this.getService.gettingDataById(this.uniqueId).subscribe((fetchedData: dataFormat) => { // setting the form control values with the fetched data of a particular user . this.profileForm.controls['full_name'].setValue(fetchedData.first_name + " " + fetchedData.last_name); this.profileForm.controls['email'].setValue(fetchedData.email); this.profileForm.controls['phone_number'].setValue(fetchedData.phone_number); this.profileForm.controls['address'].setValue(fetchedData.address); this.profileForm.controls['medical_history'].setValue(fetchedData.medical_history); if (this.profileForm.controls['medical_history'].value == "") { this.profileForm.controls['medical_history'].setValue("NA"); } }); } updateUserData() { // function for updating the form //checking if the form is valid, and if it is then asking the user whether he is sure to update. if (this.profileForm.valid) { if (window.confirm("Are you sure you want to update your details?")) { this.fullName = this.profileForm.get("full_name").value.split(" "); console.log(this.fullName.length) if (this.fullName.length < 2) { alert("Please enter last name"); } else { this.profileForm.get("first_name").setValue(this.fullName[0]); this.profileForm.controls['last_name'].setValue(this.fullName[1]); this.patchService.patchingUserData(this.uniqueId, this.profileForm.value).subscribe(() => { // success callback localStorage.setItem("firstName", this.fullName[0]); localStorage.setItem("lastName", this.fullName[1]); localStorage.setItem("user",this.profileForm.value.email) alert("Details updated successfully!"); //reloading our current webpage. location.reload(); }, // error callback () => { alert("Cannot Update your details currently!(ERROR)"); }) } } } else { // if the form is not valid alert("Please fill your details correctly!"); } } }
3d2b71fbbc0a79188c4660613301ce4bdd2d47a3
TypeScript
rjrodger/nid
/test/nid.test.ts
2.921875
3
/* Copyright (c) 2013-2022 Richard Rodger, MIT License */ import Nid from '../nid' let defruns = 100000 function def_id_fmt_ok(id: string) { return id.match(/^[0-9a-z]{6,6}$/) } function fmt_ok(opts: any) { if (opts.hex) { opts.alphabet = '0123456789abcdef' } else if (opts.HEX) { opts.alphabet = '0123456789ABCDEF' } let re = '^[' + opts.alphabet + ']+$' return function(id: string) { return id.length === (opts.length || 6) && id.match(re) } } function repeat(runs: any, nidf: any, passf: any) { let now = new Date().getTime() let nids = new Array(runs) for (let i = 0; i < runs; i++) { nids[i] = nidf() } let end = new Date().getTime() if (passf) { for (let i = 0; i < runs; i++) { passf(nids[i]) } } return end - now } function report(name: string, runs: any, dur: number, opts: any) { console.log( name + ': ' + Math.floor(runs / (dur / 1000)) + ' ids per second; ' + runs + ' runs in ' + dur + 'ms; len=' + opts.length + ' A=' + opts.alphabet ) } describe('happy', function() { test('works', function() { let default_cursed_list = Nid.curses() expect(Array.isArray(default_cursed_list)) let id = Nid() expect(def_id_fmt_ok(id)) }) test('basic', function() { let dur = repeat(defruns, Nid, def_id_fmt_ok) report('basic', defruns, dur, Nid) }) test('curses-spec', function() { let n0 = Nid({ len: 1, alphabet: 'abc', curses: 'a,b' }) expect(n0()).toEqual('c') let n1 = Nid({ len: 1, alphabet: 'abc', curses: /[ab]/ }) expect(n1()).toEqual('c') let n2 = Nid({ len: 1, alphabet: 'abc', curses: (code: string) => code.match(/[ab]/) }) expect(n2()).toEqual('c') }) test('options.len', function() { let opts = { length: 8 } let nid8: Nid = Nid(opts) let id = nid8() expect(fmt_ok(opts)(id)) id = Nid(8) expect(fmt_ok(opts)(id)) // let opts1 = { len: 8 } let nid8a = Nid(opts) let ida = nid8a() expect(fmt_ok(opts)(ida)) }) test('options.uuid-ish', function() { let opts = { length: 32, hex: true, curses: false } let dur = repeat(defruns, Nid(opts), fmt_ok(opts)) report('options.uuid-ish', defruns, dur, opts) }) test('options.alphabet.a', function() { let opts = { length: 1, alphabet: 'a' } let dur = repeat(defruns, Nid(opts), fmt_ok(opts)) report('options.alphabet.a', defruns, dur, opts) }) test('options.alphabet.ab', function() { let opts = { length: 1, alphabet: 'ab' } let dur = repeat(defruns, Nid(opts), fmt_ok(opts)) report('options.alphabet.ab', defruns, dur, opts) }) test('options.hex', function() { let opts = { length: 1, hex: 1 } let dur = repeat(defruns, Nid(opts), fmt_ok(opts)) report('options.hex', defruns, dur, opts) }) test('options.HEX', function() { let opts = { length: 1, HEX: 1 } let dur = repeat(defruns, Nid(opts), fmt_ok(opts)) report('options.HEX', defruns, dur, opts) }) test('options.curses.array.one', function() { let opts = { length: 1, alphabet: 'ab', curses: ['b'] } let dur = repeat(defruns, Nid(opts), fmt_ok({ length: 1, alphabet: 'a' })) report('options.curses.array.one', defruns, dur, opts) }) test('options.exclude.array.one', function() { let opts = { length: 1, alphabet: 'ab', exclude: ['b'] } let dur = repeat(defruns, Nid(opts), fmt_ok({ length: 1, alphabet: 'a' })) report('options.curses.array.one', defruns, dur, opts) }) test('options.curses.array.many', function() { let opts = { length: 1, alphabet: 'abcd', curses: ['b', 'c'] } let dur = repeat(defruns, Nid(opts), fmt_ok({ length: 1, alphabet: 'ad' })) report('options.curses.array.many', defruns, dur, opts) }) test('options.curses.csv.one', function() { let opts = { length: 1, alphabet: 'ab', curses: 'b' } let dur = repeat(defruns, Nid(opts), fmt_ok({ length: 1, alphabet: 'a' })) report('options.curses.csv.one', defruns, dur, opts) }) test('options.curses.csv.many', function() { let opts = { length: 1, alphabet: 'abcd', curses: 'b,c' } let dur = repeat(defruns, Nid(opts), fmt_ok({ length: 1, alphabet: 'ad' })) report('options.curses.csv.many', defruns, dur, opts) }) test('options.curses.re', function() { let opts = { length: 1, alphabet: 'ab', curses: /b/ } let dur = repeat(defruns, Nid(opts), fmt_ok({ length: 1, alphabet: 'a' })) report('options.curses.re', defruns, dur, opts) }) test('options.curses.function', function() { let opts = { length: 1, alphabet: 'ab', curses: function(id: string) { return 'a' === id }, } let dur = repeat(defruns, Nid(opts), fmt_ok({ length: 1, alphabet: 'a' })) report('options.curses.function', defruns, dur, opts) }) test('options.curses.case', function() { let opts = { length: 1, alphabet: 'aAbB', curses: 'b' } let dur = repeat(defruns, Nid(opts), fmt_ok({ length: 1, alphabet: 'aA' })) report('options.curses.case', defruns, dur, opts) }) })
78ff29f716955789dc4f10bbbaccbe726d19da3a
TypeScript
GorkaPawel/gym-progress-app
/src/app/shared/store.service.ts
2.53125
3
import { Injectable } from '@angular/core'; import { Rekord, State, Trening } from "~/app/shared/models"; import { BehaviorSubject } from "rxjs"; @Injectable({ providedIn: 'root', }) export class StoreService { private state: State = { rekordy: [new Rekord("wiosłowanie", '3', '10', '60', 0, new Date())], cwiczenia: ["wiosłowanie", "przysiad", "martwy ciąg"], profile: { name: "Tymoteusz", surname: "Sztacheta", gender: "male", weight: '85', height: '185', bmi: '22' }, treningi: [] }; profileSubject$ = new BehaviorSubject(this.state.profile); addRecord(record: Rekord) { const treningCopy = JSON.parse(JSON.stringify(record)); this.state.rekordy.push(treningCopy); } addTrening(trening: Trening) { const treningCopy = JSON.parse(JSON.stringify(trening)); this.state.treningi.push(treningCopy); } addCwiczenie(cwiczenie: string) { this.state.cwiczenia.push(cwiczenie); } getRecords() { return JSON.parse(JSON.stringify(this.state.rekordy)); } getTreningi() { return JSON.parse(JSON.stringify(this.state.treningi)); } getCwiczenia() { return [...this.state.cwiczenia]; } constructor() { } }
d2d415c719c40f9c5d89409fd086afb5bc305435
TypeScript
blslade-neumont/agile-html5-game
/src/engine/test/mock-dom.ts
2.640625
3
/// <reference types="mocha" /> export class MockContext { constructor(readonly canvas: MockElement) { } save() { } restore() { } translate() { } rotate() { } scale() { } fillRect() { } fillText() { } measureText() { return { width: 42 } } drawImage() { } } export class MockElement { width = 925; height = 295; scrollWidth = 640; scrollHeight = 480; //canvas getContext() { return new MockContext(this); } } export class MockDocument { constructor() { } private element = new MockElement(); createElement(type: string) { if (type == 'img') return new MockImage(); else if (type == 'audio') return new MockAudio(); return this.element; } getElementById() { return this.element; } getElementsByClassName() { return [this.element]; } getElementsByName() { return [this.element]; } getElementsByTagName() { return [this.element]; } getElementsByTagNameNS() { return [this.element]; } } export class MockImage extends MockElement { constructor(width?: number, height?: number) { super(); this.width = width; this.height = height; } } export class MockAudio extends MockElement { constructor() { super(); } play() { this.paused = false; } pause() { this.paused = true; } paused = true; } export class MockWindow { location = new MockLocation(); } export class MockLocation { origin = 'null/C:/agile-html5-game'; pathname = '/agile-html5-game/index.html'; } declare let global: any; export function stubDOM() { let previousDocument: any; let previousWindow: any; let previousCanvas: any; let previousImage: any; let previousAudio: any; beforeEach(() => { previousDocument = global.document; global.document = new MockDocument(); previousWindow = global.window; global.window = new MockWindow(); previousCanvas = global.HTMLCanvasElement; global.HTMLCanvasElement = MockElement; previousImage = global.HTMLImageElement; global.HTMLImageElement = MockImage; previousAudio = global.HTMLAudioElement; global.HTMLAudioElement = MockAudio; }); afterEach(() => { delete global.document; if (typeof previousDocument !== 'undefined') global.document = previousDocument; delete global.window; if (typeof previousWindow !== 'undefined') global.window = previousWindow; delete global.HTMLCanvasElement; if (typeof previousCanvas !== 'undefined') global.HTMLCanvasElement = previousCanvas; delete global.HTMLImageElement; if (typeof previousImage !== 'undefined') global.HTMLImageElement = previousImage; delete global.HTMLAudioElement; if (typeof previousAudio !== 'undefined') global.HTMLAudioElement = previousAudio; }); } stubDOM();
810e27abf85860c293a7ab7ad04d7fbfccb2db0f
TypeScript
rafaelsanzio/ioasys
/src/modules/users/repositories/fakes/FakeUsersRepository.ts
2.75
3
import { v4 } from 'uuid'; import AppError from '@shared/errors/AppError'; import User from '@modules/users/infra/typeorm/entities/User'; import ICreateUserDTO from '@modules/users/dtos/ICreateUserDTO'; import IUpdateUserDTO from '@modules/users/dtos/IUpdateUserDTO'; import IUsersRepository from '@modules/users/repositories/IUsersRepository'; import IUpdateUserRoleDTO from '@modules/users/dtos/IUpdateUserRoleDTO'; class FakeUsersRepository implements IUsersRepository { private users: User[] = []; public async findById(id: string): Promise<User | undefined> { const user = this.users.find(user => user.id === id); return user; } public async findByEmail(email: string): Promise<User | undefined> { const user = this.users.find(user => user.email === email); return user; } public async create({ name, email, role, password, }: ICreateUserDTO): Promise<User> { const user = new User(); Object.assign(user, { id: v4() }, { name, email, role, password }); this.users.push(user); return user; } public async update({ id, name }: IUpdateUserDTO): Promise<User> { const user = this.users.find(user => user.id === id); if (!user) { throw new AppError('User does not found', 404); } user.name = name; return user; } public async updateRole({ id, role }: IUpdateUserRoleDTO): Promise<User> { const user = this.users.find(user => user.id === id); if (!user) { throw new AppError('User does not found', 404); } user.role = role; return user; } public async delete(id: string): Promise<User> { const user = this.users.find(user => user.id === id); if (!user) { throw new AppError('User does not found', 404); } user.deleted_at = new Date(); return user; } public async save(user: User): Promise<User> { const findIndex = this.users.findIndex(findUser => findUser.id === user.id); this.users[findIndex] = user; return user; } } export default FakeUsersRepository;
a8755896b5e462a38e518460275b7c372750c4ab
TypeScript
petterigit/TheSir
/src/utils/ruokaa-utils/generalUtils.ts
3.296875
3
import path from "path"; import { DayChangeHourUtc } from "./consts"; export const getWeekday = () => { const date = new Date(); const hour = date.getUTCHours(); let day = date.getUTCDay(); if (hour >= DayChangeHourUtc) day++; if (day === 7) day = 0; return day; }; export const getNextFinnishDay = (weekDay: number) => { const nextDay = { 0: "Maanantai", // On sunday, give next monday's list 1: "Maanantai", 2: "Tiistai", 3: "Keskiviikko", 4: "Torstai", 5: "Perjantai", 6: "Lauantai", }[weekDay]; return nextDay; }; export const getNextFinnishDayShort = (weekDay: number) => { const nextDay = { 0: "su", 1: "ma", 2: "ti", 3: "ke", 4: "to", 5: "pe", 6: "la", }[weekDay]; return nextDay; }; export const getNextEnglishDayShort = (weekDay: number) => { const nextDay = { 0: "Sun", 1: "Mon", 2: "Tue", 3: "Wed", 4: "Thu", 5: "Fri", 6: "Sat", }[weekDay]; return nextDay; }; export const pathToPNG = (imageName: string) => path.join(process.cwd(), `${imageName}.png`); export const getCurrentWeekNumber = () => { const currentDate = new Date(); const startDate = new Date(currentDate.getFullYear(), 0, 1); const days = Math.floor( (currentDate.getUTCMilliseconds() - startDate.getUTCMilliseconds()) / (24 * 60 * 60 * 1000) ); const weekNumber = Math.ceil(days / 7); // Display the calculated result console.log("Week number of " + currentDate + " is : " + weekNumber); return weekNumber; };
a2d9847cc629c8e8a93e1ae670dbeb97f4f9cb66
TypeScript
Dinkimom/configuration-module
/src/services/AbstractClient.ts
2.578125
3
/* eslint-disable no-console */ import axios, { AxiosRequestConfig, AxiosError, AxiosResponse } from 'axios' import { serverEntryPoint } from '../shared/constants/serverEntryPoint' import { RequestsEnum } from '../shared/enums/RequestsEnum' import { Entity } from '../shared/types/Entity' import { notificationSystem } from '../app/app' export abstract class AbstractClient { public entity: Entity public URL: string public axios = axios.create({ timeout: 20000 }) public abstract add: (...args: any) => any public abstract update: (...args: any) => any public abstract delete: (...args: any) => any public abstract getItem: (...args: any) => any public abstract getItems: (...args: any) => any public constructor(entity: Entity) { this.entity = entity this.URL = `${serverEntryPoint}${this.entity}` } public helper = ( request: RequestsEnum, data: { _id?: string body?: any } = {}, params: { [key: string]: any } = {}, ): AxiosRequestConfig => { switch (request) { case RequestsEnum.add: return { url: `${this.URL}/item`, method: 'POST', data: data.body, } case RequestsEnum.update: return { url: `${this.URL}/item/${data._id}`, method: 'PUT', data: data.body, } case RequestsEnum.delete: return { url: `${this.URL}/item/${data._id}`, method: 'DELETE', } case RequestsEnum.getItem: return { url: `${this.URL}/item/${data._id}`, method: 'GET', } case RequestsEnum.getItems: return { url: `${this.URL}/items/`, method: 'GET', params: { ...params }, } default: return {} as AxiosRequestConfig } } public errorHandler = (error: AxiosError): AxiosResponse | AxiosError => { // Error 😨 if (error.response) { /* * The request was made and the server responded with a * status code that falls out of the range of 2xx */ console.log(error.response.data) console.log(error.response.status) console.log(error.response.headers) return error.response } if (error.request) { /* * The request was made but no response was received, `error.request` * is an instance of XMLHttpRequest in the browser and an instance * of http.ClientRequest in Node.js */ console.log(error.request) notificationSystem.current.addNotification({ position: 'tc', message: error.message, level: 'error', }) return { data: { error: error.message, }, } as AxiosResponse } // Something happened in setting up the request and triggered an Error console.log('Error', error.message) return error } }
37d021c224eb3a06e035da32ac6b5be6fbe1eee0
TypeScript
typecli/framework
/spec/book/value_types_of_arguments_and_options/string.spec.ts
2.65625
3
import { capture } from '@typescript-plus/stream-capture'; import { Argument, parseSync } from '../../../src'; class Args { @Argument() s?: string; } it('Book - Value Types of Arguments and Options - String', () => { const captured = capture(process.stdout, (buffer) => { const parsed = new Args(); parseSync(parsed, ['foo']); console.log(parsed.s); return buffer.join(''); }); expect(captured).toEqual(`foo\n`); });
0805ea35a2819479f572f2a2dca7b7064fc1fc08
TypeScript
tuongvy2679/thuchanh1
/src/app/bai8/bai8.component.ts
2.953125
3
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-bai8', templateUrl: './bai8.component.html', styleUrls: ['./bai8.component.css'] }) export class Bai8Component implements OnInit { constructor() { } V = 1; a = 3; b = 6; c = 4; h = 12; title = "Bài 8: Tính thể tích của hình chóp khi biết diện tích đáy và chiều cao"; ngOnInit(): void { var n = new HinhChop(this.a, this.b, this.c, this.h); if (n.kiemtratamgiac() == true) { this.V = Math.round(n.thetich()); } } } export class HinhTamGiac { protected a: number; protected b: number; protected c: number; constructor(a: number, b: number, c: number) { this.a = a; this.b = b; this.c = c; } public kiemtratamgiac() { if (this.a + this.b > this.c && this.b + this.c > this.a) { if (this.a + this.c > this.b) { return true; } else return false; } else return false; } public dientich(): number { return Math.sqrt((this.a + this.b + this.c) * (this.b + this.c - this.a) * (this.a + this.b - this.c) * (this.a + this.c - this.b)); } } export class HinhChop extends HinhTamGiac { protected h: number; constructor(a: number, b: number, c: number, h: number) { super(a, b, c); this.h = h; } public thetich(): number { return this.dientich() * this.h / 3; } }
1f376377e5b674785f1bc48cb58e6d86258d7af4
TypeScript
garoqui/Angular-Ngrx
/src/app/reducers/offer.reducer.ts
2.734375
3
import { Action } from '@ngrx/store' import { ADDOFFER, CLEANOFFER } from '../actions/offer.action' import { Offer } from '../model/offer' interface customAction{ type : string, payload : string } const initialState = { offer : new Offer("","", [], []) } export function offerReducer(state = [initialState ] , action : customAction){ switch( action.type){ case ADDOFFER: return [action.payload] case CLEANOFFER: state = undefined return state } }
89f1e352947a547b0626178fafc4af09545fd8c6
TypeScript
tiagowanke/counting-words
/src/app/word-frequency-analyzer/helpers/word-splitter/word-splitter.helper.ts
3.53125
4
export class WordSplitterHelper { /** * * @returns array of string with each word from the given text. * Word: A word is represented by a sequence of one * or more characters between „a‟ and „z‟ or between „A‟ and * „Z‟). For example “agdfBh”. */ static splitTextInWords(text: string): string[] { let words: string[] = []; if (text) { const wordPattern = /[A-Za-z]+/g; const matchWords = text.match(wordPattern); words = matchWords ? matchWords.map((word) => word.toString()) : []; } return words; } }
ac3fd96d3b7e8a47d42a3a2592dc6fc81a2c657a
TypeScript
smurwafer/backend
/src/routes/story/update.ts
2.5625
3
import express, { Request, Response, NextFunction } from 'express'; import { requireAuth } from '../../middlewares/require-auth'; import { Story } from '../../models/story'; const Router = express.Router(); Router.put('/api/story/:id', requireAuth, async (req: Request, res: Response, next: NextFunction) => { try { const id = req.params.id; const { title, text, gallery, hashtags } = req.body; const story = await Story.findById(id); if(!story) { throw new Error('No such story exists!'); } story.set({ title, text, gallery, hashtags, }); await story.save(); res.status(204).send({ message: 'story updated successfully', story, }); } catch (err) { next(err); } }); export { Router as StoryUpdateRouter };
519126243194ac88c8f18a55c1df116ba5cd716b
TypeScript
ywarezk/angular-beginners-asal
/06-asynchronous-programming/02-promise-example.ts
3.53125
4
/** Promise Promise class */ // promise is good here // ------O--|----------> // ------X-------------> // promise is not good here // ----O----O----O----O----O----> // Promise states // pending ----> Fullfilled // pending ----> Rejected const myFirstPromise: Promise<string> = new Promise((resolve, reject) => { // you place a callback in the constructor with your async code // inside that callback setTimeout(() => { // console.log('hello world'); resolve('hello world'); // resolve(36); // resolve('foo bar'); // reject(new Error('describe the error that happened')) }, 1000); }); myFirstPromise.then( (msg: string) => { console.log(msg); }, (err) => { console.log('something happened: ' + err.message) } ) myFirstPromise.then( (msg: string) => { console.log(msg); }, (err) => { console.log('something happened: ' + err.message) } )
89474dfb660550bae586f5b48a4f44aef3c54cce
TypeScript
Doned-cmd/OCL1-Proyecto2-201801528
/src/Clases/Expresiones/Ternario.ts
2.921875
3
import Errores from "../Ast/Errores"; import Nodo from "../Ast/Nodo"; import Controlador from "../Controlador"; import { Expresion } from "../Interfaces/Expresion"; import { TablaSimbolos } from "../TablaSimbolos/TablaSimbolos"; import { tipo } from "../TablaSimbolos/Tipo"; export default class Ternario implements Expresion{ public condicion : Expresion; public verdadero : Expresion; public falso : Expresion; public linea : number; public columna : number; constructor(condicion, verdadero, falso, linea, columna) { this.condicion = condicion; this.verdadero = verdadero; this.falso = falso; this.linea = linea; this.columna = columna; } getTipo(controlador: Controlador, ts: TablaSimbolos): tipo { let valor_condicion = this.condicion.getValor(controlador,ts); if(typeof valor_condicion == 'boolean'){ return valor_condicion ? this.verdadero.getTipo(controlador,ts) : this.falso.getTipo(controlador,ts); }else{ let error = new Errores('Semantico', `Error al obtener el tipo en la operacion ternaria el valor de condicion no es buleano `, this.linea, this.columna); controlador.errores.push(error); controlador.append(`Error al obtener el tipo en la operacion ternaria el valor de condicion no es buleano `+ "Linea: " +this.linea ); return null; } } getValor(controlador: Controlador, ts: TablaSimbolos) { let valor_condicion = this.condicion.getValor(controlador,ts); if(typeof valor_condicion == 'boolean'){ return valor_condicion ? this.verdadero.getValor(controlador,ts) : this.falso.getValor(controlador,ts); }else{ let error = new Errores('Semantico', `Error al obtener el valor en la operacion ternaria el valor de condicion no es buleano `, this.linea, this.columna); controlador.errores.push(error); controlador.append(`Error al obtener el valor en la operacion ternaria el valor de condicion no es buleano `+ "Linea: " +this.linea ); return null; } } recorrer(): Nodo { let padre = new Nodo("Ternario",""); let hijoCondicion = new Nodo("condicion",""); hijoCondicion.AddHijo(this.condicion.recorrer()) padre.AddHijo(hijoCondicion); padre.AddHijo(new Nodo("?","")) padre.AddHijo(new Nodo(":","")) return padre; } }
cdaedde3a4acad0fd8872049cb1109570bf5a0d5
TypeScript
dmarku/starship-garden
/src/index.ts
2.703125
3
import { Engine, Scene, ArcRotateCamera, HemisphericLight, MeshBuilder, Vector3, Matrix, Color3, StandardMaterial, Color4, TransformNode, ActionManager, ExecuteCodeAction } from "@babylonjs/core"; import { TreeParameters } from "./ITreeParameters"; import { NewTreeGraphics } from "./NewTreeGraphics"; import { FMSynth } from "./audio/FMSynth"; // cache halftones from C1 - C7 let notes: number[] = []; for (let halftones = -57; halftones < 28; halftones++) { notes.push(440 * Math.pow(2, halftones / 12)); } // finds the closest frequency match in the notes array function roundToChromatic(frequency: number): number { return notes.reduce( (best, current) => Math.abs(current - frequency) < Math.abs(best - frequency) ? current : best, Infinity ); } // NOTE TO SELF: y-axis is up! const canvas = document.getElementById("scene") as HTMLCanvasElement; const engine = new Engine(canvas, true); const scene = new Scene(engine); scene.clearColor = Color4.FromHexString("#8baff3ff"); new ArcRotateCamera("cam", 0, 0.32 * Math.PI, 30, Vector3.Zero(), scene); //camera.attachControl(canvas, true); new HemisphericLight("light", new Vector3(1, 1, 0), scene); const ground = MeshBuilder.CreateGround( "ground", { width: 25, height: 25, subdivisions: 3 }, scene ); const seedIndicator = MeshBuilder.CreateCylinder( "seed indicator", { diameterTop: 0, diameterBottom: 0.5, height: 1, subdivisions: 1, tessellation: 4 }, scene ); seedIndicator.rotate(Vector3.Left(), Math.PI); seedIndicator.bakeTransformIntoVertices(Matrix.Translation(0, -0.5, 0)); seedIndicator.visibility = 0; const indicatorMaterial = new StandardMaterial("indicatorMaterial", scene); indicatorMaterial.emissiveColor = Color3.Gray(); seedIndicator.material = indicatorMaterial; const groundMaterial = new StandardMaterial("groundMaterial", scene); groundMaterial.diffuseColor = Color3.FromHexString("#edb76d"); ground.material = groundMaterial; const treeMaterial = new StandardMaterial("trunkMaterial", scene); treeMaterial.diffuseColor = Color3.FromHexString("#38d051"); treeMaterial.specularColor = new Color3(0.1, 0.1, 0.1); interface ITree { root: TransformNode; audio: { carrier: OscillatorNode; envelopeFrequency: AudioParam; frequency: AudioParam; }; size: number; } function getFrequency(size: number): number { // let's assume reasonable scaling factors go from 0.1 to 10 // set frequencies between 220 and 880 hertz (so that two orders of magnitude ~ two octaves) // map [0.1, 10] -> [0, 1] const s = (10 - size) / (10 - 0.1); // map exponentially [0, 1] -> [0, 1] const factor = (Math.exp(s) - 1) / (Math.E - 1); const frequency = factor * 2093.0 /* C7 */ + (1 - factor) * 32.7; /* C1 */ return roundToChromatic(frequency); } function getEnvelopeFrequency(size: number): number { // for explanation, see `getFrequency()` const s = (10 - size) / (10 - 0.1); const factor = (Math.exp(s) - 1) / (Math.E - 1); return (factor * 1) / 5 + ((1 - factor) * 1) / 51; } class Tree implements ITree { //public root: TreeGraphics; public root: NewTreeGraphics; public audio: ITree["audio"]; public size: number; private carrierFrequency: ConstantSourceNode; private envelopeFrequency: ConstantSourceNode; constructor( parameters: TreeParameters, scene: Scene, ctx: AudioContext, output: AudioNode ) { parameters.size = parameters.size || 2; this.size = parameters.size; //////////////////////////////////////////////////////// // setup graphics const root = new NewTreeGraphics("tree", parameters, treeMaterial, scene); //////////////////////////////////////////////////////// // setup audio const carrier = new OscillatorNode(ctx, { type: "sine", frequency: 0 }); const envelope = new GainNode(ctx, { gain: 0.15 }); const envOsc = new OscillatorNode(ctx, { type: "sine", frequency: 0 }); const envOscWidth = new GainNode(ctx, { gain: 0.1 }); envOsc.connect(envOscWidth).connect(envelope.gain); carrier.connect(envelope).connect(output); carrier.start(); envOsc.start(); this.carrierFrequency = new ConstantSourceNode(ctx, { offset: getFrequency(this.size) }); this.carrierFrequency.start(); this.carrierFrequency.connect(carrier.frequency); this.envelopeFrequency = new ConstantSourceNode(ctx, { offset: getEnvelopeFrequency(this.size) }); this.envelopeFrequency.start(); this.envelopeFrequency.connect(envOsc.frequency); //////////////////////////////////////////////////////// // setup interaction const actionManager = root.actionManager; actionManager.registerAction( new ExecuteCodeAction( { trigger: ActionManager.OnPickUpTrigger }, () => { if (tool === "Tree Remover") { removeTree(this); } if (tool === "Fertilizer") { this.grow(); } } ) ); actionManager.registerAction( new ExecuteCodeAction( { trigger: ActionManager.OnPointerOverTrigger }, () => focusTree(this) ) ); actionManager.registerAction( new ExecuteCodeAction( { trigger: ActionManager.OnPointerOutTrigger }, () => blurTree(this) ) ); root.position = parameters.position ? new Vector3( parameters.position.x, parameters.position.y, parameters.position.z ) : Vector3.Zero(); // placeholder for audio props const audio = { carrier, frequency: this.carrierFrequency.offset, envelopeFrequency: this.envelopeFrequency.offset }; this.root = root; this.audio = audio; } toJson(): TreeParameters { return { position: { x: this.root.position.x, y: this.root.position.y, z: this.root.position.z }, size: this.size }; } grow() { this.size += 1; this.root.update(this.size); this.carrierFrequency.offset.value = getFrequency(this.size); this.envelopeFrequency.offset.value = getEnvelopeFrequency(this.size); save(); } } function removeTree(tree: Tree) { tree.root.dispose(); tree.audio.carrier.stop(); trees = trees.filter(t => t !== tree); save(); } const ctx = new AudioContext(); const master = ctx.createGain(); master.gain.value = 0.25; master.connect(ctx.destination); let trees: Tree[] = []; function save() { localStorage.setItem("scene", serialize()); } function load() { const serializedScene = localStorage.getItem("scene"); trees = serializedScene ? deserialize(serializedScene) : defaultScene(); } function serialize(): string { const data = trees.map(tree => ({ position: { x: tree.root.position.x, y: tree.root.position.y, z: tree.root.position.z }, size: tree.size })); return JSON.stringify(data); } function deserialize(json: string) { const data = JSON.parse(json) as any[]; // TODO: clear everything before return data.map( parameters => new Tree( { ...parameters, position: new Vector3( parameters.position.x, parameters.position.y, parameters.position.z ) }, scene, ctx, master ) ); } function defaultScene(): Tree[] { return [ new Tree({ position: new Vector3(0, 0, -3), size: 1 }, scene, ctx, master), new Tree({ position: new Vector3(0.5, 0, 5), size: 3 }, scene, ctx, master) ]; } type Tool = null | "Seed Placement" | "Tree Remover" | "Fertilizer"; let tool: Tool = null; let focusedTree: Tree | null = null; function focusTree(tree: Tree) { if (focusedTree !== tree) { if (focusedTree) { focusedTree.root.material.emissiveColor = Color3.Black(); } focusedTree = tree; if (tool === "Tree Remover") { tree.root.material.emissiveColor = Color3.Red(); } else if (tool === "Fertilizer") { tree.root.material.emissiveColor = Color3.Green(); } else { tree.root.material.emissiveColor = Color3.Gray(); } } } function blurTree(tree: Tree) { if (tree === focusedTree) { tree.root.material.emissiveColor = Color3.Black(); focusedTree = null; } } function toggleTool(newTool: Tool) { if (tool !== newTool) { tool = newTool; console.log(`${newTool} selected`); // purely visual changes if (focusedTree) { if (tool === "Tree Remover") { focusedTree.root.material.emissiveColor = Color3.Red(); } else if (tool === "Fertilizer") { focusedTree.root.material.emissiveColor = Color3.Green(); } else { focusedTree.root.material.emissiveColor = Color3.Gray(); } } } else { tool = null; if (focusedTree) { focusedTree.root.material.emissiveColor = Color3.Gray(); } console.log("no tool selected"); } if (tool === "Seed Placement") { seedIndicator.visibility = 1; } else { seedIndicator.visibility = 0; } if (toolDisplay) { toolDisplay.innerText = tool ? tool : "Nothing"; } } scene.actionManager = new ActionManager(scene); scene.actionManager.registerAction( new ExecuteCodeAction( { trigger: ActionManager.OnKeyUpTrigger, parameter: "s" }, () => toggleTool("Seed Placement") ) ); scene.actionManager.registerAction( new ExecuteCodeAction( { trigger: ActionManager.OnKeyUpTrigger, parameter: "d" }, () => toggleTool("Tree Remover") ) ); scene.actionManager.registerAction( new ExecuteCodeAction( { trigger: ActionManager.OnKeyUpTrigger, parameter: "f" }, () => toggleTool("Fertilizer") ) ); ground.actionManager = new ActionManager(scene); ground.actionManager.registerAction( new ExecuteCodeAction({ trigger: ActionManager.OnPickUpTrigger }, () => { if (tool === "Seed Placement") { const result = scene.pick( scene.pointerX, scene.pointerY, mesh => mesh === ground ); if (result && result.hit) { trees.push( new Tree( { size: 1, position: result.pickedPoint || Vector3.Zero() }, scene, ctx, master ) ); console.log("seed placed"); save(); } } }) ); const matchIndicatorToCursor = new ExecuteCodeAction( { trigger: ActionManager.OnEveryFrameTrigger }, () => { const result = scene.pick( scene.pointerX, scene.pointerY, mesh => mesh === ground ); if (result && result.hit && result.pickedPoint) { seedIndicator.position.copyFrom(result.pickedPoint); } } ); ground.actionManager.registerAction( new ExecuteCodeAction({ trigger: ActionManager.OnPointerOverTrigger }, () => { scene.actionManager.registerAction(matchIndicatorToCursor); }) ); ground.actionManager.registerAction( new ExecuteCodeAction({ trigger: ActionManager.OnPointerOutTrigger }, () => { scene.actionManager.unregisterAction(matchIndicatorToCursor); }) ); load(); engine.runRenderLoop(() => { scene.render(); }); function onVisibilityChange() { if (document.hidden) { ctx.suspend(); } else { ctx.resume(); } } document.addEventListener("visibilitychange", onVisibilityChange); // trigger once for initialization onVisibilityChange(); const noToolButton = document.getElementById("select-nothing"), seedToolButton = document.getElementById("select-seed"), fertilizeToolButton = document.getElementById("select-fertilize"), removeToolButton = document.getElementById("select-remove"); const toolDisplay = document.getElementById("tool-display"); if (noToolButton) noToolButton.addEventListener("click", () => toggleTool(null)); if (seedToolButton) seedToolButton.addEventListener("click", () => toggleTool("Seed Placement")); if (fertilizeToolButton) fertilizeToolButton.addEventListener("click", () => toggleTool("Fertilizer")); if (removeToolButton) removeToolButton.addEventListener("click", () => toggleTool("Tree Remover")); const synth = new FMSynth(ctx, master); document.addEventListener("keydown", ev => { if (ev.key === "g" && !ev.repeat) { synth.trigger(); } }); document.addEventListener("keyup", ev => { if (ev.key === "g") { synth.release(); } });
93322117b6a1e216458618e391388c31ccdf3ac1
TypeScript
lvjiaming/pinusTest
/client/assets/Game/40107/script/GameLogic_40107.ts
3.46875
3
const MASK_COLOR = 0xF0; const MASK_VALUE = 0x0F; enum SAME { KING = 0, ONE, TWO, THREE, FOUR, } export enum TYPE { ERROR = 0, //错误类型 SINGLE, //单牌类型 DOUBLE, //对牌类型 THREE, //三条类型 SINGLE_LINE, //单连类型 DOUBLE_LINE, //对连类型 THREE_LINE, //三连类型 THREE_TAKE_ONE, //三带一单 THREE_TAKE_TWO, //三带一对 THREE_LINE_TAKE_ONE, //飞机带俩单 THREE_LINE_TAKE_TWO, //飞机带俩对 FOUR_TAKE_ONE, //四带两单 FOUR_TAKE_TWO, //四带两对 BOMB, //炸弹类型 MISSILE //火箭类型 } export default class GameLogic_40107 { static _instance: GameLogic_40107 = null; public static get instance(): GameLogic_40107 { if (this._instance == null) { this._instance = new GameLogic_40107(); } return this._instance; } public getColor(cardData: number) { return (cardData & MASK_COLOR) >> 4; } public getValue(cardData: number) { return (cardData & MASK_VALUE); } public getLogicValue(card: number) { let value = this.getValue(card); let color = this.getColor(card); if (color == 4) return value + 2; else return value <= 2 ? (value + 13) : value; } // 小到大排序 public sortCard(cards: number[]) { cards.sort((a, b) => { if (this.getLogicValue(a) > this.getLogicValue(b)) return 1; else if (this.getLogicValue(a) < this.getLogicValue(b)) return -1; else { if (a > b) return 1; else if (a < b) return -1; else return 0; } }); } // 分析牌, 1234张同牌的数量 private analyseCard(cardData: number[]): number[][] { let res: number[][] = []; for (let i = SAME.KING; i <= SAME.FOUR; i++) { res[i] = []; } let sameCnt = 0; let cards = cardData.slice(0); this.sortCard(cards); for (let i = 0; i < cards.length; i++) { if (cards[i] == 0) continue; let value = this.getLogicValue(cards[i]); if (this.getColor(cards[i]) == 4) { res[SAME.KING].push(value); res[SAME.ONE].push(value); continue; } sameCnt = 1; for (let j = i + 1; j < cards.length; j++) { if (this.getLogicValue(cards[j]) == value) { sameCnt++; } } if (sameCnt > SAME.FOUR) { console.log('analyseCard error sameCnt:' + sameCnt); return res; } res[sameCnt].push(value); i += sameCnt - 1; } return res; } public getCardType(cards: number[]): TYPE { if (cards.length == 0) { console.log('getCardType error length = 0'); return TYPE.ERROR; } else if (cards.length == 1) return TYPE.SINGLE; let res = this.analyseCard(cards); if (cards.length == 2) { if (res[SAME.KING].length == 2) return TYPE.MISSILE; if (res[SAME.TWO].length == 1) return TYPE.DOUBLE; } if (res[SAME.FOUR].length == 1) { if (cards.length == 4) return TYPE.BOMB; if (cards.length == 6 && (res[SAME.ONE].length == 2 && res[SAME.KING].length <= 1)) return TYPE.FOUR_TAKE_ONE; if (cards.length == 8 && res[SAME.TWO].length == 2) return TYPE.FOUR_TAKE_TWO; } if (res[SAME.THREE].length == 1) { if (cards.length == 3) return TYPE.THREE; if (cards.length == 4 && res[SAME.ONE].length == 1) return TYPE.THREE_TAKE_ONE; if (cards.length == 5 && res[SAME.TWO].length == 1) return TYPE.THREE_TAKE_TWO; } let checkLine = (values: number[]) => { let first = values[0]; for (let i = 1; i < values.length; i++) { if (first + i != values[i] || first + i > 14) return false; } return true; }; if (res[SAME.THREE].length > 1 && checkLine(res[SAME.THREE])) { if (cards.length == (res[SAME.THREE].length * 3)) return TYPE.THREE_LINE; if (res[SAME.TWO].length == res[SAME.THREE].length && cards.length == (res[SAME.THREE].length * 3 + res[SAME.TWO].length * 2)) return TYPE.THREE_LINE_TAKE_TWO; if (res[SAME.ONE].length == res[SAME.THREE].length && cards.length == (res[SAME.THREE].length * 3 + res[SAME.ONE].length)) return TYPE.THREE_LINE_TAKE_ONE; } if (res[SAME.ONE].length >= 5 && checkLine(res[SAME.ONE]) && res[SAME.ONE].length == cards.length) return TYPE.SINGLE_LINE; if (res[SAME.TWO].length >= 3 && checkLine(res[SAME.TWO]) && cards.length == 2 * res[SAME.TWO].length) return TYPE.DOUBLE_LINE; console.log('getCardType error', cards); return TYPE.ERROR; } getBiggerCard(cardData: number[], currentCard: number[]) { let res: number[][] = []; // 牌数量比当前牌少 if (cardData.length < currentCard.length) return res; let cards = cardData.slice(0); this.sortCard(cards); if (currentCard.length > 0) { let cur = currentCard.slice(0); this.sortCard(cur); let type = this.getCardType(cur); let analyseCur = this.analyseCard(cur); switch (type) { case TYPE.SINGLE: case TYPE.DOUBLE: case TYPE.THREE: case TYPE.BOMB: { let result = this.searchSameCard(cards, type == TYPE.BOMB ? 4 : type, this.getLogicValue(cur[0])); res = res.concat(result); break; } case TYPE.MISSILE: { return []; } case TYPE.SINGLE_LINE: case TYPE.DOUBLE_LINE: case TYPE.THREE_LINE: { let same = 0; if (type == TYPE.SINGLE_LINE) same = 1; else if (type == TYPE.DOUBLE_LINE) same = 2; else same = 3; let result = this.searchLine(cards, currentCard.length / same, same, this.getLogicValue(cur[0])); res = res.concat(result); break; } case TYPE.THREE_TAKE_ONE: { let result = this.searchSameTake(cards, 3, 1, 1, analyseCur[SAME.THREE][0]); res = res.concat(result); break; } case TYPE.THREE_TAKE_TWO: { let result = this.searchSameTake(cards, 3, 1, 2, analyseCur[SAME.THREE][0]); res = res.concat(result); break; } case TYPE.FOUR_TAKE_ONE: { let result = this.searchSameTake(cards, 4, 2, 1, analyseCur[SAME.FOUR][0]); res = res.concat(result); break; } case TYPE.FOUR_TAKE_TWO: { let result = this.searchSameTake(cards, 4, 2, 2, analyseCur[SAME.FOUR][0]); res = res.concat(result); break; } case TYPE.THREE_LINE_TAKE_ONE: { let result = this.searchThreeLineTake(cards, 1, analyseCur[SAME.THREE].length, analyseCur[SAME.THREE][0]); res = res.concat(result); break; } case TYPE.THREE_LINE_TAKE_TWO: { let result = this.searchThreeLineTake(cards, 2, analyseCur[SAME.THREE].length, analyseCur[SAME.THREE][0]); res = res.concat(result); break; } } if (type != TYPE.BOMB) { let result = this.searchSameCard(cards, 4); res = res.concat(result); } let analyse = this.analyseCard(cards); if ((analyse[SAME.KING].length == 2)) { res.push(this.getCardsByValue(cards, [16, 17], 1)); } return res; } else { // 如果最后一手牌能出, 提示一手牌 let type = this.getCardType(cards); if (type != TYPE.ERROR) return [cards]; let valueCnt = this.analyseValueCnt(cards); for (let i = 3; i < valueCnt.length; i++) { if (valueCnt[i] > 0) { res.push(this.getCardsByValue(cards, [i], valueCnt[i])); } } return res; } } searchThreeLineTake(cards: number[], takeType: number, lineCnt: number, smallValue: number) { let same: number[][] = this.searchLine(cards, lineCnt, 3, smallValue); return this._getRemoveTake(cards, same, lineCnt, takeType); } // takeType 1 单 2 对 searchSameTake(cards: number[], sameCnt: number, takeCnt: number, takeType: number, smallValue: number) { let res: number[][] = []; let analyse = this.analyseCard(cards); let isFind = false; for (let i = sameCnt; i <= SAME.FOUR; i++) { analyse[i].forEach(value => { if (value > smallValue) isFind = true; }); } if (!isFind) return res; let same = this.searchSameCard(cards, sameCnt, smallValue); return this._getRemoveTake(cards, same, takeCnt, takeType); } // 删除牌再找单张和对 _getRemoveTake(cards: number[], removeCard: number[][], takeCnt: number, takeType: number) { let res: number[][] = []; for (let key of removeCard) { let temp = cards.slice(0); let tempRes = key.slice(0); this.removeCards(temp, tempRes); let left = this.searchSameCard(temp, takeType); if (left.length < takeCnt) continue; for (let j = 0; j < takeCnt; j++) { tempRes = tempRes.concat(left[j]); } res.push(tempRes); } return res; } // 优先返回完全符合的牌 // 返回的同牌要大于smaller searchSameCard(cards: number[], sameCnt: number, smallValue?: number) { let res: number[][] = []; if (sameCnt > SAME.FOUR) { console.log('斗地主只有一副牌'); return res; } let analyseRes = this.analyseCard(cards); for (let i = sameCnt; i < SAME.FOUR + 1; i++) { analyseRes[i].forEach(value => { if (smallValue == null || value > smallValue) { res.push(this.getCardsByValue(cards, [value], sameCnt)); } }); } return res; } getCardsByValue(cardData: number[], values: number[], sameCnt): number[] { let cards = cardData.slice(0); let res: number[] = []; for (let v of values) { let cnt = sameCnt; while (cnt--) { for (let i = 0; i < cards.length; i++) { if (this.getLogicValue(cards[i]) == v) { res.push(cards.splice(i, 1)[0]); break; } } } } return res; } searchLine(cards: number[], lineCnt: number, sameCnt: number, smallValue?: number) { let res: number[][] = []; if (cards.length < lineCnt * sameCnt) return res; if (!smallValue) smallValue = 2; if (smallValue + lineCnt - 1 > 14) return res; let valueCnt = this.analyseValueCnt(cards); for (let i = smallValue + 1; i < 15; i++) { if (valueCnt[i] >= sameCnt) { if (i + lineCnt - 1 > 14) return res; let isFind = true; let value: number[] = []; for (let j = i; j < 15; j++) { if (value.length >= lineCnt) break; if (valueCnt[j] < sameCnt) { isFind = false; break; } else { value.push(j); } } if (isFind && value.length == lineCnt) { res.push(this.getCardsByValue(cards, value, sameCnt)); } } } return res; } //搜索卡牌分步 analyseValueCnt(cards: number[]) { let result: number[] = []; for (let i = 0; i <= 17; i++) { result[i] = 0; } for (let i = 0; i < cards.length; i++) { let value = this.getLogicValue(cards[i]); result[value]++; } return result; } public removeCards(cardsA: number[], cardsB: number[]): boolean { for (let i in cardsB) { let isFind = false; for (let j = 0; j < cardsA.length; j++) { if (cardsA[j] == cardsB[i]) { isFind = true; cardsA.splice(j, 1); break; } } if (!isFind) { console.trace('removeCards error', cardsA, cardsB); return false; } } return true; } // true A 大 false B 大 public compareCard(cardsA: number[], cardsB: number[]): boolean { let typeA = this.getCardType(cardsA); let typeB = this.getCardType(cardsB); if (typeA == TYPE.MISSILE) return true; if (typeB == TYPE.MISSILE) return false; if (typeA != typeB) { if (typeA == TYPE.BOMB) return true; if (typeB == TYPE.BOMB) return false; console.log('compareCard type error', cardsA, cardsB); return false; } if (cardsA.length != cardsB.length) { console.log('compareCard length error', cardsA, cardsB); return false; } switch (typeA) { case TYPE.SINGLE: case TYPE.DOUBLE: case TYPE.THREE: case TYPE.SINGLE_LINE: case TYPE.DOUBLE_LINE: case TYPE.THREE_LINE: case TYPE.BOMB: { return this.getLogicValue(cardsA[0]) > this.getLogicValue(cardsB[0]); } case TYPE.THREE_TAKE_ONE: case TYPE.THREE_TAKE_TWO: case TYPE.FOUR_TAKE_ONE: case TYPE.FOUR_TAKE_TWO: case TYPE.THREE_LINE_TAKE_ONE: case TYPE.THREE_LINE_TAKE_TWO: { let resA = this.analyseCard(cardsA); let resB = this.analyseCard(cardsB); if (typeA == TYPE.FOUR_TAKE_ONE || typeA == TYPE.FOUR_TAKE_TWO) { return (resA[SAME.FOUR][0]) > (resB[SAME.FOUR][0]); } else { return (resA[SAME.THREE][0]) > (resB[SAME.THREE][0]); } } } console.log('compareCard ' + typeA, cardsA, cardsB); return false } }
68f742a187e400f837cd807e61ed149a874fbf0e
TypeScript
peterblazejewicz/roosterjs
/packages/roosterjs-editor-dom/lib/utils/applyFormat.ts
2.625
3
import { DefaultFormat } from 'roosterjs-editor-types'; export default function applyFormat(element: HTMLElement, format: DefaultFormat) { if (format) { let elementStyle = element.style; if (format.fontFamily) { elementStyle.fontFamily = format.fontFamily; } if (format.fontSize) { elementStyle.fontSize = format.fontSize; } if (format.textColor) { elementStyle.color = format.textColor; } if (format.backgroundColor) { elementStyle.backgroundColor = format.backgroundColor; } if (format.bold) { elementStyle.fontWeight = 'bold'; } if (format.italic) { elementStyle.fontStyle = 'italic'; } if (format.underline) { elementStyle.textDecoration = 'underline'; } } }
33d47ad3a38dc26b11cfcce2df57045c0202ff2a
TypeScript
ymonb1291/chrono
/test/substract_hour_test.ts
3.046875
3
import { Chrono } from "../chrono.ts"; import { expect, Rhum } from "../deps_test.ts"; interface TestCase { description: string; startDate: string; targetDate: string; param: number | undefined; } Rhum.testPlan("substract_hour_test.ts", () => { Rhum.testSuite("substractHour()", () => { const testCases: TestCase[] = [ { description: "substractHour() substracts 1 hour", startDate: "Jan 15 2000 11:15:50.015", targetDate: "Jan 15 2000 10:15:50.015", param: void 0, }, { description: "substractHour(2) substracts 2 hours in the middle of a day", startDate: "Jan 15 2000 12:15:50.015", targetDate: "Jan 15 2000 10:15:50.015", param: 2, }, { description: "substractHour(2) substracts 2 hours at year's change", startDate: "Jan 01 2000 01:15:50.015", targetDate: "Dec 31 1999 23:15:50.015", param: 2, }, { description: "substractHour(2) skips February 29th on a non leap-year", startDate: "Mar 01 1999 01:15:50.015", targetDate: "Feb 28 1999 23:15:50.015", param: 2, }, { description: "substractHour(2) counts February 29th on a leap-year", startDate: "Feb 29 2000 01:15:50.015", targetDate: "Feb 28 2000 23:15:50.015", param: 2, }, ]; testCases.forEach((testCase) => { Rhum.testCase(testCase.description, () => { const chrono = new Chrono(testCase.startDate); const target = new Chrono(testCase.targetDate); chrono.substractHour(testCase.param); expect(chrono.getFullYear()).toEqual(target.getFullYear()); expect(chrono.getMonth()).toEqual(target.getMonth()); expect(chrono.getDate()).toEqual(target.getDate()); expect(chrono.getHours()).toEqual(target.getHours()); expect(chrono.getMinutes()).toEqual(target.getMinutes()); expect(chrono.getSeconds()).toEqual(target.getSeconds()); expect(chrono.getMilliseconds()).toEqual(target.getMilliseconds()); }); }); }); }); Rhum.run();
e431bf2c13620e9a7223084e91040514676a3125
TypeScript
roots/bud
/sources/@roots/bud-framework/test/extension/decorators/when.test.ts
2.828125
3
import {describe, expect, it} from 'vitest' import {when} from '../../../src/extension/decorators/when' // @ts-ignore @when(() => true) class TestClass {} describe(`when`, () => { it(`should return a decorator`, async () => { expect(when(() => true)).toBeInstanceOf(Function) }) it(`should add a when property to the class`, async () => { // @ts-ignore expect(new TestClass().when).toBeInstanceOf(Function) // @ts-ignore expect(await new TestClass().when()).toBe(true) }) })
24e82614f21a9b3dedddf2b9383bb36b068b0742
TypeScript
ismacaulay/code-adventures
/src/toolkit/rendering/buffers/uniformBuffer.ts
3.015625
3
import { BufferType, type BaseBuffer } from './base'; import { createBuffer } from './common'; export enum UniformType { Bool = 'bool', Scalar = 'scalar', Vec2 = 'vec2', Vec3 = 'vec3', Vec4 = 'vec4', Mat2 = 'mat2', Mat2x3 = 'mat2x3', Mat2x4 = 'mat2x4', Mat3x2 = 'mat3x2', Mat3 = 'mat3', Mat3x4 = 'mat3x4', Mat4x2 = 'mat4x2', Mat4x3 = 'mat4x3', Mat4 = 'mat4', } export type UniformBufferDescriptorEntry = | UniformType | UniformBufferDescriptor | [UniformType, number] | [UniformBufferDescriptor, number]; export interface UniformBufferDescriptor { [key: string]: UniformBufferDescriptorEntry; } export type UniformValue = | boolean | number | ArrayLike<number> | ArrayLike<number>[] | UniformDictionary | UniformDictionary[]; export interface UniformDictionary { [key: string]: UniformValue | UniformDictionary; } export interface UniformLocationDictionary { [key: string]: number | boolean | { offset: number; c: number; r: number }; } export interface UniformBuffer extends BaseBuffer { type: BufferType.Uniform; readonly data: Float32Array; needsUpdate: boolean; hasUniform(name: string): boolean; updateUniform(name: string, value: UniformValue): void; updateUniforms(uniforms: UniformDictionary): void; destroy(): void; } function getSizeForUniformType(type: UniformType) { switch (type) { case UniformType.Bool: case UniformType.Scalar: return 1; case UniformType.Vec2: return 2; case UniformType.Vec3: return 3; case UniformType.Vec4: return 4; case UniformType.Mat2: case UniformType.Mat2x3: case UniformType.Mat2x4: return 8; case UniformType.Mat3x2: case UniformType.Mat3: case UniformType.Mat3x4: return 12; case UniformType.Mat4x2: case UniformType.Mat4x3: case UniformType.Mat4: return 16; default: throw new Error(`Unknown uniform type: ${type}`); } } function locationForValue(value: UniformType, offset: number) { switch (value) { case UniformType.Bool: case UniformType.Scalar: case UniformType.Vec2: case UniformType.Vec3: case UniformType.Vec4: return offset; case UniformType.Mat2: return { offset, c: 2, r: 2 }; case UniformType.Mat2x3: return { offset, c: 2, r: 3 }; case UniformType.Mat2x4: return { offset, c: 2, r: 4 }; case UniformType.Mat3x2: return { offset, c: 3, r: 2 }; case UniformType.Mat3: return { offset, c: 3, r: 3 }; case UniformType.Mat3x4: return { offset, c: 3, r: 4 }; case UniformType.Mat4x2: return { offset, c: 4, r: 2 }; case UniformType.Mat4x3: return { offset, c: 4, r: 3 }; case UniformType.Mat4: return { offset, c: 4, r: 4 }; default: throw new Error(`Unknown matrix type: ${value}`); } } function convertValueToBuffer(value: ArrayLike<number>, c: number, r: number) { const buffer = new Float32Array(c * 4); for (let i = 0; i < c; ++i) { for (let j = 0; j < r; j++) { buffer[4 * i + j] = value[r * i + j]; } } return buffer; } function computeTwoBytePadding(offset: number) { if (offset % 2 !== 0) { return 1; } return 0; } function computeFourBytePadding(offset: number) { if (offset % 4 !== 0) { return 4 - (offset % 4); } return 0; } export function processUniforms(uniforms: UniformBufferDescriptor) { let offset = 0; const locations: UniformLocationDictionary = {}; function processUniformsRecursive(uniforms: UniformBufferDescriptor, keyBase = '') { const entries = Object.entries(uniforms); for (let i = 0; i < entries.length; ++i) { const [key, value] = entries[i]; let locationKey = key; if (keyBase) { locationKey = `${keyBase}.${key}`; } if (Array.isArray(value)) { const [descriptor, length] = value; if (typeof descriptor === 'object') { locations[locationKey] = true; for (let j = 0; j < length; ++j) { offset += computeFourBytePadding(offset); const arrLocationKey = `${locationKey}[${j}]`; locations[arrLocationKey] = true; processUniformsRecursive(descriptor, arrLocationKey); offset += computeFourBytePadding(offset); } } else { offset += computeFourBytePadding(offset); locations[locationKey] = true; for (let j = 0; j < length; ++j) { locations[`${locationKey}[${j}]`] = locationForValue(descriptor, offset); offset += getSizeForUniformType(descriptor); offset += computeFourBytePadding(offset); } } } else if (typeof value === 'object') { offset += computeFourBytePadding(offset); locations[locationKey] = true; processUniformsRecursive(value, locationKey); offset += computeFourBytePadding(offset); } else { if (value === UniformType.Scalar || value === UniformType.Bool) { // no padding } else if (value === UniformType.Vec2) { offset += computeTwoBytePadding(offset); } else if (value === UniformType.Vec3 || value === UniformType.Vec4) { offset += computeFourBytePadding(offset); } else { // padding for matrix types offset += computeFourBytePadding(offset); } locations[locationKey] = locationForValue(value, offset); offset += getSizeForUniformType(value); } } } processUniformsRecursive(uniforms); offset += computeFourBytePadding(offset); return { buffer: new Float32Array(offset), locations }; } export function createUniformBuffer( device: GPUDevice, descriptor: UniformBufferDescriptor, values?: UniformDictionary, ): UniformBuffer { const { buffer, locations } = processUniforms(descriptor); let needsUpdate = false; function updateUniform(name: string, value: UniformValue) { const location = locations[name]; if (location === undefined) { throw new Error(`Unknown uniform: ${name}`); } if (typeof location === 'boolean') { if (Array.isArray(value)) { value.forEach((v: UniformValue, idx: number) => { updateUniform(`${name}[${idx}]`, v); }); } else { Object.entries(value).forEach(([k, v]) => { updateUniform(`${name}.${k}`, v); }); } return; } else if (typeof location === 'object') { const { offset, c, r } = location; buffer.set(convertValueToBuffer(value as ArrayLike<number>, c, r), offset); } else { if (typeof value === 'number') { buffer.set([value], location); } else if (Array.isArray(value) || value instanceof Float32Array) { buffer.set(value as ArrayLike<number>, location); } else if (typeof value === 'boolean') { buffer.set([+value], location); } } needsUpdate = true; } function updateUniforms(uniforms: UniformDictionary) { Object.entries(uniforms).forEach(([key, value]) => updateUniform(key, value)); } if (values) { updateUniforms(values); needsUpdate = false; } const gpuBuffer = createBuffer(device, buffer, GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST); return { type: BufferType.Uniform, buffer: gpuBuffer, data: buffer, get needsUpdate() { return needsUpdate; }, set needsUpdate(value: boolean) { needsUpdate = value; }, hasUniform(name: string): boolean { return name in locations; }, updateUniform, updateUniforms, destroy() { gpuBuffer.destroy(); }, }; }
31333f10981130764f89f40c26e60e6fbc82a673
TypeScript
EastSun5566/cc-gram
/__tests__/core.test.ts
2.734375
3
import { describe, beforeEach, it, expect, } from 'vitest'; /* eslint-disable @typescript-eslint/no-non-null-assertion */ import { CCgram } from '../src'; import { DEFAULT_FILTERS } from '../src/filters'; describe('Read/Write filter list', (): void => { let cg: CCgram | null = null; beforeEach(() => { cg = new CCgram({ init: false }); }); it('should get all filter name', (): void => { expect(cg!.filterNames).toEqual([...DEFAULT_FILTERS.keys()]); }); it('should add filter', (): void => { cg!.setFilter('my-filter', { saturate: 0.8 }); expect(cg!.filterNames).toContain('my-filter'); }); it('should remove filter', (): void => { const { filterNames } = cg!; const targetFilterName = filterNames[Math.floor(Math.random() * (filterNames.length - 1))]!; cg!.removeFilter(targetFilterName); expect(cg!.filterNames.includes(targetFilterName)).toBe(false); }); }); const IMAGE_SRC = 'https://media.giphy.com/media/sIIhZliB2McAo/giphy.gif'; const FILTER_NAME = '1977'; const getTargetImage = (dateAttr = 'filter'): HTMLImageElement | null => ( document.querySelector<HTMLImageElement>(`img[data-${dateAttr}="${FILTER_NAME}"]`) ); describe('Apply filter to target Image', () => { beforeEach(() => { document.body.innerHTML = ''; }); it('should apply CSS filter when init', (): void => { document.body.innerHTML = ` <img src="${IMAGE_SRC}" data-filter="${FILTER_NAME}"> `; const cg = new CCgram(); const { style } = getTargetImage()!; expect(cg.getFilterStyle(FILTER_NAME)).toBe(style.filter); }); it('should apply CSS filter when call applyFilter method', (): void => { const cg = new CCgram({ init: false }); document.body.innerHTML = ` <img src="${IMAGE_SRC}" data-filter="${FILTER_NAME}"> `; cg.applyFilter(); const { style } = getTargetImage()!; expect(cg.getFilterStyle(FILTER_NAME)).toBe(style.filter); }); it(' should apply filter with customized data attr', (): void => { const DATA_ATTR = 'cg'; document.body.innerHTML = ` <img src="${IMAGE_SRC}" data-${DATA_ATTR}="${FILTER_NAME}"> `; const cg = new CCgram({ dataAttribute: DATA_ATTR }); const { style } = getTargetImage(DATA_ATTR)!; expect(cg.getFilterStyle(FILTER_NAME)).toBe(style.filter); }); }); describe.skip('Access filter image data', () => { let cg: CCgram | null = null; beforeEach(() => { document.body.innerHTML = ` <img src="${IMAGE_SRC}" data-filter="${FILTER_NAME}"> `; cg = new CCgram(); }); it('should return dataURL when call getDataURL method', async (): Promise<void> => { const target = getTargetImage()!; const dataURL = await cg!.getDataURL(target, { quality: 0.8 }); const regEx = /data:([\w/+]+);(charset=[\w-]+|base64).*,([a-zA-Z0-9+/]+={0,2})/; expect(regEx.test(dataURL!)).toBe(true); }); it('should return blob when call getBlob method', async (): Promise<void> => { const target = getTargetImage()!; const blob = await cg!.getBlob(target, { quality: 0.8 }); expect(blob instanceof Blob).toBe(true); }); });
9a53161973c90dde70cf826f1654fba7c989626a
TypeScript
llopez93/logistic-app-frontend
/src/app/core/service/validation-messages.ts
3.1875
3
import {AbstractControl, FormControl, ValidatorFn} from "@angular/forms"; export class ValidationMessages { getValidatorErrorMessage(validatorName: string, validatorValue?: any) { let config = { 'required': 'Este campo es obligatorio.', 'email': 'No es un email valido.', 'invalidPassword': 'Password invalido. El password debe al menos 6 caracteres, y contener un numero.', 'minlength': `Este campo debe tener al menos ${validatorValue.requiredLength} caracteres.`, 'maxlength': `Este campo no debe tener mas de ${validatorValue.requiredLength} caracteres.`, 'min': `El valor mínimo de este campo es ${validatorValue.min}.`, 'max': `El valor máximo de este campo es ${validatorValue.max}.`, 'isNumber': 'Este campo solo puede contener números.' }; return config[validatorName]; } errorMessages(control: AbstractControl): string[] { const messages = []; if (control) { for (let propertyName in control.errors) { if (!control.pristine) { messages.push(this.getValidatorErrorMessage(propertyName, control.errors[propertyName])); } } } return messages.slice(0, 1); } passwordValidator(control) { // {6,100} - Assert password is between 6 and 100 characters // (?=.*[0-9]) - Assert a string has at least one number if (control.value.match(/^(?=.*[0-9])[a-zA-Z0-9!@#$%^&*]{6,100}$/)) { return null; } else { return {'invalidPassword': true}; } } /** Validación numerica */ isNumber(): ValidatorFn { return (control: AbstractControl): { [key: string]: any } | null => { const exp = new RegExp('^[0-9]+$'); const valid = exp.test(control.value); return valid ? null : {'isNumber': {value: control.value}}; }; } }
6c0ed67d93e0f9616c24f7f25f7d10ef7a1c9470
TypeScript
SergeyVolynkin/stacks-wallet-web
/src/common/hooks/use-loadable.ts
2.828125
3
import { useEffect, useState } from 'react'; import { useRecoilValueLoadable, RecoilValue } from 'recoil'; /** * Wrap a Recoil loadable and add a `value` property, which * returns the latest value if the loadable is revalidating. */ export const useLoadable = <T>(recoilValue: RecoilValue<T>) => { const loadable = useRecoilValueLoadable(recoilValue); const [value, setValue] = useState<T | undefined>(loadable.valueMaybe() || undefined); useEffect(() => { if (loadable.state === 'hasValue' && loadable.contents !== value) { setValue(loadable.contents); } }, [loadable, value]); return { ...loadable, key: recoilValue.key, value, isLoading: !value && loadable.state === 'loading', }; };
7a82c48032ce7677246bded7d8265a69c3c2ad77
TypeScript
khusamov/express-typescript
/src/http/status/4xxClientError/MethodNotAllowedStatus.ts
2.859375
3
import HttpStatus from '../HttpStatus'; /** * 405 Method Not Allowed — указанный клиентом метод нельзя применить * к текущему ресурсу. В ответе сервер должен указать доступные методы * в заголовке Allow, разделив их запятой. Эту ошибку сервер должен возвращать, * если метод ему известен, но он не применим именно к указанному в запросе ресурсу, * если же указанный метод не применим на всём сервере, то клиенту нужно * вернуть код 501 (Not Implemented). * Появился в HTTP/1.1. */ export default class MethodNotAllowedStatus extends HttpStatus { code: number = 405; }
a69f94814d230c0a110c2c90b9614218720fbdfa
TypeScript
joanllenas/Slaying-a-UI-Antipattern-with-Angular
/src/app/remote-data.ts
2.90625
3
import { Pipe, PipeTransform } from '@angular/core'; export class NotAsked {} export class Loading {} export class Faliure<E> { constructor(private error: E){} fold(): E { return this.error; } } export class Success<T> { constructor(private value: T){} fold(): T { return this.value; } } export type RemoteData<E, T> = NotAsked | Loading | Faliure<E> | Success<T> // Pipes @Pipe({name: 'isNotAsked'}) export class IsNotAskedPipe implements PipeTransform { transform(value: RemoteData<any, any>): boolean { return value instanceof NotAsked; } } @Pipe({name: 'isLoading'}) export class IsLoadingPipe implements PipeTransform { transform(value: RemoteData<any, any>): boolean { return value instanceof Loading; } } @Pipe({name: 'isFaliure'}) export class IsFaliurePipe implements PipeTransform { transform(value: RemoteData<any, any>): boolean { return value instanceof Faliure; } } @Pipe({name: 'isSuccess'}) export class IsSuccessPipe implements PipeTransform { transform(value: RemoteData<any, any>): boolean { return value instanceof Success; } }
67f7b16166443a4c13fd8e19d8a207e59a6350c2
TypeScript
mickeypearce/oradew-vscode
/src/cli/common/globs.ts
2.6875
3
// const glob = require("fast-glob"); not preserving order import { sync } from "globby"; import * as multimatch from "multimatch"; import { pipe, compact, uniq, sortBy, identity, map, isEqual } from "lodash/fp"; import { rootPrepend, splitLines } from "./utility"; import { getChangesNotStaged } from "./git"; // Get array of files matched by glob patterns array export function fromGlobsToFilesArray(globArray, options?) { return sync(globArray, { ...options, caseSensitiveMatch: false }).map(rootPrepend); } // Get filepaths from matchArray (file paths) matched by globArray // matchArray is not necesarry actual files on disk // (Intersection between globArray matches and matchArray) export function getGlobMatches(globArray, matchArray) { return multimatch(matchArray, globArray, { nocase: true }); } // True if matchArray equals globArray matches // Matches against a list instead of the filesystem export function isGlobMatch(globArray, matchArray) { const matches = multimatch(matchArray, globArray, { nocase: true }); return isEqual(matchArray, matches); } // Get array of files from output stream string export function fromStdoutToFilesArray(stdout) { return pipe( // Generate array from lines splitLines, // Remove empty items and duplicates compact, uniq, // Scripts first sortBy(identity), // Add ./ if it doesn't already exists map(rootPrepend) )(stdout); } export const getOnlyChangedFiles = async (source) => { // Get array of changed files from git const stdout = await getChangesNotStaged(); const changed = fromStdoutToFilesArray(stdout); // Get array of files matched by source array parameter return getGlobMatches(source, changed); };
08a9243705110e1687d0c80a98655fac92fbaba6
TypeScript
sivakusayan/smogon-usage-fetch
/src/url/UrlBuilder.ts
2.59375
3
import { isNil } from "lightdash"; import { IFormatData, joinFormatDataLine } from "../parse/smogon/format"; import { ITimeframeData, joinTimeframeDataLine } from "../parse/smogon/timeframe"; import { urlJoin } from "../util/httpUtil"; import { Extension } from "./Extension"; import { SubFolder } from "./SubFolder"; import { URL_STATS } from "./urlBase"; /** * Builder for smogon stat URLs. * * @private * @class */ class UrlBuilder { private subFolder?: SubFolder; private extension?: Extension; private timeframe?: ITimeframeData; private format?: IFormatData; public setSubFolder(subFolder: SubFolder): UrlBuilder { this.subFolder = subFolder; return this; } public setExtension(extension: Extension): UrlBuilder { this.extension = extension; return this; } public setTimeframe(timeframe: ITimeframeData): UrlBuilder { this.timeframe = timeframe; return this; } public setFormat(format: IFormatData): UrlBuilder { this.format = format; return this; } /** * Builds the current instance and returns the URL. * * @public * @return Built URL. */ public build(): string { let folderUrl = URL_STATS; if (!isNil(this.timeframe)) { folderUrl = urlJoin( folderUrl, joinTimeframeDataLine(this.timeframe) ); } if (!isNil(this.format) && !isNil(this.format.monotype)) { folderUrl = urlJoin(folderUrl, SubFolder.MONOTYPE); } if (!isNil(this.subFolder)) { folderUrl = urlJoin(folderUrl, this.subFolder); } if (!isNil(this.format)) { let fileName: string = joinFormatDataLine(this.format); if (!isNil(this.extension)) { fileName += "." + this.extension; } return urlJoin(folderUrl, fileName); } return folderUrl; } } export { UrlBuilder };
b5e206bc7a7dbf0cc7a74b776f9cfca66d4dd566
TypeScript
mljs/random
/src/index.ts
3.40625
3
import XSAdd from 'ml-xsadd'; import { ChoiceOptions } from './Options'; import { RandomNumberGenerator } from './RandomNumberGenerator'; import choice from './choice'; /** * @classdesc Random class */ export default class Random { private randomGenerator: RandomNumberGenerator; /** * @param [seedOrRandom=Math.random] - Control the random number generator used by the Random class instance. Pass a random number generator function with a uniform distribution over the half-open interval [0, 1[. If seed will pass it to ml-xsadd to create a seeded random number generator. If undefined will use Math.random. */ constructor(seedOrRandom: RandomNumberGenerator | number = Math.random) { if (typeof seedOrRandom === 'number') { const xsadd = new XSAdd(seedOrRandom); this.randomGenerator = xsadd.random; } else { this.randomGenerator = seedOrRandom; } } /** * Returns an array of elements choosen from a list * @param values - The values to choose from. If a number, the list will be a range of integer from 0 to that number. * @param options - option object * @return The choosen values */ public choice<T>(values: T[], options?: ChoiceOptions): T[]; public choice(values: number, options?: ChoiceOptions): number[]; public choice<T>( values: T[] | number, options?: ChoiceOptions, ): Array<T | number> { if (typeof values === 'number') { return choice(values, options, this.randomGenerator); } return choice(values, options, this.randomGenerator); } /** * Draw a random number from a uniform distribution on [0,1) * @return The random number */ public random(): number { return this.randomGenerator(); } /** * Draw a random integer from a uniform distribution on [low, high). If only low is specified, the number is drawn on [0, low) * @param low - The lower bound of the uniform distribution interval. * @param high - The higher bound of the uniform distribution interval. */ public randInt(low: number, high?: number): number { if (high === undefined) { high = low; low = 0; } return low + Math.floor(this.randomGenerator() * (high - low)); } /** * Draw several random number from a uniform distribution on [0, 1) * @param size - The number of number to draw * @return - The list of drawn numbers. */ public randomSample(size: number): number[] { const result: number[] = []; for (let i = 0; i < size; i++) { result.push(this.random()); } return result; } } export * from './Options'; export * from './RandomNumberGenerator';
d8b65992d90843c9a8f7edcff562e079a4d85c2a
TypeScript
gksriharsha/Family-Tree-UI
/src/app/model/Alert.model.ts
2.765625
3
export class AlertModel{ text:string; cls:string; time:number; constructor(text: string, cls: string, time: number) { this.text = text; this.cls = cls; this.time = time; } }
904b8a9903723fe889396a950b6cdd0702c67a2b
TypeScript
ArturoDuran0711/LogingServerHTTP
/src/services/user.ts
2.703125
3
//Para utilizar el decorador @Injectable import { Injectable } from "@angular/core"; //Para realizar la peticion HTTP import { Http } from "@angular/http"; @Injectable() export class UserService{ private http:any; //Se utiliza en esta clase por eso es provado public user:any; //Guardo datos que me regrese el JSON y es publico porque desde cualquier clase se puede acceder constructor(http:Http){ this.http = http; } getUser(){ this.http.get("http://localhost:8080/eje06.json") .subscribe(data=>{ this.user =data.json(); }, err=>{ console.log("err"); }); //se ejecutara despues de una peticion asincrona } }
f972345f684c44adc4f4c2aadf1beb6a1d89f8d0
TypeScript
WuLiFang/csheet
/web/src/composables/usePolling.ts
2.6875
3
import useCleanup from '@/composables/useCleanup'; /** * @returns polling stop function */ export default function usePolling( update: () => Promise<void> | void, scheduleNext: (update: () => void) => void = requestAnimationFrame ) { const { addCleanup } = useCleanup(); let isStopped = false; const stop = () => { isStopped = true; }; addCleanup(stop); const run = async () => { if (isStopped) { return; } await update(); scheduleNext(run); }; run(); return { dispose: stop, }; }
f8e468b88b7565fbe375e88ff8ffd690c3047bbb
TypeScript
andiCR/ShieldBattery
/server/lib/matchmaking/matchmaking-status.ts
2.703125
3
import { is, Map, Record } from 'immutable' import { NydusServer } from 'nydus' import { injectable } from 'tsyringe' import { MatchmakingType } from '../../../common/matchmaking' import log from '../logging/logger' import { getCurrentMatchmakingTime, getMatchmakingSchedule } from '../models/matchmaking-times' class StatusRecord extends Record({ type: null as MatchmakingType | null, enabled: false, startDate: null as Date | null, nextStartDate: null as Date | null, nextEndDate: null as Date | null, }) {} @injectable() export default class MatchmakingStatus { private statusByType = Map<MatchmakingType, StatusRecord>() private timerByType = Map<MatchmakingType, ReturnType<typeof setTimeout>>() constructor(private nydus: NydusServer) { for (const type of Object.values(MatchmakingType)) { this.maybePublish(type) } } isEnabled(type: MatchmakingType): boolean { return !!this.statusByType.get(type)?.enabled } subscribe(socket: any) { const statuses = [] for (const type of Object.values(MatchmakingType)) { const status = this.statusByType.get(type) if (status) { statuses.push(status) } } this.nydus.subscribeClient(socket, '/matchmakingStatus', statuses) } private async getStatus(type: MatchmakingType) { const current = await getCurrentMatchmakingTime(type) const schedule = await getMatchmakingSchedule(type, current?.startDate, !current?.enabled) return new StatusRecord({ type, enabled: !!current?.enabled, startDate: current?.startDate, nextStartDate: schedule[0]?.startDate, nextEndDate: schedule[1]?.startDate, }) } /** * Publishes the current matchmaking status to subscribed users, if the status or the schedule * has changed since the last cached value. * * If a change has occurred, a timeout will be set up for the next scheduled change to publish * that as well. */ maybePublish(type: MatchmakingType) { this.getStatus(type) .then(status => { const oldStatus = this.statusByType.get(type) // If the status hasn't changed, no need to notify the users if (is(oldStatus, status)) return this.statusByType = this.statusByType.set(type, status) this.nydus.publish('/matchmakingStatus', [status]) // If the `nextStartDate` hasn't changed, no need to update the timer if (oldStatus?.nextStartDate === status.nextStartDate) return const oldTimer = this.timerByType.get(type) if (oldTimer) { clearTimeout(oldTimer) } if (status.nextStartDate) { const timer = setTimeout( () => this.maybePublish(type), +status.nextStartDate - Date.now(), ) this.timerByType = this.timerByType.set(type, timer) } else { this.timerByType = this.timerByType.delete(type) } }) .catch(err => log.error({ err }, 'error getting matchmaking status')) } }
b58f25da388ecb1a571bd184f53a37d956ade87c
TypeScript
CambriaSolutions/mdhs-csa
/hosting/analytics/src/store/reducers/filtersReducer.ts
2.640625
3
import * as actionTypes from '../actions/actionTypes' const initialState = { // Set Today filter by default filterLabel: 'Last 7 days', dateFilters: { start: null, end: null, }, isCustomDateRange: false, openDateDialog: false, colors: [], mainColor: '#8681A6', context: '', timezoneOffset: -7, // Offset Firebase } const reducer = (state = initialState, action) => { switch (action.type) { case actionTypes.UPDATE_FILTERS: return { ...state, filterLabel: action.filterLabel, dateFilters: action.dateFilters, } case actionTypes.UPDATE_CONTEXT: return { ...state, context: action.context, mainColor: action.mainColor, colors: action.colors, timezoneOffset: action.timezoneOffset, dateFilters: action.dateFilters, } case actionTypes.UPDATE_MAIN_COLOR: return { ...state, mainColor: action.mainColor, colors: action.colors, } case actionTypes.SET_IS_CUSTOM_DATE_RANGE: return { ...state, isCustomDateRange: action.isCustomDateRange, } case actionTypes.TOGGLE_DATE_DIALOG: return { ...state, openDateDialog: action.shouldOpen, } default: return state } } export default reducer
1b90cfa6263397145e8f79774bdf62a86bad9ef2
TypeScript
okraciunas/gs-d06-go-finances-api-v2
/src/services/CreateTransactionService.ts
2.875
3
import { getRepository, getCustomRepository } from 'typeorm' import Category from './../models/Category' import CreateCategoryService from './CreateCategoryService' import TransactionsRepository from './../repositories/TransactionsRepository' import Transaction, { TransactionType } from './../models/Transaction' import AppError from './../errors/AppError' export interface TransactionRequest { title: string value: number type: TransactionType categoryTitle: string } export default class CreateTransactionService { public async execute({ title, value, type, categoryTitle, }: TransactionRequest): Promise<Transaction> { const repository = getCustomRepository(TransactionsRepository) const transactions = await repository.find() const { total } = repository.getBalance(transactions) if (type === TransactionType.Outcome && value > total) { throw new AppError('It is not possible to create a outcome transaction.') } let category = await this.findCategory(categoryTitle) if (!category) { category = await this.createCategory(categoryTitle) } const transaction = repository.create({ title, value, type, category_id: category.id, }) await repository.save(transaction) return transaction } private async findCategory(title: string): Promise<Category | undefined> { const repository = getRepository(Category) const category = await repository.findOne({ where: { title }, }) return category } private async createCategory(title: string): Promise<Category> { const service = new CreateCategoryService() const category = await service.execute(title) return category } }
f575a659351d34a4a6dd5f7b0efeb9554525998f
TypeScript
milesj/interweave
/packages/autolink/src/UrlMatcher.ts
2.703125
3
import React from 'react'; import { ChildrenNode, Matcher, MatchResponse, Node } from 'interweave'; import { EMAIL_DISTINCT_PATTERN, TOP_LEVEL_TLDS, URL_PATTERN } from './constants'; import { UrlMatcherOptions, UrlProps } from './types'; import { Url } from './Url'; export type UrlMatch = Pick<UrlProps, 'url' | 'urlParts'>; export class UrlMatcher extends Matcher<UrlProps, UrlMatcherOptions> { constructor( name: string, options?: UrlMatcherOptions, factory?: React.ComponentType<UrlProps> | null, ) { super( name, { customTLDs: [], validateTLD: true, ...options, }, factory, ); } replaceWith(children: ChildrenNode, props: UrlProps): Node { return React.createElement(Url, props, children); } asTag(): string { return 'a'; } match(string: string): MatchResponse<UrlMatch> | null { const response = this.doMatch(string, URL_PATTERN, this.handleMatches); // False positives with URL auth scheme if (response?.match.match(EMAIL_DISTINCT_PATTERN)) { response.valid = false; } if (response?.valid && this.options.validateTLD) { const { host } = (response.urlParts as unknown) as UrlProps['urlParts']; const validList = [...TOP_LEVEL_TLDS, ...(this.options.customTLDs ?? [])]; const tld = host.slice(host.lastIndexOf('.') + 1).toLowerCase(); if (!validList.includes(tld)) { return null; } } return response; } /** * Package the matched response. */ handleMatches(matches: string[]): UrlMatch { return { url: matches[0], urlParts: { auth: matches[2] ? matches[2].slice(0, -1) : '', fragment: matches[7] || '', host: matches[3], path: matches[5] || '', port: matches[4] ? matches[4] : '', query: matches[6] || '', scheme: matches[1] ? matches[1].replace('://', '') : 'http', }, }; } }
90748df8859048bc595ee7c671aa49fed992c442
TypeScript
JanUrbanNeto/rentx
/src/modules/cars/useCases/createSpecification/CreateSpecificationUseCase.ts
2.640625
3
import { inject, injectable } from "tsyringe"; import { ISpecificationsRepository } from "../../../../modules/cars/repositories/ISpecificationsRepository"; import { AppError } from "../../../../errors/AppError"; interface IRequest { name: string; description: string; } @injectable() class CreateSpecificationUseCase { constructor( @inject("SpecificationsRepository") private specificationsRespository: ISpecificationsRepository ) {} async execute({ name, description }: IRequest): Promise<void> { const specificationAlreadyExists = await this.specificationsRespository.findByName(name); if(specificationAlreadyExists) { throw new AppError("Specification already exists"); } await this.specificationsRespository.create({ name, description }); } } export { CreateSpecificationUseCase }
06a07dfe19901ed9423b5a8a936c8b10a3544c2b
TypeScript
marcospss/ngrx-shop
/src/app/checkout/reducers/cep.reducer.ts
2.703125
3
import { CepActions } from './../actions'; import { Address } from '@core/models/address.model'; export interface State { address: Address; zipcode: string; loading: boolean; error: string; } const initialState: State = { address: null, zipcode: '', loading: false, error: '' }; export function reducer( state = initialState, action: CepActions.CepApiActionsUnion ): State { switch (action.type) { case CepActions.CepApiActionTypes.CepZipcode: { return { ...state, loading: true, zipcode: action.payload }; } case CepActions.CepApiActionTypes.CepAddressSuccess: { return { ...state, loading: false, address: action.payload }; } case CepActions.CepApiActionTypes.CepAddressFailure: { return { ...state, loading: false, error: action.payload }; } default: { return state; } } } export const getLoading = (state: State) => state.loading; export const getError = (state: State) => state.error; export const getZipcode = (state: State) => state.zipcode; export const getAddress = (state: State) => state.address;
92e0683ef6291112bf731d141bb9563f1c5ab264
TypeScript
morphatic/v-address-fields
/src/VStateSelect.ts
2.53125
3
// Imported Types /// <reference path="../node_modules/vuetify/src/globals.d.ts" /> import Vue from 'vue' // 3rd Party Libs import { UsaStates } from 'usa-states' // Styles import './VStateSelect.sass' /** * Import the Vuetify components you plan to extend here. */ // @ts-ignore import { VAutocomplete } from 'vuetify/lib' // Create Base Mixins and Define Custom Properties const base = Vue.extend({ mixins: [VAutocomplete] }) interface options extends InstanceType<typeof base> { /** * !Props unique to VStateSelect */ contiguousOnly: boolean exclude: string[] includeTerritories: boolean } // Extend VAutocomplete to define the VStateSelect component export default base.extend<options>().extend({ name: 'v-state-select', props: { contiguousOnly: { type: Boolean, default: false, }, exclude: { type: Array, default: () => [], }, includeTerritories: { type: Boolean, default: false, }, storedValue: { type: String, default: 'abbr', }, text: { type: String, default: 'name', }, }, computed: { allItems (): object[] { const { contiguousOnly, exclude, includeTerritories, storedValue, text } = this const usaStates = new UsaStates({ contiguousOnly, exclude, includeTerritories, }) return usaStates.format({ $text: text, $value: storedValue, }) }, classes (): object { return { ...VAutocomplete.options.computed.classes.call(this), 'v-state-select': true, } }, }, })
2cb741893be4aa57d851f2656a247963c67e27cd
TypeScript
DTURoadrunners/VCFRONTEND
/src/app/service/auth.service.ts
2.609375
3
import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { logging } from 'selenium-webdriver'; import { USERS } from '../mock/mock-users'; import { User } from "../models/user"; import { CAMPUSNETUSERS } from "../mock/mock-campusnetUser"; import { CampusnetUser } from "../models/CampusnetUser"; /** * Handles communication related to user authorization with the API */ @Injectable() export class AuthService { private loggedIn: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false); // Control if the user is logged in or not, with BehaviorSubject private currentUser: BehaviorSubject<User> = new BehaviorSubject<User>(null); /** * getter for loggedIn, also expose the Subject as an Observable. * The BehaviorSubject keeps the latest value cached */ get isLoggedIn() { return this.loggedIn.asObservable(); } get getCurrentUser() { return this.currentUser.asObservable(); } constructor( private router: Router ) { } /** * Checks if the fields for login is validated and corresponds to an user, redircts the user to the homepage * TODO implement API call and login check * @param userName - the users username * @param password - the users password */ login(userName: String, password: String): boolean{ if ((userName !== '' && password != '')) { var user = USERS.find(user => user.id == userName && user.password == password); if (user) { this.loggedIn.next(true); this.currentUser.next(user); this.router.navigate(['/myprojects']); return true; } } return false; } /** * Logs the user out, and sets the loggedIn variable to false, * Redirects the user to the login page */ logout() { this.loggedIn.next(false); this.router.navigate(['/login']); this.currentUser.next(null); } /** * Register the user with the API * @param userName * @param password */ registerAccount(cnUser: CampusnetUser, password: string): boolean { if (cnUser.id !== '' && cnUser.password != '') { USERS.push(new User(cnUser.id, password, [], cnUser.name, cnUser.email, cnUser.phone, cnUser.studyline)) this.router.navigate(['/login']); return true; } return false; } }
a0bfa2dc1bc7acb66419df4a628ee7ec4b35ceb8
TypeScript
ababakhanlou/the-shopping-centre
/src/types.ts
2.625
3
export interface Basket { item: string; price: number; qty: number; } export interface State { selectedCategory: string; basket: Basket[]; } export interface Action { type: string; payload: any; } export interface Stock { brand: string; model: string; item: string; price: number; displayName: string; }
f9363f2590e69a7823a6c20915d99e49976942c5
TypeScript
rafaelmarinhos/calendar-plan
/src/app/model/calendar-period.ts
2.5625
3
export const PERIOD_TYPE_INFO = { liturgical: { name: 'Litúrgico', symbol: '&#9651;', type: 'liturgical' }, catechetical: { name: 'Catequético', symbol: '&#9671;', type: 'catechetical' }, civil: { name: 'Civil', symbol: '&#9678;', type: 'civil' } }; export const LITURGICAL_PERIODS = { advent: { name: 'Tempo do Advento', periodType: PERIOD_TYPE_INFO.liturgical }, christmastide: { name: 'Tempo do Natal', periodType: PERIOD_TYPE_INFO.liturgical }, firstOrdinaryTime: { name: 'Tempo Comum (I)', periodType: PERIOD_TYPE_INFO.liturgical }, lent: { name: 'Quaresma', periodType: PERIOD_TYPE_INFO.liturgical }, easterTriduum: { name: 'Tríduo Pascal', periodType: PERIOD_TYPE_INFO.liturgical }, eastertide: { name: 'Páscoa', periodType: PERIOD_TYPE_INFO.liturgical }, secondOrdinaryTime: { name: 'Tempo Comum (II)', periodType: PERIOD_TYPE_INFO.liturgical } }; export const CATECHETICAL_PERIODS = { purificationAndIllumination: { name: 'Purificação e Iluminação', periodType: PERIOD_TYPE_INFO.catechetical }, examination: { name: 'Examinação', periodType: PERIOD_TYPE_INFO.catechetical }, catechumenate: { name: 'Catecumenato', periodType: PERIOD_TYPE_INFO.catechetical } }; export interface CalendarPeriod { id?: string; originalId?: string; name?: string; periodType?: string; planId?: string; originalPlanId?: string; startDate?: Date, startsAt?: string; endsAt?: string; createdAt?: string; updatedAt?: string; }
5f170ae933d86cd26a032080daaf90cd651ddff3
TypeScript
kabeleced77/foxfm2
/src/Common/Toolkit/SplitStrings.ts
3.359375
3
import { SplitStringToNumbers } from './SplitString'; import { IValues, Values } from './Values'; export interface ISplitStrings<T1, T2> { firstValues(): IValues<T1>; secondValues(): IValues<T2>; } export class SplitStringsToNumbers implements ISplitStrings<Number, Number> { private readonly strings: IValues<String>; private readonly splitBy: String; private readonly decimalPoint: String; private firstValuesOfStrings: Number[]; private secondValuesOfStrings: Number[]; constructor( strings: IValues<String>, splitBy: String, decimalPoint: String ) { this.strings = strings; this.splitBy = splitBy; this.decimalPoint = decimalPoint; this.firstValuesOfStrings = []; this.secondValuesOfStrings = []; } firstValues(): IValues<Number> { if (this.strings.values().length !== this.firstValuesOfStrings.length) this.split(); return new Values<Number>(this.firstValuesOfStrings); } secondValues(): IValues<Number>{ if (this.strings.values().length !== this.secondValuesOfStrings.length) this.split(); return new Values<Number>(this.secondValuesOfStrings); } private split(): void { this.strings.values().forEach(string => { let values = new SplitStringToNumbers(string, this.splitBy, this.decimalPoint); this.firstValuesOfStrings.push(values.firstValue()); this.secondValuesOfStrings.push(values.secondValue()); }); } }
ce96e78070ebec4b58614f6ff0b1dc0dbfac7892
TypeScript
dejametecuento/dejametecuento-site
/lib/hooks/use-media-queries.ts
2.65625
3
import { useState, useEffect } from 'react' const useMediaQuery = (width: number) => { const [targetReached, setTargetReached] = useState(false) useEffect(() => { const updateTarget = (e: MediaQueryListEvent) => { if (e.matches) { setTargetReached(true) } else { setTargetReached(false) } } const media = window.matchMedia(`(max-width: ${width}px)`) media.addEventListener('change', updateTarget) if (media.matches) { setTargetReached(true) } return () => media.removeEventListener('change', updateTarget) }, [width]) return targetReached } const useIsMobile = () => { return useMediaQuery(640) } export { useMediaQuery, useIsMobile }
748325dc0c55b5a338c35457613cba5e70ad4fa1
TypeScript
CatchoftheDay/coding101
/src/reducers.ts
2.625
3
import { AnyAction, combineReducers } from "redux"; import { createReducer } from "deox"; import runnerReducer, { addMaze, resetState } from "./services/runner/reducers"; import { Stage, TutorialState } from "./types"; import { addAchievement, addKey, advanceTo } from "./actions"; const mazePropsByState = { [Stage.ACTIONS]: { addDoor: false, mazeSize: 4, smallMaze: false, randomSeed: "hello" }, [Stage.CONTROL]: { addDoor: false, mazeSize: 6, smallMaze: false, randomSeed: "Hi there" }, [Stage.VARIABLES]: { addDoor: true, mazeSize: 6, smallMaze: false, randomSeed: "maze" } }; const stageReducer = createReducer(Stage.ACTIONS, handle => [ handle(advanceTo, (currStage, { payload: newStage }) => Math.max(currStage, newStage) ) ]); const keystrokeReducer = createReducer("", handle => [ handle( addKey, (enteredSoFar, { payload: char }) => enteredSoFar.substr(-15) + char ) ]); const achievementReducer = createReducer([] as string[], handle => [ handle(addAchievement, (achievements, { payload: achievement }) => { if (achievements.indexOf(achievement) === -1) { return [...achievements, achievement]; } else { return achievements; } }) ]); const baseReducers = combineReducers({ runner: runnerReducer, stage: stageReducer, keystrokes: keystrokeReducer, achievements: achievementReducer }); const reducers = (state: TutorialState | undefined, action: AnyAction) => { const oldStage = state && state.stage; state = baseReducers(state, action) as TutorialState; if (state.stage !== oldStage) { state = { ...state, runner: resetState( addMaze({ ...state.runner, ...mazePropsByState[state.stage] }) ) }; } return state; }; export const initialState = reducers(undefined, { type: null }); export default reducers;
fad8477d4bb81d18360b838a31b5de564d0a8533
TypeScript
rolik-deni/nestjs-crud
/src/users/entities/user.entity.ts
2.734375
3
import { BaseEntity, Column, CreateDateColumn, DeleteDateColumn, Entity, PrimaryGeneratedColumn, } from 'typeorm'; @Entity({ name: 'users' }) export class User extends BaseEntity { @PrimaryGeneratedColumn() id: number; @Column() name: string; @Column() email: string; @Column() password: string; @CreateDateColumn() createdAt: string; @DeleteDateColumn({ nullable: true }) removedAt: string; constructor( name: string, email: string, password: string, createdAt?: string, removedAt?: string, id?: number, ) { super(); this.id = id; this.name = name; this.email = email; this.password = password; this.createdAt = createdAt; this.removedAt = removedAt; } }
d07e2403ce9c3eed315a76f530be60a27d86e72d
TypeScript
JanithaSampathBandara/Ramping-Up-With-Krish
/nestjs-angular-algorithm-exercises/backend-nestjs/algorithm-service/src/algorithms/algorithms.service.ts
3.671875
4
import { Injectable } from '@nestjs/common'; @Injectable() export class AlgorithmsService { isAnagram(word1: String, word2: String): boolean { word1 = word1.toLowerCase(); word2 = word2.toLowerCase(); //Check whether both words have same no of letters if (word1.length === word2.length) { //Create two char arrays from both words let [charArray1, charArray2] = [[...word1], [...word2]]; //Sort both char arrays into alphabetical order for (let index=0; index < charArray1.length-1; index++) { for (let innerIndex=0; innerIndex<charArray1.length-1; innerIndex++) { // Swapping letters of word1 into alphabetical order if (charArray1[innerIndex+1] < charArray1[innerIndex]) { [charArray1[innerIndex], charArray1[innerIndex+1]] = [charArray1[innerIndex+1], charArray1[innerIndex]]; } // Swapping letters of word2 into alphabetical order if (charArray2[innerIndex+1] < charArray2[innerIndex]) { [charArray2[innerIndex], charArray2[innerIndex+1]] = [charArray2[innerIndex+1], charArray2[innerIndex]]; } } } //Check whether both char arrays have same letters from the begining since both are sorted into alphabetical order let count = 0; for (let index=0; index < charArray1.length; index++) { if (charArray1[index] != charArray2[index]) { count++; } } if (count > 0) { return false; } else { return true; } } else { return false; } } countOccurences(inputSentence: String): any { let sentence = inputSentence.toLowerCase().replace(/\s/g, ''); let charArray = [...sentence]; let map = new Map(); for (let index=0; index<charArray.length; index++) { const letter = charArray[index]; // Checking whether the letter is exist or not inside map. If not, add to the map. if (!map.has(letter)) { map.set(letter, 1); } else { // Getting the value associated with letter(key) and increment the value and set again. map.set(letter, map.get(letter) + 1); } } return Object.fromEntries(map); } findNthLargestNumber(nthNumber: number, numberSequence: number[]): number { // Sorting the number sequence array for three times only since we need the 3rd largest number. for(let index=0; index < nthNumber; index++){ let largest = numberSequence[index]; let largestIndex = index; for(let indexIn=index; indexIn < numberSequence.length-1; indexIn++){ if(numberSequence[indexIn+1] > largest){ largest = numberSequence[indexIn+1]; largestIndex = indexIn+1; } } // Swapping numbers into descending order [numberSequence[index], numberSequence[largestIndex]] = [numberSequence[largestIndex], numberSequence[index]] } return numberSequence[nthNumber-1]; } }
0f1087f89565c2c8230cc21e12afec75b0a4d1e0
TypeScript
bagbag/tstdl
/base/source/injector/interfaces.ts
3.046875
3
import type { Type } from '#/types.js'; import type { InjectionToken } from './token.js'; export const resolveArgumentType: unique symbol = Symbol('resolveArgumentType'); export const afterResolve: unique symbol = Symbol('after resolve'); export type ResolveArgumentType = typeof resolveArgumentType; export type ResolveArgument<T, Fallback = undefined> = ( T extends Resolvable<infer U> ? U : T extends Type<Resolvable<infer U>> ? U : T extends InjectionToken<infer U, infer A> ? ResolveArgument<U, A> : Fallback) | undefined; export interface Resolvable<A = unknown> { /** * type of resolve argument * @deprecated only used for type inference */ readonly [resolveArgumentType]: A; [afterResolve]?(argument: A): void | Promise<void>; }
20b376c939d1df7cbbaad787265772dcea2c92d1
TypeScript
WaywardGame/types
/definitions/game/ui/screen/screens/game/static/stats/component/StatusEffects.d.ts
2.546875
3
/*! * Copyright 2011-2023 Unlok * https://www.unlok.ca * * Credits & Thanks: * https://www.unlok.ca/credits-thanks/ * * Wayward is a copyrighted and licensed work. Modification and/or distribution of any source files is prohibited. If you wish to modify the game in any way, please refer to the modding guide: * https://github.com/WaywardGame/types/wiki */ import type { Events, IEventEmitter } from "event/EventEmitter"; import type EntityWithStats from "game/entity/EntityWithStats"; import { StatusType } from "game/entity/IEntity"; import Component from "ui/component/Component"; export interface IStatusEffectsEvents extends Events<Component> { update(): any; } export default class StatusEffects extends Component { readonly event: IEventEmitter<this, IStatusEffectsEvents>; private readonly entity; private readonly effectIcons; constructor(entity: EntityWithStats); /** * Event handler for the status effects of this entity changing */ onStatusChange(_: any, status: StatusType, level: number): void; }
7d39197a65e9706b4aea7747f4b55286dad909a0
TypeScript
gustavoGarrido/angularClaseLunMierc
/src/app/pipes/pipe/estados.pipe.ts
2.578125
3
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'estados' }) export class EstadosPipe implements PipeTransform { transform(value:number): string { switch (value) { case 0: return "ANULADO" break; case 1: return "ACTIVO" default: return "SIN ESTADO" break; } } }
d5e6d5eb138d103f930ad0a31727b0236951d95b
TypeScript
bpiggin/mindful-timer-app
/src/components/DayStreak/helpers.ts
3.171875
3
import AsyncStorage from '@react-native-community/async-storage'; const getStreakData = async () => { const lastDay = await AsyncStorage.getItem('@last_Day'); return { count: Number(await AsyncStorage.getItem('@streak_Count')), lastDay: lastDay ? new Date(String(lastDay)) : null, }; }; const updateStreakData = async (count: number, currentDay: Date) => { try { await AsyncStorage.setItem('@streak_Count', String(count)); await AsyncStorage.setItem('@last_Day', currentDay.toISOString()); } catch (e) { console.error(e); } }; export const getDayStreak = async () => { let { count, lastDay } = await getStreakData(); const currentDay = new Date(); currentDay.setHours(0); currentDay.setMinutes(0); currentDay.setSeconds(0, 0); const yesterday = new Date(currentDay.getTime()); yesterday.setDate(yesterday.getDate() - 1); // Compare the stored "last day meditated" values with the // current day values to determine the streak. if ( lastDay == null || count == null || lastDay.getTime() < yesterday.getTime() ) { // There is no last day stored or the last day is more // than one day ago. // In either case, reset the streak to 1 and // the "last day meditated" to today. count = 1; updateStreakData(count, currentDay); } else if (count != null && lastDay.getTime() == yesterday.getTime()) { // The last day meditated was yesterday, so the user's // streak continues! count++; updateStreakData(count, currentDay); } else if (lastDay.getTime() == currentDay.getTime()) { // The user has already meditated today, so do nothing. // (The stored count is the correct value to return) } else if (lastDay.getTime() > currentDay.getTime()) { // Error, the date must be in the future. Quietly fail // for now... count = 0; updateStreakData(count, currentDay); } else { // Error, invalid branch. We shouldn't be in here. // Set count to 0 to indicate something has gone horribly wrong. count = 0; updateStreakData(count, currentDay); } return count; };
0c16ad790efb14487a4958e2fb24f5c59d431777
TypeScript
pcapelo/EightBittr
/packages/timehandlr/src/types.ts
3.71875
4
/** * Lookup of current events, mapping times to all associated events. */ export interface CurrentEvents { [i: number]: TimeEventLike[]; } /** * General-purpose Function for events. * * @param args Any arguments, passed through a TimeHandlr. * @returns Anyactor truthy to stop repetition. */ export type EventCallback = (...args: any[]) => any; /** * General-purpose calculator for numeric values. * * @returns Some numeric value. */ export type NumericCalculator = () => number; /** * Calculator for event repetition. * * @param args Any arguments, which will be the same as the * parent event's passed args. * @returns Whether an event should keep repeating. */ export type RepeatCalculator = (...args: any[]) => boolean; /** * An event to be played, including a callback, repetition settings, and arguments. */ export interface TimeEventLike { /** * The time at which to call this event. */ time: number; /** * Something to run when this event is triggered. */ callback(): unknown | void; /** * Arguments to be passed to the callback. */ args?: any[]; /** * How many times this should repeat. If a Function, called for whether to repeat. */ repeat?: number | RepeatCalculator; /** * How long to wait between calls, if repeat isn't 1. */ timeRepeat?: number | NumericCalculator; /** * How many times this has been called. */ count?: number; /** * Set the next call time using timeRepeat. * * @returns The new call time. */ scheduleNextRepeat(): number; } /** * Settings to initialize a new TimeHandlr. */ export interface TimeHandlrSettings { /** * Default time separation between repeated events (by default, 1). */ timingDefault?: number; }
1eae1543edc4e784c434615a83150a04f2723dfa
TypeScript
trustedtomato/font-awesome-svgs
/src/lib/chunkArray.ts
3.390625
3
export function chunkArray<T> (array: T[], chunkLength: number): T[][] { const newArray: T[][] = [] for (let i = 0; i < array.length; i += chunkLength) { newArray.push(array.slice(i, i + chunkLength)) } return newArray }
b0f52348dbf9d6fc3ee07943dd850864bd479ea6
TypeScript
Mai-HealthTracker/WebApp
/src/app/home/meal-tracker-item/meal/meal.component.ts
2.53125
3
import { Input } from '@angular/core'; import { Component, OnInit, OnChanges } from '@angular/core'; import { Icon } from 'src/app/model/records/icon'; @Component({ selector: 'app-meal', templateUrl: './meal.component.html', styleUrls: ['./meal.component.css'] }) export class MealComponent implements OnInit { @Input() meal: any; @Input() title: any; @Input() date: any; @Input() canEdit: any; food_names: string[] = [] drink_names: string[] = [] symptom_names: string[] = [] food: Icon[] = []; drink: Icon[] = []; symptom: Icon[] = []; constructor() { } ngOnInit(): void { this.food_names = ['Bakery', 'Oats', 'Eggs', 'Fruits', 'Vegetables', 'Rice', 'Wheat', 'Salad', 'Sweet', 'Soup', 'Pizza', 'Burger', 'Noodles']; this.drink_names = ['Water', 'Tea', 'Coffee', 'Soda', 'Milk', 'Juice', 'Energy Drink', 'Alcohol']; this.symptom_names = ['Reflux', 'Gas', 'Rash', 'Vomiting', 'Diarrhea', 'Belly Pain', 'Headache', 'Fatigue', 'Constipation']; for (let food_name of this.food_names) { var index:number; if (this.meal){ index = this.meal.foods.map((ele: any) => { return ele.name; }).indexOf(food_name); } else { index = -1; } if (index == -1) { console.log("inserting in index -1"); this.food.push(new Icon(food_name, 'food', true, 0)); } else { this.food.push(new Icon(food_name, 'food', true, this.meal.foods[index].count)); } } for (let drink_name of this.drink_names) { var index:number; if (this.meal){ index = this.meal.drinks.map((ele: any) => { return ele.name; }).indexOf(drink_name); } else { index = -1; } if (index == -1) { console.log("inserting drink in index -1"); this.drink.push(new Icon(drink_name, 'drink', true, 0)); } else { this.drink.push(new Icon(drink_name, 'drink', true, this.meal.drinks[index].count)); } } for (let food_name of this.symptom_names) { var index:number; if (this.meal){ index = this.meal.symptoms.map((ele: any) => { return ele.name; }).indexOf(food_name); } else { index = -1; } if (index == -1) { this.symptom.push(new Icon(food_name, 'symptom', true, 0)); } else { this.symptom.push(new Icon(food_name, 'symptom', true, this.meal.symptoms[index].count)); } } console.log("meal", this.meal); console.log("foods",this.food,"drinks",this.drink); } ngOnChanges(){ console.log("meallllll change",this.meal) this.food = []; this.drink = []; this.symptom = []; for (let food_name of this.food_names) { var index:number; if (this.meal){ index = this.meal.foods.map((ele: any) => { return ele.name; }).indexOf(food_name); } else { index = -1; } if (index == -1) { console.log("inserting in index -1"); this.food.push(new Icon(food_name, 'food', true, 0)); } else { this.food.push(new Icon(food_name, 'food', true, this.meal.foods[index].count)); } } for (let drink_name of this.drink_names) { var index:number; if (this.meal){ index = this.meal.drinks.map((ele: any) => { return ele.name; }).indexOf(drink_name); } else { index = -1; } if (index == -1) { this.drink.push(new Icon(drink_name, 'drink', true, 0)); } else { this.drink.push(new Icon(drink_name, 'drink', true, this.meal.drinks[index].count)); } } for (let food_name of this.symptom_names) { var index:number; if (this.meal){ index = this.meal.symptoms.map((ele: any) => { return ele.name; }).indexOf(food_name); } else { index = -1; } if (index == -1) { this.symptom.push(new Icon(food_name, 'symptom', true, 0)); } else { this.symptom.push(new Icon(food_name, 'symptom', true, this.meal.symptoms[index].count)); } } console.log("change foods",this.food,"drinks",this.drink); } }
2952ac3d4adde9475bfd7d3444ecc31d73313181
TypeScript
ThaNarie/AutoListing
/source/inc/script/lib/jquery/jquery.d.ts
2.515625
3
/* ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. 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 THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ // Typing for the jQuery library, version 1.10.x / 2.0.x // Project: http://jquery.com/ // Definitions by: Boris Yankov <https://github.com/borisyankov/>, Christian Hoffmeister <https://github.com/choffmeister>, Steve Fenton, Diullei Gomes <https://github.com/Diullei>, Tass Iliopoulos <https://github.com/tasoili>, Jason Swearingen, Sean Hill <https://github.com/seanski>, Guus Goossens <https://github.com/Guuz>, Kelly Summerlin <https://github.com/ksummerlin>, Basarat Ali Syed <https://github.com/basarat>, Nicholas Wolverson <https://github.com/nwolverson>, Derek Cicerone <https://github.com/derekcicerone>, Andrew Gaspar <https://github.com/AndrewGaspar>, James Harrison Fisher <https://github.com/jameshfisher>, Seikichi Kondo <https://github.com/seikichi>, Benjamin Jackman <https://github.com/benjaminjackman>, Poul Sorensen <https://github.com/s093294>, Josh Strobl <https://github.com/JoshStrobl>, John Reilly <https://github.com/johnnyreilly/> // Definitions: https://github.com/borisyankov/DefinitelyTyped /* Interface for the AJAX setting that will configure the AJAX request */ interface JQueryAjaxSettings { /** * The content type sent in the request header that tells the server what kind of response it will accept in return. If the accepts setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. */ accepts?: any; /** * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success(). */ async?: boolean; /** * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request. */ beforeSend? ( jqXHR:JQueryXHR, settings:JQueryAjaxSettings ): any; /** * If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET. */ cache?: boolean; /** * A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. */ complete? ( jqXHR:JQueryXHR, textStatus:string ): any; /** * An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. (version added: 1.5) */ contents?: { [key: string]: any; }; //According to jQuery.ajax source code, ajax's option actually allows contentType to set to "false" // https://github.com/borisyankov/DefinitelyTyped/issues/742 /** * When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. */ contentType?: any; /** * This object will be made the context of all Ajax-related callbacks. By default, the context is an object that represents the ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). */ context?: any; /** * An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. (version added: 1.5) */ converters?: { [key: string]: any; }; /** * If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. (version added: 1.5) */ crossDomain?: boolean; /** * Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). */ data?: any; /** * A function to be used to handle the raw response data of XMLHttpRequest.This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter. */ dataFilter? ( data:any, ty:any ): any; /** * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). */ dataType?: string; /** * A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. */ error? ( jqXHR:JQueryXHR, textStatus:string, errorThrow:string ): any; /** * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events. */ global?: boolean; /** * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. (version added: 1.5) */ headers?: { [key: string]: any; }; /** * Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data. */ ifModified?: boolean; /** * Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. (version added: 1.5.1) */ isLocal?: boolean; /** * Override the callback function name in a jsonp request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" } */ jsonp?: string; /** * Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function. */ jsonpCallback?: any; /** * A mime type to override the XHR mime type. (version added: 1.5.1) */ mimeType?: string; /** * A password to be used with XMLHttpRequest in response to an HTTP access authentication request. */ password?: string; /** * By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false. */ processData?: boolean; /** * Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. */ scriptCharset?: string; /** * An object of numeric HTTP codes and functions to be called when the response has the corresponding code. f the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. (version added: 1.5) */ statusCode?: { [key: string]: any; }; /** * A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. */ success? ( data:any, textStatus:string, jqXHR:JQueryXHR ): any; /** * Set a timeout (in milliseconds) for the request. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period. */ timeout?: number; /** * Set this to true if you wish to use the traditional style of param serialization. */ traditional?: boolean; /** * The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers. */ type?: string; /** * A string containing the URL to which the request is sent. */ url?: string; /** * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. */ username?: string; /** * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory. */ xhr?: any; /** * An object of fieldName-fieldValue pairs to set on the native XHR object. For example, you can use it to set withCredentials to true for cross-domain requests if needed. In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it. (version added: 1.5.1) */ xhrFields?: { [key: string]: any; }; } /* Interface for the jqXHR object */ interface JQueryXHR extends XMLHttpRequest, JQueryPromise<any> { overrideMimeType( mimeType:string ): any; abort( statusText?:string ): void; } /* Interface for the JQuery callback */ interface JQueryCallback { add( ...callbacks:any[] ): any; disable(): any; empty(): any; fire( ...arguments:any[] ): any; fired(): boolean; fireWith( context:any, ...args:any[] ): any; has( callback:any ): boolean; lock(): any; locked(): boolean; remove( ...callbacks:any[] ): any; } /* Allows jQuery Promises to interop with non-jQuery promises */ interface JQueryGenericPromise<T> { then<U>( onFulfill:( value:T ) => U, onReject?:( reason:any ) => U ): JQueryGenericPromise<U>; then<U>( onFulfill:( value:T ) => JQueryGenericPromise<U>, onReject?:( reason:any ) => U ): JQueryGenericPromise<U>; then<U>( onFulfill:( value:T ) => U, onReject?:( reason:any ) => JQueryGenericPromise<U> ): JQueryGenericPromise<U>; then<U>( onFulfill:( value:T ) => JQueryGenericPromise<U>, onReject?:( reason:any ) => JQueryGenericPromise<U> ): JQueryGenericPromise<U>; } /* Interface for the JQuery promise, part of callbacks */ interface JQueryPromise<T> { // Generic versions of callbacks always( ...alwaysCallbacks:T[] ): JQueryPromise<T>; done( ...doneCallbacks:T[] ): JQueryPromise<T>; fail( ...failCallbacks:T[] ): JQueryPromise<T>; error( ...failCallbacks:T[] ): JQueryPromise<T>; progress( ...progressCallbacks:T[] ): JQueryPromise<T>; always( ...alwaysCallbacks:any[] ): JQueryPromise<T>; done( ...doneCallbacks:any[] ): JQueryPromise<T>; fail( ...failCallbacks:any[] ): JQueryPromise<T>; error( ...failCallbacks:any[] ): JQueryPromise<T>; progress( ...progressCallbacks:any[] ): JQueryPromise<T>; // Deprecated - given no typings pipe( doneFilter?:( x:any ) => any, failFilter?:( x:any ) => any, progressFilter?:( x:any ) => any ): JQueryPromise<any>; then<U>( onFulfill:( value:T ) => U, onReject?:( ...reasons:any[] ) => U, onProgress?:( ...progression:any[] ) => any ): JQueryPromise<U>; then<U>( onFulfill:( value:T ) => JQueryGenericPromise<U>, onReject?:( ...reasons:any[] ) => U, onProgress?:( ...progression:any[] ) => any ): JQueryPromise<U>; then<U>( onFulfill:( value:T ) => U, onReject?:( ...reasons:any[] ) => JQueryGenericPromise<U>, onProgress?:( ...progression:any[] ) => any ): JQueryPromise<U>; then<U>( onFulfill:( value:T ) => JQueryGenericPromise<U>, onReject?:( ...reasons:any[] ) => JQueryGenericPromise<U>, onProgress?:( ...progression:any[] ) => any ): JQueryPromise<U>; // Because JQuery Promises Suck then<U>( onFulfill:( ...values:any[] ) => U, onReject?:( ...reasons:any[] ) => U, onProgress?:( ...progression:any[] ) => any ): JQueryPromise<U>; then<U>( onFulfill:( ...values:any[] ) => JQueryGenericPromise<U>, onReject?:( ...reasons:any[] ) => U, onProgress?:( ...progression:any[] ) => any ): JQueryPromise<U>; then<U>( onFulfill:( ...values:any[] ) => U, onReject?:( ...reasons:any[] ) => JQueryGenericPromise<U>, onProgress?:( ...progression:any[] ) => any ): JQueryPromise<U>; then<U>( onFulfill:( ...values:any[] ) => JQueryGenericPromise<U>, onReject?:( ...reasons:any[] ) => JQueryGenericPromise<U>, onProgress?:( ...progression:any[] ) => any ): JQueryPromise<U>; } /* Interface for the JQuery deferred, part of callbacks */ interface JQueryDeferred<T> extends JQueryPromise<T> { // Generic versions of callbacks always( ...alwaysCallbacks:T[] ): JQueryDeferred<T>; done( ...doneCallbacks:T[] ): JQueryDeferred<T>; fail( ...failCallbacks:T[] ): JQueryDeferred<T>; progress( ...progressCallbacks:T[] ): JQueryDeferred<T>; always( ...alwaysCallbacks:any[] ): JQueryDeferred<T>; done( ...doneCallbacks:any[] ): JQueryDeferred<T>; fail( ...failCallbacks:any[] ): JQueryDeferred<T>; progress( ...progressCallbacks:any[] ): JQueryDeferred<T>; notify( ...args:any[] ): JQueryDeferred<T>; notifyWith( context:any, ...args:any[] ): JQueryDeferred<T>; reject( ...args:any[] ): JQueryDeferred<T>; rejectWith( context:any, ...args:any[] ): JQueryDeferred<T>; resolve( val:T ): JQueryDeferred<T>; resolve( ...args:any[] ): JQueryDeferred<T>; resolveWith( context:any, ...args:any[] ): JQueryDeferred<T>; state(): string; promise( target?:any ): JQueryPromise<T>; } /* Interface of the JQuery extension of the W3C event object */ interface BaseJQueryEventObject extends Event { data: any; delegateTarget: Element; isDefaultPrevented(): boolean; isImmediatePropogationStopped(): boolean; isPropagationStopped(): boolean; namespace: string; preventDefault(): any; relatedTarget: Element; result: any; stopImmediatePropagation(): void; stopPropagation(): void; pageX: number; pageY: number; which: number; metaKey: boolean; } interface JQueryInputEventObject extends BaseJQueryEventObject { altKey: boolean; ctrlKey: boolean; metaKey: boolean; shiftKey: boolean; } interface JQueryMouseEventObject extends JQueryInputEventObject { button: number; clientX: number; clientY: number; offsetX: number; offsetY: number; pageX: number; pageY: number; screenX: number; screenY: number; } interface JQueryKeyEventObject extends JQueryInputEventObject { char: any; charCode: number; key: any; keyCode: number; } interface JQueryPopStateEventObject extends BaseJQueryEventObject { originalEvent: PopStateEvent; } interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject, JQueryPopStateEventObject { } /* Collection of properties of the current browser */ interface JQuerySupport { ajax?: boolean; boxModel?: boolean; changeBubbles?: boolean; checkClone?: boolean; checkOn?: boolean; cors?: boolean; cssFloat?: boolean; hrefNormalized?: boolean; htmlSerialize?: boolean; leadingWhitespace?: boolean; noCloneChecked?: boolean; noCloneEvent?: boolean; opacity?: boolean; optDisabled?: boolean; optSelected?: boolean; scriptEval? (): boolean; style?: boolean; submitBubbles?: boolean; tbody?: boolean; } interface JQueryParam { ( obj:any ): string; ( obj:any, traditional:boolean ): string; } /* Static members of jQuery (those on $ and jQuery themselves) */ interface JQueryStatic { /**** AJAX *****/ ajax( settings:JQueryAjaxSettings ): JQueryXHR; ajax( url:string, settings?:JQueryAjaxSettings ): JQueryXHR; ajaxPrefilter( dataTypes:string, handler:( opts:any, originalOpts:any, jqXHR:JQueryXHR ) => any ): any; ajaxPrefilter( handler:( opts:any, originalOpts:any, jqXHR:JQueryXHR ) => any ): any; ajaxSettings: JQueryAjaxSettings; ajaxSetup(): void; ajaxSetup( options:JQueryAjaxSettings ): void; get( url:string, data?:any, success?:any, dataType?:any ): JQueryXHR; getJSON( url:string, data?:any, success?:any ): JQueryXHR; getScript( url:string, success?:any ): JQueryXHR; param: JQueryParam; post( url:string, data?:any, success?:any, dataType?:any ): JQueryXHR; // Callbacks Callbacks( flags?:string ): JQueryCallback; // Core holdReady( hold:boolean ): any; ( selector:string, context?:any ): JQuery; ( element:Element ): JQuery; ( object:{ } ): JQuery; ( elementArray:Element[] ): JQuery; ( object:JQuery ): JQuery; ( func:Function ): JQuery; ( array:any[] ): JQuery; (): JQuery; noConflict( removeAll?:boolean ): Object; when<T>( ...deferreds:JQueryGenericPromise<T>[] ): JQueryPromise<T>; when<T>( ...deferreds:T[] ): JQueryPromise<T>; when<T>( ...deferreds:any[] ): JQueryPromise<T>; // CSS css( e:any, propertyName:string, value?:any ): any; css( e:any, propertyName:any, value?:any ): any; cssHooks: { [key: string]: any; }; cssNumber: any; // Data data( element:Element, key:string, value:any ): any; data( element:Element, key:string ): any; data( element:Element ): any; dequeue( element:Element, queueName?:string ): any; hasData( element:Element ): boolean; queue( element:Element, queueName?:string ): any[]; queue( element:Element, queueName:string, newQueueOrCallback:any ): JQuery; removeData( element:Element, name?:string ): JQuery; // Deferred Deferred<T>( beforeStart?:( deferred:JQueryDeferred<T> ) => any ): JQueryDeferred<T>; // Effects fx: { tick: () => void; interval: number; stop: () => void; speeds: { slow: number; fast: number; }; off: boolean; step: any; }; // Events proxy( fn:( ...args:any[] ) => any, context:any, ...args:any[] ): any; proxy( context:any, name:string, ...args:any[] ): any; Event: { ( name:string, eventProperties?:any ): JQueryEventObject; new ( name:string, eventProperties?:any ): JQueryEventObject; }; // Internals error( message:any ): JQuery; // Miscellaneous expr: any; fn: any; //TODO: Decide how we want to type this isReady: boolean; // Properties support: JQuerySupport; // Utilities contains( container:Element, contained:Element ): boolean; each( collection:any, callback:( indexInArray:any, valueOfElement:any ) => any ): any; each( collection:JQuery, callback:( indexInArray:number, valueOfElement:HTMLElement ) => any ): any; each<T>( collection:T[], callback:( indexInArray:number, valueOfElement:T ) => any ): any; extend( target:any, ...objs:any[] ): any; extend( deep:boolean, target:any, ...objs:any[] ): any; globalEval( code:string ): any; grep<T>( array:T[], func:( elementOfArray:T, indexInArray:number ) => boolean, invert?:boolean ): T[]; inArray<T>( value:T, array:T[], fromIndex?:number ): number; isArray( obj:any ): boolean; isEmptyObject( obj:any ): boolean; isFunction( obj:any ): boolean; isNumeric( value:any ): boolean; isPlainObject( obj:any ): boolean; isWindow( obj:any ): boolean; isXMLDoc( node:Node ): boolean; makeArray( obj:any ): any[]; map<T, U>( array:T[], callback:( elementOfArray:T, indexInArray:number ) => U ): U[]; map( array:any, callback:( elementOfArray:any, indexInArray:any ) => any ): any; merge<T>( first:T[], second:T[] ): T[]; merge<T,U>( first:T[], second:U[] ): any[]; noop(): any; now(): number; parseJSON( json:string ): any; //FIXME: This should return an XMLDocument parseXML( data:string ): any; queue( element:Element, queueName:string, newQueue:any[] ): JQuery; trim( str:string ): string; type( obj:any ): string; unique( arr:any[] ): any[]; /** * Parses a string into an array of DOM nodes. * * @param data HTML string to be parsed * @param context DOM element to serve as the context in which the HTML fragment will be created * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string */ parseHTML( data:string, context?:HTMLElement, keepScripts?:boolean ): any[]; Animation( elem:any, properties:any, options:any ): any; cookie:any; } /* The jQuery instance members */ interface JQuery { // AJAX ajaxComplete( handler:any ): JQuery; ajaxError( handler:( event:any, jqXHR:any, settings:any, exception:any ) => any ): JQuery; ajaxSend( handler:( event:any, jqXHR:any, settings:any, exception:any ) => any ): JQuery; ajaxStart( handler:() => any ): JQuery; ajaxStop( handler:() => any ): JQuery; ajaxSuccess( handler:( event:any, jqXHR:any, settings:any, exception:any ) => any ): JQuery; load( url:string, data?:any, complete?:any ): JQuery; serialize(): string; serializeArray(): any[]; // Attributes addClass( classNames:string ): JQuery; addClass( func:( index:any, currentClass:any ) => string ): JQuery; // http://api.jquery.com/addBack/ addBack( selector?:string ): JQuery; attr( attributeName:string ): string; attr( attributeName:string, value:any ): JQuery; attr( map:{ [key: string]: any; } ): JQuery; attr( attributeName:string, func:( index:any, attr:any ) => any ): JQuery; hasClass( className:string ): boolean; html(): string; html( htmlString:string ): JQuery; html( htmlContent:( index:number, oldhtml:string ) => string ): JQuery; html( obj:JQuery ): JQuery; prop( propertyName:string ): any; prop( propertyName:string, value:any ): JQuery; prop( map:any ): JQuery; prop( propertyName:string, func:( index:any, oldPropertyValue:any ) => any ): JQuery; removeAttr( attributeName:string ): JQuery; removeClass( className?:string ): JQuery; removeClass( func:( index:any, cls:any ) => any ): JQuery; removeProp( propertyName:string ): JQuery; toggleClass( className:string, swtch?:boolean ): JQuery; toggleClass( swtch?:boolean ): JQuery; toggleClass( func:( index:any, cls:any, swtch:any ) => any ): JQuery; val(): any; val( value:string[] ): JQuery; val( value:string ): JQuery; val( value:number ): JQuery; val( func:( index:any, value:any ) => any ): JQuery; // CSS css( propertyName:string ): string; css( propertyNames:string[] ): string; css( properties:any ): JQuery; css( propertyName:string, value:any ): JQuery; css( propertyName:any, value:any ): JQuery; height(): number; height( value:number ): JQuery; height( value:string ): JQuery; height( func:( index:any, height:any ) => any ): JQuery; innerHeight(): number; innerHeight( value:number ): JQuery; innerWidth(): number; innerWidth( value:number ): JQuery; offset(): { left: number; top: number; }; offset( coordinates:any ): JQuery; offset( func:( index:any, coords:any ) => any ): JQuery; outerHeight( includeMargin?:boolean ): number; outerHeight( value:number, includeMargin?:boolean ): JQuery; outerWidth( includeMargin?:boolean ): number; outerWidth( value:number, includeMargin?:boolean ): JQuery; position(): { top: number; left: number; }; scrollLeft(): number; scrollLeft( value:number ): JQuery; scrollTop(): number; scrollTop( value:number ): JQuery; width(): number; width( value:number ): JQuery; width( value:string ): JQuery; width( func:( index:any, height:any ) => any ): JQuery; // Data clearQueue( queueName?:string ): JQuery; data( key:string, value:any ): JQuery; data( obj:{ [key: string]: any; } ): JQuery; data( key?:string ): any; dequeue( queueName?:string ): JQuery; removeData( nameOrList?:any ): JQuery; // Deferred promise( type?:any, target?:any ): JQueryPromise<any>; // Effects animate( properties:any, duration?:any, complete?:Function ): JQuery; animate( properties:any, duration?:any, easing?:string, complete?:Function ): JQuery; animate( properties:any, options:{ duration?: any; easing?: string; complete?: Function; step?: Function; queue?: boolean; specialEasing?: any; } ): JQuery; delay( duration:number, queueName?:string ): JQuery; fadeIn( duration?:any, callback?:any ): JQuery; fadeIn( duration?:any, easing?:string, callback?:any ): JQuery; fadeOut( duration?:any, callback?:any ): JQuery; fadeOut( duration?:any, easing?:string, callback?:any ): JQuery; fadeTo( duration:any, opacity:number, callback?:any ): JQuery; fadeTo( duration:any, opacity:number, easing?:string, callback?:any ): JQuery; fadeToggle( duration?:any, callback?:any ): JQuery; fadeToggle( duration?:any, easing?:string, callback?:any ): JQuery; finish(): JQuery; hide( duration?:any, callback?:any ): JQuery; hide( duration?:any, easing?:string, callback?:any ): JQuery; show( duration?:any, callback?:any ): JQuery; show( duration?:any, easing?:string, callback?:any ): JQuery; slideDown( duration?:any, callback?:any ): JQuery; slideDown( duration?:any, easing?:string, callback?:any ): JQuery; slideToggle( duration?:any, callback?:any ): JQuery; slideToggle( duration?:any, easing?:string, callback?:any ): JQuery; slideUp( duration?:any, callback?:any ): JQuery; slideUp( duration?:any, easing?:string, callback?:any ): JQuery; stop( clearQueue?:boolean, jumpToEnd?:boolean ): JQuery; stop( queue?:any, clearQueue?:boolean, jumpToEnd?:boolean ): JQuery; toggle( duration?:any, callback?:any ): JQuery; toggle( duration?:any, easing?:string, callback?:any ): JQuery; toggle( showOrHide:boolean ): JQuery; // Events bind( eventType:string, eventData?:any, handler?:( eventObject:JQueryEventObject ) => any ): JQuery; bind( eventType:string, eventData:any, preventBubble:boolean ): JQuery; bind( eventType:string, preventBubble:boolean ): JQuery; bind( ...events:any[] ): JQuery; blur( handler:( eventObject:JQueryEventObject ) => any ): JQuery; blur( eventData?:any, handler?:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Trigger the "change" event on an element. */ change(): JQuery; /** * Bind an event handler to the "change" JavaScript event * * @param handler A function to execute each time the event is triggered. */ change( handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Bind an event handler to the "change" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ change( eventData?:any, handler?:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Trigger the "click" event on an element. */ click(): JQuery; /** * Bind an event handler to the "click" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. */ click( handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Bind an event handler to the "click" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ click( eventData?:any, handler?:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Trigger the "dblclick" event on an element. */ dblclick(): JQuery; /** * Bind an event handler to the "dblclick" JavaScript event * * @param handler A function to execute each time the event is triggered. */ dblclick( handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Bind an event handler to the "dblclick" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ dblclick( eventData?:any, handler?:( eventObject:JQueryEventObject ) => any ): JQuery; delegate( selector:any, eventType:string, handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Trigger the "focus" event on an element. */ focus(): JQuery; /** * Bind an event handler to the "focus" JavaScript event * * @param handler A function to execute each time the event is triggered. */ focus( handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Bind an event handler to the "focus" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ focus( eventData?:any, handler?:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Bind an event handler to the "focusin" JavaScript event * * @param handler A function to execute each time the event is triggered. */ focusin( handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Bind an event handler to the "focusin" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ focusin( eventData:any, handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Bind an event handler to the "focusout" JavaScript event * * @param handler A function to execute each time the event is triggered. */ focusout( handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Bind an event handler to the "focusout" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ focusout( eventData:any, handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Bind two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements. * * @param handlerIn A function to execute when the mouse pointer enters the element. * @param handlerOut A function to execute when the mouse pointer leaves the element. */ hover( handlerIn:( eventObject:JQueryEventObject ) => any, handlerOut:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Bind a single handler to the matched elements, to be executed when the mouse pointer enters or leaves the elements. * * @param handlerInOut A function to execute when the mouse pointer enters or leaves the element. */ hover( handlerInOut:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Trigger the "keydown" event on an element. */ keydown(): JQuery; /** * Bind an event handler to the "keydown" JavaScript event * * @param handler A function to execute each time the event is triggered. */ keydown( handler:( eventObject:JQueryKeyEventObject ) => any ): JQuery; /** * Bind an event handler to the keydown"" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ keydown( eventData?:any, handler?:( eventObject:JQueryKeyEventObject ) => any ): JQuery; /** * Trigger the "keypress" event on an element. */ keypress(): JQuery; /** * Bind an event handler to the "keypress" JavaScript event * * @param handler A function to execute each time the event is triggered. */ keypress( handler:( eventObject:JQueryKeyEventObject ) => any ): JQuery; /** * Bind an event handler to the "keypress" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ keypress( eventData?:any, handler?:( eventObject:JQueryKeyEventObject ) => any ): JQuery; /** * Trigger the "keyup" event on an element. */ keyup(): JQuery; /** * Bind an event handler to the "keyup" JavaScript event * * @param handler A function to execute each time the event is triggered. */ keyup( handler:( eventObject:JQueryKeyEventObject ) => any ): JQuery; /** * Bind an event handler to the "keyup" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ keyup( eventData?:any, handler?:( eventObject:JQueryKeyEventObject ) => any ): JQuery; /** * Bind an event handler to the "load" JavaScript event. * * @param handler A function to execute when the event is triggered. */ load( handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Bind an event handler to the "load" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ load( eventData?:any, handler?:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Trigger the "mousedown" event on an element. */ mousedown(): JQuery; /** * Bind an event handler to the "mousedown" JavaScript event. * * @param handler A function to execute when the event is triggered. */ mousedown( handler:( eventObject:JQueryMouseEventObject ) => any ): JQuery; /** * Bind an event handler to the "mousedown" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mousedown( eventData:any, handler:( eventObject:JQueryMouseEventObject ) => any ): JQuery; /** * Trigger the "mouseenter" event on an element. */ mouseenter(): JQuery; /** * Bind an event handler to be fired when the mouse enters an element. * * @param handler A function to execute when the event is triggered. */ mouseenter( handler:( eventObject:JQueryMouseEventObject ) => any ): JQuery; /** * Bind an event handler to be fired when the mouse enters an element. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mouseenter( eventData:any, handler:( eventObject:JQueryMouseEventObject ) => any ): JQuery; /** * Trigger the "mouseleave" event on an element. */ mouseleave(): JQuery; /** * Bind an event handler to be fired when the mouse leaves an element. * * @param handler A function to execute when the event is triggered. */ mouseleave( handler:( eventObject:JQueryMouseEventObject ) => any ): JQuery; /** * Bind an event handler to be fired when the mouse leaves an element. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mouseleave( eventData:any, handler:( eventObject:JQueryMouseEventObject ) => any ): JQuery; /** * Trigger the "mousemove" event on an element. */ mousemove(): JQuery; /** * Bind an event handler to the "mousemove" JavaScript event. * * @param handler A function to execute when the event is triggered. */ mousemove( handler:( eventObject:JQueryMouseEventObject ) => any ): JQuery; /** * Bind an event handler to the "mousemove" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mousemove( eventData:any, handler:( eventObject:JQueryMouseEventObject ) => any ): JQuery; /** * Trigger the "mouseout" event on an element. */ mouseout(): JQuery; /** * Bind an event handler to the "mouseout" JavaScript event. * * @param handler A function to execute when the event is triggered. */ mouseout( handler:( eventObject:JQueryMouseEventObject ) => any ): JQuery; /** * Bind an event handler to the "mouseout" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mouseout( eventData:any, handler:( eventObject:JQueryMouseEventObject ) => any ): JQuery; /** * Trigger the "mouseover" event on an element. */ mouseover(): JQuery; /** * Bind an event handler to the "mouseover" JavaScript event. * * @param handler A function to execute when the event is triggered. */ mouseover( handler:( eventObject:JQueryMouseEventObject ) => any ): JQuery; /** * Bind an event handler to the "mouseover" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mouseover( eventData:any, handler:( eventObject:JQueryMouseEventObject ) => any ): JQuery; /** * Trigger the "mouseup" event on an element. */ mouseup(): JQuery; /** * Bind an event handler to the "mouseup" JavaScript event. * * @param handler A function to execute when the event is triggered. */ mouseup( handler:( eventObject:JQueryMouseEventObject ) => any ): JQuery; /** * Bind an event handler to the "mouseup" JavaScript event. * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute when the event is triggered. */ mouseup( eventData:any, handler:( eventObject:JQueryMouseEventObject ) => any ): JQuery; /** * Remove an event handler. */ off(): JQuery; /** * Remove an event handler. * * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as "click", "keydown.myPlugin", or ".myPlugin". * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. * @param handler A handler function previously attached for the event(s), or the special value false. */ off( events:string, selector?:string, handler?:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Remove an event handler. * * @param events An object where the string keys represent one or more space-separated event types and optional namespaces, and the values represent handler functions previously attached for the event(s). * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. */ off( events:{ [key: string]: any; }, selector?:string ): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. */ on( events:string, handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. */ on( events:string, selector:string, handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. */ on( events:string, selector:string, data:any, handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Attach an event handler function for one or more events to the selected elements. * * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event occurs. */ on( events:{ [key: string]: any; }, selector?:any, data?:any ): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. * @param handler A function to execute at the time the event is triggered. */ one( events:string, handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. * @param data An object containing data that will be passed to the event handler. * @param handler A function to execute at the time the event is triggered. */ one( events:string, data:Object, handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. */ one( events:string, selector:string, handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events One or more space-separated event types and optional namespaces, such as "click" or "keydown.myPlugin". * @param selector A selector string to filter the descendants of the selected elements that trigger the event. If the selector is null or omitted, the event is always triggered when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event is triggered. * @param handler A function to execute when the event is triggered. The value false is also allowed as a shorthand for a function that simply does return false. */ one( events:string, selector:string, data:any, handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Attach a handler to an event for the elements. The handler is executed at most once per element per event type. * * @param events An object in which the string keys represent one or more space-separated event types and optional namespaces, and the values represent a handler function to be called for the event(s). * @param selector A selector string to filter the descendants of the selected elements that will call the handler. If the selector is null or omitted, the handler is always called when it reaches the selected element. * @param data Data to be passed to the handler in event.data when an event occurs. */ one( events:{ [key: string]: any; }, selector?:string, data?:any ): JQuery; /** * Specify a function to execute when the DOM is fully loaded. * * @param handler A function to execute after the DOM is ready. */ ready( handler:Function ): JQuery; resize( handler:( eventObject:JQueryEventObject ) => any ): JQuery; resize( eventData?:any, handler?:( eventObject:JQueryEventObject ) => any ): JQuery; scroll( handler:( eventObject:JQueryEventObject ) => any ): JQuery; scroll( eventData?:any, handler?:( eventObject:JQueryEventObject ) => any ): JQuery; select( handler:( eventObject:JQueryEventObject ) => any ): JQuery; select( eventData?:any, handler?:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Trigger the "submit" event on an element. */ submit(): JQuery; /** * Bind an event handler to the "submit" JavaScript event * * @param handler A function to execute each time the event is triggered. */ submit( handler:( eventObject:JQueryEventObject ) => any ): JQuery; /** * Bind an event handler to the "submit" JavaScript event * * @param eventData An object containing data that will be passed to the event handler. * @param handler A function to execute each time the event is triggered. */ submit( eventData?:any, handler?:( eventObject:JQueryEventObject ) => any ): JQuery; trigger( eventType:string, ...extraParameters:any[] ): JQuery; trigger( event:JQueryEventObject ): JQuery; triggerHandler( eventType:string, ...extraParameters:any[] ): Object; unbind( eventType?:string, handler?:( eventObject:JQueryEventObject ) => any ): JQuery; unbind( eventType:string, fls:boolean ): JQuery; unbind( evt:any ): JQuery; undelegate(): JQuery; undelegate( selector:any, eventType:string, handler?:( eventObject:JQueryEventObject ) => any ): JQuery; undelegate( selector:any, events:any ): JQuery; undelegate( namespace:string ): JQuery; unload( handler:( eventObject:JQueryEventObject ) => any ): JQuery; unload( eventData?:any, handler?:( eventObject:JQueryEventObject ) => any ): JQuery; // Internals context: Element; jquery: string; error( handler:( eventObject:JQueryEventObject ) => any ): JQuery; error( eventData:any, handler:( eventObject:JQueryEventObject ) => any ): JQuery; pushStack( elements:any[] ): JQuery; pushStack( elements:any[], name:any, arguments:any ): JQuery; // Manipulation after( ...content:any[] ): JQuery; after( func:( index:any ) => any ): JQuery; append( ...content:any[] ): JQuery; append( func:( index:any, html:any ) => any ): JQuery; appendTo( target:any ): JQuery; before( ...content:any[] ): JQuery; before( func:( index:any ) => any ): JQuery; clone( withDataAndEvents?:boolean, deepWithDataAndEvents?:boolean ): JQuery; detach( selector?:any ): JQuery; empty(): JQuery; insertAfter( target:any ): JQuery; insertBefore( target:any ): JQuery; prepend( ...content:any[] ): JQuery; prepend( func:( index:any, html:any ) => any ): JQuery; prependTo( target:any ): JQuery; remove( selector?:any ): JQuery; replaceAll( target:any ): JQuery; replaceWith( func:any ): JQuery; text(): string; text( textString:any ): JQuery; text( textString:( index:number, text:string ) => string ): JQuery; toArray(): any[]; unwrap(): JQuery; wrap( wrappingElement:any ): JQuery; wrap( func:( index:any ) => any ): JQuery; wrapAll( wrappingElement:any ): JQuery; wrapInner( wrappingElement:any ): JQuery; wrapInner( func:( index:any ) => any ): JQuery; // Miscellaneous each( func:( index:any, elem:Element ) => any ): JQuery; get( index?:number ): any; index(): number; index( selector:string ): number; index( element:any ): number; // Properties length: number; selector: string; [x: string]: any; [x: number]: HTMLElement; // Traversing add( selector:string, context?:any ): JQuery; add( ...elements:any[] ): JQuery; add( html:string ): JQuery; add( obj:JQuery ): JQuery; children( selector?:any ): JQuery; closest( selector:string ): JQuery; closest( selector:string, context?:Element ): JQuery; closest( obj:JQuery ): JQuery; closest( element:any ): JQuery; closest( selectors:any, context?:Element ): any[]; contents(): JQuery; end(): JQuery; eq( index:number ): JQuery; filter( selector:string ): JQuery; filter( func:( index:any ) => any ): JQuery; filter( element:any ): JQuery; filter( obj:JQuery ): JQuery; find( selector:string ): JQuery; find( element:any ): JQuery; find( obj:JQuery ): JQuery; first(): JQuery; has( selector:string ): JQuery; has( contained:Element ): JQuery; is( selector:string ): boolean; is( func:( index:any ) => any ): boolean; is( element:any ): boolean; is( obj:JQuery ): boolean; last(): JQuery; map( callback:( index:any, domElement:Element ) => any ): JQuery; next( selector?:string ): JQuery; nextAll( selector?:string ): JQuery; nextUntil( selector?:string, filter?:string ): JQuery; nextUntil( element?:Element, filter?:string ): JQuery; nextUntil( obj?:JQuery, filter?:string ): JQuery; not( selector:string ): JQuery; not( func:( index:any ) => any ): JQuery; not( element:any ): JQuery; not( obj:JQuery ): JQuery; offsetParent(): JQuery; parent( selector?:string ): JQuery; parents( selector?:string ): JQuery; parentsUntil( selector?:string, filter?:string ): JQuery; parentsUntil( element?:Element, filter?:string ): JQuery; parentsUntil( obj?:JQuery, filter?:string ): JQuery; prev( selector?:string ): JQuery; prevAll( selector?:string ): JQuery; prevUntil( selector?:string, filter?:string ): JQuery; prevUntil( element?:Element, filter?:string ): JQuery; prevUntil( obj?:JQuery, filter?:string ): JQuery; siblings( selector?:string ): JQuery; slice( start:number, end?:number ): JQuery; // Utilities queue( queueName?:string ): any[]; queue( queueName:string, newQueueOrCallback:any ): JQuery; queue( newQueueOrCallback:any ): JQuery; } declare module "jquery" { export = $; } declare var jQuery:JQueryStatic; declare var $:JQueryStatic;
20cbe06de2d3c2385dbe65edf1a39fa7bfdd70ae
TypeScript
nii-gakunin-cloud/sinetstream
/docs/tutorial-android/sinetstreamhelper-tutorial-container/chart/src/store/chart-state-type.ts
2.546875
3
export type TypeChart = 'line' | 'bar'; export interface ChartOption { id: number; title: string; chart: TypeChart; sensor: string; color?: string; }
986bce76f8a19c8466a1dd2b53d8e650230498f1
TypeScript
RaduMilici/pulsar-game
/src/util/findElement.ts
2.65625
3
const findElement = (selector: string): HTMLElement | null => { const container: HTMLElement | null = document.querySelector(selector); if (container === null) { console.error(`Can't find container with selector ${selector}`); } return container; }; export default findElement;
7e31631b48afdb56485d808338243ee85fc22889
TypeScript
OmniCar/tfetch
/src/api.ts
3.4375
3
export interface IJsonStatus<T, E> { data?: T errorData?: E networkError?: NetworkError statusCode?: number } export type NetworkError = 'TIMEOUT' | 'OTHER' export type HttpType = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' export interface IExtraHeader { key: string value: string } export interface IRequestBasicParams<B = any> { body?: B extraHeaders?: IExtraHeader[] method?: HttpType jsonRequest?: boolean jsonResponse?: boolean timeout?: number // timeout in milliseconds url: string } export interface IValidStatusCode { validStatusCodes?: number[] validStatusCodeStart?: number validStatusCodeEnd?: number } export type IRequestParams<B> = IRequestBasicParams<B> & IValidStatusCode const bodyHttpTypes: HttpType[] = ['POST', 'PUT', 'PATCH', 'DELETE'] const defaultRequestParams = { method: 'GET', jsonRequest: true, jsonResponse: true, validStatusCodeStart: 200, validStatusCodeEnd: 299, timeout: 10000, } /** * Sends a standard request, and handles JSON parsing and response mapping to IJSonStatus * If the IJsonStatus data is defined, it means the request was successful. * If the networkError is set it means a network error happened. * If data is undefined, and networkError is unset, errorData will be defined * T is the expected type to be returned on success, E the expected type on errors * @param body Optional body for POST requests * @param extraHeaders Optional extra headers to add * @param method Http method to use (one of httpType) * @param jsonRequest Optional boolean whether this is a boolean request. Defaults to JSON - set this to false to omit json request headers * @param jsonResponse Optional boolean whether this is a boolean response. Defaults to JSON - set this to false to omit json response headers * @param validStatusCodes Optional array of HTTP status codes to consider success. Default is 200 - 299 * @param url Full path for request - example: https://github.com/api/test * @return IJsonStatus object with the parsed data or error */ export function requestJson<T, E, B = Object>( requestParams: IRequestParams<B>, ): Promise<IJsonStatus<T, E>> { const processedParams = { ...defaultRequestParams, ...requestParams } const { url, method, body, extraHeaders, jsonResponse, jsonRequest, validStatusCodes, validStatusCodeStart, validStatusCodeEnd, timeout, } = processedParams const statusResponse: IJsonStatus<T, E> = {} const headers = new Headers() if (jsonRequest) { // Add default JSON headers headers.append('Content-Type', 'application/json') } if (jsonResponse) { headers.append('Accept', 'application/json') // Add default JSON headers } if (extraHeaders) { extraHeaders.map(h => headers.append(h.key, h.value)) } const params: RequestInit = { method, headers, } if (body && bodyHttpTypes.includes(method as HttpType)) { params.body = JSON.stringify(body) } return Promise.race([ fetch(url, params), // This promise will never resolve new Promise((_, reject) => setTimeout(() => { statusResponse.statusCode = 408 // Timeout status code const err: NetworkError = 'TIMEOUT' reject(err) }, timeout), ), ]) .then((res: {} | Response) => { // response will always be type 'Response' const response = res as Response statusResponse.statusCode = response.status if (jsonResponse) { return response.json() } else { return response.text() } }) .then((json: T | E) => { // Allow expecting something other than 200s const validStatusCode = isValidStatusCode(statusResponse.statusCode!, { validStatusCodes, validStatusCodeStart, validStatusCodeEnd, }) if (validStatusCode) { // Success - type is T statusResponse.data = json as T } else { // Error - type is ApiError statusResponse.errorData = json as E } return statusResponse }) .catch((err: NetworkError | Error) => { // The error is either a timeout ('TIMEOUT'), a network error or a JSON parsing error // For now we're only handling the timeout, and calling all others 'OTHER' statusResponse.networkError = err === 'TIMEOUT' ? 'TIMEOUT' : 'OTHER' return statusResponse }) } const isValidStatusCode = ( statusCode: number, validation: IValidStatusCode, ) => { const { validStatusCodes, validStatusCodeStart, validStatusCodeEnd, } = validation if (validStatusCodes) { return validStatusCodes.find(sc => sc === statusCode) !== undefined } if (validStatusCodeStart && validStatusCodeEnd) { return ( statusCode >= validStatusCodeStart && statusCode <= validStatusCodeEnd ) } return false }
0289b894f2e23fbce0f609b56c77457c55574268
TypeScript
kpritam/gateway-tsclient
/test/params/Key.test.ts
2.6875
3
import * as TestData from 'jsons/keys.json' import { AltAzCoord, CometCoord, EqCoord, MinorPlanetCoord, SolarSystemCoord, Key, Parameter } from 'models' import * as Keys from 'models/params/Key' const stringify = (param: Parameter<Key>) => JSON.stringify(param.toJSON()[param.keyTag]) // ======== Simple Keys ======== const intParam = Keys.intKey('numbers').set([1, 2, 3]) const longParam = Keys.longKey('numbers').set([1, 2, 3]) const shortParam = Keys.shortKey('numbers').set([1, 2, 3]) const floatParam = Keys.floatKey('numbers').set([1, 2, 3]) const doubleParam = Keys.doubleKey('numbers').set([1, 2, 3]) const byteParam = Keys.byteKey('numbers').set([1, 2, 3]) const booleanParam = Keys.booleanKey('BooleanKey').set([true]) const stringParam = Keys.stringKey('days').set(['monday', 'tuesday']) const charParam = Keys.charKey('days').set(['monday', 'tuesday']) const utcTimeParam = Keys.utcTimeKey('utcTimeKey').set(['2017-09-04T16:28:00.123456789Z']) const taiTimeParam = Keys.taiTimeKey('taiTime').set(['2017-09-04T16:28:00.123456789Z']) // ======== Array Keys ======== const intArrayParam = Keys.intArrayKey('arrayOfNumbers').set([[1, 2], [3]]) const longArrayParam = Keys.longArrayKey('arrayOfNumbers').set([[1, 2], [3]]) const shortArrayParam = Keys.shortArrayKey('arrayOfNumbers').set([[1, 2], [3]]) const floatArrayParam = Keys.floatArrayKey('arrayOfNumbers').set([[1.2, 2.4243], [3.3]]) const doubleArrayParam = Keys.doubleArrayKey('arrayOfNumbers').set([[1.2, 2.4243], [3.3]]) const byteArrayParam = Keys.byteArrayKey('arrayOfNumbers').set([[1, 2], [3]]) // ======== Matrix Keys ======== const numberMatrixData = [ [1, 2, 3], [4, 5, 6] ] const intMatrixParam = Keys.intMatrixKey('test matrix').set([numberMatrixData]) const longMatrixParam = Keys.longMatrixKey('test matrix').set([numberMatrixData]) const shortMatrixParam = Keys.shortMatrixKey('test matrix').set([numberMatrixData]) const byteMatrixParam = Keys.byteMatrixKey('test matrix').set([numberMatrixData]) const fractionMatrixData = [ [1.0, 2.2, 3.3], [4.444, 5.34, 6.77] ] const floatMatrixParam = Keys.floatMatrixKey('test matrix').set([fractionMatrixData]) const doubleMatrixParam = Keys.doubleMatrixKey('test matrix').set([fractionMatrixData]) const structParam = Keys.structKey('structKey').set([{ paramSet: [intParam, stringParam] }]) const resetKey = Keys.choiceKey('mode-reset') const choices = resetKey.makeChoices('c', 'x', 'v', 'y') const choiceParam = resetKey.setChoice(choices, ['c']) const raDecParam = Keys.raDecKey('RaDecKey').set([{ ra: 7.3, dec: 12.1 }]) // ======== Coord Keys ======== const eqCoord: EqCoord = { _type: 'EqCoord', tag: 'BASE', ra: 659912250000, dec: -109892300000, frame: 'ICRS', catalogName: 'none', pm: { pmx: 0.5, pmy: 2.33 } } const solarSystemCoord: SolarSystemCoord = { _type: 'SolarSystemCoord', tag: 'BASE', body: 'Venus' } const minorPlanetCoord: MinorPlanetCoord = { _type: 'MinorPlanetCoord', tag: 'GUIDER1', epoch: 2000.0, inclination: 324000000000, longAscendingNode: 7200000000, argOfPerihelion: 360000000000, meanDistance: 1.4, eccentricity: 0.234, meanAnomaly: 792000000000 } const cometCoord: CometCoord = { _type: 'CometCoord', tag: 'BASE', epochOfPerihelion: 2000.0, inclination: 324000000000, longAscendingNode: 7200000000, argOfPerihelion: 360000000000, perihelionDistance: 1.4, eccentricity: 0.234 } const altAzCoord: AltAzCoord = { _type: 'AltAzCoord', tag: 'BASE', alt: 1083600000000, az: 153000000000 } const eqParam = Keys.eqCoordKey('EqCoordKey').set([eqCoord]) const solarSystemParam = Keys.solarSystemCoordKey('SolarSystemCoordKey').set([solarSystemCoord]) const minorPlanetParam = Keys.minorPlanetCoordKey('MinorPlanetCoordKey').set([minorPlanetCoord]) const cometParam = Keys.cometCoordKey('CometCoordKey').set([cometCoord]) const altAzParam = Keys.altAzCoordKey('AltAzCoordKey').set([altAzCoord]) const coordParam = Keys.coordKey('CoordKey').set([eqCoord, solarSystemCoord]) describe('Key-Parameter Contract', () => { test.each([ ['IntKey', intParam, TestData.GeneralKey], ['LongKey', longParam, TestData.GeneralKey], ['ShortKey', shortParam, TestData.GeneralKey], ['FloatKey', floatParam, TestData.GeneralKey], ['DoubleKey', doubleParam, TestData.GeneralKey], ['ByteKey', byteParam, TestData.GeneralKey], ['BooleanKey', booleanParam, TestData.BooleanKey], ['StringKey', stringParam, TestData.StringKey], ['CharKey', charParam, TestData.StringKey], ['UTCTimeKey', utcTimeParam, TestData.UTCTimeKey], ['TAITimeKey', taiTimeParam, TestData.TAITimeKey], ['IntArrayKey', intArrayParam, TestData.ArrayKey], ['LongArrayKey', longArrayParam, TestData.ArrayKey], ['ShortArrayKey', shortArrayParam, TestData.ArrayKey], ['FloatArrayKey', floatArrayParam, TestData.GeneralArrayKey], ['DoubleArrayKey', doubleArrayParam, TestData.GeneralArrayKey], ['ByteArrayKey', byteArrayParam, TestData.ArrayKey], ['IntMatrixKey', intMatrixParam, TestData.GeneralMatrixKey], ['LongMatrixKey', longMatrixParam, TestData.GeneralMatrixKey], ['ShortMatrixKey', shortMatrixParam, TestData.GeneralMatrixKey], ['FloatMatrixKey', floatMatrixParam, TestData.FractionMatrixKey], ['DoubleMatrixKey', doubleMatrixParam, TestData.FractionMatrixKey], ['ByteMatrixKey', byteMatrixParam, TestData.GeneralMatrixKey], ['StructKey', structParam, TestData.StructKey], ['ChoiceKey', choiceParam, TestData.ChoiceKey], ['RaDecKey', raDecParam, TestData.RaDecKey], ['EqCoordKey', eqParam, TestData.EqCoordKey], ['SolarSystemCoordKey', solarSystemParam, TestData.SolarSystemCoordKey], ['MinorPlaneCoordKey', minorPlanetParam, TestData.MinorPlanetCoordKey], ['CometCoordKey', cometParam, TestData.CometCoordKey], ['AltAzCoordKey', altAzParam, TestData.AltAzCoordKey], ['CoordKey', coordParam, TestData.CoordKey] ])('%s', (_, actual, expected) => expect(stringify(actual)).toEqual(JSON.stringify(expected))) })
55a992f00284e4d6017840f30f1af8d4b9cb27de
TypeScript
Keynesking/blog
/TS/base/dist/interface1.d.ts
2.90625
3
interface LabelledValue { label: string; } declare function printLabel(labelledObj: LabelledValue): void; declare let myObj: { size: number; label: string; }; interface SearchFunc { (source: string, subString: string): boolean; } declare let mySearch: SearchFunc; interface Person1 { name: string; age: number; } interface PersonArray { [index: number]: Person1; } declare let manyPerson: PersonArray; interface ClockConstructor { new (hour: number, minute: number): number; } declare class Control { private state; } interface SelectableControl extends Control { select(): void; } declare class Button extends Control implements SelectableControl { select(): void; } declare class TextBox extends Control { select(): void; }
1a44b5b38a68e1eaac3072a4b590ae6fb71417f3
TypeScript
AmeetGill/Trison
/test/Tunnels/ConditionalTunnel.ts
2.84375
3
import ReadOnlyMessage from "../../src/Messages/ReadOnlyMessage"; import Message from "../../src/Messages/Message"; import {describe,it} from "mocha" import * as chai from "chai"; import chaiExclude from 'chai-exclude'; import Queue from "../../src/Queue"; import {NO_CONDITIONAL_TUNNEL_FOUND_MESSAGE} from "../../src/Utils/const"; import Tunnel from "../../src/interfaces/Tunnel"; chai.use(chaiExclude); let expect = chai.expect; let data1 = { userId: "lk3kj3kj3kj3k3jk3j", text: "Hello Testing", tunnel: "tunnel1" } let data2 = { userId: "lk3kj3kj3kj3k3jk3j", text: "Hello Testing", tunnel: "tunnel2" } let processorFunction = async (message: ReadOnlyMessage<object>) => { let extractedData = message.getData(); extractedData["processed"] = true; return new ReadOnlyMessage(message); } let preProcessorFunction = (message: ReadOnlyMessage<object>) => { let extractedData = message.getData(); extractedData["processed"] = true; return new ReadOnlyMessage(message); } let matcherFunction1 = (message: ReadOnlyMessage<object>) => { let data = message.getData(); return data && data["tunnel"] && data["tunnel"] === "tunnel1"; } let matcherFunction2 = (message: ReadOnlyMessage<object>) => { let data = message.getData(); return data && data["tunnel"] && data["tunnel"] === "tunnel2"; } let reshuffleArray = (arr: Array<any>) => { for(let i = arr.length-1; i > 0; i--){ let randomIndex = Math.round(Math.random() * (i)); let temp = arr[i]; arr[i] = arr[randomIndex]; arr[randomIndex] = temp; } } export default () => { describe('test create ConditionalTunnel ', function () { it('should be able to add WritableMessage according to condition', function () { let multilevelQueue = new Queue<object>(); let conditionalTunnel1 = multilevelQueue.createConditionalTunnel( matcherFunction1, processorFunction, false ); let conditionalTunnel2 = multilevelQueue.createConditionalTunnel( matcherFunction2, processorFunction, false ); let writableMessage1 = new Message<object>( data1, () => { }, 2 ) let writableMessage2 = new Message<object>( data2, () => { }, 2 ) multilevelQueue.offer(writableMessage1); multilevelQueue.offer(writableMessage2); expect(writableMessage1.getTunnelId()).to.equal(conditionalTunnel1.getTunnelId()); expect(writableMessage2.getTunnelId()).to.equal(conditionalTunnel2.getTunnelId()); expect(conditionalTunnel1.containsMessageWithId(writableMessage1.getMessageId())).to.be.true; expect(conditionalTunnel1.containsMessageWithId(writableMessage2.getMessageId())).to.be.false; expect(conditionalTunnel2.containsMessageWithId(writableMessage2.getMessageId())).to.be.true; expect(conditionalTunnel2.containsMessageWithId(writableMessage1.getMessageId())).to.be.false; expect(conditionalTunnel1.getMessagesWithId(writableMessage1.getMessageId())) .excluding("_callbackFunction") .to.deep.equal([writableMessage1.createNewReadOnlyMessage()]); expect(conditionalTunnel2.getMessagesWithId(writableMessage2.getMessageId())) .excluding("_callbackFunction") .to.deep.equal([writableMessage2.createNewReadOnlyMessage()]); let polledMessage1 = conditionalTunnel1.pollMessage(); let polledMessage2 = conditionalTunnel2.pollMessage(); expect(polledMessage1).excluding("_callbackFunction").to.deep.equals(writableMessage1.createNewReadOnlyMessage()); expect(polledMessage2).excluding("_callbackFunction").to.deep.equals(writableMessage2.createNewReadOnlyMessage()); }); it('should error if no matching tunnel is found for a message', function () { let multilevelQueue = new Queue<object>(); let conditionalTunnel1 = multilevelQueue.createConditionalTunnel( matcherFunction1, processorFunction, false ); let writableMessage1 = new Message<object>( data1, () => { }, 2 ) let writableMessage2 = new Message<object>( data2, () => { }, 2 ) multilevelQueue.offer(writableMessage1); expect(() => multilevelQueue.offer(writableMessage2)).to.throw(Error).with.property("message", NO_CONDITIONAL_TUNNEL_FOUND_MESSAGE) expect(writableMessage1.getTunnelId()).to.equal(conditionalTunnel1.getTunnelId()); expect(conditionalTunnel1.containsMessageWithId(writableMessage1.getMessageId())).to.be.true; expect(conditionalTunnel1.containsMessageWithId(writableMessage2.getMessageId())).to.be.false; expect(conditionalTunnel1.getMessagesWithId(writableMessage1.getMessageId())) .excluding("_callbackFunction") .to.deep.equal([writableMessage1.createNewReadOnlyMessage()]); let polledMessage1 = conditionalTunnel1.pollMessage(); expect(polledMessage1).excluding("_callbackFunction").to.deep.equals(writableMessage1.createNewReadOnlyMessage()); }); }); describe('test create ConditionalTunnel multiple ', function () { it('should be able to push to tunnel only if condition matches', function () { let multilevelQueue = new Queue<object>(); let functionCreator = (tunnelId) => { return (message: ReadOnlyMessage<object>) => { let data = message.getData(); return data && data["tunnel"] && data["tunnel"] === tunnelId; }; } let tunnels: Tunnel<object>[] = []; let messages: Message<object>[] = []; let tunnelMessageMap = {}; for (let i = 1; i <= 20; i++) { let tunnelName = "tunnel" + i; let newMatcherFunction = functionCreator(tunnelName); let tunnel = multilevelQueue.createConditionalTunnel( newMatcherFunction, processorFunction, false ) tunnels.push(tunnel); let dataNew = {...data1}; dataNew["tunnel"] = tunnelName; let message = new Message<object>( dataNew, () => { }, 2 ); messages.push(message) tunnelMessageMap[tunnel.getTunnelId()] = message; } reshuffleArray(messages); for (let message of messages) { multilevelQueue.offer(message); } for (let tunnel of tunnels) { let message: Message<object> = tunnelMessageMap[tunnel.getTunnelId()]; expect(tunnel.containsMessageWithId(message.getMessageId())).to.be.true; expect(tunnel.getMessagesWithId(message.getMessageId())).to.deep.equals([message.createNewReadOnlyMessage()]) expect(tunnel.getLength()).to.equal(1); } }); }); }
fe6dbbb55d19b9e6fd37ea3ecc6b476e96ec2c98
TypeScript
ukstv/js-ceramic
/packages/key-did-resolver/src/nist_weierstrass_common.ts
3.234375
3
// Brent Shambaugh <brent.shambaugh@gmail.com>. 2021. import * as u8a from 'uint8arrays' import { base64url } from 'multiformats/bases/base64' /** * x,y point as a BigInt (requires at least ES2020) * For BigInt see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt */ interface BigIntPoint { x: BigInt, y : BigInt } /** * xm,ym point with components expresse with base64url utilizing multiformats * * base64url is expressed in the Multibase Table: https://github.com/multiformats/multibase/blob/master/multibase.csv */ interface base64urlPoint { xm: string, ym: string } /** * Elliptic curve point with coordinates expressed as byte arrays (Uint8Array) */ interface octetPoint { xOctet: Uint8Array, yOctet: Uint8Array } /** * Converts a byte array into a Hex String. * * @param pubKeyBytes - public key * @returns hex string * @throws TypeError: input cannot be null or undefined. */ export function pubKeyBytesToHex(pubKeyBytes: Uint8Array) : string { if(!testUint8Array(pubKeyBytes)) { throw new TypeError('input must be a Uint8Array'); } const bbf = u8a.toString(pubKeyBytes,'base16') return bbf; } /** * * @param publicKeyHex - public key as hex string. * @returns * @throws TypeError: input cannot be null or undefined. */ export function publicKeyToXY(publicKeyHex: string) : base64urlPoint { if(!testHexString(publicKeyHex)) { throw new TypeError('input must be string with characters 0-9,A-F,a-f'); } const u8aOctetPoint = publicKeyHexToUint8ArrayPointPair(publicKeyHex); const xm = base64url.encode(u8aOctetPoint.xOctet).slice(1); const ym = base64url.encode(u8aOctetPoint.yOctet).slice(1); return { xm, ym }; } /** * * @param publicKeyHex - public key as hex string. * @returns - point with Uint8Array bytes using base16 * @throws TypeError: input cannot be null or undefined. */ export function publicKeyHexToUint8ArrayPointPair(publicKeyHex: string) : octetPoint { if(!testHexString(publicKeyHex)) { throw new TypeError('input must be string with characters 0-9,A-F,a-f'); } const xHex = publicKeyHex.slice(0,publicKeyHex.length/2); const yHex = publicKeyHex.slice(publicKeyHex.length/2,publicKeyHex.length); const xOctet = u8a.fromString(xHex,'base16'); const yOctet = u8a.fromString(yHex,'base16'); return { xOctet, yOctet }; } /** * Tests to see if the argument is a Hex String. * @param str * @returns */ export function testHexString(str : string) : boolean { const regex = new RegExp(/^[A-Fa-f0-9]+/i); if(regex.test(str)) { if(str.length == regex.exec(str)[0].length) { return true; } } return false; } /** * Test to see if the argument is the Uint8Array * @param param * @returns */ export function testUint8Array(param: Uint8Array) : boolean { if(param == null) { return false; } if(param.constructor === Uint8Array) { return true; } else { return false; } } /** * * @param ecpoint - Public key. * @returns Uint8Array with bytes as base16 * @throws TypeError: input cannot be null or undefined. * @throws Error: Input coordinates must be BigInt * @throws Error: Input must have properties x and y * @throws TypeError: Input must be an object with properties x and y * Points xm and ym follow the base64url format in JSON Web Key (JWK) in RFC 7517: https://datatracker.ietf.org/doc/html/rfc7517 */ export function publicKeyIntToXY(ecpoint: BigIntPoint): base64urlPoint { if(ecpoint == null) { throw new TypeError('input cannot be null or undefined.'); } if(typeof ecpoint !== "object") { throw new TypeError("Input must be an object with properties x and y"); } if(!Object.prototype.hasOwnProperty.call(ecpoint, "x") || !Object.prototype.hasOwnProperty.call(ecpoint, "y")) { throw new Error("Input must have properties x and y"); } if(typeof ecpoint.x !== "bigint" && typeof ecpoint.y !== "bigint") { throw new Error("Input coordinates must be BigInt"); } const u8aOctetPoint = publicKeyIntToUint8ArrayPointPair(ecpoint); const xm = base64url.encode(u8aOctetPoint.xOctet).slice(1); const ym = base64url.encode(u8aOctetPoint.yOctet).slice(1); return { xm, ym }; } /** * * @param ecpoint - Public key. * @returns Uint8Array with bytes as base10 * @throws TypeError: input cannot be null or undefined. * @throws Error: Input coordinates must be BigInt * @throws Error: Input must have properties x and y * @throws TypeError: Input must be an object with properties x and y */ export function publicKeyIntToUint8ArrayPointPair(ecpoint: BigIntPoint) : octetPoint { if(ecpoint == null) { throw new TypeError('input cannot be null or undefined.'); } if(typeof ecpoint !== "object") { throw new TypeError("Input must be an object with properties x and y"); } if(!Object.prototype.hasOwnProperty.call(ecpoint, "x") || !Object.prototype.hasOwnProperty.call(ecpoint, "y")) { throw new Error("Input must have properties x and y"); } if(typeof ecpoint.x !== "bigint" && typeof ecpoint.y !== "bigint") { throw new Error("Input coordinates must be BigInt"); } const xHex = (ecpoint.x).toString(); const yHex = (ecpoint.y).toString(); const xOctet = u8a.fromString(xHex,'base10'); const yOctet = u8a.fromString(yHex,'base10'); return { xOctet, yOctet }; }
48482b88b7517b5f2aac8a2038f9d35391e732b4
TypeScript
maolaya15/Biblioteca
/src/app/components/crear-libro/crear-libro.component.ts
2.515625
3
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Book } from 'src/app/models/book.model'; import { BookService } from 'src/app/service/book.service'; import Swal from 'sweetalert2'; import { DashboardComponent } from '../dashboard/dashboard.component'; /** * Componente para la creacion de un libro */ @Component({ selector: 'app-crear-libro', templateUrl: './crear-libro.component.html', styleUrls: ['./crear-libro.component.scss'] }) export class CrearLibroComponent implements OnInit { /** * Parametros de la interface Book */ book : Book ={ titulo: "", autor: "", tema: "", imagen: "", isbn: 0, descripcion :"", resumen : "", serie : "", edicion : "" } /** * @ignore */ constructor(public readonly bookService: BookService, public dashboardComponent: DashboardComponent, private router: Router, ) { } /** * @ignore */ ngOnInit(): void { } /** * Metodo que subscribe la informacion del libro nuevo * @returns void */ public crear():void{ Swal.fire({ title: '¿Está seguro de crear el libro?', showDenyButton: true, showCancelButton: true, confirmButtonText: `Guardar`, denyButtonText: `No guardar`, }).then((result) => { /* Read more about isConfirmed, isDenied below */ if (result.isConfirmed) { this.bookService.crearLibro(this.book).subscribe(newBook => console.log(newBook)) Swal.fire('Libro guardado!', '', 'success') console.log('crear libro'+ this.book) this.router.navigate(['/dashboard']) } else if (result.isDenied) { Swal.fire('No se ha agregado el libro', '', 'info') } }) } /** * Metodo que regresa a la ventana del componente DashboardComponent * @returns void */ public regresar():void{ this.router.navigate(['/dashboard']) } }
cebbc20350e0bf815b79d3a4009295501393bf38
TypeScript
travis-lxu/Graphics-II
/Lab4/lib/objects/EdgeTableElement.ts
2.796875
3
import { Vector3d } from "../math/Vector3d"; /* * @Author: GXwar * @Date: 2019-02-17 21:37:10 * @Last Modified by: GXwar * @Last Modified time: 2019-05-09 19:05:45 */ class EdgeTableElement { yStart: number; yMax: number; xStart: number; delta: number; zStart: number; zDeltaToY: number; normalStart: Vector3d; normalEnd: Vector3d; textureStart: Array<number>; textureDeltaToY: Array<number>; constructor(yStart: number, yMax: number, xStart: number, delta: number, zStart: number, zDeltaToY: number, normalStart: Vector3d, normalEnd: Vector3d, textureStart: Array<number>, textureDeltaToY: Array<number>) { this.yStart = yStart; this.yMax = yMax; this.xStart = xStart; this.delta = delta; this.zStart = zStart; this.zDeltaToY = zDeltaToY; this.normalStart = normalStart; this.normalEnd = normalEnd; this.textureStart = textureStart; // console.log("init: " + this.textureStart[0] + " " + this.textureStart[1]); this.textureDeltaToY = textureDeltaToY; // console.log("created: "); // console.log(this.textureStart[0]); // console.log(this.textureStart[1]); } }; export { EdgeTableElement };
b92445fda57da52ac12783d87e6b448f77c83e55
TypeScript
DKurilo/hackerrank
/leetcode/src/construct-target-array-with-multiple-sums/solution.ts
3.625
4
const constructTargetArrayWithMultipleSums = () => { const isPossible = (target: number[]): boolean => { // eslint-disable-next-line no-constant-condition while (true) { let maxIndex; let max = 0; let sum = 0; for (let i = 0; i < target.length; i += 1) { if (target[i] > max) { maxIndex = i; max = target[i]; } sum += target[i]; } if (max === 1) { return true; } sum -= max; if (max < sum + 1 || sum <= 0) { return false; } if (sum === 1) { return true; } // eslint-disable-next-line no-param-reassign target[maxIndex] %= sum; if (target[maxIndex] <= 0) { return false; } } }; console.log(isPossible([9, 3, 5]), true); console.log(isPossible([1, 1, 1, 2]), false); console.log(isPossible([8, 5]), true); const arr1 = new Array(50000) .fill(0) .map(() => Math.floor(Math.random() * 1000000000) + 1); console.log(isPossible(arr1)); console.log(isPossible([2, 900000001]), true); console.log(isPossible([2, 900000002]), false); console.log(isPossible([1, 5, 27]), true); console.log(isPossible([2]), false); }; constructTargetArrayWithMultipleSums();
6b2a3c20a635ef82622ec063bdb975d9bda8cdb7
TypeScript
frainmaster/mintbean_musichacks_synthesizer
/Tone.js-dev/Tone/component/channel/Split.ts
3
3
import { ToneAudioNode, ToneAudioNodeOptions } from "../../core/context/ToneAudioNode"; import { optionsFromArguments } from "../../core/util/Defaults"; interface SplitOptions extends ToneAudioNodeOptions { channels: number; } /** * Split splits an incoming signal into the number of given channels. * * @example * const split = new Tone.Split(); * // stereoSignal.connect(split); * @category Component */ export class Split extends ToneAudioNode<SplitOptions> { readonly name: string = "Split"; /** * The splitting node */ private _splitter: ChannelSplitterNode; readonly input: ChannelSplitterNode; readonly output: ChannelSplitterNode; /** * @param channels The number of channels to merge. */ constructor(channels?: number); constructor(options?: Partial<SplitOptions>); constructor() { super(optionsFromArguments(Split.getDefaults(), arguments, ["channels"])); const options = optionsFromArguments(Split.getDefaults(), arguments, ["channels"]); this._splitter = this.input = this.output = this.context.createChannelSplitter(options.channels); this._internalChannels = [this._splitter]; } static getDefaults(): SplitOptions { return Object.assign(ToneAudioNode.getDefaults(), { channels: 2, }); } dispose(): this { super.dispose(); this._splitter.disconnect(); return this; } }
efb7ebb4da2f26cb9143bb9ed89a8a02fb9e0e8b
TypeScript
yvelianyk/ipfinder-rest-server
/handlers/getCurrentUser.ts
2.671875
3
import { Response, Request } from "express"; import { IUser } from '../models/users'; import * as _ from 'underscore'; import { AccessRoles } from '../services/ac.service'; interface RequestWithUser extends Request { user: string; } const getCurrentUser = function(request: RequestWithUser, response: Response){ let currentUser: IUser = request.user; currentUser.connected = true; if (currentUser.access === AccessRoles.ADMIN) { currentUser.isAdmin = true; } response.json(_.pick(currentUser, 'name', 'email', 'avatar', 'connected', 'isAdmin')); }; export { getCurrentUser }
d7b1963579aa7727277dfc2fb95d57da053920dc
TypeScript
wolffman122/Screeps
/src/processTypes/buildingProcesses/towerRepair.ts
2.578125
3
import {Process} from '../../os/process' export class TowerRepairProcess extends Process { type = 'tr'; metaData: TowerRepairProcessMetaData; run() { if(!Game.rooms[this.metaData.roomName]) { this.completed = true; return; } if(Game.rooms[this.metaData.roomName]?.find(FIND_HOSTILE_CREEPS)?.length > 0) { return; } // const ramparts = this.roomData().ramparts.filter(rampart => { // return (rampart.hits < 50000); // }); const containers = this.roomData().generalContainers.filter(container => { return (container.hits < container.hitsMax); }); const sourceContainers = this.roomData().sourceContainers.filter(sourceContainer => { return (sourceContainer.hits < sourceContainer.hitsMax); }); let roads: StructureRoad[] = []; if(Game.time % 111 === 0) { this.metaData.roads = []; const room = Game.rooms[this.metaData.roomName]; const roads = room.find(FIND_STRUCTURES, {filter: s => s.structureType === STRUCTURE_ROAD }).sort((a,b) => (a.hits < b.hits) ? -1 : 1); if(roads?.length) { const lowestRoads = roads.splice(0, 10); for(const road of lowestRoads) { this.metaData.roads.push(road.id); } } } else { if(this.metaData.roads) { let allRepaired = true; for(let id of this.metaData.roads) { const road = <StructureRoad>Game.getObjectById(id); if(road.hits < road.hitsMax) { roads.push(road); allRepaired = false; } } if(allRepaired) delete this.metaData.roads; } } const spawns = this.roomData().spawns.filter(s => s.hits < s.hitsMax); let sortedRamparts = _.sortBy(<Structure[]>[].concat( <never[]>spawns, //<never[]>ramparts, <never[]>containers, <never[]>sourceContainers, <never[]>[this.roomData().controllerContainer], <never[]>[this.roomData().mineralContainer], <never[]>[this.roomData().extractor], <never[]>roads ), 'hits') let usedTowers = <{[towerId: string]: boolean}>{} _.forEach(this.roomData().towers, function(tower){ usedTowers[tower.id] = (tower.energy < 500) }); let proc = this; _.forEach(sortedRamparts, function(rampart){ let towers = proc.roomData().towers?.filter(tower => { return !usedTowers[tower.id]; }); if(towers?.length > 0 && rampart) { let tower = rampart.pos.findClosestByRange(towers); tower.repair(rampart); usedTowers[tower.id] = true; } }); } }
0bc366b9aa52faa98aae418e3107b3076f43e26e
TypeScript
serggin/rpn_calc
/src/custom-inputs/RPN.ts
3.8125
4
/** * Arithmetic formula calculator * Based on Reverse Polish notation Algorithm * See https://en.wikipedia.org/wiki/Reverse_Polish_notation * * Restictions: * Allowed numbers, operators "+", "-", "*", "/" (included infix "+", "-") and parentheses * * Usage: * const rpn = new RPN(); * const formula = "-2*(3+4)+5/6"; * rpn.change(formula); * const value = rpn.value; //value of the calculation * * @author serggin <serggin1@yandex.ru> */ type Token = number | string; type Value = number | undefined export class RPN { static getOperatorFunction(char: string): ((x: number, y: number) => number) { switch (char) { case '+': return (x: number, y: number): number => x + y; case '-': return (x: number, y: number): number => x - y; case '*': return (x: number, y: number): number => x * y; case '/': return (x: number, y: number): number => x / y; default: // "never" option return (x: number, y: number): number => 0; } } static getPriority(char: string): number { switch (char) { case '(': case ')': return 1; case '+': case '-': case '=': return 2; case '*': case '/': return 3; default: // "never" option return 0; } } static readonly numChars = '.0123456789'; static readonly opChars = '-+*/()'; static readonly binopChars = '-+*/'; static isNumChar(char: string): boolean { return char.length === 1 && RPN.numChars.indexOf(char) > -1; } static isOpChar(char: string): boolean { return char.length === 1 && RPN.opChars.indexOf(char) > -1; } static isBinOpChar(char: string): boolean { return char.length === 1 && RPN.binopChars.indexOf(char) > -1; } private stack: Token[] = []; private out: Token[] = []; private tokens: Token[] = []; private error: boolean = false; private text: string = ''; private _value: Value = undefined; private index: number = 0; /** * Get calculation result * * @return {number | undefined} undefined in case of invalid formula */ get value(): Value { return this._value; } private clear(): void { this.stack = []; this.out = []; this.error = false; this.tokens = []; } /** * Provide formula for calculation * * @param text formula */ change(text: string): void { this.clear(); this.text = text; this.parse(); } private parse(): void { this._value = undefined; this.index = 0; let token: Token | false; try { do { token = this.getToken(); if (token || token === 0) { this.tokens.push(token); } } while (token || token === 0); this.parseInfix(); this.calculate(); if (this.stack.length === 1 && !Number.isNaN(this.stack[0])) { if (typeof this.stack[0] === 'number') { this._value = this.stack[0]; } else { // option impossible } } } catch (err) { // console.log('tokens=', this.tokens); // console.error(err); } } private getToken(): Token | false { if (this.index > this.text.length - 1) { return false; } let lexeme = ''; let lexemeClosed = false; let opChar = ''; do { const char = this.text[this.index]; switch (char) { case ' ': lexemeClosed = lexeme.length > 0; this.index += 1; break; default: if (RPN.isNumChar(char)) { lexeme += char; this.index += 1; } else if (RPN.isOpChar(char)) { if (lexeme.length > 0) { lexemeClosed = true; } else { opChar = char; this.index += 1; } } else { throw new SyntaxError(`Invalid character "${char}"`); } } if (lexemeClosed || opChar.length > 0) { break; } } while (this.index < this.text.length); if (lexeme.length > 0) { const num = Number(lexeme); if (Number.isNaN(num)) { throw new SyntaxError(`Invalid number "${lexeme}"`); } return num; } if (opChar.length > 0) { return opChar; } else { return false; } } private parseInfix(): void { let prevToken: Token | undefined = undefined; let token: Token; for (let i = 0; i < this.tokens.length; i += 1) { token = this.tokens[i]; if (typeof token === 'number') { this.out.push(token); } else if (token === '(') { this.stack.push(token); } else if (token === ')') { let valid = false; do { const top = this.stack.pop(); if (top === '(') { valid = true; break; } this.out.push(top!); } while (this.stack.length > 0); if (!valid) { throw new SyntaxError('"(" has not previos "("'); } } else if (RPN.isBinOpChar(token)) { // test if operation is unary let opToken: string | undefined = undefined; if (prevToken === undefined || prevToken === '(') { if (token === '-') { opToken = '='; // unary "-" } else if (token === '+') { // ignore unary "+" } else { throw new SyntaxError(`Invalid unary ${token}`); } } else { opToken = token; do { const top: string = this.stack[this.stack.length - 1] as string; if (top === '=' || RPN.getPriority(top) >= RPN.getPriority(token)) { this.stack.pop(); this.out.push(top); } else { break; } } while (this.stack.length > 0); } if (opToken) { this.stack.push(opToken); } } prevToken = token; } if (this.stack.length > 0) { for (let i = this.stack.length - 1; i >= 0; i -= 1) { token = this.stack[i] as string; if (RPN.isBinOpChar(token) || token === '=') { this.out.push(token); } else { throw new SyntaxError(`Invalid ${token}`); } } this.stack = []; } } private calculate(): void { this.stack = []; let token: Token; let operand1: number; let operand2: number; for (let i = 0; i < this.out.length; i += 1) { token = this.out[i]; if (typeof token === 'number') { this.stack.push(token); } else if (token === '=') { operand1 = this.stack.pop() as number; this.stack.push(-operand1); } else { operand2 = this.stack.pop() as number; operand1 = this.stack.pop() as number; this.stack.push(RPN.getOperatorFunction(token)(operand1, operand2)); } } } }
0c87b3bd7263a5db3446cca71e734b208a8ec2ad
TypeScript
pfych/kbinxml-ts
/src/sixBit/sixbit.ts
3.296875
3
import { bigintToBuf } from "bigint-conversion"; // TODO: Make this more readable, It functions but it could be confusing. const CHAR_MAP = "0123456789:ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"; const BYTE_MAP: { [key: string]: number } = CHAR_MAP.split("").reduce( (acc: Record<string, number>, val) => { acc[val] = CHAR_MAP.split("").indexOf(val); return acc; }, {} ); export const unpack = (compactBuffer: Buffer): string => { return "STUB"; }; export const pack = (string: string): any => { const chars: number[] = string.split("").map((char) => BYTE_MAP[char]); // Calculate padding and fallback to 0 if its equal to 8 const calcPadding = 8 - ((string.length * 6) % 8); const padding = calcPadding === 8 ? 0 : calcPadding; // Javascript represents all numbers as 64-bit double precision IEEE 754 floating point numbers // We need a 64 bit integer here! let bits = BigInt(0); chars.forEach((char) => { const bigChar = BigInt(char); bits = bits <<= BigInt(6); bits = bits | bigChar; // OR bitwise operator }); bits <<= BigInt(padding); // TODO: I could not figure this out myself, Replace this library eventually! return bigintToBuf(bits); };
ec9b6e3d92d0cb50cbcb833034e9613d45abcd9e
TypeScript
yzessta/storefront
/src/braintree.ts
2.53125
3
export async function createClient(paymentClientToken?: string) { const braintree = await import('braintree-web'); return braintree.client.create({ authorization: paymentClientToken ?? '', }); } type CreditCardData = { billingAddress: { postalCode?: string; }; cvv: string; expirationDate: string; number: string; options?: { validate?: boolean; }; }; export function makePayment(paymentClientToken: string, creditCard: CreditCardData) { return new Promise<{ cardType: string; lastFour: string; nonce: string }>((resolve, reject) => { // eslint-disable-next-line promise/prefer-await-to-then createClient(paymentClientToken).then((client) => { client.request( { data: { creditCard }, endpoint: 'payment_methods/credit_cards', method: 'post', }, ( error: | { details: { originalError: { fieldErrors: { field: string; fieldErrors: object }[]; }; }; } | undefined, data: { creditCards: { details: { cardType: string; lastFour: string }; nonce: string }[]; }, ) => { if (error == null) { const { nonce, details: { cardType, lastFour }, } = data.creditCards[0]; resolve({ cardType, lastFour, nonce }); } else if (error.details.originalError.fieldErrors.length > 0) { error.details.originalError.fieldErrors.forEach( (fieldError: { field: string; fieldErrors: object }) => { if (fieldError.field === 'creditCard') { reject(fieldError.fieldErrors); } }, ); } }, ); }); }); }
7d2e5a94914eccdc46243d6e2076a6e4818c909f
TypeScript
robert-harbison/super-validator
/lib/validators/Equals.ts
2.546875
3
import { createValidator } from '..' import { config } from '../core/Config' import { ErrorReturnTypes, ValidatorFunction } from '../core/Validator' const equals = (toEqual: unknown, strict = true, customMessage?: string): ValidatorFunction => createValidator((fieldKey: string, value: unknown): ErrorReturnTypes => { const check = strict ? value !== toEqual : value != toEqual return check ? config.language.equals : null }, customMessage) export default equals
84d11d2f468b0715387807b046df566deeec0d32
TypeScript
boa070270/engine-model
/src/playground/tty-properties.ts
2.734375
3
import {ReadStream, WriteStream} from 'tty'; import {EngineModel, EngineProperty, EnginePropertyFunc, PropertySource} from "engine-model"; import {EMPTY, Observable, of, Subscription} from "rxjs"; import {propertyNamesToPropertyArrays} from "../model/properties"; const rs: ReadStream = process.stdin; const ws: WriteStream = process.stdout; const TTYRead = new Observable(subscriber => { rs.on('data', data => { subscriber.next(data); }); }); const RsOfTTYRead = (m: EngineModel, s: PropertySource): EngineProperty<any> => { return new Observable(subscriber => { const subs = TTYRead.subscribe(v => subscriber.next(v)); return { unsubscribe() { subs.unsubscribe(); } } }); } const RsOfTTYIsRaw = (m: EngineModel, s: PropertySource): EngineProperty<any> => { return of(rs.isRaw); } const RsOfTTYIsTTY = (m: EngineModel, s: PropertySource): EngineProperty<any> => { return of(rs.isTTY); } const RsOfTTYSetRawMode = (m: EngineModel, s: PropertySource): EngineProperty<any> => { if (typeof s.data === 'boolean') { return of(rs.setRawMode(s.data)); } return EMPTY } const WsOfTTYResize = (m: EngineModel, s: PropertySource): EngineProperty<any> => { return new Observable(subscriber => { ws.on('resize', () => { subscriber.next([process.stdout.columns, process.stdout.rows]); }); }); } const WsOfTTYClearLine = (m: EngineModel, s: PropertySource): EngineProperty<any> => { if (typeof s.data === 'number' && [-1,0,1].includes(s.data)) { return new Observable(subscriber => { ws.clearLine(s.data, () => subscriber.next(true)); }); } return EMPTY; } const WsOfTTYClearScreenDown = (m: EngineModel, s: PropertySource): EngineProperty<any> => { return new Observable(subscriber => { ws.clearScreenDown(() => subscriber.next(true)); }); } const WsOfTTYColumns = (m: EngineModel, s: PropertySource): EngineProperty<any> => { return of(ws.columns); } const WsOfTTYRows = (m: EngineModel, s: PropertySource): EngineProperty<any> => { return of(ws.rows); } const WsOfTTYCursorTo = (m: EngineModel, s: PropertySource): EngineProperty<any> => { const data = s.data; if (typeof data === 'object' && typeof data.x === 'number') { const x = data.x; const y = typeof data.y === 'number' ? data.y : undefined; return new Observable(subscriber => { ws.cursorTo(x, y, () => subscriber.next(true)); }); } return EMPTY; } const WsOfTTYGetColorDepth = (m: EngineModel, s: PropertySource): EngineProperty<any> => { return of(ws.getColorDepth()); } const WsOfTTYGetWindowSize = (m: EngineModel, s: PropertySource): EngineProperty<any> => { return of(ws.getWindowSize()); } const WsOfTTYHasColors = (m: EngineModel, s: PropertySource): EngineProperty<any> => { const count = typeof s.data === 'number' ? s.data : undefined; return of(ws.hasColors(count)); } const WsOfTTYIsTTY = (m: EngineModel, s: PropertySource): EngineProperty<any> => { return of(ws.isTTY); } const WsOfTTYMoveCursor = (m: EngineModel, s: PropertySource): EngineProperty<any> => { if (typeof s.data === 'object') { const dx = typeof s.data.dx === 'number' ? s.data.dx : 0; const dy = typeof s.data.dy === 'number' ? s.data.dy : 0; return new Observable(subscriber => { ws.moveCursor(dx, dy, () => subscriber.next(true)); }); } return EMPTY; } const WsOfTTYWrite = (m: EngineModel, s: PropertySource): EngineProperty<any> => { const p = s.data?.property; const encoding = s.data?.encoding?? undefined; if (typeof p === 'string') { return new Observable(subscriber => { const subs = new Subscription(); subs.add(m.properties[p].subscribe(v => { if (typeof v === 'string') { ws.write(v, encoding, (err) => { if (err) { subscriber.error(err); } else { subscriber.next(true); } }); } else if (Buffer.isBuffer(v)){ ws.write(v, (err) => { if (err) { subscriber.error(err); } else { subscriber.next(true); } }); } else { // unknown data subscriber.next(false); } })); return { unsubscribe() { subs.unsubscribe(); } } }); } return EMPTY; } export const TTY_PROPERTIES: {[key: string]: EnginePropertyFunc} = { RsOfTTYRead, RsOfTTYIsRaw, RsOfTTYIsTTY, RsOfTTYSetRawMode, WsOfTTYClearLine, WsOfTTYClearScreenDown, WsOfTTYIsTTY, WsOfTTYColumns, WsOfTTYRows, WsOfTTYCursorTo, WsOfTTYGetWindowSize, WsOfTTYGetColorDepth, WsOfTTYHasColors, WsOfTTYMoveCursor, WsOfTTYResize, WsOfTTYWrite }
5ba82b3a18b68e015221376c09e9db8e43c80c93
TypeScript
validated-changeset/validated-changeset
/src/utils/get-deep.ts
3.0625
3
import { isChange, getChangeValue } from '../-private/change'; /** * Handles both single key or nested string keys ('person.name') * * @method getDeep */ export default function getDeep<T extends Record<string, any>>( root: T, path: string | string[] ): any { let obj: T = root; if (path.indexOf('.') === -1) { return obj[path as string]; } const parts: string[] = typeof path === 'string' ? path.split('.') : path; for (let i = 0; i < parts.length; i++) { if (obj === undefined || obj === null) { return undefined; } // next iteration has next level obj = obj[parts[i]]; } return obj; } /** * Returns subObject while skipping `Change` instances * * @method getSubObject */ export function getSubObject<T extends Record<string, any>>(root: T, path: string | string[]): any { let obj: T = root; if (path.indexOf('.') === -1) { return obj[path as string]; } const parts: string[] = typeof path === 'string' ? path.split('.') : path; for (let i = 0; i < parts.length; i++) { if (obj === undefined || obj === null) { return undefined; } if (isChange(obj[parts[i]])) { obj = getChangeValue(obj[parts[i]]); } else { obj = obj[parts[i]]; } } return obj; }
98feb956a249a971c01a99e9d5ac041d178ef070
TypeScript
EagleLizard/FactorySimulator
/Component/GlassComponent.ts
2.609375
3
import { Component, IMaterial, Glass, MaterialStore } from '../I'; export class GlassComponent extends Component{ input:IMaterial[]; output:Glass; constructor(){ super( 'GlassComponent', { name: 'Silica', units: 9 }, { name: 'Lime', units: 1} ); } process(store:MaterialStore):Glass{ let results = this.resultsFromStore(store); let success = this.validatedResults(results); if(success){ return new Glass(1); }else{ return new Glass(0); } } }
c2f52f6ba51af829e7cd67a84395ed05b39aaed0
TypeScript
diegoncollazo/UTN
/Laboratorio III/Cursada/Laboratorio III/PP.Práctica/Televisores/FRONTEND/producto.ts
3.25
3
namespace Entidades { export class Producto { //atributos codigo: number; marca: string; precio: number; //cosntructor que reciba los tres public constructor(codigo: number, marca: string, precio: number) { this.codigo = codigo; this.marca = marca; this.precio = precio; } //ToString():string, que retorne la representación de la clase en formato cadena (preparar la cadena para que, al juntarse con el método ToJSON, forme //una cadena JSON válida public ToString(): string { return ('"codigo":' + this.codigo + ',"marca":"' + this.marca + '","precio":"' + this.precio + '",'); } } }
03197e4945473e1f8311c4de8f63393a5c6f5cf0
TypeScript
kingokeke/farmunity
/server/src/models/UserModel.ts
2.640625
3
// USER MODEL FILE import { User as UserType } from '../typings/index'; import mongoose from 'mongoose'; import { hash } from 'bcryptjs'; const userSchema = new mongoose.Schema( { firstName: String, lastName: String, email: String, phone: String, password: String, role: String, streetAddress: String, localGovt: String, state: String, profilePic: String }, { timestamps: true } ); userSchema.pre<UserType>('save', async function(next) { if (this.isModified('password')) { try { this.password = await hash(this.password, 12); } catch (err) { console.log(err); next(err); } } next(); }); export default mongoose.model<UserType>('User', userSchema);
4a7db5931ceadab0bf9fb1c133430b738636b1c0
TypeScript
radko94/algorithms-and-data-structures
/sort/sort.ts
3.5
4
exports.bubbleSort = (array: number[], arrayLength: number) => { let firstIndex: number; let secondIndex: number; let swapped: boolean; let temporaryValue: number; for (firstIndex = 0; firstIndex < (arrayLength - 1); firstIndex++) { swapped = false; for (secondIndex = 0; secondIndex < arrayLength - firstIndex - 1; secondIndex++) { if (array[secondIndex] > array[secondIndex + 1]) { temporaryValue = array[secondIndex]; array[secondIndex] = array[secondIndex + 1]; array[secondIndex + 1] = temporaryValue; swapped = true; } } if(!swapped) break; } } exports.selectionSort = (array: number[]) => { for (let x = 0; x < array.length - 1; x++) { let lowestIndex: number = x; for (let y = x + 1; y < array.length; y++) { if (array[y] < array[lowestIndex]) lowestIndex = y; const temporaryValue = array[lowestIndex]; array[lowestIndex] = array[x]; array[x] = temporaryValue; } } } exports.insertionSort = (array: Array<number>) => { let y: number; let key: number; for (let x = 1; x < array.length; x++) { key = array[x]; y = x - 1; while (y >= 0 && array[y] > key) { array[y + 1] = array[y]; y--; } array[y + 1] = key; } }
faad1452a561021ffe38e98ba6a91172eab945a6
TypeScript
daviseford/aos-reminders
/src/factions/ogor_mawtribes/artifacts.ts
2.703125
3
import { tagAs } from 'factions/metatagger' import { CHARGE_PHASE, COMBAT_PHASE, END_OF_COMBAT_PHASE, MOVEMENT_PHASE, SHOOTING_PHASE, START_OF_ANY_PHASE, } from 'types/phases' const Artifacts = { //GUTBUSTERS HERO only. 'Gruesome Trophy Rack': { effects: [ { name: `Gruesome Trophy Rack`, desc: `Add 1 to hit rolls for attacks made by friendly GUTBUSTERS units wholly within 12" of the bearer that target a MONSTER or HERO.`, when: [COMBAT_PHASE, SHOOTING_PHASE], }, ], }, 'Splatter-cleaver': { effects: [ { name: `Splatter-cleaver`, desc: `Pick 1 of the bearer's melee weapons. At the end of the combat phase, if any wounds inflicted by that weapon in that phase were allocated to an enemy unit, you can heal D3 wounds allocated to each friendly OGOR unit wholly within 12" of the bearer (roll separately for each unit).`, when: [END_OF_COMBAT_PHASE], }, ], }, 'The Fang of Ghur': { effects: [ { name: `The Fang of Ghur`, desc: `TYRANT only. The bearer's Beastskewer Glaive has a Rend characteristic of -3 instead of -1.`, when: [COMBAT_PHASE], }, ], }, 'Flask of Stonehorn Blood': { effects: [ { name: `Flask of Stonehorn Blood`, desc: `Once per battle, at the start of a phase, you can say that the bearer will drink this potion. The bearer has a ward of 3+ until the end of that phase.`, when: [START_OF_ANY_PHASE], }, ], }, //BEASTCLAW RAIDERS HERO only, 'Elixir of Frostwyrm': { effects: [ { name: `Elixir of Frostwyrm`, desc: `Once per battle, in your shooting phase, you can pick 1 enemy unit within 6" of the bearer and roll a dice. On a 2+, that unit suffers D6 mortal wounds.`, when: [SHOOTING_PHASE], }, ], }, 'Frost-talon Shardbolts': { effects: [ { name: `Frost-talon Shardbolts`, desc: `If the unmodified hit roll for an attack made with the bearer's Hunter's Crossbow is 6, that attack causes D3 mortal wounds to the target in addition to any damage it inflicts.`, when: [SHOOTING_PHASE], }, ], }, 'Carvalox Flank': { effects: [ { name: `Carvalox Flank`, desc: `Friendly ICEFALL YHETEE units wholly within 12" of the bearer at the start of the movement phase can move an extra 2" when they make a normal move during that phase.`, when: [MOVEMENT_PHASE], }, ], }, 'The Seat of Alvagr': { effects: [ { name: `The Seat of Alvagr`, desc: `Once per battle, in the charge phase, you can carry out a second monstrous rampage with the bearer. The second monstrous rampage cannot be monstrous rampage you have already carried out in that phase.`, when: [CHARGE_PHASE], }, ], }, } export default tagAs(Artifacts, 'artifact')
86bc5bcb304cd40ed5970fa7325b926503062482
TypeScript
jashieh/typescript_practice
/typescript-fundamentals/challenges/dict/src/index.ts
3.734375
4
// <T> captures the generic type of the variable/function // allowing this type to be used elsewhere to make the // function more generic export type Dict<T> = { [k: string]: T | undefined; }; // Array.prototype.map, but for Dict export function mapDict<T, S>( dict: Dict<T>, fn: (arg: T, idx: number) => S ): Dict<S> { const out: Dict<S> = {}; Object.keys(dict).forEach((dKey, idx) => { const item = dict[dKey]; if(typeof item !== 'undefined') { out[dKey] = fn(item,idx); } }); return out; } // Array.prototype.reduce, but for Dict // export function reduceDict<T>(dict: Dict<T>) {}
f08c88f62f1a0ecbbe85487879513bb81e98608f
TypeScript
renavigation2/renavigation2
/packages/history/src/typings/Events.ts
2.6875
3
export type Events<F> = { length: number push: (fn: F) => () => void call: (arg: any) => void }
b71afcc61c7d32da76a6b0db596eea3a0052672f
TypeScript
abhishekkagrawal/angular_js
/typescript/ClassDemo.ts
3.453125
3
class Associate{ associateId:any; firstName:string; lastName:string; basicSalary:number; hra:number; ta:number; da:number; totalSalary:number; constructor(associatedId:number,firstName:string,lastName:string,basicSalary:number){ this.associateId=associatedId; this.firstName=firstName; this.lastName=lastName; this.basicSalary=basicSalary; } calculateTotalSalary():void{ this.hra=this.basicSalary*10/100; this.ta=this.basicSalary*7/100; this.da=this.basicSalary*6/100; this.totalSalary=this.basicSalary+this.hra+this.da+this.ta; } toString():string{ return this.associateId+" "+this.firstName+" "+this.lastName+" "+this.basicSalary+" "+this.hra+" "+this.da+" "+this.ta+" "+this.totalSalary } } var associatesList = new Array<Associate>(3); associatesList[0]= new Associate(101,"Satish","Mahajan",15000); associatesList[1]= new Associate(102,"Kumar","Raj",25000); associatesList[2]= new Associate(103,"Rakesh","Patil",25000); associatesList.forEach(associate => { associate.calculateTotalSalary(); console.log(associate.toString()) })
c10920f942a327110f537995733bfd6491535d50
TypeScript
alexisbertholom/node-basic-scheduler
/src/index.ts
3.28125
3
interface EventData<T> { timestamp: number, payload: T, }; type ActionF<T> = (payload: T) => any; type EventGetterF<T> = () => Promise<EventData<T> | null>; export class Scheduler<PayloadT> { private _timer: NodeJS.Timer | null; constructor( private action: ActionF<PayloadT>, private getNextEvent: EventGetterF<PayloadT>, private nextEvent: EventData<PayloadT> | null = null, ) { if (nextEvent) this._schedule(); else this.refresh(); } public refresh = async () => { try { this.nextEvent = await this.getNextEvent(); this._schedule(); } catch (e) { throw new Error('node-basic-scheduler: getNextEvent unhandled rejection: ' + e.toString()); } } public scheduleIn(payload: PayloadT, delay: number) { const timestamp = Date.now() + delay; return this.schedule({ timestamp, payload }); } public schedule(event: EventData<PayloadT>) { if (this.nextEvent && this.nextEvent.timestamp < event.timestamp) return; this.nextEvent = event; this._schedule(); } public get nextEventTimestamp(): number | null { return this.nextEvent && this.nextEvent.timestamp; } private _schedule = () => { if (this._timer) { clearTimeout(this._timer); this._timer = null; } if (!this.nextEvent) { this._timer = setTimeout(this.refresh, 0x7FFFFFFF); return; } const delay = this.nextEvent.timestamp - Date.now(); if (delay <= 0) this._run(); else if (delay >= 0x7FFFFFFF) this._timer = setTimeout(this._schedule, 0x7FFFFFFF); else this._timer = setTimeout(this._run, delay); } private _run = () => { this.action(this.nextEvent!.payload); this.refresh(); } }; export default Scheduler;
4e326fd62cc597cd13cabc43e29ff6f407bfa5b4
TypeScript
T4rk1n/dazzler
/src/icons/ts/types.d.ts
2.796875
3
type IconPackDict = { [name: string]: IconPackType; }; type IconPackType = { url: string; name: string; } type IconContextType = { packs: IconPackDict; addPack: (pack: IconPackType) => void; isLoaded: (packName: string) => boolean; }
3b2fdd761056aa41bafd45dcd1e6f528e9f542d1
TypeScript
alufers/openscad-parser
/src/CodeFile.ts
2.984375
3
import * as fs from "fs"; import * as path from "path"; export default class CodeFile { constructor(public path: string, public code: string) {} get filename() { return path.basename(this.path); } /** * Loads an openscad file from the filesystem. */ static async load(pathToLoad: string): Promise<CodeFile> { pathToLoad = path.resolve(pathToLoad); // normalize the path const contents = await new Promise<string>((res, rej) => { fs.readFile( pathToLoad, { encoding: "utf8", }, (err, data) => { if (err) { rej(err); return; } res(data); } ); }); return new CodeFile(pathToLoad, contents); } }
aa2b28a352843832a9ddd78dd8d8c9f60a4aaf35
TypeScript
yanche/compiler
/src/utility/number/idgen.ts
2.921875
3
import { isInt } from "../validate"; export class IdGen { private _cur: number; constructor(start: number = 0) { if (!isInt(start)) { throw new Error(`input to IdGen must be an integer`); } this._cur = start; } public next(): number { return this._cur++; } public get cur(): number { return this._cur; } }
6db74e2f850a3189862441dc96c90fa70af48e79
TypeScript
adam-rolain/DevBuildLab_13_2
/Inventory.ts
3.15625
3
import { Product } from "./Products"; interface InventoryItem { product: Product; quantity: number; }; let inventory: InventoryItem[] = [ { product: { name: 'motor', price: 10.00 }, quantity: 10 }, { product: { name: 'sensor', price: 12.50 }, quantity: 4 }, { product: { name: 'LED', price: 1.00 }, quantity: 20 } ]; const calcInventoryValue = (items: InventoryItem[]): number => { let total: number = 0; items.forEach(item => { total += item.product.price * item.quantity}); return total; }; let inventoryValue = calcInventoryValue(inventory); console.log(inventoryValue);
9fe0b7b9862b6a1d3bea03e743540a57dc2e7f9c
TypeScript
camizzilla/blog
/src/app/shared/components/canvas/services/canvas.service.ts
2.578125
3
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CanvasService { start = false; animationFrame; drawRect(ctx, { color, x, y, w, h }) { ctx.fillStyle = color; ctx.fillRect(x, y, w, h); } drawText(ctx, WIDTH, HEIGHT, { font, color, align, text }) { ctx.font = font; ctx.fillStyle = color; ctx.textAlign = align; ctx.fillText(text, WIDTH, HEIGHT); } canvas1(ctx, WIDTH, HEIGHT) { const rect = { color: '#ffad6a', x: 10, y: 10, w: 580, h: 380 }; this.drawRect(ctx, rect); } canvas2(ctx, WIDTH: number, HEIGHT: number) { this.canvas1(ctx, WIDTH, HEIGHT); const text = { font: '50px Impact', color: '#6a8aff', align: 'center', text: 'Platform Single Screen' }; this.drawText(ctx, WIDTH / 2, HEIGHT / 2, text); } canvas3(ctx, WIDTH, HEIGHT) { this.canvas2(ctx, WIDTH, HEIGHT); const rect1 = { color: '#000', x: WIDTH / 2 - 95, y: HEIGHT / 2 + 30, w: 200, h: 80 }; const rect2 = { color: '#85FF88', x: WIDTH / 2 - 100, y: HEIGHT / 2 + 35, w: 200, h: 80 }; const text = { font: '50px Impact', color: '#B37039', align: 'center', text: 'START' }; this.drawRect(ctx, rect1); this.drawRect(ctx, rect2); this.drawText(ctx, WIDTH / 2, HEIGHT / 2 + 95, text); } playerCharact(HEIGHT) { const playerWidth = 50; const playerHeight = 100; const playerX = 100; const playerY = HEIGHT - playerHeight; return { color: 'red', x: playerX, y: playerY, w: playerWidth, h: playerHeight }; } canvas4(ctx, WIDTH, HEIGHT) { const player = this.playerCharact(HEIGHT); this.drawRect(ctx, player); } canvas5(ctx, WIDTH, HEIGHT) { const step = 5; const player = this.playerCharact(HEIGHT); this.animationFrame = requestAnimationFrame(() => this.loop(ctx, player, step, WIDTH, HEIGHT)); } canvas6(ctx, WIDTH, HEIGHT) { const step = 5; const player = this.playerCharact(HEIGHT); this.animationFrame = requestAnimationFrame(() => this.loop(ctx, player, step, WIDTH, HEIGHT)); } canvas7(ctx, WIDTH, HEIGHT) { const step = 5; const player = this.playerCharact(HEIGHT); this.animationFrame = requestAnimationFrame(() => this.loop(ctx, player, step, WIDTH, HEIGHT)); } loop(ctx, player, step, WIDTH, HEIGHT) { this.drawRect(ctx, player); player.x = player.x + step; if (this.start) { requestAnimationFrame(() => this.loop(ctx, player, step, WIDTH, HEIGHT)); } } isStart(ctx, WIDTH, HEIGHT) { this.start = true; this.canvas5(ctx, WIDTH, HEIGHT); } // private color: string = '#000'; // private x: number = 100; // private w: number = 50; // private h: number = 100; // private y: number = 0; // private step: number = 5 // constructor(private ctx: CanvasRenderingContext2D) { // this.y = this.canvasHeight - this.h; // this.init(); // } // init() { // this.draw(); // } // reset() { // this.x = 0; // } // start() { // this.x += this.step; // this.draw(); // } // clear() { // this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight); // } // private draw() { // this.clear(); // this.ctx.fillStyle = this.color; // this.ctx.fillRect(this.x, this.y, this.w, this.h); // } }
358c86aa589a92eadd2fe993e6ebd5dafa4f701b
TypeScript
willemneal/assemblyscript
/lib/parse/tests/index.ts
2.625
3
import * as fs from "fs"; import * as assert from "assert"; import { Type, SectionId, ExternalKind, WasmParser } from "../src"; type CompileError = WebAssembly.CompileError; [ "../build/test.wasm", // "../build/index.wasm", // "libm.wasm" ].forEach((filename: string): void => { const binary: Uint8Array = fs.readFileSync(__dirname + "/" + filename); console.log("Testing '" + filename + "' ..."); var parser = new WasmParser(binary); assert(parser.hasStart()); console.log("Test binary has start section"); assert(parser.hasSection(SectionId.Data)) console.log("Test binary has data section"); assert(parser.hasSection(SectionId.Memory)) // console.log("\nType Section\n------------------------------"); // console.log(parser.Type); // parser.printModule(); //Remove Start Section var strippedBinary = parser.removeStartFunction(); assert(WebAssembly.validate(strippedBinary)); var parser2 = new WasmParser(strippedBinary); var dataSectionOnly = parser.exportDataSection(); assert(!parser2.hasStart()); console.log("Start section removed succesfully"); //Export Data Section // new WebAssembly.Module(dataSectionOnly); var parser3 = new WasmParser(dataSectionOnly); assert(parser3.hasSection(SectionId.Data)); assert(parser3.hasSection(SectionId.Memory)) new WebAssembly.Module(dataSectionOnly); console.log("Data section exported to module successfully"); // parser2.printModule(); }); console.log("Tests Pass!")
c200ea7815d0c22657f876d99bb373e877b49d8d
TypeScript
jovotech/jovo-framework
/platforms/platform-facebookmessenger/src/output/decorators/validation/CastedMaxLength.ts
2.734375
3
import { registerDecorator, ValidationOptions } from '@jovotech/output'; export function CastedMaxLength(max: number, options?: ValidationOptions): PropertyDecorator { return function (object, propertyKey) { registerDecorator({ name: 'castedMaxLength', target: object.constructor, propertyName: propertyKey.toString(), constraints: [max], options, validator: { validate(value: string) { if (!value.toString()) { return false; } return value.toString().length <= max; }, }, }); }; }
f749d3ad4d9555946bbc0fc2a1e6506b5f1bfc23
TypeScript
polynote/polynote
/polynote-frontend/polynote/ui/component/leftpane.ts
2.625
3
import {div, h2, TagElement} from "../tags"; import {LeftMenuSections, Pane} from "../layout/splitview"; import { LeftBarPreferences, LeftBarPrefsHandler, StickyLeftBarPreferences, ViewPreferences, ViewPrefsHandler } from "../../state/preferences"; import {Disposable, setProperty, setValue, StateHandler} from "../../state"; import {deepCopy} from "../../util/helpers"; export type LeftPaneDrawer = { content: Pane, nav: LeftPaneNav, section?: LeftMenuSections }; export type LeftPaneModal = { nav: LeftPaneNav, action: () => void }; export type LeftPaneNav = { title: string, icon: TagElement<"button"> }; /** * Handler for the contents of the left pane. Handles opening/closing different panes, opening modals, and updating state accordingly. * Takes in an array of drawers and modals, where each element's name is also its class name in the left-hand bar, for easy state management. */ export class LeftPaneHandler extends Disposable { readonly leftBar: TagElement<"div">; readonly leftPane: TagElement<"div">; private leftBarPrefs: StateHandler<LeftBarPreferences["stickyLeftBar"]>; private leftPanePrefs: StateHandler<ViewPreferences["leftPane"]>; constructor(drawers: LeftPaneDrawer[], modals: LeftPaneModal[]) { super(); this.leftBarPrefs = LeftBarPrefsHandler.lens("stickyLeftBar").disposeWith(this); this.leftPanePrefs = ViewPrefsHandler.lens("leftPane").disposeWith(this); this.leftBar = div(['sticky-left-bar'], []); // default to using the notebooks list if no state exists yet this.leftPane = div(['ui-panel'], [ drawers[0].content.header, div(['ui-panel-content', 'left'], [drawers[0].content.el]) ]); drawers.forEach((drawer) => { this.leftBar.appendChild(this.generateLeftBarEl(drawer).click(() => this.onDrawerChange(drawer.nav.title.toLowerCase()))); }) modals.forEach((modal) => { this.leftBar.appendChild(this.generateLeftBarEl(modal).click(() => modal.action())); }) const leftBarStatus = (leftBarPrefs: LeftBarPreferences) => { const oldActiveEl = this.leftBar.querySelector('.active'); oldActiveEl?.classList.remove('active'); drawers.forEach((drawer) => { const title = drawer.nav.title.toLowerCase(); if (leftBarPrefs.stickyLeftBar[title as keyof StickyLeftBarPreferences]) { // The drawer's title (in lowercase) is its class - we use that to denote it as active in the left bar const newActiveEl = this.leftBar.querySelector(`.${title}`); newActiveEl?.classList.add('active'); this.setLeftPane(drawer.content.header, drawer.content.el); } }) } leftBarStatus(LeftBarPrefsHandler.state); LeftBarPrefsHandler.addObserver(leftBarStatus).disposeWith(this); } // Handler for generating the initial element for drawers/modals in the left bar private generateLeftBarEl(el: LeftPaneDrawer | LeftPaneModal) { return div([el.nav.title.toLowerCase()], [ h2([], [el.nav.title]), el.nav.icon ]); } // Handler for updating the left pane when a new drawer elemenet is selected private setLeftPane(header: TagElement<"h2">, el: TagElement<"div">): void { this.leftPane.innerHTML = ""; // we can't use replaceWith and have to modify the innerHTML because of the CSS grid this.leftPane.appendChild(header); this.leftPane.appendChild(div(['ui-panel-content', 'left'], [el])); } // Handler for changing the open drawer private onDrawerChange(selected: string) { let paneIsOpen = false; const newLeftBarPrefs: StickyLeftBarPreferences = this.leftBarPrefs.state; // For each preference, check if it should be open or closed now, closing the old one if necessary. for (const [key, val] of Object.entries(newLeftBarPrefs)) { const res = key === selected ? !val : false; if (res) paneIsOpen = true; newLeftBarPrefs[key as keyof StickyLeftBarPreferences] = res; } this.leftBarPrefs.updateAsync(() => setValue(deepCopy(newLeftBarPrefs))); // If there are no more open panes, then signal to collapse the left pane entirely this.leftPanePrefs.updateAsync(state => setProperty("collapsed", !paneIsOpen)).then(() => { window.dispatchEvent(new CustomEvent('resize')); }) } }
2d9a8d019cd49486754bb74aa41933acd0ab3e7a
TypeScript
binary-com/SmartCharts
/src/components/ui/Helper.ts
3.109375
3
import Context from './Context'; /** * Abstract class for UI Helpers * @name CIQ.UI.Helper * @constructor */ class Helper { context: Context | null; injections: any; node: HTMLElement; constructor(node: HTMLElement, context: Context | null) { this.node = node; this.context = context; this.injections = []; // To keep track of injections for later removal } /** * Adds an injection. These will be automatically destroyed if the helper object is destroyed * @param {string} position "prepend" or "append" * @param {string} injection The injection name. i.e. "draw" * @param {Function} code The code to be run * @memberof CIQ.UI.Helper */ addInjection(position: string, injection: string, code: any) { this.injections.push(this.context?.stx[position](injection, code)); } /** * Removes injections from the ChartEngine * @memberof CIQ.UI.Helper */ destroy() { for (let i = 0; i < this.injections.length; i++) { this.context?.stx.removeInjection(this.injections[i]); } this.injections = []; } } export default Helper;
73ca7db29e5a4f91fadb0dfb87c5f98934fb47be
TypeScript
kefniark/Coopa
/tests/events/onchange.test.ts
2.78125
3
/// <reference types="jest" /> import { onChange } from "../../src" test("on-change", () => { const a: any = {} const proxy = onChange(a, (prop, val, prev) => { console.log("on-change", prop, val, prev) }) proxy.a = 2 proxy.a = 3 proxy.b = { b: 1, c: 4 } proxy.b.c = 5 proxy.b.d = { a: 1, b: 2 } proxy.b.d.a = 3 delete proxy.b }) test("on-change event", () => { let events = 0 const a: any = { a: 1, b: 2 } const proxy = onChange(a, () => events++) proxy.a = 1 proxy.b = 3 proxy.b = 2 proxy.b = 2 expect(events).toBe(2) })
f0c01468b8521a98c3a4a4f460872de64af981ef
TypeScript
luismdavid/examen-final-moviles
/src/app/home/home.page.ts
2.75
3
import { Component } from '@angular/core'; @Component({ selector: 'app-home', templateUrl: 'home.page.html', styleUrls: ['home.page.scss'], }) export class HomePage { array = { 0: { id: 72, name: "David Beckham" }, 1: { 0: [ { id: 11, name: "Brad Pitt" }, { id: 1, name: "Alexandra Daddario" }, ], 1: { id: 19, name: "Michael Myers" }, }, 2: { 0: { 0: [{ id: 33, name: "Matthew Heafy" }] } }, 3: [ [ { id: 4, name: "John Petrucci" }, { id: 55, name: "Wayne Rooney" }, ], [ { id: 57, name: "Garbeil Tronpis" }, { id: 10, name: "Donald Trump" }, { 0: { id: 69, name: "[Object object]" } }, ], { id: 13, name: "Ester Exposito" }, { 0: [ { id: 3, name: "Jordan Rudess" }, { id: 8, name: "Michael Jackson" }, ], 1: { id: 99, name: "undefined undefined" }, }, { id: 47, name: "Raul Garcia" }, { id: 40, name: "Benito Martinez" }, ], 4: [ { id: 68, name: "Lionel Messi" }, { id: 84, name: "Kobe Bryant" }, { id: 71, name: "Gilgamesh" }, [ { id: 7, name: "Miyamoto Musashi" }, { 0: [{ id: 23, name: "Arthur Pendragon" }], 1: [{ id: 5, name: "Bedivere" }], }, { id: 96, name: "Lord Valdomero" }, { id: 18, name: "Literalmente nadie" }, ], ], }; currentTime = 0; bestTime = Infinity; bestAlgo = ''; setMetrics(time: number, algorithm) { time = Number(time.toFixed(4)); this.currentTime = time; if (time < this.bestTime) { this.bestTime = time; this.bestAlgo = algorithm; } } quickSort() { const getPivot = (arr, start = 0, end = ((arr instanceof Array) ? arr.length : Object.keys(arr).length) + 1) => { const swap = (array, x, y) => { let temp = array[x]; if (x == 2) { debugger; } array[x] = array[y]; array[y] = temp; }; let pivot = arr[start]; let pointer = start; for (let i = start; i < ((arr instanceof Array) ? arr.length : Object.keys(arr).length); i++) { if (!arr[i].hasOwnProperty('id') || arr[i] instanceof Array) { quickSort(arr[i]) } else if (arr[i].id < pivot.id) { swap(arr, pointer, i); pointer++; } } return pointer; }; const quickSort = (arr, start = 0, end = ((arr instanceof Array) ? arr.length : Object.keys(arr).length)) => { let pivotIndex = getPivot(arr, start, end); if (start >= end) return arr; quickSort(arr, start, pivotIndex); quickSort(arr, pivotIndex + 1, end); return arr; }; var t0 = performance.now(); this.array = quickSort(this.array); var t1 = performance.now(); this.setMetrics(t1 - t0, 'quicksort'); } tree() { var t0 = performance.now(); let tree = new GFG(); tree.treeins(this.array); tree.inorderRec(tree.root); var t1 = performance.now(); this.setMetrics(t1 - t0, 'tree'); } constructor() {} } class Node { key: { id: number }; left: Node; right: Node; constructor(item: { id: number }) { this.key = item; this.left = this.right = null; } } class GFG { root: Node; constructor() { this.root = null; } public insert(key: { id: number }): void { this.root = this.insertRec(this.root, key); } insertRec(root: Node, key: { id: number }): Node { if (root == null) { root = new Node(key); return root; } if (key.id < root.key.id) root.left = this.insertRec(root.left, key); else if (key.id > root.key.id) root.right = this.insertRec(root.right, key); return root; } inorderRec(root: Node): void { if (root != null) { this.inorderRec(root.left); this.inorderRec(root.right); } } treeins(arr: any): void { for (let i = 0; i < ((arr instanceof Array) ? arr.length : Object.keys(arr).length); i++) { if (!arr[i].hasOwnProperty('id') || arr[i] instanceof Array) { let tree = new GFG(); tree.treeins(arr[i]); tree.inorderRec(tree.root); } else { this.insert(arr[i]); } } } }