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
d889f4135b1902f426b1d3a6d00b14b7dbb73d84
TypeScript
mahmoudsror/backend_user_stories_task
/src/controllers/UsersController.ts
2.609375
3
import {Request, Response} from 'express'; import UserRepository from '../repositories/UsersRepository'; export class UsersController{ public async create(request:Request, response: Response){ const repo = new UserRepository() const body = request.body; console.log("Body", body) const usersSeed = [ { name:'John' }, { name: 'ali' } ] const newUsers = await repo.save(usersSeed); return response.send(newUsers); } }
e232f78a329a61a6c26cf2a11d1274cc5354cd76
TypeScript
OneWorldHackathon/owm-app
/pledge/functions/src/EntityBase.ts
2.546875
3
import { FirestoreEntity } from './Repository' import { validateSync, ValidationError, IsNotEmpty, IsString } from 'class-validator' export abstract class EntityBase implements FirestoreEntity { @IsString() @IsNotEmpty() private readonly _id: string constructor(id: string) { this._id = id } id(): string { return this._id } validate(): ValidationError[] { return validateSync(this) } abstract toFirestore(): FirebaseFirestore.DocumentData }
48f1e8c70a2cb0aec7f8392e600070d3d7087e94
TypeScript
aybarsakgun/b2b-backend
/src/common/utils/resolveAsyncRelation.ts
2.59375
3
import { Repository } from "typeorm"; export function resolveAsyncRelation<T, K extends keyof T>( repository: Repository<T>, relation: K ) { return async (entity: T) => { const record = await repository.findOne(entity["id"], { relations: [relation as string], withDeleted: true, }); return record[relation]; }; }
3eba99aae764e49248b17f00a303ca1a36076dc8
TypeScript
danursin/rubiks-cube
/src/types/RubiksCubeObject.ts
2.671875
3
import { CubeObject } from "./CubeObject"; export class RubiksCubeObject { public readonly cubeUnitLength: number; public cubes: CubeObject[]; constructor(cubeUnitLength: number) { this.cubeUnitLength = cubeUnitLength; const n = this.cubeUnitLength; this.cubes = [ new CubeObject({ translate: [2 * n, 0, 0], rotate: [0, 0, 0] }), new CubeObject({ translate: [4 * n, 0, 0], rotate: [0, 0, 0] }), new CubeObject({ translate: [6 * n, 0, 0], rotate: [0, 0, 0] }) ]; } }
dedcea3c6a6833e483229eb9253db812d35d2f6b
TypeScript
Dcivan226/my-games
/图形配对/matchCard/src/HeadMc.ts
2.6875
3
class HeadMc extends egret.Sprite { private _headImg:egret.Bitmap; private _headID:number; private _bg:egret.Shape; private _state:string="noselected"; private _hideMc:egret.Shape; public constructor(headImg) { super(); this._headImg=headImg; this.create(); } public set state(value:string){ this._state=value; this.draw(); } public set headID(value:number){ this._headID=value; } public get headID():number{ return this._headID; } public set headImg(value:egret.Bitmap){ this._headImg=value; } public get headImg():egret.Bitmap{ return this._headImg; } private create(){ this._bg=new egret.Shape(); this.addChild(this._bg); this.addChild(this._headImg); this._headImg.width=80; this._headImg.height=80; /*this._hideMc=new egret.Shape(); this._hideMc.graphics.beginFill(0x000000,0.5); this._hideMc.graphics.drawRect(0,0,80,80); this._hideMc.graphics.endFill(); this.addChild(this._hideMc); this.draw();*/ } private draw(){ this._bg.graphics.clear(); if(this._state=="current"){ this._bg.graphics.lineStyle(2,0xff0000); } this._bg.graphics.beginFill(0xffffff); this._bg.graphics.drawRect(0,0,80,80); if(this._state=="selected"){ this.alpha=0.2; }else{ this.alpha=1; } } }
5ebd4661e4c39d74b10cd6b78b201bf5b0a9bbc7
TypeScript
MaximSamusenko/ProtobufRpc
/protobuf-rpc-client/src/ping_pong/proto_client/ServiceClient.ts
2.5625
3
import { Message, Method, rpc, RPCImplCallback } from "protobufjs"; import { IRequestInfo, ServiceMessage } from "../../proto"; import loggerFor from "../../winston"; import ServiceSubscription from "./ServiceSubscription"; enum WebSocketConnectionState { "CONNECTING" = WebSocket.CONNECTING, "OPEN" = WebSocket.OPEN, "CLOSING" = WebSocket.CLOSING, "CLOSED" = WebSocket.CLOSED } export default abstract class ServiceClient { private readonly logger; private static readonly SUBSCRIPTION_CANCELLED = "CANCELLED"; private static readonly SUBSCRIPTION_ERROR = "ERROR"; private readonly webSocket: WebSocket; private callbackMap: Map<number, RPCImplCallback> = new Map(); private subscriptionIndex = 0; private activeRequestInfo: IRequestInfo | null = null; constructor(webSocketConnection: string) { this.logger = loggerFor(`${ServiceClient.name}<${this.constructor.name}>`); this.logger.debug(`creating new client for ${webSocketConnection}`); this.webSocket = new WebSocket(webSocketConnection); this.webSocket.onopen = this.onWebSocketOpen.bind(this); this.webSocket.binaryType = "arraybuffer"; this.webSocket.onerror = this.onWebSocketError.bind(this); this.webSocket.onclose = this.onWebSocketClose.bind(this); this.webSocket.onmessage = this.onWebSocketMessage.bind(this); } protected request(method: (Method | rpc.ServiceMethod<Message<{}>, Message<{}>>), requestData: Uint8Array, callback: RPCImplCallback): void { if (this.webSocket.readyState !== WebSocketConnectionState.OPEN) { this.logger.warn(`websocket connection in ${WebSocketConnectionState[this.webSocket.readyState]} state. The request ${method.name} will not be processed`); return; } this.logger.debug(`processing request ${method.name}`); let requestInfo = this.activeRequestInfo; if (requestInfo) { this.activeRequestInfo = null; } else { requestInfo = { cancelled: false, errorText: '', failed: false, requestId: this.subscriptionIndex++ }; } this.callbackMap.set(requestInfo.requestId, callback); const message = ServiceMessage.create({ methodName: method.name, payload: requestData, status: requestInfo }); this.webSocket.send(ServiceMessage.encode(message).finish()); } disconnect() { this.logger.debug('disconnecting...'); this.webSocket.close(1000); } withSubscriptionDo<K, S>(action: (arg: K, callback: (error: null | Error, response: S | undefined) => void) => void, argument: K) { var runAction = (s: ServiceSubscription<K, S>, arg: K) => { this.activeRequestInfo = s.toRequestInfo(); action(arg, (error: null | Error, response: S | undefined) => { if (error) { if (error.name === ServiceClient.SUBSCRIPTION_CANCELLED) { this.logger.debug(`subscription ${s.id} cancelled`); s.dispose(); } else if (error.name === ServiceClient.SUBSCRIPTION_ERROR) { this.logger.debug(`subscription ${s.id} received error: ${error.message}`); s.error(error.message); } } else if (response) { this.logger.debug(`subscription ${s.id} received new message: ${response}`); s.update(response); } }) }; this.logger.debug(`withSubscriptionDo ${action.name}`); var subscription = new ServiceSubscription<K, S>(this.subscriptionIndex++, s => { runAction(s, argument); this.callbackMap.delete(s.id); }, runAction); this.logger.debug(`new subscription created id=${subscription.id}`); runAction(subscription, argument); return subscription; } onWebSocketOpen(event: Event) { this.logger.debug("websocket connection opened"); } onWebSocketMessage(event: MessageEvent<Uint8Array>) { this.logger.debug('new websocket message received'); const serviceMessage = ServiceMessage.decode(new Uint8Array(event.data)); const requestStatus = serviceMessage.status; const callback = this.callbackMap.get(requestStatus.requestId); this.logger.debug(`request status: ${JSON.stringify(requestStatus)}`); if (typeof (callback) !== 'undefined') { if (requestStatus.failed) { callback({ name: ServiceClient.SUBSCRIPTION_ERROR, message: serviceMessage.status.errorText }); } else if (requestStatus.cancelled) { callback({ name: ServiceClient.SUBSCRIPTION_CANCELLED, message: '' }); } else { callback(null, serviceMessage.payload); } } else { this.logger.warn(`no subscription found for id=${requestStatus.requestId}`); } } onWebSocketError(event: Event) { this.logger.warn('websocket connection errror'); } onWebSocketClose(event: CloseEvent) { this.logger.debug('closing websocket connection...'); if (!event.wasClean) { this.logger.warn(`unexpected websocket closing, ${event.reason}`); this.logger.debug('sending err to subscriptions'); this.callbackMap.forEach((callback, id) => { callback({ name: ServiceClient.SUBSCRIPTION_ERROR, message: event.reason }); }); } this.logger.debug('cancelling subscriptions'); this.callbackMap.forEach((callback, id) => { callback({ name: ServiceClient.SUBSCRIPTION_CANCELLED, message: '' }); }); this.logger.debug('websocket connection closed'); } }
a4e29a6a1da4bdf0ef19edf62f577f59a87e22fa
TypeScript
ph1p/rp-character-manager
/src/store/inventory.ts
2.9375
3
import { v4 as uuidv4 } from 'uuid'; import { ignore } from 'mobx-sync'; import { makeAutoObservable } from 'mobx'; import { CharacterStore } from './character'; export class InventoryItem { name: string = ''; description: string = ''; quantity: number = 0; weight: number = 0; id: string = ''; isAttack: boolean = false; constructor(item?: InventoryItem) { makeAutoObservable(this); if (item) { this.id = uuidv4(); this.name = item.name; this.description = item.description; this.quantity = item.quantity ? parseFloat(item.quantity.toString()) : 1; this.weight = item.weight; } } setName(name: string) { this.name = name; } setWeight(weight: number) { this.weight = weight; } increase() { this.quantity += 1; } decrease() { this.quantity -= 1; } } export type Coins = | 'platinum-coin' | 'gold-coin' | 'electric-coin' | 'silver-coin' | 'copper-coin'; interface InventoryOptions { unit?: string; coins?: Record<Coins, number>; } export class InventoryStore { items: InventoryItem[] = []; unit: string = 'kg'; coins: Record<Coins, number> = { 'platinum-coin': 0, 'gold-coin': 0, 'electric-coin': 0, 'silver-coin': 0, 'copper-coin': 0, }; @ignore store: CharacterStore; constructor(store: CharacterStore, options?: InventoryOptions) { makeAutoObservable(this); this.store = store; if (options?.unit) { this.unit = options.unit; } if (options?.coins) { this.coins = { ...this.coins, ...options.coins, }; } } setCoin(coin: Coins, value: number) { this.coins[coin] = value; } remove(id: string) { this.items = this.items.filter((i) => i.id !== id); } get totalLoad() { return this.items.reduce( (prev, item) => prev + item.quantity * item.weight, 0 ); } get maxLoad() { const strength = this.store.attributes.values.find( (attribute) => attribute.name === 'strength' )?.score || 0; return strength * 5; } get maxHeavyLoad() { const strength = this.store.attributes.values.find( (attribute) => attribute.name === 'strength' )?.score || 0; return strength * 10; } get isLoaded() { return this.totalLoad > this.maxLoad; } get isHeavyLoaded() { return this.totalLoad > this.maxHeavyLoad; } get maxLiftPushPull() { const strength = this.store.attributes.values.find( (attribute) => attribute.name === 'strength' )?.score || 0; return strength * 15; } createItem(data: InventoryItem) { if (data.name && !this.items.some((item) => item.name === data.name)) { const item = new InventoryItem(data); this.items.push(item); return item; } } }
49b37490da3942db0d8a59f1aefe4f3b496606fa
TypeScript
HamdiMegdiche/redspher-calculator
/back/test/helpers.test.ts
3.4375
3
import { checkExpressionToCompute, computeExpression } from "../src/helpers"; describe("Check expression to compute function", () => { it("Checks allowing simple numbers", () => { expect(checkExpressionToCompute("123")).toBe(true); expect(checkExpressionToCompute("23.45")).toBe(true); expect(checkExpressionToCompute("3.-3")).toBe(true); expect(checkExpressionToCompute(".45")).toBe(true); expect(checkExpressionToCompute("-123")).toBe(true); expect(checkExpressionToCompute("-273.15")).toBe(true); expect(checkExpressionToCompute("-42.")).toBe(true); expect(checkExpressionToCompute("-.45")).toBe(true); }); it("Checks disallowing multiple successive operations in the beginning", () => { expect(checkExpressionToCompute(".5+-.5")).toBe(false); expect(checkExpressionToCompute("--5.3+6-9*9")).toBe(false); expect(checkExpressionToCompute("+-5.3+6-9*9")).toBe(false); expect(checkExpressionToCompute("+*5.3+6-9*9")).toBe(false); expect(checkExpressionToCompute("/5.3+6-9*9")).toBe(false); expect(checkExpressionToCompute("*5.3+6-9*9")).toBe(false); }); it("Checks disallowing multiple successive operations in the middle", () => { expect(checkExpressionToCompute("5.3++6-9*9")).toBe(false); expect(checkExpressionToCompute("5.3+6--9*9")).toBe(false); expect(checkExpressionToCompute("5.3+6-9*+9")).toBe(false); expect(checkExpressionToCompute("5.3+6-9**9")).toBe(false); expect(checkExpressionToCompute("5.3+6-9*9//3")).toBe(false); }); it("Checks allowing digits after floating point without having digits before", () => { expect(checkExpressionToCompute("-.3+6")).toBe(true); expect(checkExpressionToCompute("-3+.6")).toBe(true); expect(checkExpressionToCompute("-3+0.6")).toBe(true); }); }); describe("Compute expressions", () => { it("Computes simple expression", () => { expect(computeExpression("123")).toBe("123"); expect(computeExpression("5+.5")).toBe("5.5"); expect(computeExpression(".5+.5")).toBe("1"); expect(computeExpression(".5-.5")).toBe("0"); expect(computeExpression(".5+-.5")).toBe("0"); expect(computeExpression(".5+--.5")).toBe("0"); expect(computeExpression("5.+2")).toBe("7"); }); it("Computes expression with floating point", () => { expect(computeExpression("0.00005+0.00004")).toBe("0.00009"); // NOTE using BigNumber fixes the floating decimal issue // with basic arithmetic js : 3*3.3 = 9.899999999999999 expect(computeExpression("3*3.3")).toBe("9.9"); }); it("Computes expression & respect the right order : / * - + ", () => { expect(computeExpression("-1/3*0")).toBe("0"); expect(computeExpression("1/3*0")).toBe("0"); expect(computeExpression("1/3*0-2+3")).toBe("1"); }); it("Computes infinity case ", () => { expect(computeExpression("1/0")).toBe("∞"); expect(computeExpression("1/0")).toBe("∞"); expect(computeExpression("-3*0/0")).toBe("∞"); expect(computeExpression("-3/0*0")).toBe("∞"); }); });
478bf3a5edf7839ef144f84b8896696050a11091
TypeScript
kamibababa/SplitTime
/src/engine/ui/conversation/dsl.ts
2.8125
3
namespace splitTime.conversation { export type Condition = true | (() => boolean) export interface DSL { say(speaker: Speaker, line: string): void section(sectionSetup: () => void): SectionChain do(action: time.MidEventCallback): void // waitUntil(condition: Condition): void } export interface SectionChain extends SectionChainInterruptible { /** * The modified section can be canceled when the player walks away */ cancelable(sectionSetup?: () => void): void } export interface SectionChainInterruptible { /** * The modified section can be interrupted when the player interacts */ interruptible( condition?: Condition, sectionSetup?: () => void ): SectionChainInterruptible /** * The modified section can be interrupted when the body is detected by some speaker */ interruptibleByDetection( condition?: Condition, sectionSetup?: () => void, body?: Body ): SectionChainInterruptible } }
341438121f84d4a7879961deea846dd5c330c335
TypeScript
bigro/sal-mane
/src/model/member.ts
2.828125
3
/** * メンバー */ export class Member { name:string; isPlayer:boolean; constructor(name: string) { this.name = name; } }
e069ead9751b6eaa1626c3f49d356bcc598f89ea
TypeScript
DavidDecraene/marchingCubesGL
/src/lib/utils/lvec.ts
3.046875
3
import { vec3 } from 'gl-matrix'; export const LVecs = { add: function(result: vec3, target: vec3) { result[0] += target[0]; result[1] += target[1]; result[2] += target[2]; return result; }, rescale: function(value: number, fromRange: Array<number>, toRange: Array<number>) { if (!value) { value = 0; } const a = (value - fromRange[0]) / (fromRange[1] - fromRange[0]); const b = toRange[1] - toRange[0]; return a * b + toRange[0]; } }; export class LVec { constructor(public data: Array<number>) { this.data = data; } add(x?: number, y?: number, z?: number) { if(x) this.data[0] += x; if(y) this.data[1] += y; if(z) this.data[2] += z; return this; } calcUv(x: number, y: number, s: number) { this.data[3] = (this.data[x] + s) / (2 * s); // problem is: bot left is zero, so 1 becomes zero and zero becomes one this.data[4] = 1 - (this.data[y] + s) / (2 * s); return this; } public x(): number; public x(y: number): this; x(x?: number) { if (x === undefined) return this.data[0]; this.data[0] = x; return this; } public y(): number; public y(y: number): this; y(y?: number) { if (y === undefined) return this.data[1]; this.data[1] = y; return this; } public z(): number; public z(y: number): this; z(z?: number) { if (z === undefined) return this.data[2]; this.data[2] = z; return this; } public u(): number; public u(y: number): this; u(u?: number) { if (u === undefined) return this.data[3]; this.data[3] = u; return this; } public v(): number; public v(y: number): this; v(v?: number) { if (v === undefined) return this.data[4]; this.data[4] = v; return this; } copy(other: LVec) { this.data = other.data.slice(); return this; } clone() { const data = this.data.slice(); return new LVec(data); } }
94bcba9fe4f5d5c36989b46a97daeef7252504e5
TypeScript
skaeneman/CS701-Rich-Internet-Application-Development
/Module_Samples/TypeScript_Examples/Basics/ex09.ts
2.96875
3
// any let x: any; x = "Hello"; console.log(typeof(x)); console.log(x.length); x = 12; console.log(typeof(x)); console.log(x.length); let y: number = 12; console.log(y.length);
c52759ee90a8e5583520265a71af2a98a6c4c74d
TypeScript
jon-grangien/magical-forest-architect
/src/components/MainPlane/subobjects/PlaneEnvObjects.ts
2.75
3
import * as THREE from 'three' import { LoadOBJMTL } from '../../../utils/LoadOBJMTL' export interface IPlaneEnvObjects { amount: number posRangeMin: number posRangeMax: number waterIsRendering: boolean calculateHeight: (x: number, y: number) => number spawnObjects: () => void } export interface IObjMtl { path: string modelName: string objFilename: string mtlFilename: string onLoadObjCallback: (group: THREE.Group) => void } /** * Base class for objects on the plane */ abstract class PlaneEnvObjects { readonly SEA_LEVEL_SURPLUS_SPACE: number = 5 protected _objects: THREE.Object3D[] protected _amountObjects: number protected _posRangeMin: number protected _posRangeMax: number protected _waterIsRendering: boolean protected calculateHeight: (x: number, y: number) => number protected spawnObjects: () => void constructor(params: IPlaneEnvObjects) { this._objects = [] this._amountObjects = params.amount this._posRangeMin = params.posRangeMin this._posRangeMax = params.posRangeMax this._waterIsRendering = params.waterIsRendering this.calculateHeight = params.calculateHeight this.spawnObjects = params.spawnObjects } public updateHeightValues() { for (let obj of this._objects) { const { position } = obj const newZ = this.calculateHeight(position.x, position.y) obj.position.set(position.x, position.y, newZ) } } public showAll(): void { for (let obj of this._objects) { obj.visible = true } } public hideAll(): void { for (let obj of this._objects) { obj.visible = false } } public hideAllBelowSeaLevel(): void { for (let obj of this._objects) { this.hideBelowSeaLevel(obj) } } public hideBelowSeaLevel(obj: THREE.Object3D): void { if (obj.position.z < - this.SEA_LEVEL_SURPLUS_SPACE) { obj.visible = false } else { obj.visible = true } } public forEach(callback: (obj: THREE.Object3D) => void): void { for (const obj of this._objects) { callback(obj) } } public hasObjects(): boolean { return this._objects.length > 0 } protected loadObjMtl(params: IObjMtl) { LoadOBJMTL({ path: params.path, modelName: params.modelName, objFilename: params.objFilename, mtlFilename: params.mtlFilename, onLoadObjCallback: params.onLoadObjCallback }) } get objects(): THREE.Object3D[] { return this._objects } set waterIsRendering(isRendering: boolean) { this._waterIsRendering = isRendering } } export default PlaneEnvObjects
5de07033ee716a0f1c45e6979953fe7309c179f0
TypeScript
Johan-Ortegon-1/404-DinamicOng
/DinamicOng/src/app/auth/register/register-ong/register-ong.component.ts
2.703125
3
import { Component, Input, OnInit } from '@angular/core'; import { Ong } from 'src/app/models/ong'; import { AuthService } from '../../services/auth.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-register-ong', templateUrl: './register-ong.component.html', styleUrls: ['./register-ong.component.css'] }) // Clase que representa el componente del Register de una Ong export class RegisterOngComponent implements OnInit { public ong: Ong; // Objeto que se llenará mediante el registro public contrasena: string; // Contraseña ingresada por el usuario public confirmContrasena: string; // Constraña de verificación ingresada por el usuario public preview: string; // URL para mostrar la previsualización de la imagen de perfil de la Ong public telefonoNuevo = ''; // Teléfono nuevo para registrar en los telefonos de la Ong public errorTelefonos = ''; // Mensaje de error a mostrarle al usuario // Metodo constructor para crear un objeto del componente // Parámetros: // - authSvc: Objeto que permite el acceso al servicio de Autenticación y Registro // - router: Objeto que permite la navegación entre componentes por la URL constructor(private authSvc: AuthService, private router: Router) { } // Metodo que se ejecuta al iniciar el componente // Se inicializa el objeto Ong ngOnInit(): void { this.ong = new Ong(); } // Metodo para realizar el registro de la Ong async registrar() { if (this.contrasena === this.confirmContrasena) { const result = (await this.authSvc.registerOng(this.ong, this.contrasena)); console.log(result); if(result == null) { alert('ERROR: Ya existe un usuario con ese correo, por favor ingrese otro'); } else { localStorage.setItem('uid', result.user.uid); localStorage.setItem('rol', 'Ong'); this.router.navigate(['/ong']); } } else { alert('ERROR: Las contraseñas no coinciden'); } } // Metodo para guardar la imagen de perfil de la Ong y en la previsualización // Parametros: // - $event: Evento resultante de un input file que contiene la imagen uploadImage($event) { if ($event.target.files && $event.target.files[0]) { this.ong.imagenPerfil = $event.target.files[0]; const reader = new FileReader(); reader.onload = (event: any) => { this.preview = event.target.result; } reader.readAsDataURL($event.target.files[0]); } } // Metodo para agregar un teléfono a la lista de teléfonos de la Ong addTelefono() { if (this.telefonoNuevo !== '' && this.telefonoNuevo != null) { if (this.ong.telefonos.indexOf(this.telefonoNuevo) == -1) { const str = String(this.telefonoNuevo); if (!str.includes('-')) { this.ong.telefonos.push(this.telefonoNuevo); this.telefonoNuevo = ''; this.errorTelefonos = ''; } else { this.errorTelefonos = 'Ingrese solo números'; } } else { this.errorTelefonos = 'El teléfono ya existe, ingrese un teléfono distinto'; } } else { this.errorTelefonos = 'Ingrese un teléfono'; } } // Metodo para eliminar un télefono de la lista de télefonos de la Ong deleteTelefono(tel: string) { const i = this.ong.telefonos.indexOf( tel ); if ( i !== -1 ) { this.ong.telefonos.splice( i, 1 ); } } }
065be82ce1965d2bf2f20cbb53c41d483e540034
TypeScript
sergiubutnarasu/register
/modules/platform/helpers/calculate-today-total.helper.ts
2.6875
3
import { roundNumber } from "~/modules/common"; import { RegisterEntry } from "~/modules/excel"; export const calculateTodayTotal = (fields: RegisterEntry[]) => fields.reduce( ( { todayPositive, todayNegative, }: { todayPositive: number; todayNegative: number }, { value } ) => { let positive = todayPositive; let negative = todayNegative; const currentValue = +value; if (currentValue < 0) { negative += currentValue; } else { positive += currentValue; } return { todayPositive: +positive, todayNegative: +negative, }; }, { todayPositive: 0, todayNegative: 0 } );
c77be9486f7cb0e563b5b8d312fb18ffc3faea5e
TypeScript
Mobysick/dependabot
/src/http/http-api.ts
2.734375
3
import axios from 'axios'; // TODO: Fix any. type GetResponse = { status: number; data?: any; }; export class HttpApi { static async get(url: string): Promise<GetResponse> { const response = await axios.get(url); return { status: response.status, data: response.data }; } }
4fb7531524e7c7d70c25ad28d358fe0ba7ec8699
TypeScript
Boris6235551/mineVisual
/renderer.ts
3.1875
3
const Konva = require('konva'); let inRectArr = []; let layer; function test() { // var x: string = '1'; // var y: number; // console.log( typeof x, typeof y ); // x = 'hello'; // y = 2; // console.log( typeof x, typeof y ); // x = 'true'; // y = 3; // console.log( typeof x, typeof y ); let width: number = window.innerWidth; let height: number = window.innerHeight; // first we need to create a stage var stage = new Konva.Stage({ container: 'container', // id of container <div> width: width, //500, height: height //500 }); // then create layer layer = new Konva.Layer(); let main = new Konva.Rect({ x: 10, y: 10, width: 240, height: 80, fill: 'white', stroke: 'black', strokeWidth: 4, cornerRadius: 16 }); layer.add(main); for(let i = 0; i < 6; i++){ let x = 10 + 40 * i; let color; if(i == 2 || i == 5) color = 'white'; else color = 'blue'; let r = new Konva.Rect({ x: i==5 ? x-20 : x, y: 10, width: (i==0 || i==5) ? 60 : 40, height: 80, fill: color, stroke: 'black', strokeWidth: 4, cornerRadius: (i==0 || i==5) ? 16 : 0 }); inRectArr.push(r); } for(let i = 0; i < 4; i++){ layer.add(inRectArr[i]); } layer.add(inRectArr[5]); layer.add(inRectArr[4]); // create our shape var circle = new Konva.Circle({ x: stage.width() / 2, y: stage.height() / 2, radius: 70, fill: 'red', stroke: 'black', strokeWidth: 4 }); // add the shape to the layer layer.add(circle); // add the layer to the stage stage.add(layer); // draw the image layer.draw(); } test(); function move(i: number){ switch (i){ case 0: // 2, 5 inRectArr[1].fill('blue'); inRectArr[2].fill('white'); inRectArr[4].fill('blue'); inRectArr[5].fill('white'); break; case 1: // 0, 3 inRectArr[5].fill('blue'); inRectArr[0].fill('white'); inRectArr[2].fill('blue'); inRectArr[3].fill('white'); break; case 2: // 1, 4 inRectArr[0].fill('blue'); inRectArr[1].fill('white'); inRectArr[3].fill('blue'); inRectArr[4].fill('white'); break; } layer.draw(); } let ind = 0; setInterval(()=>{ move(ind); if(ind == 2) ind = 0; else ind++; }, 150); //move(2);
8e884c7ed47700bb6ccb850f76dde7dfdeed2ebd
TypeScript
osuthailand/Goose
/commands/pr.ts
2.75
3
import * as Discord from 'discord.js'; const config = require('../config/config.json'); // Responsible for sending the #playerreporting embedded message export async function sendPlayerReportingEmbed(client: Discord.Client, message: Discord.Message, args: string[]) { try { if (message.author.id != config.ownerId) return; const embed: Discord.RichEmbed = getPlayerReportingEmbed(); return await message.channel.sendEmbed(embed); } catch(err) { console.log(err); return await message.reply("Unable to send the Player Reporting embedded message."); } } // Returns the embedded message that'll be sent in the channel. const getPlayerReportingEmbed = () => { return new Discord.RichEmbed() .setTitle('Welcome To The Player Reporting Channel!') .setColor(0xDB88C2) .setThumbnail('https://eggplants.org/7kw3b4.png') .setTimestamp() .addField('Information', "**PLEASE READ EVERYTHING TO AVOID GETTING SILENCED!!!**\n\n"+ "• Welcome to the #playerreporting channel. Here, you can report players you suspect of rule breaking.", true) .addField('Rules', "**TO ENSURE WE ONLY RECEIVE QUALITY REPORTS, WE HAVE A FEW RULES, SO READ THEM.**\n\n" + "• Please **DO NOT** highlight the Community Managers in this channel.\n\n" + "• Do **NOT** spam in this channel. You only need to post **ONE TIME!!**\n\n" + "• Any troll or false reports will **NOT** be tolerated, and will result in a silence.\n\n", true) .addField('Report Format', "**• TO SUBMIT A REPORT, PLEASE COPY AND FILL IN THE DETAILS.** \n\n **• REMEMBER, YOU ONLY NEED TO SUBMIT ONE REPORT**\n\n" + "```Player's Username:\n\n"+ "Link To Player's Profile:\n\nReason For Reporting (Cheating, Multi-Accouting, Etc.):\n\n"+ "Any Evidence You Might Have (Suspicious Plays, Videos, Screenshots, Etc.):```", true); };
da3c564d9f81d09182f5c19137f677a31c7391d7
TypeScript
ssuniltikoo/jtran
/employee.ts
3.515625
4
var num = 2; class employee{ private empName:string; private num=13; static sval = 10; constructor(empName:string){ this.empName=empName; num=-4; } public printNum():void{ console.log("global variable"+num); console.log("local variable"+this.num); console.log("static value"+employee.sval); } display():void{ console.log("hello GM"+this.empName); } } let e = new employee("sunil"); e.display(); e.printNum();
7164198f97c590a34258b744137ea69abfb41273
TypeScript
EmmaRamirez/Clickopolis
/src/classes/queue.ts
3.359375
3
export class Queue<T> { oldestIndex:number = 1; newestIndex:number = 1; storage:T[]; size ():number { return this.newestIndex - this.oldestIndex; } enqueue (data:T):void { this.storage[this.newestIndex] = data; this.newestIndex++; } dequeue ():T { let oldestIndex:number = this.oldestIndex, newestIndex:number = this.newestIndex, deletedData:T; if (oldestIndex !== newestIndex) { deletedData = this.storage[oldestIndex]; delete this.storage[oldestIndex]; this.oldestIndex++; return deletedData; } } constructor(storage:T[]) { this.storage = storage; } }
8c7541408a5f9d1cb573d12ba612586366259013
TypeScript
NesibeHatzi/PRIMA-Endabgabe
/FudgeSpaceShooter/Entity.ts
2.53125
3
namespace FudgeSpaceShooter { // import ƒ = FudgeCore; export enum DIRECTION { UP, DOWN, LEFT, RIGHT, NEUTRAL } export class Entity extends ƒ.Node { protected maxSpeed: number = 5; protected speed: ƒ.Vector3; protected hitbox: ƒ.Mesh; protected hitboxNode: ƒ.Node; protected hitboxSize: ƒ.Vector2 = new ƒ.Vector2(0.5, 0.5); constructor(_name: string) { super(_name); this.speed = ƒ.Vector3.ZERO(); } public destroy() { let parent: ƒ.Node = this.getParent(); parent.removeChild(this); } } }
efa0fd4820988383fef05eaf0521adf93b07b0a1
TypeScript
Klowar/cdb
/src/cache/index.ts
2.546875
3
import { logger } from './../globals'; import { getBlockSize } from '../entity/util'; import { Option, TypedIdentifier } from './../parser/types'; import { createTemporaryFile, TemporaryFile } from './../temp/index'; import { Comparator } from '../union/filter/compare/index'; export type Cache = { data: Map<string, any>; tf: TemporaryFile; getDataType: () => string; getValues: (comparator: Comparator<any>) => Promise<any[]>; getIndices: (data: string | number) => Promise<number[]>; write: (data: string | number) => Promise<any>; update: (records: number[], data: string | number) => Promise<any>; read: (records: number[] | undefined) => Promise<any>; delete: (records: number[]) => Promise<any>; } function Cache(this: Cache, tf: TemporaryFile) { this.tf = tf; this.data = new Map<string, any>(); } Cache.prototype.getDataType = function (this: Cache) { return this.tf.getDataType(); } Cache.prototype.getValues = async function (this: Cache, comparator: Comparator<any>) { return this.tf.getValues(comparator); } Cache.prototype.getIndices = async function (this: Cache, data: string | number) { return this.tf.getIndices(data); } Cache.prototype.write = function (this: Cache, data: string | number) { logger.debug("Write cache"); return this.tf.write(data); } Cache.prototype.update = function (this: Cache, records: number[], data: string | number) { logger.debug("Update cache"); return this.tf.update(records, data); } Cache.prototype.read = function (this: Cache, records: number[] | undefined) { logger.debug("Read cache"); return this.tf.read(records); } Cache.prototype.delete = function (this: Cache, records: number[]) { logger.debug("Delete cache"); return this.tf.delete(records); } export function getCache(tf: TemporaryFile): Cache | null { return new Cache(tf); } export function newCache(req: TypedIdentifier, options?: Option): Cache { const tf = createTemporaryFile(options); tf.setDataType(req.type); tf.setBlockSize(req.size ? Number(req.size) : getBlockSize(req.type)); return new Cache(tf); }
296b1fe07919962b95f969f94e3ed10a20509529
TypeScript
MasterMoritz/TypoX
/src/app/equation/services/translator.service.ts
2.71875
3
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class TranslatorService { private decimalsign: string; private greek_letters: string[]; private relations: any; private constants: any; private left_brackets: any; private right_brackets: any; private leftright_brackets: any; private unary_symbols: any; private binary_symbols: any; private non_constant_symbols: string[]; private _source: any; constructor() { this.decimalsign = '\\.'; this.setup_symbols(); this.sort_symbols(); } //the following functions were edited and adjusted to work correctly in this project. //the originals come from https://github.com/christianp/asciimath2tex Copyright 2018 Christian Lawson-Perfect parse(input: string): string { this.input(input); const result = this.consume(); return result.tex; } private literal(token) { if (token) { return { tex: token.token, pos: token.pos, end: token.end, ttype: 'literal' }; } } private longest(matches) { matches = matches.filter(x => !!x); matches.sort((x, y) => { x = x.end; y = y.end; return x > y ? -1 : x < y ? 1 : 0; }); return matches[0]; } private escape_text(str) { return str .replace(/\{/g, '\\{') .replace(/\}/g, '\\}') ; } private input(str) { this._source = str; } private source(pos = 0, end = -1) { if (end !== -1) { return this._source.slice(pos, end); } else { return this._source.slice(pos); } } private eof(pos = 0) { pos = this.strip_space(pos); return pos == this._source.length; } private unbracket(tok) { if (!tok) { return; } if (!tok.bracket) { return tok; } const skip_brackets = ['(', ')', '[', ']', '{', '}']; const skipleft = skip_brackets.includes(tok.left.asciimath); const skipright = skip_brackets.includes(tok.right.asciimath); const pos = skipleft ? tok.left.end : tok.pos; const end = skipright ? tok.right.pos : tok.end; let left = skipleft ? '' : tok.left.tex; let right = skipright ? '' : tok.right.tex; const middle = tok.middle ? tok.middle.tex : ''; if (left || right) { left = left || '.'; right = right || '.'; return { tex: `\\left ${left} ${middle} \\right ${right}`, pos: tok.pos, end: tok.end }; } else { return { tex: middle, pos: tok.pos, end: tok.end, middle_asciimath: this.source(pos, end) }; } } private consume(pos = 0) { let tex = ''; const exprs = []; while (!this.eof(pos)) { let expr = this.expression_list(pos); if (!expr) { const rb = this.right_bracket(pos); if (rb) { if (rb.def.free_tex) { rb.tex = rb.def.free_tex; } expr = rb; } const lr = this.leftright_bracket(pos); if (lr) { expr = lr; const ss = this.subsup(lr.end); if (ss) { expr = { tex: `${expr.tex}${ss.tex}`, pos: pos, end: ss.end, ttype: 'expression' } } } } if (expr) { if (tex) { tex += ' '; } tex += expr.tex; pos = expr.end; exprs.push(expr); } else if (!this.eof(pos)) { throw (new Error("Didn't EOF")); } } return { tex: tex, exprs: exprs }; } private strip_space(pos = 0) { const osource = this.source(pos); const reduced = osource.replace(/^(\s|\\(?!\\))*/, ''); return pos + osource.length - reduced.length; } /* Does the given regex match next? */ private match(re, pos) { pos = this.strip_space(pos); const m = re.exec(this.source(pos)); if (m) { const token = m[0]; return { token: token, pos: pos, match: m, end: pos + token.length, ttype: 'regex' }; } } /* Does the exact given string occur next? */ private exact(str, pos) { pos = this.strip_space(pos); if (this.source(pos).slice(0, str.length) == str) { return { token: str, pos: pos, end: pos + str.length, ttype: 'exact' }; } } private expression_list(pos = 0) { let expr = this.expression(pos); if (!expr) { return; } let end = expr.end; let tex = expr.tex; let exprs = [expr]; while (!this.eof(end)) { const comma = this.exact(",", end); if (!comma) { break; } tex += ' ,'; end = comma.end; expr = this.expression(end); if (!expr) { break; } tex += ' ' + expr.tex; exprs.push(expr); end = expr.end; } return { tex: tex, pos: pos, end: end, exprs: exprs, ttype: 'expression_list' }; } // E ::= IE | I/I Expression private expression(pos = 0) { const negative = this.negative_expression(pos); if (negative) { return negative; } const first = this.intermediate_or_fraction(pos); if (!first) { for (let c of this.non_constant_symbols) { const m = this.exact(c, pos); if (m) { return { tex: c, pos: pos, end: m.end, ttype: 'constant' }; } } return; } if (this.eof(first.end)) { return first; } const second = this.expression(first.end); if (second) { return { tex: first.tex + ' ' + second.tex, pos: first.pos, end: second.end, ttype: 'expression', exprs: [first, second] }; } else { return first; } } private negative_expression(pos = 0) { const dash = this.exact("-", pos); if (dash && !this.other_constant(pos)) { const expr = this.expression(dash.end); if (expr) { return { tex: `- ${expr.tex}`, pos: pos, end: expr.end, ttype: 'negative_expression', dash: dash, expression: expr } } else { return { tex: '-', pos: pos, end: dash.end, ttype: 'constant' }; } } } private intermediate_or_fraction(pos = 0) { const first = this.intermediate(pos); if (!first) { return; } let frac = this.match(/^\/(?!\/)/, first.end); if (frac) { const second = this.intermediate(frac.end); if (second) { const ufirst = this.unbracket(first); const usecond = this.unbracket(second); return { tex: `\\frac{${ufirst.tex}}{${usecond.tex}}`, pos: first.pos, end: second.end, ttype: 'fraction', numerator: ufirst, denominator: usecond }; } else { const ufirst = this.unbracket(first); return { tex: `\\frac{${ufirst.tex}}{}`, pos: first.pos, end: frac.end, ttype: 'fraction', numerator: ufirst, denominator: null }; } } else { return first; } } // I ::= S_S | S^S | S_S^S | S Intermediate expression private intermediate(pos = 0) { const first = this.simple(pos); if (!first) { return; } const ss = this.subsup(first.end); if (ss) { return { tex: `${first.tex}${ss.tex}`, pos: pos, end: ss.end, ttype: 'intermediate', expression: first, subsup: ss }; } else { return first; } } private subsup(pos = 0) { let tex = ''; let end = pos; let sub = this.exact('_', pos); let sub_expr, sup_expr; if (sub) { sub_expr = this.unbracket(this.simple(sub.end)); if (sub_expr) { tex = `${tex}_{${sub_expr.tex}}`; end = sub_expr.end; } else { tex = `${tex}_{}`; end = sub.end; } } let sup = this.match(/^\^(?!\^)/, end); if (sup) { sup_expr = this.unbracket(this.simple(sup.end)); if (sup_expr) { tex = `${tex}^{${sup_expr.tex}}`; end = sup_expr.end; } else { tex = `${tex}^{}`; end = sup.end; } } if (sub || sup) { return { tex: tex, pos: pos, end: end, ttype: 'subsup', sub: sub_expr, sup: sup_expr }; } } // S ::= v | lEr | uS | bSS Simple expression private simple(pos = 0) { return this.longest([this.matrix(pos), this.bracketed_expression(pos), this.binary(pos), this.constant(pos), this.text(pos), this.unary(pos), this.negative_simple(pos)]); } private negative_simple(pos = 0) { const dash = this.exact("-", pos); if (dash && !this.other_constant(pos)) { const expr = this.simple(dash.end); if (expr) { return { tex: `- ${expr.tex}`, pos: pos, end: expr.end, ttype: 'negative_simple', dash: dash, expr: expr } } else { return { tex: '-', pos: pos, end: dash.end, ttype: 'constant' }; } } } // matrix: leftbracket "(" expr ")" ("," "(" expr ")")* rightbracket // each row must have the same number of elements private matrix(pos = 0) { let left = this.left_bracket(pos); let lr = false; if (!left) { left = this.leftright_bracket(pos, 'left'); if (!left) { return; } lr = true; } const contents = this.matrix_contents(left.end, lr); if (!contents) { return; } const right = lr ? this.leftright_bracket(contents.end, 'right') : this.right_bracket(contents.end); if (!right) { return; } const contents_tex = contents.rows.map(r => r.tex).join(' \\\\ '); const matrix_tex = contents.is_array ? `\\begin{array}{${contents.column_desc}} ${contents_tex} \\end{array}` : `\\begin{matrix} ${contents_tex} \\end{matrix}`; return { tex: `\\left ${left.tex} ${matrix_tex} \\right ${right.tex}`, pos: pos, end: right.end, ttype: 'matrix', rows: contents.rows, left: left, right: right }; } private matrix_contents(pos = 0, leftright = false) { let rows = []; let end = pos; let row_length = undefined; let column_desc = undefined; let is_array = false; while (!this.eof(end) && !(leftright ? this.leftright_bracket(end) : this.right_bracket(end))) { if (rows.length) { const comma = this.exact(",", end); if (!comma) { return; } end = comma.end; } const lb = this.match(/^[(\[]/, end); if (!lb) { return; } const cells = []; const columns = []; end = lb.end; while (!this.eof(end)) { if (cells.length) { const comma = this.exact(",", end); if (!comma) { break; } end = comma.end; } const cell = this.matrix_cell(end); if (!cell) { break; } if (cell.ttype == 'column') { columns.push('|'); is_array = true; if (cell.expr !== null) { columns.push('r'); cells.push(cell.expr); } } else { columns.push('r'); cells.push(cell); } end = cell.end; } if (!cells.length) { return; } if (row_length === undefined) { row_length = cells.length; } else if (cells.length != row_length) { return; } const rb = this.match(/^[)\]]/, end); if (!rb) { return; } const row_column_desc = columns.join(''); if (column_desc === undefined) { column_desc = row_column_desc; } else if (row_column_desc != column_desc) { return; } rows.push({ ttype: 'row', tex: cells.map(c => c.tex).join(' & '), pos: lb.end, end: end, cells: cells }); end = rb.end; } if (row_length === undefined || (row_length <= 1 && rows.length <= 1)) { return; } return { rows: rows, end: end, column_desc: column_desc, is_array: is_array }; } private matrix_cell(pos = 0) { const lvert = this.exact('|', pos); if (lvert) { const middle = this.expression(lvert.end); if (middle) { const rvert = this.exact('|', middle.end); if (rvert) { const second = this.expression(rvert.end); if (second) { return { tex: `\\left \\lvert ${middle.tex} \\right \\rvert ${second.text}`, pos: lvert.pos, end: second.end, ttype: 'expression', exprs: [middle, second] }; } } else { return { ttype: 'column', expr: middle, pos: lvert.pos, end: middle.end }; } } else { return { ttype: 'column', expr: null, pos: lvert.pos, end: lvert.end } } } return this.expression(pos); } private bracketed_expression(pos = 0) { const l = this.left_bracket(pos); if (l) { const middle = this.expression_list(l.end); if (middle) { const r = this.right_bracket(middle.end) || this.leftright_bracket(middle.end, 'right'); if (r) { return { tex: `\\left${l.tex} ${middle.tex} \\right ${r.tex}`, pos: pos, end: r.end, bracket: true, left: l, right: r, middle: middle, ttype: 'bracket' }; } else if (this.eof(middle.end)) { return { tex: `\\left${l.tex} ${middle.tex} \\right.`, pos: pos, end: middle.end, ttype: 'bracket', left: l, right: null, middle: middle }; } else { return { tex: `${l.tex} ${middle.tex}`, pos: pos, end: middle.end, ttype: 'expression', exprs: [l, middle] }; } } else { const r = this.right_bracket(l.end) || this.leftright_bracket(l.end, 'right'); if (r) { return { tex: `\\left ${l.tex} \\right ${r.tex}`, pos: pos, end: r.end, bracket: true, left: l, right: r, middle: null, ttype: 'bracket' }; } else { return { tex: l.tex, pos: pos, end: l.end, ttype: 'constant' }; } } } if (this.other_constant(pos)) { return; } const left = this.leftright_bracket(pos, 'left'); if (left) { const middle = this.expression_list(left.end); if (middle) { const right = this.leftright_bracket(middle.end, 'right') || this.right_bracket(middle.end); if (right) { return { tex: `\\left ${left.tex} ${middle.tex} \\right ${right.tex}`, pos: pos, end: right.end, bracket: true, left: left, right: right, middle: middle, ttype: 'bracket' }; } } } } // r ::= ) | ] | } | :) | :} | other right brackets private right_bracket(pos = 0) { for (let bracket of this.right_brackets) { const m = this.exact(bracket.asciimath, pos); if (m) { return { tex: bracket.tex, pos: pos, end: m.end, asciimath: bracket.asciimath, def: bracket, ttype: 'right_bracket' }; } } } // l ::= ( | [ | { | (: | {: | other left brackets private left_bracket(pos = 0) { for (let bracket of this.left_brackets) { const m = this.exact(bracket.asciimath, pos); if (m) { return { tex: bracket.tex, pos: pos, end: m.end, asciimath: bracket.asciimath, ttype: 'left_bracket' }; } } } private leftright_bracket(pos = 0, position = '') { for (let lr of this.leftright_brackets) { const b = this.exact(lr.asciimath, pos); if (b) { return { tex: position == 'left' ? lr.left_tex : position == 'right' ? lr.right_tex : lr.free_tex, pos: pos, end: b.end, ttype: 'leftright_bracket', asciimath: null }; } } } private text(pos = 0) { const quoted = this.match(/^"([^"]*)"/, pos); if (quoted) { const text = this.escape_text(quoted.match[1]); return { tex: `\\text{${text}}`, pos: pos, end: quoted.end, ttype: 'text', text: text }; } const textfn = this.match(/^(?:mbox|text)\s*(\([^)]*\)?|\{[^}]*\}?|\[[^\]]*\]?)/, pos); if (textfn) { const text = this.escape_text(textfn.match[1].slice(1, textfn.match[1].length - 1)); return { tex: `\\text{${text}}`, pos: pos, end: textfn.end, ttype: 'text', text: text }; } } // b ::= frac | root | stackrel | other binary symbols private binary(pos = 0) { for (let binary of this.binary_symbols) { const m = this.exact(binary.asciimath, pos); const [lb1, rb1] = binary.option ? ['[', ']'] : ['{', '}']; if (m) { const a = this.unbracket(this.simple(m.end)); if (a) { const atex = binary.rawfirst ? a.middle_asciimath : a.tex; const b = this.unbracket(this.simple(a.end)); if (b) { return { tex: `${binary.tex}${lb1}${atex}${rb1}{${b.tex}}`, pos: pos, end: b.end, ttype: 'binary', op: binary, arg1: a, arg2: b }; } else { return { tex: `${binary.tex}${lb1}${atex}${rb1}{}`, pos: pos, end: a.end, ttype: 'binary', op: binary, arg1: a, arg2: null }; } } else { return { tex: `${binary.tex}${lb1}${rb1}{}`, pos: pos, end: m.end, ttype: 'binary', op: binary, arg1: null, arg2: null }; } } } } // u ::= sqrt | text | bb | other unary symbols for font commands private unary(pos = 0) { for (let u of this.unary_symbols) { const m = this.exact(u.asciimath, pos); if (m) { const ss = this.subsup(m.end); const sstex = ss ? ss.tex : ''; const end = ss ? ss.end : m.end; const barg = this.simple(end); const arg = u.func ? barg : this.unbracket(barg); const argtex = arg && (u.raw ? arg.middle_asciimath : arg.tex); if (u.rewriteleftright) { const [left, right] = u.rewriteleftright; if (arg) { return { tex: `\\left ${left} ${argtex} \\right ${right} ${sstex}`, pos: pos, end: arg.end, ttype: 'unary', op: m, subsup: ss, arg: arg }; } else { return { tex: `\\left ${left} \\right ${right} ${sstex}`, pos: pos, end: m.end, ttype: 'unary', op: m, subsup: ss, arg: null }; } } else { if (arg) { return { tex: `${u.tex}${sstex}{${argtex}}`, pos: pos, end: arg.end, ttype: 'unary', op: m, subsup: ss, arg: arg }; } else { return { tex: `${u.tex}${sstex}{}`, pos: pos, end: m.end, ttype: 'unary', op: m, subsup: ss, arg: null }; } } } } } // v ::= [A-Za-z] | greek letters | numbers | other constant symbols private constant(pos = 0) { if (this.right_bracket(pos)) { return; } return this.longest([this.other_constant(pos), this.greek(pos), this.name(pos), this.number(pos), this.arbitrary_constant(pos)]); } private name(pos = 0) { return this.literal(this.match(/^[A-Za-z]/, pos)); } private greek(pos = 0) { const re_greek = new RegExp('^(' + this.greek_letters.join('|') + ')'); const m = this.match(re_greek, pos); if (m) { return { tex: '\\' + m.token, pos: pos, end: m.end, ttype: 'greek' }; } } private number(pos = 0) { const re_number = new RegExp('^\\d+(' + this.decimalsign + '\\d+)?'); return this.literal(this.match(re_number, pos)); } private other_constant(pos = 0) { for (let sym of this.relations) { if (!sym.asciimath.match(/^!/)) { let notm = this.exact('!' + sym.asciimath, pos); if (notm) { return { tex: `\\not ${sym.tex}`, pos: notm.pos, end: notm.end, ttype: 'other_constant' }; } } } for (let sym of this.constants) { let m = this.exact(sym.asciimath, pos); if (m) { return { tex: `${sym.tex}`, pos: m.pos, end: m.end, ttype: 'other_constant' }; } } } private arbitrary_constant(pos = 0) { if (!this.eof(pos)) { if (this.exact(",", pos)) { return; } for (let nc of this.non_constant_symbols.concat(this.left_brackets.map(x => x.asciimath), this.right_brackets.map(x => x.asciimath), this.leftright_brackets.map(x => x.asciimath))) { if (this.exact(nc, pos)) { return; } } const spos = this.strip_space(pos); const symbol = this.source(spos).slice(0, 1); return { tex: symbol, pos: pos, end: spos + 1, ttype: 'arbitrary_constant' }; } } private setup_symbols() { this.greek_letters = ['alpha', 'beta', 'gamma', 'Gamma', 'delta', 'Delta', 'epsilon', 'varepsilon', 'zeta', 'eta', 'theta', 'Theta', 'vartheta', 'iota', 'kappa', 'lambda', 'Lambda', 'mu', 'nu', 'xi', 'Xi', 'pi', 'Pi', 'rho', 'sigma', 'Sigma', 'tau', 'upsilon', 'phi', 'Phi', 'varphi', 'chi', 'psi', 'Psi', 'omega', 'Omega']; this.relations = [ { "asciimath": ":=", "tex": ":=" }, { "asciimath": ":|:", "tex": "\\|" }, { "asciimath": "=>", "tex": "\\Rightarrow" }, { "asciimath": "approx", "tex": "\\approx" }, { "asciimath": "~~", "tex": "\\approx" }, { "asciimath": "cong", "tex": "\\cong" }, { "asciimath": "~=", "tex": "\\cong" }, { "asciimath": "equiv", "tex": "\\equiv" }, { "asciimath": "-=", "tex": "\\equiv" }, { "asciimath": "exists", "tex": "\\exists" }, { "asciimath": "EE", "tex": "\\exists" }, { "asciimath": "forall", "tex": "\\forall" }, { "asciimath": "AA", "tex": "\\forall" }, { "asciimath": ">=", "tex": "\\ge" }, { "asciimath": "ge", "tex": "\\ge" }, { "asciimath": "gt=", "tex": "\\geq" }, { "asciimath": "geq", "tex": "\\geq" }, { "asciimath": "gt", "tex": "\\gt" }, { "asciimath": "in", "tex": "\\in" }, { "asciimath": "<=", "tex": "\\le" }, { "asciimath": "le", "tex": "\\le" }, { "asciimath": "lt=", "tex": "\\leq" }, { "asciimath": "leq", "tex": "\\leq" }, { "asciimath": "lt", "tex": "\\lt" }, { "asciimath": "models", "tex": "\\models" }, { "asciimath": "|==", "tex": "\\models" }, { "asciimath": "!=", "tex": "\\ne" }, { "asciimath": "ne", "tex": "\\ne" }, { "asciimath": "notin", "tex": "\\notin" }, { "asciimath": "!in", "tex": "\\notin" }, { "asciimath": "prec", "tex": "\\prec" }, { "asciimath": "-lt", "tex": "\\prec" }, { "asciimath": "-<", "tex": "\\prec" }, { "asciimath": "preceq", "tex": "\\preceq" }, { "asciimath": "-<=", "tex": "\\preceq" }, { "asciimath": "propto", "tex": "\\propto" }, { "asciimath": "prop", "tex": "\\propto" }, { "asciimath": "subset", "tex": "\\subset" }, { "asciimath": "sub", "tex": "\\subset" }, { "asciimath": "subseteq", "tex": "\\subseteq" }, { "asciimath": "sube", "tex": "\\subseteq" }, { "asciimath": "succ", "tex": "\\succ" }, { "asciimath": ">-", "tex": "\\succ" }, { "asciimath": "succeq", "tex": "\\succeq" }, { "asciimath": ">-=", "tex": "\\succeq" }, { "asciimath": "supset", "tex": "\\supset" }, { "asciimath": "sup", "tex": "\\supset" }, { "asciimath": "supseteq", "tex": "\\supseteq" }, { "asciimath": "supe", "tex": "\\supseteq" }, { "asciimath": "vdash", "tex": "\\vdash" }, { "asciimath": "|--", "tex": "\\vdash" }, ] this.constants = [ { "asciimath": "dt", "tex": "dt" }, { "asciimath": "dx", "tex": "dx" }, { "asciimath": "dy", "tex": "dy" }, { "asciimath": "dz", "tex": "dz" }, { "asciimath": "prime", "tex": "'" }, { "asciimath": "implies", "tex": "\\implies" }, { "asciimath": "epsi", "tex": "\\epsilon" }, { "asciimath": "leftrightarrow", "tex": "\\leftrightarrow" }, { "asciimath": "Leftrightarrow", "tex": "\\Leftrightarrow" }, { "asciimath": "rightarrow", "tex": "\\rightarrow" }, { "asciimath": "Rightarrow", "tex": "\\Rightarrow" }, { "asciimath": "backslash", "tex": "\\backslash" }, { "asciimath": "leftarrow", "tex": "\\leftarrow" }, { "asciimath": "Leftarrow", "tex": "\\Leftarrow" }, { "asciimath": "setminus", "tex": "\\setminus" }, { "asciimath": "bigwedge", "tex": "\\bigwedge" }, { "asciimath": "diamond", "tex": "\\diamond" }, { "asciimath": "bowtie", "tex": "\\bowtie" }, { "asciimath": "bigvee", "tex": "\\bigvee" }, { "asciimath": "bigcap", "tex": "\\bigcap" }, { "asciimath": "bigcup", "tex": "\\bigcup" }, { "asciimath": "square", "tex": "\\square" }, { "asciimath": "lamda", "tex": "\\lambda" }, { "asciimath": "Lamda", "tex": "\\Lambda" }, { "asciimath": "aleph", "tex": "\\aleph" }, { "asciimath": "angle", "tex": "\\angle" }, { "asciimath": "frown", "tex": "\\frown" }, { "asciimath": "qquad", "tex": "\\qquad" }, { "asciimath": "cdots", "tex": "\\cdots" }, { "asciimath": "vdots", "tex": "\\vdots" }, { "asciimath": "ddots", "tex": "\\ddots" }, { "asciimath": "cdot", "tex": "\\cdot" }, { "asciimath": "star", "tex": "\\star" }, { "asciimath": "|><|", "tex": "\\bowtie" }, { "asciimath": "circ", "tex": "\\circ" }, { "asciimath": "oint", "tex": "\\oint" }, { "asciimath": "grad", "tex": "\\nabla" }, { "asciimath": "quad", "tex": "\\quad" }, { "asciimath": "uarr", "tex": "\\uparrow" }, { "asciimath": "darr", "tex": "\\downarrow" }, { "asciimath": "downarrow", "tex": "\\downarrow" }, { "asciimath": "rarr", "tex": "\\rightarrow" }, { "asciimath": ">->>", "tex": "\\twoheadrightarrowtail" }, { "asciimath": "larr", "tex": "\\leftarrow" }, { "asciimath": "harr", "tex": "\\leftrightarrow" }, { "asciimath": "rArr", "tex": "\\Rightarrow" }, { "asciimath": "lArr", "tex": "\\Leftarrow" }, { "asciimath": "hArr", "tex": "\\Leftrightarrow" }, { "asciimath": "ast", "tex": "\\ast" }, { "asciimath": "***", "tex": "\\star" }, { "asciimath": "|><", "tex": "\\ltimes" }, { "asciimath": "><|", "tex": "\\rtimes" }, { "asciimath": "^^^", "tex": "\\bigwedge" }, { "asciimath": "vvv", "tex": "\\bigvee" }, { "asciimath": "cap", "tex": "\\cap" }, { "asciimath": "nnn", "tex": "\\bigcap" }, { "asciimath": "cup", "tex": "\\cup" }, { "asciimath": "uuu", "tex": "\\bigcup" }, { "asciimath": "not", "tex": "\\neg" }, { "asciimath": "<=>", "tex": "\\Leftrightarrow" }, { "asciimath": "_|_", "tex": "\\bot" }, { "asciimath": "bot", "tex": "\\bot" }, { "asciimath": "int", "tex": "\\int" }, { "asciimath": "del", "tex": "\\partial" }, { "asciimath": "...", "tex": "\\ldots" }, { "asciimath": "/_\\", "tex": "\\triangle" }, { "asciimath": "|__", "tex": "\\lfloor" }, { "asciimath": "__|", "tex": "\\rfloor" }, { "asciimath": "dim", "tex": "\\dim" }, { "asciimath": "mod", "tex": "\\operatorname{mod}" }, { "asciimath": "lub", "tex": "\\operatorname{lub}" }, { "asciimath": "glb", "tex": "\\operatorname{glb}" }, { "asciimath": ">->", "tex": "\\rightarrowtail" }, { "asciimath": "->>", "tex": "\\twoheadrightarrow" }, { "asciimath": "|->", "tex": "\\mapsto" }, { "asciimath": "lim", "tex": "\\lim" }, { "asciimath": "Lim", "tex": "\\operatorname{Lim}" }, { "asciimath": "and", "tex": "\\quad\\text{and}\\quad" }, { "asciimath": "**", "tex": "\\ast" }, { "asciimath": "//", "tex": "/" }, { "asciimath": "\\", "tex": "\\," }, { "asciimath": "\\\\", "tex": "\\backslash" }, { "asciimath": "xx", "tex": "\\times" }, { "asciimath": "-:", "tex": "\\div" }, { "asciimath": "o+", "tex": "\\oplus" }, { "asciimath": "ox", "tex": "\\otimes" }, { "asciimath": "o.", "tex": "\\odot" }, { "asciimath": "^", "tex": "\\hat{}" }, { "asciimath": "_", "tex": "\\_" }, { "asciimath": "^^", "tex": "\\wedge" }, { "asciimath": "vv", "tex": "\\vee" }, { "asciimath": "nn", "tex": "\\cap" }, { "asciimath": "uu", "tex": "\\cup" }, { "asciimath": "TT", "tex": "\\top" }, { "asciimath": "+-", "tex": "\\pm" }, { "asciimath": "O/", "tex": "\\emptyset" }, { "asciimath": "oo", "tex": "\\infty" }, { "asciimath": ":.", "tex": "\\therefore" }, { "asciimath": ":'", "tex": "\\because" }, { "asciimath": "/_", "tex": "\\angle" }, { "asciimath": "|~", "tex": "\\lceil" }, { "asciimath": "~|", "tex": "\\rceil" }, { "asciimath": "CC", "tex": "\\mathbb{C}" }, { "asciimath": "NN", "tex": "\\mathbb{N}" }, { "asciimath": "QQ", "tex": "\\mathbb{Q}" }, { "asciimath": "RR", "tex": "\\mathbb{R}" }, { "asciimath": "ZZ", "tex": "\\mathbb{Z}" }, { "asciimath": "->", "tex": "\\to" }, { "asciimath": "or", "tex": "\\quad\\text{or}\\quad" }, { "asciimath": "if", "tex": "\\quad\\text{if}\\quad" }, { "asciimath": "iff", "tex": "\\iff" }, { "asciimath": "*", "tex": "\\cdot" }, { "asciimath": "@", "tex": "\\circ" }, { "asciimath": "%", "tex": "\\%" }, { "asciimath": "boxempty", "tex": "\\square" }, { "asciimath": "lambda", "tex": "\\lambda" }, { "asciimath": "Lambda", "tex": "\\Lambda" }, { "asciimath": "nabla", "tex": "\\nabla" }, { "asciimath": "uparrow", "tex": "\\uparrow" }, { "asciimath": "downarrow", "tex": "\\downarrow" }, { "asciimath": "twoheadrightarrowtail", "tex": "\\twoheadrightarrowtail" }, { "asciimath": "ltimes", "tex": "\\ltimes" }, { "asciimath": "rtimes", "tex": "\\rtimes" }, { "asciimath": "neg", "tex": "\\neg" }, { "asciimath": "partial", "tex": "\\partial" }, { "asciimath": "ldots", "tex": "\\ldots" }, { "asciimath": "triangle", "tex": "\\triangle" }, { "asciimath": "lfloor", "tex": "\\lfloor" }, { "asciimath": "rfloor", "tex": "\\rfloor" }, { "asciimath": "rightarrowtail", "tex": "\\rightarrowtail" }, { "asciimath": "twoheadrightarrow", "tex": "\\twoheadrightarrow" }, { "asciimath": "mapsto", "tex": "\\mapsto" }, { "asciimath": "times", "tex": "\\times" }, { "asciimath": "div", "tex": "\\div" }, { "asciimath": "divide", "tex": "\\div" }, { "asciimath": "oplus", "tex": "\\oplus" }, { "asciimath": "otimes", "tex": "\\otimes" }, { "asciimath": "odot", "tex": "\\odot" }, { "asciimath": "wedge", "tex": "\\wedge" }, { "asciimath": "vee", "tex": "\\vee" }, { "asciimath": "top", "tex": "\\top" }, { "asciimath": "pm", "tex": "\\pm" }, { "asciimath": "emptyset", "tex": "\\emptyset" }, { "asciimath": "infty", "tex": "\\infty" }, { "asciimath": "therefore", "tex": "\\therefore" }, { "asciimath": "because", "tex": "\\because" }, { "asciimath": "lceil", "tex": "\\lceil" }, { "asciimath": "rceil", "tex": "\\rceil" }, { "asciimath": "to", "tex": "\\to" }, { "asciimath": "langle", "tex": "\\langle" }, { "asciimath": "lceiling", "tex": "\\lceil" }, { "asciimath": "rceiling", "tex": "\\rceil" }, { "asciimath": "max", "tex": "\\max" }, { "asciimath": "min", "tex": "\\min" }, { "asciimath": "prod", "tex": "\\prod" }, { "asciimath": "sum", "tex": "\\sum" }, ]; this.constants = this.constants.concat(this.relations); this.left_brackets = [ { asciimath: 'langle', tex: '\\langle' }, { asciimath: '(:', tex: '\\langle' }, { asciimath: '<<', tex: '\\langle' }, { asciimath: '{:', tex: '.' }, { asciimath: '(', tex: '(' }, { asciimath: '[', tex: '[' }, { asciimath: '{', tex: '\\lbrace' }, { asciimath: 'lbrace', tex: '\\lbrace' }, ]; this.right_brackets = [ { asciimath: 'rangle', tex: '\\rangle' }, { asciimath: ':)', tex: '\\rangle' }, { asciimath: '>>', tex: '\\rangle' }, { asciimath: ':}', tex: '.', free_tex: ':\\}' }, { asciimath: ')', tex: ')' }, { asciimath: ']', tex: ']' }, { asciimath: '}', tex: '\\rbrace' }, { asciimath: 'rbrace', tex: '\\rbrace' }, ]; this.leftright_brackets = [ { asciimath: '|', left_tex: '\\lvert', right_tex: '\\rvert', free_tex: '|' }, ]; this.unary_symbols = [ { asciimath: "sqrt", tex: "\\sqrt" }, { asciimath: "f", tex: "f", func: true }, { asciimath: "g", tex: "g", func: true }, { asciimath: "sin", tex: "\\sin", func: true }, { asciimath: "cos", tex: "\\cos", func: true }, { asciimath: "tan", tex: "\\tan", func: true }, { asciimath: "arcsin", tex: "\\arcsin", func: true }, { asciimath: "arccos", tex: "\\arccos", func: true }, { asciimath: "arctan", tex: "\\arctan", func: true }, { asciimath: "sinh", tex: "\\sinh", func: true }, { asciimath: "cosh", tex: "\\cosh", func: true }, { asciimath: "tanh", tex: "\\tanh", func: true }, { asciimath: "cot", tex: "\\cot", func: true }, { asciimath: "coth", tex: "\\coth", func: true }, { asciimath: "sech", tex: "\\operatorname{sech}", func: true }, { asciimath: "csch", tex: "\\operatorname{csch}", func: true }, { asciimath: "sec", tex: "\\sec", func: true }, { asciimath: "csc", tex: "\\csc", func: true }, { asciimath: "log", tex: "\\log", func: true }, { asciimath: "ln", tex: "\\ln", func: true }, { asciimath: "abs", rewriteleftright: ["|", "|"] }, { asciimath: "norm", rewriteleftright: ["\\|", "\\|"] }, { asciimath: "floor", rewriteleftright: ["\\lfloor", "\\rfloor"] }, { asciimath: "ceil", rewriteleftright: ["\\lceil", "\\rceil"] }, { asciimath: "Sin", tex: "\\Sin", func: true }, { asciimath: "Cos", tex: "\\Cos", func: true }, { asciimath: "Tan", tex: "\\Tan", func: true }, { asciimath: "Arcsin", tex: "\\Arcsin", func: true }, { asciimath: "Arccos", tex: "\\Arccos", func: true }, { asciimath: "Arctan", tex: "\\Arctan", func: true }, { asciimath: "Sinh", tex: "\\Sinh", func: true }, { asciimath: "Cosh", tex: "\\Cosh", func: true }, { asciimath: "Tanh", tex: "\\Tanh", func: true }, { asciimath: "Cot", tex: "\\Cot", func: true }, { asciimath: "Sec", tex: "\\Sec", func: true }, { asciimath: "Csc", tex: "\\Csc", func: true }, { asciimath: "Log", tex: "\\Log", func: true }, { asciimath: "Ln", tex: "\\Ln", func: true }, { asciimath: "Abs", tex: "\\Abs", rewriteleftright: ["|", "|"] }, { asciimath: "det", tex: "\\det", func: true }, { asciimath: "exp", tex: "\\exp", func: true }, { asciimath: "gcd", tex: "\\gcd", func: true }, { asciimath: "lcm", tex: "\\operatorname{lcm}", func: true }, { asciimath: "cancel", tex: "\\cancel" }, { asciimath: "Sqrt", tex: "\\Sqrt" }, { asciimath: "hat", tex: "\\hat", acc: true }, { asciimath: "bar", tex: "\\overline", acc: true }, { asciimath: "overline", tex: "\\overline", acc: true }, { asciimath: "vec", tex: "\\vec", acc: true }, { asciimath: "tilde", tex: "\\tilde", acc: true }, { asciimath: "dot", tex: "\\dot", acc: true }, { asciimath: "ddot", tex: "\\ddot", acc: true }, { asciimath: "ul", tex: "\\underline", acc: true }, { asciimath: "underline", tex: "\\underline", acc: true }, { asciimath: "ubrace", tex: "\\underbrace", acc: true }, { asciimath: "underbrace", tex: "\\underbrace", acc: true }, { asciimath: "obrace", tex: "\\overbrace", acc: true }, { asciimath: "overbrace", tex: "\\overbrace", acc: true }, { asciimath: "bb", atname: "mathvariant", atval: "bold", tex: "\\mathbf" }, { asciimath: "mathbf", atname: "mathvariant", atval: "bold", tex: "mathbf" }, { asciimath: "sf", atname: "mathvariant", atval: "sans-serif", tex: "\\mathsf" }, { asciimath: "mathsf", atname: "mathvariant", atval: "sans-serif", tex: "mathsf" }, { asciimath: "bbb", atname: "mathvariant", atval: "double-struck", tex: "\\mathbb" }, { asciimath: "mathbb", atname: "mathvariant", atval: "double-struck", tex: "\\mathbb" }, { asciimath: "cc", atname: "mathvariant", atval: "script", tex: "\\mathcal" }, { asciimath: "mathcal", atname: "mathvariant", atval: "script", tex: "\\mathcal" }, { asciimath: "tt", atname: "mathvariant", atval: "monospace", tex: "\\mathtt" }, { asciimath: "mathtt", atname: "mathvariant", atval: "monospace", tex: "\\mathtt" }, { asciimath: "fr", atname: "mathvariant", atval: "fraktur", tex: "\\mathfrak" }, { asciimath: "mathfrak", atname: "mathvariant", atval: "fraktur", tex: "\\mathfrak" }, ]; this.binary_symbols = [ { asciimath: "root", tex: "\\sqrt", option: true }, { asciimath: "frac", tex: "\\frac" }, { asciimath: "stackrel", tex: "\\stackrel" }, { asciimath: "overset", tex: "\\overset" }, { asciimath: "underset", tex: "\\underset" }, { asciimath: "color", tex: "\\color", rawfirst: true }, ] this.non_constant_symbols = ['_', '^', '/']; } private sort_symbols() { const by_asciimath = (a, b) => { a = a.asciimath.length, b = b.asciimath.length; return a > b ? -1 : a < b ? 1 : 0 }; this.constants.sort(by_asciimath); this.relations.sort(by_asciimath); this.left_brackets.sort(by_asciimath); this.right_brackets.sort(by_asciimath); this.leftright_brackets.sort(by_asciimath); this.unary_symbols.sort(by_asciimath); this.binary_symbols.sort(by_asciimath); } }
1b362e9b94b6566622cbb10bc1791f4bba4a79d8
TypeScript
iwfan/happy-http
/src/core/http_params.ts
3.109375
3
import { isArray, isDate, isObject, toString } from '../helpers' export type HttpParamValue = Exclude< string | string[] | boolean | number | object | Date | RegExp, null > export interface HttpParamsInit { readonly [param: string]: HttpParamValue } export class HttpParams { static encode(v: string) { return encodeURIComponent(v) .replace(/%20/g, '+') .replace(/%40/gi, '@') .replace(/%3A/gi, ':') .replace(/%24/gi, '$') .replace(/%2C/gi, ',') .replace(/%3B/gi, ';') .replace(/%2B/gi, '+') .replace(/%3D/gi, '=') .replace(/%3F/gi, '?') .replace(/%2F/gi, '/') } static queryPairFor(key: string, value: string) { return `${key}=${this.encode(value)}` } private params = new Map<string, HttpParamValue>() constructor(init?: HttpParams | HttpParamsInit) { if (init) { this.merge(init) } } merge(init: HttpParams | HttpParamsInit): HttpParams { const entries = init instanceof HttpParams ? init.entries() : Object.entries(init) entries.forEach(([key, value]) => { this.params.set(key, value) }) return this } entries() { return [...this.params.entries()] } serialize(): string { return this.entries() .map(([key, value]) => { if (isDate(value)) { return HttpParams.queryPairFor(key, value.toISOString()) } if (isObject(value)) { return HttpParams.queryPairFor(key, JSON.stringify(value)) } if (isArray(value)) { return value .map(toString) .map(str => HttpParams.queryPairFor(key, str)) .join('&') } return HttpParams.queryPairFor(key, value as string) }) .join('&') } }
bb11392fde487139e7cf536aa486cce2b21e361a
TypeScript
sysidos/koatty
/src/util/ValidUtil.ts
2.671875
3
/** * @ author: richen * @ copyright: Copyright (c) - <richenlin(at)gmail.com> * @ license: MIT * @ version: 2020-01-02 09:36:59 */ import helper from "think_lib"; import { plainToClass } from "class-transformer"; import { validate, registerDecorator, ValidationArguments, ValidationOptions, Validator } from "class-validator"; // export decorators of class-validator export { IsDefined, Equals, NotEquals, Contains, IsIn, IsNotIn, IsDate, Min, Max, Length, IsEmail, IsIP, IsPhoneNumber, IsUrl, IsHash } from "class-validator"; export const validatorCls = new Validator(); /** * * * @export * @class ValidateUtil */ export class ValidateUtil { private static instance: ValidateUtil; private constructor() { } /** * * * @static * @returns * @memberof ValidateUtil */ static getInstance() { return this.instance || (this.instance = new ValidateUtil()); } /** * * * @param {*} Clazz * @param {*} data * @returns {Promise<any>} * @memberof ValidateUtil */ async valid(Clazz: any, data: any): Promise<any> { const obj = plainToClass(Clazz, data); const errors = await validate(obj, { skipMissingProperties: true }); if (errors.length > 0) { throw new Error(Object.values(errors[0].constraints)[0]); } return obj; } } /** * Checks if value is a chinese name. * * @param {string} value * @returns {boolean} */ export function iscnname(value: string): boolean { const reg = /^([a-zA-Z0-9\u4e00-\u9fa5\·]{1,10})$/; return reg.test(value); } /** * Checks if value is a idcard number. * * @param {string} value * @returns */ export function isidnumber(value: string): boolean { if (/^\d{15}$/.test(value)) { return true; } if ((/^\d{17}[0-9X]$/).test(value)) { const vs = '1,0,x,9,8,7,6,5,4,3,2'.split(','); const ps: any[] = '7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2'.split(','); const ss: any[] = value.toLowerCase().split(''); let r = 0; for (let i = 0; i < 17; i++) { r += ps[i] * ss[i]; } const isOk = (vs[r % 11] === ss[17]); return isOk; } return false; } /** * Checks if value is a mobile phone number. * * @param {string} value * @returns {boolean} */ export function ismobile(value: string): boolean { const reg = /^(13|14|15|16|17|18|19)\d{9}$/; return reg.test(value); } /** * Checks if value is a zipcode. * * @param {string} value * @returns {boolean} */ export function iszipcode(value: string): boolean { const reg = /^\d{6}$/; return reg.test(value); } /** * Checks if value is a platenumber. * * @param {string} value * @returns {boolean} */ export function isplatenumber(value: string): boolean { // let reg = new RegExp('^(([\u4e00-\u9fa5][a-zA-Z]|[\u4e00-\u9fa5]{2}\d{2}|[\u4e00-\u9fa5]{2}[a-zA-Z])[-]?|([wW][Jj][\u4e00-\u9fa5]{1}[-]?)|([a-zA-Z]{2}))([A-Za-z0-9]{5}|[DdFf][A-HJ-NP-Za-hj-np-z0-9][0-9]{4}|[0-9]{5}[DdFf])$'); // let xreg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/; const xreg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([DF][A-HJ-NP-Z0-9][0-9]{4}$))/; // let creg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/; const creg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/; if (value.length === 7) { return creg.test(value); } else { //新能源车牌 return xreg.test(value); } } /** * Checks if value is a chinese name. * * @export * @param {string} property * @param {ValidationOptions} [validationOptions] * @returns */ export function IsCnName(validationOptions?: ValidationOptions) { return function (object: Object, propertyName: string) { registerDecorator({ name: "IsCnName", target: object.constructor, propertyName, options: validationOptions, validator: { validate(value: any, args: ValidationArguments) { return iscnname(value); }, defaultMessage(args: ValidationArguments) { // here you can provide default error message if validation failed return "The ($value) must be a chinese name!"; } } }); }; } /** * Checks if value is a idcard number(chinese). * * @export * @param {string} property * @param {ValidationOptions} [validationOptions] * @returns */ export function IsIdNumber(validationOptions?: ValidationOptions) { return function (object: Object, propertyName: string) { registerDecorator({ name: "IsIdNumber", target: object.constructor, propertyName, options: validationOptions, validator: { validate(value: any, args: ValidationArguments) { return isidnumber(value); }, defaultMessage(args: ValidationArguments) { // here you can provide default error message if validation failed return "The ($value) must be a idcard number!"; } } }); }; } /** * Checks if value is a zipcode(chinese). * * @export * @param {string} property * @param {ValidationOptions} [validationOptions] * @returns */ export function IsZipCode(validationOptions?: ValidationOptions) { return function (object: Object, propertyName: string) { registerDecorator({ name: "IsZipCode", target: object.constructor, propertyName, options: validationOptions, validator: { validate(value: any, args: ValidationArguments) { return iszipcode(value); }, defaultMessage(args: ValidationArguments) { // here you can provide default error message if validation failed return "The ($value) must be a zip code!"; } } }); }; } /** * Checks if value is a mobile phone number(chinese). * * @export * @param {string} property * @param {ValidationOptions} [validationOptions] * @returns */ export function IsMobile(validationOptions?: ValidationOptions) { return function (object: Object, propertyName: string) { registerDecorator({ name: "IsMobile", target: object.constructor, propertyName, options: validationOptions, validator: { validate(value: any, args: ValidationArguments) { return ismobile(value); }, defaultMessage(args: ValidationArguments) { // here you can provide default error message if validation failed return "The ($value) must be a mobile number!"; } } }); }; } /** * Checks if value is a plate number(chinese). * * @export * @param {string} property * @param {ValidationOptions} [validationOptions] * @returns */ export function IsPlateNumber(validationOptions?: ValidationOptions) { return function (object: Object, propertyName: string) { registerDecorator({ name: "IsPlateNumber", target: object.constructor, propertyName, options: validationOptions, validator: { validate(value: any, args: ValidationArguments) { return isplatenumber(value); }, defaultMessage(args: ValidationArguments) { // here you can provide default error message if validation failed return "The ($value) must be a plate number!"; } } }); }; } /** * Checks value is not empty, undefined, null, '', NaN, [], {} and any empty string(including spaces, tabs, formfeeds, etc.), returns false. * * @export * @param {ValidationOptions} [validationOptions] * @returns */ export function IsNotEmpty(validationOptions?: ValidationOptions) { return function (object: Object, propertyName: string) { registerDecorator({ name: "IsNotEmpty", target: object.constructor, propertyName, options: validationOptions, validator: { validate(value: any, args: ValidationArguments) { return !helper.isEmpty(value); }, defaultMessage(args: ValidationArguments) { // here you can provide default error message if validation failed return "The ($property)'s value must be not empty!"; } } }); }; }
68dcd0daa8eff93557c378d55fb3e8bc9dcb0481
TypeScript
tarioto/leetcoding-challenge-december
/tests/06-12-20.test.ts
2.984375
3
import { connect, Node } from "../problems/06-12-20"; test('connect of [1,2,3,4,5,null,7] to equal [1,#,2,3,#,4,5,7,#]', () => { const root = new Node(1, new Node(2, new Node(4), new Node(5)), new Node(3, undefined, new Node(7))) let seven = new Node(7) let three = new Node(3, undefined, seven) let five = new Node(5, undefined, undefined, seven) const result = new Node(1, new Node(2, new Node(4, undefined, undefined, five), five, three), three, undefined) expect(connect(root)).toEqual(result); });
e255f95049a20078f78c94f893844b908e7c745a
TypeScript
kdharani/protractor-ui-reference
/protractor-typescript/pages/ownersPage.ts
2.890625
3
import FedexBasePage from "./FedexBasePage"; import Owner from "../model/owner"; import Pet from "../model/pet"; const route = 'owners'; const selector = { ownersTable : {css: '.table.table-striped'}, ownerNameList : {css: '.table-responsive td a'}, petName : {css: '.table.table-striped .dl-horizontal dd:nth-child(2)'}, petDob : {css: '.table.table-striped .dl-horizontal dd:nth-child(4)'}, petType : {css: '.table.table-striped .dl-horizontal dd:nth-child(6)'} } class OwnersPage extends FedexBasePage { constructor(){ super(selector, route); } public async navigate(): Promise<void> { return await this.log(`Navigate to owner page`, async () => { return super.navigate(); }); } public async getOwnerDetails(owner): Promise<Owner> { return await this.log(`Get owner details'`, async () => { let name = ""; let address = ""; let city = ""; let telephone = ""; await this.waitForElementVisible('ownersTable', this.timeout.SHORT); const nameList = await this.getElements('ownerNameList'); for (let index = 0; index < nameList.length; index += 1) { name = await nameList[index].getText(); if(name === `${owner.firstName} ${owner.lastName}`) { address = await this.getTableColumnText('ownersTable', index+1, 'Address'); city = await this.getTableColumnText('ownersTable', index+1, 'City'); telephone = await this.getTableColumnText('ownersTable', index+1, 'Telephone'); break; } } this.log(`Got owner details: '${name}, ${address}, ${city}, ${telephone}'`) return new Owner(name, address, city, telephone); }) } public async selectOwner (owner) { const message = `Select owner ${owner.name}'`; this.log(message , async () => { this.log(message); await this.waitForElementVisible('ownersTable', this.timeout.SHORT); const nameList = await this.getElements('ownerNameList'); for (let index = 0; index < nameList.length; index += 1) { const name = await nameList[index].getText(); if(name === `${owner.name}`){ await nameList[index].click(); break; } } }); } public async getPetName (): Promise<string> { return this.log(`Get pet name`, async () => { await this.waitForElementVisible('petName', this.timeout.SHORT); const name = await this.getElement('petName').getText(); this.log(`Got pet name '${name}'`); return name; }); } public async getPetDob (): Promise<string> { return this.log(`Get pet D.O.B`, async () => { await this.waitForElementVisible('petDob', this.timeout.SHORT); const dob = await this.getElement('petDob').getText(); this.log(`Got pet DOB '${dob}'`); return dob; }); } public async getPetType (): Promise<string> { return this.log(`Get pet type`, async () => { await this.waitForElementVisible('petType', this.timeout.SHORT); const type = await this.getElement('petType').getText(); this.log(`Got pet type '${type}'`); return type; }) } public async getPetDetails (): Promise<Pet> { return this.log(`Get pet details`, async () => { this.log(`Get pet details`); const name = await this.getPetName(); const dob = await this.getPetDob(); const type = await this.getPetType(); return new Pet(name, dob, type); }); } } export const ownersPage = new OwnersPage();
38c6bbd27ab964c3255dd47427508152cf2dceac
TypeScript
EduardoModel/react-typescript-next-setup
/src/styles/styled.d.ts
2.578125
3
// Disable the eslint rule for a file without the need to change the main config file /* eslint @typescript-eslint/no-empty-interface: "off" */ import 'styled-components' import theme from './theme' // Easy way to define the types of the content of an object export type Theme = typeof theme declare module 'styled-components' { export interface DefaultTheme extends Theme {} }
fb262d268c14a16a657c275e95cdee4a2af1b9c4
TypeScript
hisland/my-learn
/typescript/08.type-compatibility/30.type-extends-any.ts
4.15625
4
// T extends U ? X : Y // The type above means when T is assignable to U the type is X, otherwise the type is Y { // "yes" type T01 = number extends any ? 'yes' : 'no' // "yes" type T02 = string extends any ? 'yes' : 'no' // "yes" type T03 = boolean extends any ? 'yes' : 'no' // "yes" type T04 = null extends any ? 'yes' : 'no' // "yes" type T05 = undefined extends any ? 'yes' : 'no' // "yes" type T06 = void extends any ? 'yes' : 'no' // "yes" type T07 = symbol extends any ? 'yes' : 'no' // "yes" type T08 = object extends any ? 'yes' : 'no' // "yes" type T09 = Function extends any ? 'yes' : 'no' // "yes" type T10 = any extends any ? 'yes' : 'no' // "yes" type T11 = unknown extends any ? 'yes' : 'no' // "yes" type T12 = never extends any ? 'yes' : 'no' } { // "yes" | "no" type T01 = any extends number ? 'yes' : 'no' // "yes" | "no" type T02 = any extends string ? 'yes' : 'no' // "yes" | "no" type T03 = any extends boolean ? 'yes' : 'no' // "yes" | "no" type T04 = any extends null ? 'yes' : 'no' // "yes" | "no" type T05 = any extends undefined ? 'yes' : 'no' // "yes" | "no" type T06 = any extends void ? 'yes' : 'no' // "yes" | "no" type T07 = any extends symbol ? 'yes' : 'no' // "yes" | "no" type T08 = any extends object ? 'yes' : 'no' // "yes" | "no" type T09 = any extends Function ? 'yes' : 'no' // "yes" type T10 = any extends any ? 'yes' : 'no' // "yes" type T11 = any extends unknown ? 'yes' : 'no' // "yes" | "no" type T12 = any extends never ? 'yes' : 'no' }
6335e4674a9ca46984f9b3557e8fa782b188a08c
TypeScript
Alexsey1999/ReactClothesStoreBackend
/src/models/categories.ts
2.6875
3
import { Schema, Document } from 'mongoose' export interface ICategory extends Document { id: Schema.Types.ObjectId categoryName: string products: Schema.Types.ObjectId[] onModel: 'shirt' | 'cap' | 't-shirt' | 'bag' | 'polo' } const categorySchema = new Schema({ id: Schema.Types.ObjectId, categoryName: { type: String, required: true, }, products: [{ type: Schema.Types.ObjectId, refPath: 'onModel' }], onModel: { type: String, required: true, enum: ['shirt', 'cap', 't-shirt', 'bag', 'polo'], }, }) export default categorySchema
6b051e9f56c2f4dedee1dc0a3123cb08b9360979
TypeScript
EntropyAu/TactileJS
/examples/workshopPlanner/ts/models/Workshop.ts
2.921875
3
module WorkshopPlanner { export class Workshop { name:KnockoutObservable<String> = ko.observable(""); days:KnockoutObservableArray<Day> = ko.observableArray([]); constructor(data:any) { for (let prop in data) { if (ko.isObservable(this[prop]) && prop !== 'days') this[prop](data[prop]); } let days = []; for (let day of data.days || []) days.push(new Day(day)) this.days(days); } public toJS():any { let result:any = {} for (let prop in this) if (ko.isObservable(this[prop]) && prop !== 'days') result[prop] = ko.unwrap(this[prop]); result.days = []; for (let day of this.days()) result.days.push(day.toJS()); return result; } } }
ad59e52de282bcd61603b7b8654c638a981c9561
TypeScript
mipli/cabalites
/src/containers/PriorityLinkedList.ts
3.171875
3
import * as array from './array'; import * as utils from './utils'; import {ILinkedListNode, default as LinkedList} from './LinkedList.ts'; export default class PriorityLinkedList<T> extends LinkedList<T> { private compareFunction: utils.ICompareFunction<T>; constructor(compareFunction?: utils.ICompareFunction<T>) { super(); this.compareFunction = compareFunction || utils.defaultCompare; } push(element: T): boolean { if (utils.isUndefined(element)) { return false; } const node = this.createNode(element); if (this.count === 0) { this.head = node; this.tail = node; this._count++; return true; } let current = this.head; let previous = null; while (current) { if (this.compareFunction(current.element, node.element) === 1) { node.next = current; if (previous) { previous.next = node; } else { this.head = node; } this._count++; return true; } if (current.next === null) { current.next = node; this._count++; return true; } previous = current; current = current.next; } return false; } }
58c047166870c46353f958875454054dce3b1dd1
TypeScript
ohjooyeong/store-2
/client/src/utils/index.ts
2.609375
3
export const formatPrice = (price: string | number): string => { const parsePrice = typeof price === 'string' ? parseInt(price, 10) : price; return parsePrice.toLocaleString('ko-KR'); }; export const filterId = (id: string): string => { return `${id.slice(0, 3)}***`; };
6a56208d16a8d4de87bc093cb5fd18cda54fce66
TypeScript
cardstack/cardstack
/packages/safe-tools-client/app/utils/owner.ts
2.75
3
import { getOwner } from '@ember/application'; import { assert } from '@ember/debug'; import { Registry } from '@ember/service'; // This file augments Ember's `Owner.lookup` so that it understands services in // the same way that service injection does. // This reexport is here because you cannot augment the type of a default // export, but you can augment the type of a named export. So we reexport the // type we want to augment to make it augmentable. // // https://github.com/Microsoft/TypeScript/issues/14080 export type { default as Owner } from '@ember/owner'; // This is *weird*. We are augmenting "our own module" here, and since we // reexport the underlying type from Ember we are therefore augmenting that // type. declare module './owner' { interface Owner { lookup<Name extends keyof Registry>( fullName: `service:${Name}` ): Registry[Name]; } } export function strongGetOwner(obj: unknown): Owner { const result = getOwner(obj); assert('owner is present', !!result); return result; }
2179d0b59fedca830874d1dc5d540fab2e2d1b9e
TypeScript
cafesanu/angular-pipes
/src/app/pipes/shorten/shorten.pipe.ts
2.640625
3
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'shorten' }) export class ShortenPipe implements PipeTransform { public transform(value: string, limit?: number): string { if (limit && value.length > limit) { return `${value.substr(0, limit)}...`; } return value; } }
79b4fa0ddf82c4222494c4183c20800724a9c407
TypeScript
trebbettes-screeps/screeps-ai
/src/movement/common/costMatrix.ts
2.59375
3
import {CREEPS_MOVEMENT_CONFIG} from "../config"; import {isSkRoom} from "./getRoomType"; import {roomHostilityCheck} from "./hostility"; import {isBlocking, isTraversable} from "./roomPosition"; export function getCostMatrix(roomName: string, avoidCreepsIn?: string, opts?: MovementOptions): CostMatrix | boolean { if (opts && opts.avoidRooms && _.contains(opts.avoidRooms, roomName)) { return false; } if (roomHostilityCheck(roomName)) { return false; } const room = Game.rooms[roomName]; if (room) { if (avoidCreepsIn && roomName === avoidCreepsIn) { return getCreepMatrix(room); } else if (opts && opts.avoidSk && isSkRoom(roomName)) { return getSkMatrix(room); } else { return getDefaultMatrix(room); } } return true; } export function getDefaultMatrix(room: Room): CostMatrix { if (room.__defaultMatrix) { return room.__defaultMatrix; } const matrix = new PathFinder.CostMatrix(); _.forEach(room.find(FIND_STRUCTURES), (s: Structure) => { if (s instanceof StructureRoad) { matrix.set(s.pos.x, s.pos.y, 1); } else if (isBlocking(s)) { matrix.set(s.pos.x, s.pos.y, 0xff); } }); _.forEach(room.find(FIND_CONSTRUCTION_SITES), (cs: ConstructionSite): void => { if (isBlocking(cs)) { matrix.set(cs.pos.x, cs.pos.y, 0xff); } }); if (CREEPS_MOVEMENT_CONFIG.staticCreepFilter) { _.forEach(room.find(FIND_CREEPS), (c: Creep): void => { if (CREEPS_MOVEMENT_CONFIG.staticCreepFilter!(c)) { matrix.set(c.pos.x, c.pos.y, 0xff); } }); } return room.__defaultMatrix = matrix; } export function getCreepMatrix(room: Room): CostMatrix { if (room.__creepMatrix) { return room.__creepMatrix; } const clonedMatrix = getDefaultMatrix(room).clone(); _.forEach(room.find(FIND_CREEPS), (c: Creep) => { clonedMatrix.set(c.pos.x, c.pos.y, 0xff); }); return room.__creepMatrix = clonedMatrix; } export function getSkMatrix(room: Room): CostMatrix { if (room.__skMatrix) { return room.__skMatrix; } const matrix = getDefaultMatrix(room).clone(); const toAvoid = [ ...room.find(FIND_SOURCES), ...room.find(FIND_MINERALS) ]; const range = 4; _.forEach(toAvoid, (center: RoomObject) => { for (let xO = -range; xO <= range; xO++) { for (let yO = -range; yO <= range; yO++) { if (isTraversable(new RoomPosition(center.pos.x + xO, center.pos.y + yO, room.name))) { matrix.set(center.pos.x + xO, center.pos.y + yO, 0xff); } } } }); return room.__skMatrix = matrix; }
052660fa76a704dbe45164a7733873334ad91dd5
TypeScript
KaiPUecker/nodepane-component
/src/components/NodeConnector.ts
3.03125
3
import { Point } from "../geom/Point"; import { UnitConnector } from "../model/UnitConnector"; export class NodeConnector { public static RADIUS: number = 6; public point: Point; public unitConnector: UnitConnector; public color: string; constructor(x: number, y: number, unitConnector: UnitConnector) { this.point = new Point(); this.point.x = x || 0; this.point.y = y || 0; this.color = UnitConnector.INPUT === unitConnector.type ? '#0F0' : '#F00'; this.unitConnector = unitConnector; } contains(p: Point): boolean { return p && this.point.distanceTo(p) < NodeConnector.RADIUS; } }
e61db483a0866870dfcd891174f9d23b2990935e
TypeScript
dnalborczyk/serverless-offline
/tests/old-unit/authFunctionNameExtractor.test.ts
2.796875
3
// @ts-nocheck import authFunctionNameExtractor from '../../src/events/http/authFunctionNameExtractor' describe('authFunctionNameExtractor', () => { const dummyLogging = (arrayStore) => (message) => { arrayStore.push(message) } describe('Unsupported auth method', () => { const unsupportedAuthTest = (authorizer, expectedWarningMessage) => () => { const endpoint = { authorizer } const logStorage = [] const result = authFunctionNameExtractor( endpoint, dummyLogging(logStorage), ) expect(result.unsupportedAuth).toEqual(true) expect(logStorage.length).toEqual(1) expect(logStorage[0]).toEqual(expectedWarningMessage) } describe('authorizer is a string', () => { test( 'aws_iam', unsupportedAuthTest( 'aws_iam', 'WARNING: Serverless Offline does not support the AWS_IAM authorization type', ), ) test( 'AWS_IAM', unsupportedAuthTest( 'AWS_IAM', 'WARNING: Serverless Offline does not support the AWS_IAM authorization type', ), ) test( 'AwS_IaM', unsupportedAuthTest( 'AwS_IaM', 'WARNING: Serverless Offline does not support the AWS_IAM authorization type', ), ) }) describe('authorizer is an object', () => { test( 'type: aws_iam', unsupportedAuthTest( { type: 'aws_iam' }, 'WARNING: Serverless Offline does not support the AWS_IAM authorization type', ), ) test( 'type: AWS_IAM', unsupportedAuthTest( { type: 'AWS_IAM' }, 'WARNING: Serverless Offline does not support the AWS_IAM authorization type', ), ) test( 'type: AwS_IaM', unsupportedAuthTest( { type: 'AwS_IaM' }, 'WARNING: Serverless Offline does not support the AWS_IAM authorization type', ), ) test( 'arn is specified', unsupportedAuthTest( { arn: 'anArnValue' }, 'WARNING: Serverless Offline does not support non local authorizers (arn): anArnValue', ), ) test( 'authorizerId is specified', unsupportedAuthTest( { authorizerId: 'anAuthorizerId' }, 'WARNING: Serverless Offline does not support non local authorizers (authorizerId): anAuthorizerId', ), ) test('missing name attribute', () => { unsupportedAuthTest( {}, 'WARNING: Serverless Offline supports local authorizers but authorizer name is missing', ) }) }) describe('authorizer is not a string or oject', () => { test( 'a number', unsupportedAuthTest( 4, 'WARNING: Serverless Offline supports only local authorizers defined as string or object', ), ) test( 'a boolean', unsupportedAuthTest( true, 'WARNING: Serverless Offline supports only local authorizers defined as string or object', ), ) }) }) describe('supported auth method', () => { const supportedAuthTest = (authorizer, expectedAuthorizerName) => () => { const endpoint = { authorizer } const logStorage = [] const result = authFunctionNameExtractor( endpoint, dummyLogging(logStorage), ) expect(result.unsupportedAuth).toEqual(undefined) expect(logStorage.length).toEqual(0) expect(result.authorizerName).toEqual(expectedAuthorizerName) } describe('authorizer is a string', () => { test( 'is a string anAuthorizerName', supportedAuthTest('anAuthorizerName', 'anAuthorizerName'), ) }) describe('authorizer is an object', () => { test( 'named anAuthorizerName', supportedAuthTest({ name: 'anAuthorizerName' }, 'anAuthorizerName'), ) }) }) })
c0dab3708f25c2b2ac40de0d107112d05984d4eb
TypeScript
joeldatabox/mr-meeseeks
/projects/mr-meeseeks/src/lib/sr-utils/logger/sr-logger.ts
2.78125
3
import {Level, Log, Logger} from "ng2-logger/browser"; import {isEmpty, isString} from "../commons/sr-commons.model"; export class SrLogg { private readonly _data: SrLoggData; private readonly _error: SrLoggError; private readonly _info: SrLoggInfo; private readonly _warn: SrLoggWarn; constructor(private value: string | Object) { this._data = SrLoggData.of(value); this._error = SrLoggError.of(value); this._info = SrLoggInfo.of(value); this._warn = SrLoggWarn.of(value); } public static of(value: string | Object): SrLogg { return new SrLogg(value); } public setProductionMode(value: boolean): void { this._data.setProductionMode(value); this._error.setProductionMode(value); this._info.setProductionMode(value); this._warn.setProductionMode(value); } public d(message: string, ...otherParams: any[]): SrLogg { this._data.data(message, otherParams); return this; } public e(message: string, ...otherParams: any[]): SrLogg { this._error.error(message, otherParams); return this; } public i(message: string, ...otherParams: any[]): SrLogg { this._info.info(message, otherParams); return this; } public w(message: string, ...otherParams: any[]): SrLogg { this._warn.warn(message, otherParams); return this; } } class SrLocalLog { private readonly localLog: Logger; constructor(private prefix: string, private value: string | Object, private color: string, private level: Level) { let label: string = ""; if (isString(value)) { label = value as string; } else { label = (value as Object).constructor.name; } this.localLog = Log.create(this.prefix + label, this.level); this.localLog.color = this.color; } public setProductionMode(value: boolean): void { this.localLog.setProductionMode(value); } protected send(message: string, ...otherParams: any[]): SrLocalLog { (isEmpty(otherParams)) ? this.localLog.data(message) : this.localLog.data(message, otherParams); return this; } } export class SrLoggData extends SrLocalLog { constructor(value: string | Object) { super("d_", value, "#16c6d0", Level.DATA); } public static of(value: string | Object): SrLoggData { return new SrLoggData(value); } public data(message: string, ...otherParams: any[]): SrLoggData { this.send(message, otherParams); return this; } } export class SrLoggError extends SrLocalLog { constructor(value: string | Object) { super("e_", value, "#e26a6a", Level.ERROR); } public static of(value: string | Object): SrLoggError { return new SrLoggError(value); } public error(message: string, ...otherParams: any[]): SrLoggError { this.send(message, otherParams); return this; } } export class SrLoggInfo extends SrLocalLog { constructor(value: string | Object) { super("i_", value, "#92a2b9", Level.INFO); } public static of(value: string | Object): SrLoggInfo { return new SrLoggInfo(value); } public info(message: string, ...otherParams: any[]): SrLoggInfo { this.send(message, otherParams); return this; } } export class SrLoggWarn extends SrLocalLog { constructor(value: string | Object) { super("w_", value, "#fcb66c", Level.WARN); } public static of(value: string | Object): SrLoggWarn { return new SrLoggWarn(value); } public warn(message: string, ...otherParams: any[]): SrLoggWarn { this.send(message, otherParams); return this; } }
e595e73d9049617df1862cb9185663a9218c1a85
TypeScript
eliasvargasloyola/nodejs-typeorm-test
/src/index.ts
2.578125
3
import "reflect-metadata"; import { createConnection, getConnectionOptions } from "typeorm"; import * as express from "express"; import { Request, Response } from "express"; import * as bodyParser from "body-parser"; import Routes from "./routes"; (async () => { // create express app const app = express(); app.use(bodyParser.json()); // register express routes from defined application routes Routes.forEach(route => { (app as any)[route.method](route.route, (req: Request, res: Response, next: Function) => { const result = (new (route.controller as any))[route.action](req, res, next); if (result instanceof Promise) { result.then(result => result !== null && result !== undefined ? res.send(result) : undefined); } else if (result !== null && result !== undefined) { res.json(result); } }); }); const dbOptions = await getConnectionOptions(process.env.NODE_ENV); console.log(`The database connection is ${ JSON.stringify(dbOptions) }`); // Name always have to be default, this is because TypeORM configs get always the connection named default await createConnection({ ...dbOptions, name: 'default' }); console.log("Database Connected"); // start express server app.listen(3000); console.log("Express server has started on port 3000. Open http://localhost:3000/users to see results"); })();
a2045ae2a50f0fc963572aebeabd577dd9e76c4b
TypeScript
EdwardIrby/speed-up-psds-build
/packages/util/src/__specs__/pick.spec.ts
2.8125
3
import { pick } from '../index' describe('#pick', () => { it('returns an object', () => { const obj = { name: 'David Bowie' } const result = pick(obj, []) expect(result).toBeInstanceOf(Object) }) it('picks fields from object', () => { const obj = { alias: 'Goblin King', job: 'singer/songwriter', name: 'David Bowie' } const result = pick(obj, ['name', 'job']) expect(result).toEqual({ job: obj.job, name: obj.name }) }) it('handles missing fields', () => { const obj: { alias: string; job?: string; name: string } = { alias: 'Goblin King', name: 'David Bowie' } const result = pick(obj, ['name', 'job']) expect(result).toEqual({ name: obj.name }) }) })
a8a2924be81b05d58f2208c3e556af18e35468a7
TypeScript
renzen/Mean-App
/src/app/event.service.ts
2.609375
3
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { Observable, of } from 'rxjs'; import { catchError, tap } from 'rxjs/operators'; import { MessageService } from './message.service'; @Injectable({ providedIn: 'root' }) export class EventService { // http://localhost:3000/api/register private _eventsUrl = 'http://localhost:3000/api/events'; private _specialEventsUrl = 'http://localhost:3000/api/special'; constructor(private http: HttpClient, private messageService: MessageService) { } getEvents() { // var httpOptions = { // headers: new HttpHeaders({ 'Content-Type': 'application/json', // 'accept': 'application/json', // 'Authorization' : 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWJqZWN0IjoiNWMzNDY2MTY0OTIzYjM3MGQ4NDVjNGYxIiwiaWF0IjoxNTQ3MjA2ODM0fQ._am57em5BF8HAn1F2K-_BbgQPXtpW3gRf8W2q6Xi8RE' // }) // }; return this.http.get<any>(this._eventsUrl).pipe(tap(_ => this.log(`Get add ons = ${this._eventsUrl}`)), catchError(this.handleError<any>('GetEvents'))); } getSpecialEvents() { // var httpOptions = { // headers: new HttpHeaders({  // 'Content-Type': 'application/json', // 'accept': 'application/json', // 'Authorization' : ' Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWJqZWN0IjoiNWMzNDY2MTY0OTIzYjM3MGQ4NDVjNGYxIiwiaWF0IjoxNTQ3MjA2ODM0fQ._am57em5BF8HAn1F2K-_BbgQPXtpW3gRf8W2q6Xi8RE' // }) // }; return this.http.get<any>(this._specialEventsUrl).pipe(tap(_ => this.log(`Get add ons = ${this._specialEventsUrl}`)), catchError(this.handleError<any>('GetSpecialEvents'))); } //Success handler private extractData(response: Response){ if(response.status < 200 || response.status >= 300){ throw new Error(`Bad response status: ${response.status}`); } return response.json(); } /** Log a HeroService message with the MessageService */ private log(message: string) { this.messageService.add('Data Service: ' + message); } /** * Handle Http operation that failed. * Let the app continue. * @param operation - name of the operation that failed * @param result - optional value to return as the observable result */ private handleError<T> (operation = 'operation', result?: T) { return (error: any): Observable<T> => { // TODO: send the error to remote logging infrastructure console.error(error); // log to console instead // TODO: better job of transforming error for user consumption this.log(`${operation} failed: ${error.message}`); // Let the app keep running by returning an empty result. return of(result as T); }; } }
ae8f16169dde14b33916fcf63518345876ac7c72
TypeScript
raychangrhj/mua
/src/app/questions/shared/ngrx/reducers/navigation.reducer.ts
2.78125
3
import * as NavigationActions from '../actions/navigation.action'; import { createFeatureSelector, createSelector } from '@ngrx/store'; export type Action = NavigationActions.ALL; export interface NavigationState { sections: NavigationSectionState[] } export interface NavigationSectionState { id: number; title: string; baseLink: string[]; complete: boolean; active: boolean; required: boolean; } export const initialNavigationState: NavigationState = { sections: [ { id: 10, title: 'Personal Information', baseLink: ['/welcome'], complete: false, active: true, required: true }, { id: 20, title: 'Loan Details', baseLink: ['/mortgage-intent'], complete: false, active: false, required: true }, { id: 30, title: 'Primary Borrower Income', baseLink: ['/income'], complete: false, active: false, required: true }, { id: 40, title: 'Primary Borrower Assets', baseLink: ['/assets'], complete: false, active: false, required: true }, { id: 50, title: 'Questions we must ask', baseLink: ['/required-questions'], complete: false, active: false, required: true }, { id: 60, title: 'Co-Borrower Personal Information', baseLink: ['/co-borrower/welcome'], complete: false, active: false, required: false }, { id: 80, title: 'Co-Borrower Income', baseLink: ['/co-borrower/income'], complete: false, active: false, required: false }, { id: 90, title: 'Co-Borrower Assets', baseLink: ['/co-borrower/assets'], complete: false, active: false, required: false }, { id: 100, title: 'Co-Borrower questions we must ask', baseLink: ['/co-borrower/required-questions'], complete: false, active: false, required: false }, { id: 200, title: 'Co-Borrower Inquiry', baseLink: ['/co-borrower-inquiry'], complete: false, active: false, required: true }, { id: 300, title: 'Application Complete', baseLink: ['/confirm-submission'], complete: false, active: false, required: true } ] }; export function reducer(state: NavigationState = initialNavigationState, action: Action) { switch (action.type) { case NavigationActions.COMPLETE_SECTION: { const payload = (action as NavigationActions.NavigationCompleteSectionAction).payload; const sections = []; state.sections.forEach((section: NavigationSectionState) => { sections.push(section.id === payload ? Object.assign({}, section, { complete: true }) : section ); }); return { sections }; } case NavigationActions.ACTIVATE_SECTION: { const payload = (action as NavigationActions.NavigationActivateSectionAction).payload; const sections = []; state.sections.forEach((section: NavigationSectionState) => { sections.push(section.id === payload ? Object.assign({}, section, { active: true }) : Object.assign({}, section, { active: false }) ); }); return { sections }; } case NavigationActions.SECTIONS_UPDATE: { const payload = (action as NavigationActions.NavigationSectionsUpdateAction).payload; const sections = []; state.sections.forEach(currentSection => { const section = Object.assign({}, currentSection); if (section.id === 60 || section.id === 80 || section.id === 90 || section.id === 100) { // co-borrower sections section.required = payload !== 'borrower'; } else { // borrower sections section.required = payload === 'borrower'; } sections.push(section); }); return { sections } } default: { return state; } } } export const getNavigationState = createFeatureSelector<NavigationState>('navigation'); export const getNavigationSectionsState = createSelector( getNavigationState, (state: NavigationState) => state && state.sections ); export const getNavigationActiveSectionState = createSelector( getNavigationSectionsState, (sections: NavigationSectionState[]) => sections.find(section => section.active) ); export const getNavigationActiveSectionTitleState = createSelector( getNavigationSectionsState, (sections: NavigationSectionState[]) => { const active = sections.find(section => section.active); return active && active.title ? active.title : null; } ); export const getNavigationActiveSectionIdState = createSelector( getNavigationSectionsState, (sections: NavigationSectionState[]) => { const active = sections.find(section => section.active); return active && active.id || null; } ); export const getNavigationPillsState = createSelector( getNavigationSectionsState, (sections: NavigationSectionState[]) => { const result = []; sections .filter(section => section.required) .forEach(section => result.push(section.complete ? 'solid' : 'empty')); return result; } );
1a67922996024a6ce1ba3c1380cbe9c459794a9a
TypeScript
AuxilityKiev/youhire-backend
/server/src/db/entities/addition-value.ts
2.8125
3
import { Entity, PrimaryGeneratedColumn, Column, ManyToOne } from "typeorm" import Addition from "./addition" @Entity() export default class AdditionValue { @PrimaryGeneratedColumn() public id: number @Column({ nullable: true }) public name: string @Column({ nullable: true }) public index: number @ManyToOne(type => Addition, addition => addition.values) public addition: Addition constructor(name: string, index: number) { this.name = name this.index = index } }
1a8787c419c4ee3efb32f0cbd0e75b6217f8f6a9
TypeScript
floukeiei/angular-memory-leak-demo
/src/app/sub.component.ts
2.640625
3
import { Component, OnDestroy } from '@angular/core'; import { BehaviorSubject, Subject } from 'rxjs'; import { DummyService } from './dummy.service'; import { publish, publishBehavior, publishLast, publishReplay, shareReplay, tap, takeUntil } from 'rxjs/operators'; @Component({ selector:'app-sub', template: 'mega {{rand}}' }) export class SubComponent implements OnDestroy { rand = Math.random(); rand2 = 0; subject = new BehaviorSubject(42); arr = []; /** Emits when the component is destroyed */ private destroy$: Subject<void> = new Subject<void>(); constructor(private dummyService: DummyService) { for (let i = 0; i < 100000; ++i) { this.arr.push(Math.random()); } // no leak - component is cleaned up // this.subject.subscribe(); // no leak - component is cleaned up // this.subject.subscribe(() => {const blub = 34;}); // no leak - component is cleaned up // this.subject.subscribe(() => this.rand2 = 33); // small leak - empty anonymous function remains in heap // this.dummyService.behavior$.subscribe(); // FIXED // this.dummyService.behavior$.pipe(takeUntil(this.destroy$)).subscribe(); // small leak - small anonymous function remains in heap // this.dummyService.behavior$.subscribe(() => {const blub = 34;}); // FIXED // this.dummyService.behavior$.pipe(takeUntil(this.destroy$)).subscribe(() => {}); // (!) large leak - anonymous function references the component, thus the component stays in memory // this.dummyService.behavior$.subscribe(() => this.rand2 = 33); // FIXED // this.dummyService.behavior$.pipe(takeUntil(this.destroy$)).subscribe(() => this.rand2 = 33); // no leak // this.dummyService.behavior$.pipe(tap(() => this.rand2 = 44), publish()).subscribe(() => this.rand2 = 33); // no leak // this.dummyService.behavior$.pipe(tap(() => this.rand2 = 44), publishBehavior(3), takeUntil(this.destroy$)).subscribe(() => this.rand2 = 33); // no leak // this.dummyService.behavior$.pipe(tap(() => this.rand2 = 44), publishLast(), takeUntil(this.destroy$)).subscribe(() => this.rand2 = 33); // no leak // this.dummyService.behavior$.pipe(tap(() => this.rand2 = 44), publishReplay(), takeUntil(this.destroy$)).subscribe(() => this.rand2 = 33); // (!) large leak - the subscription from the shareReplay operator to the source is never unsubscribed, thus the component stays in the heap this.dummyService.behavior$.pipe(tap(() => this.rand2 = 44), shareReplay(1), takeUntil(this.destroy$)).subscribe(() => this.rand2 = 33); // FIXED // this.dummyService.behavior$.pipe(tap(() => this.rand2 = 44), takeUntil(this.destroy$), shareReplay(1), takeUntil(this.destroy$)).subscribe(() => this.rand2 = 33); // no leak // this.dummyService.behavior$.pipe(tap(() => this.rand2 = 44), shareReplay({bufferSize: 1, refCount: true})).subscribe(() => this.rand2 = 33); // (!) large leak - the component reference in the service is not cleaned up, thus the component stays in memory // this.dummyService.register(this); } ngOnDestroy(): void { this.destroy$.next(); this.destroy$.complete(); } }
c60d172767d94545445955984b33b6f42c0c1dd6
TypeScript
kkguan/weapp-base
/typings/wx/lib.wx.component.d.ts
2.84375
3
/** * author: alan * date: 2019.01.09 * version: 1.0.0 */ declare namespace Component { interface ComponentInstanceBaseProps<D extends IAnyObject = any> { properties?: { type: any, value?: any, observer?() : void } options?: any releations?: any externalClasses?: string[] data?: D setData?<K extends keyof D>( /** 这次要改变的数据 * * 以 `key: value` 的形式表示,将 `this.data` 中的 `key` 对应的值改变成 `value`。 * * 其中 `key` 可以以数据路径的形式给出,支持改变数组中的某一项或对象的某个属性,如 `array[2].message`,`a.b.c.d`,并且不需要在 this.data 中预先定义。 */ data: D | Pick<D, K> | IAnyObject, /** setData引起的界面更新渲染完毕后的回调函数,最低基础库: `1.5.0` */ callback?: () => void ): void behaviors?: string[] } interface ComponentInstance<D extends IAnyObject = any, T extends IAnyObject = any> extends ComponentInstanceBaseProps<D> { methods?: IAnyObject created?(): void attached?(): void ready?(): void moved?(): void detached?(): void lifetimes?: { created?(): void attached?(): void ready?(): void moved?(): void detached?(): void show?(): void hide?(): void resize?(size: IAnyObject): void } error?(err: IAnyObject): void } interface ComponentConstructor { <D extends IAnyObject, T extends IAnyObject & ComponentInstance>( options: ComponentInstance<D, T> & T ): void } } declare const Component: Component.ComponentConstructor
cedbf14f0e73aeed09a756a2507b541969104729
TypeScript
eric1234463/image-post
/client/application/store/user/actions/loginUser.ts
2.6875
3
import { IUser } from "../../../../interfaces/api/user"; const LOGIN_USER_REQUEST = "LOGIN_USER_REQUEST"; const LOGIN_USER_SUCCEEDED = "LOGIN_USER_SUCCEEDED"; const LOGIN_USER_FAILED = "LOGIN_USER_FAILED"; export interface LoginUserRequestAction { type: typeof LOGIN_USER_REQUEST; payload: IUser } export interface LoginUserSucceededAction { type: typeof LOGIN_USER_SUCCEEDED; payload: IUser; } export interface LoginUserFailedAction { type: typeof LOGIN_USER_FAILED; payload: string; } type LoginUserActionTypes = | LoginUserRequestAction | LoginUserSucceededAction | LoginUserFailedAction; export default LoginUserActionTypes;
3b0d8a5ab5a58719f9e9622375f95699e6248a5b
TypeScript
AndriiMSN/Test-React-TS
/src/js/components/LocalStorage.ts
2.734375
3
class LocalStorage { readonly counter: string = "60" setUserAndVerification(isUser: boolean, isVerified: boolean) { localStorage.setItem('log', '' + isUser) localStorage.setItem('ver', '' + isVerified) } setCounterAndDate(counter: string = this.counter) { localStorage.setItem('lastCounter', counter) localStorage.setItem('lastDate', new Date().getTime().toString()) } } export const SetLocalStorage = new LocalStorage()
76aed739d68aed734c98676925dcf177f5504f87
TypeScript
jivkopiskov/GamersUnited
/GamersUnited/ClientApp/src/app/posts/votes/votes.component.ts
2.609375
3
import { Component, Input, OnInit } from '@angular/core'; import { PostsService } from 'src/app/core/posts.service'; import { IVote, VoteType } from '../Interfaces/IVote'; @Component({ selector: 'app-votes', templateUrl: './votes.component.html', styleUrls: ['./votes.component.css'] }) export class VotesComponent implements OnInit { constructor(private postsService: PostsService) { } @Input() public vote: IVote; @Input() public votesCount: number @Input() public postId: string; @Input() public commentId: string; upvoteDisabled: boolean; downvoteDisabled: boolean; ngOnInit(): void { this.upvoteDisabled = this.vote?.voteType == VoteType.upvote; this.downvoteDisabled = this.vote?.voteType == VoteType.downvote; //hack: upon first vote, it was showing 01 instead of 1, as it thought it was string. this.votesCount = +this.votesCount; } async upvote() { await this.postsService.vote(this.postId, this.commentId, VoteType.upvote).toPromise(); this.upvoteDisabled = !this.upvoteDisabled; if (this.upvoteDisabled) { this.votesCount += 1; } else { this.votesCount -= 1; } if (this.downvoteDisabled) { this.downvoteDisabled = !this.downvoteDisabled this.votesCount += 1; } } async downvote() { await this.postsService.vote(this.postId, this.commentId, VoteType.downvote).toPromise(); this.downvoteDisabled = !this.downvoteDisabled; if (this.downvoteDisabled) { this.votesCount -= 1; } else { this.votesCount += 1; } if (this.upvoteDisabled) { this.upvoteDisabled = !this.upvoteDisabled this.votesCount -= 1; } } }
8f4ac14e68e8ab371cd4aab1affc44b5b987f877
TypeScript
NavenduDuari/Scaffoldzoi-Inc
/packages/client/src/Containers/App/reducer.ts
2.671875
3
import { Action, UserDetailsI } from '../../utils/types'; import { ActionTypes, StoreStateI, TokenStatus } from './types'; const INITIAL_STATE: StoreStateI = { token: '', tokenStatus: TokenStatus.YetToFetch, loggedInUser: {} as UserDetailsI, sellers: [], }; const appReducer = (state = INITIAL_STATE, action: Action<ActionTypes>) => { switch (action.type) { case ActionTypes.ON_LOAD_LOCAL_TOKEN: return { ...state, token: action.payload?.token, tokenStatus: TokenStatus.Fetched, loggedInUser: action.payload?.loggedInUser || {}, }; case ActionTypes.ON_RECEIVE_ALL_SELLERS: return { ...state, sellers: action.payload?.sellers || [], }; default: return state; } }; export default appReducer;
30ded10c5a0cd2928629856d8294b1eb5e0a9533
TypeScript
michaelgriscom/LeaderMode
/src/test/KeyBindingTree.test.ts
2.890625
3
import { expect } from 'chai'; import { IKeybinding } from '../Configuration'; import { KeybindingTree } from '../KeybindingTree'; suite("keybindingTree Tests", function () { const letters: string[] = ["a", "b", "c", "d", "e", "f", "g", "h"]; test("empty keybindings", () => { const keybindingTree = new KeybindingTree([]); const options = keybindingTree.getTraverser().getAllowedKeys(); expect(options.length).to.equal(0); }); test("flat command tree", () => { const keybindings: IKeybinding[] = letters.map((key) => { return { keySequence: [key], command: `${key}.command`, label: `${key}.label`, args: [`${key}.arg`] }; }); const keybindingTree = new KeybindingTree(keybindings); const traverser = keybindingTree.getTraverser(); expect(traverser.isTerminal()).to.be.false; const options = traverser.getAllowedKeys(); expect(options.length).to.equal(keybindings.length); options.forEach((option, index) => { expect(option.key).to.equal(keybindings[index].keySequence[0]); expect(option.keybinding).to.deep.equal(keybindings[index]); const traverser = keybindingTree.getTraverser(); traverser.selectKey(option.key); expect(traverser.isTerminal()).to.be.true; expect(traverser.getTerminalKeybinding()).to.be.deep.equal(keybindings[index]); }); }); test("honors casing", () => { const littleAKeybinding: IKeybinding = { keySequence: ["a"], label: "littleALabel", command: "littleACommand" }; const bigAKeybinding: IKeybinding = { keySequence: ["A"], label: "bigALabel", command: "bigACommand" }; const littleBKeybinding: IKeybinding = { keySequence: ["b"], label: "littleBLabel", command: "littleBCommand" }; const bigBKeybinding: IKeybinding = { keySequence: ["B"], label: "bigBLabel", command: "bigBCommand" }; const keybindings: IKeybinding[] = [ littleBKeybinding, bigBKeybinding, bigAKeybinding, littleAKeybinding ]; const keybindingTree = new KeybindingTree(keybindings); const rootOptions = keybindingTree.getTraverser().getAllowedKeys(); expect(rootOptions[0].keybinding).to.deep.equal(littleAKeybinding); expect(rootOptions[0].key).to.equal("a"); expect(rootOptions[1].keybinding).to.deep.equal(bigAKeybinding); expect(rootOptions[1].key).to.equal("A"); expect(rootOptions[2].keybinding).to.deep.equal(littleBKeybinding); expect(rootOptions[2].key).to.equal("b"); expect(rootOptions[3].keybinding).to.deep.equal(bigBKeybinding); expect(rootOptions[3].key).to.equal("B"); }); test("alphabetizes tree by key sequence", () => { const aKeybinding: IKeybinding = { keySequence: ["a"], label: "ooooo" }; const aaKeybinding: IKeybinding = { keySequence: ["a", "a"], command: "yyyyy", label: "uuuuu" }; const abKeybinding: IKeybinding = { keySequence: ["a", "b"], command: "yyyyy", label: "iiiiiiii" }; const bKeybinding: IKeybinding = { keySequence: ["b"], label: "a" }; const baKeybinding: IKeybinding = { keySequence: ["b", "a"], label: "eeee", command: "wwww" }; const bbKeybinding: IKeybinding = { keySequence: ["b", "b"], label: "xxxx", command: "zzzz" }; const keybindings: IKeybinding[] = [bKeybinding, abKeybinding, baKeybinding, aKeybinding, bbKeybinding, aaKeybinding]; const keybindingTree = new KeybindingTree(keybindings); const rootOptions = keybindingTree.getTraverser().getAllowedKeys(); expect(rootOptions[0].keybinding).to.deep.equal(aKeybinding); expect(rootOptions[0].key).to.equal("a"); expect(rootOptions[1].keybinding).to.deep.equal(bKeybinding); expect(rootOptions[1].key).to.equal("b"); const aTraverser = keybindingTree.getTraverser(); aTraverser.selectKey("a"); const aOptions = aTraverser.getAllowedKeys(); expect(aOptions[0].keybinding).to.deep.equal(aaKeybinding); expect(aOptions[0].key).to.equal("a"); expect(aOptions[1].keybinding).to.deep.equal(abKeybinding); expect(aOptions[1].key).to.equal("b"); const bTraverser = keybindingTree.getTraverser(); bTraverser.selectKey("b"); const bOptions = bTraverser.getAllowedKeys(); expect(bOptions[0].keybinding).to.deep.equal(baKeybinding); expect(bOptions[0].key).to.equal("a"); expect(bOptions[1].keybinding).to.deep.equal(bbKeybinding); expect(bOptions[1].key).to.equal("b"); }); test("deep command tree", () => { const keybindings: IKeybinding[] = [{ keySequence: letters, command: "keyCommand", label: "keyLabel", args: ["keyArgs"] }]; const keybindingTree = new KeybindingTree(keybindings); const traverser = keybindingTree.getTraverser(); expect(traverser.isTerminal()).to.be.false; keybindings[0].keySequence.forEach((key: string, index: number) => { const options = traverser.getAllowedKeys(); expect(options.length).to.equal(1); expect(options[0].key).to.equal(key); if (index < keybindings[0].keySequence.length - 1) { expect(options[0].keybinding).to.be.undefined; } else { expect(options[0].keybinding).to.deep.equal(keybindings[0]); } traverser.selectKey(key); }); expect(traverser.getTerminalKeybinding()).to.equal(keybindings[0]); expect(traverser.isTerminal(), "should have reached the command").to.be.true; }); });
391292cfbd63323bade7512bd495e7738f3140a6
TypeScript
tadakun8/mail-stream
/lambda/module.ts
2.8125
3
import * as AWS from 'aws-sdk'; import { table } from 'console'; import * as fs from 'fs'; import * as nodemailer from 'nodemailer' import { Readable } from 'stream' const stringify = require('csv-stringify/lib/sync') /** * S3バケットから指定したオブジェクトをダウンロードする関数 * @param s3 s3クライアント * @param bucket_name ダウンロードするオブジェクトが格納されているバケット名 * @param key_name ダウンロードするオブジェクトキー * @param donwload_path ダウンロード先 */ export const downloadObject = async (s3: AWS.S3, bucket_name: string, key_name: string, donwload_path: string) => { try{ console.log('Start download object !') // ファイルをダウンロードするバケットの設定 const paramGetObject: AWS.S3.Types.GetObjectRequest = { Bucket: bucket_name, Key: key_name } // 書き込み先のストリームを生成 const dest = fs.createWriteStream(donwload_path) console.log('Download object ...') // S3バケットからオブジェクトを取得 const object = await s3.getObject(paramGetObject).promise() // 取得オブジェクトのストリームを生成 const stream = Readable.from([object.Body?.toString()]) // 送信先に保存 stream.pipe(dest) console.log('Success Download !!') } catch (err) { console.log(err) throw err; } } /** * 指定したファイル添付しメールを送信する関数 * @param ses sesクライアント * @param from 送信元メールアドレス * @param to 送信先メールアドレス * @param subject 件名 * @param text メール本文 * @param attachment_file_name 添付ファイルの名前(どのようなファイル名で添付するか) * @param attachment_file_path 添付するファイルのファイルパス */ export const sendEmail = async (ses: AWS.SES, from: string, to: string, subject: string, text: string, attachment_file_name: string, attachment_file_path: string) => { try{ console.log("Start end email ! ") // SESをnodemailerでラップ const transporter = nodemailer.createTransport({ SES: ses }); // メールの設定 const mailOption: nodemailer.SendMailOptions = { from: from, to: to, subject: subject, text: text, attachments: [{ filename: attachment_file_name, path: attachment_file_path, }] }; console.log('Send email ...') // メールの送信 await transporter.sendMail(mailOption) console.log('Success send email !'); } catch(err) { console.log(err) throw err; } } /** * Dynamodbからデータを全件取得し、取得結果を指定したファイルに保存する関数 * @param dynamodb dynamodbクライアント * @param table_name 操作するテーブル名 * @param output_file_path 結果を保存するファイルパス */ export const scanDynamodb = async (dynamodb: AWS.DynamoDB.DocumentClient, table_name: string, output_file_path: string) => { try { console.log('Start scan dynamodb !') // dynamodbのクエリパラメータの定義 const queryParam: AWS.DynamoDB.DocumentClient.QueryInput = { TableName: table_name } console.log('scan dynamodb ...') // dynamodbを全件取得 const data = await dynamodb.scan(queryParam).promise() // csv変換の設定 const csvParam = { header: true, columns: ['id', 'content', 'good'] } // 取得データをcsv形式に変換 const csvData = stringify(data.Items, csvParam) // 取得データをローカルに一時保存 fs.writeFileSync(output_file_path, csvData) console.log('Success scan dynamodb !') } catch(err) { console.log(err) throw err; } } /** * 指定したファイルをS3バケットにアップロードする関数 * @param s3 s3クライアント * @param bucket_name アップロード先のバケット名 * @param key_name アップロードファイル名(どのようなキーでアップロードするか) * @param upload_file_path アップロードするファイルのファイルパス */ export const uploadFile = async (s3: AWS.S3, bucket_name: string, key_name: string, upload_file_path: string) => { try { console.log('Start upload file !') // S3バケットにアップロードするときのパラメータを定義 const uploadParam: AWS.S3.Types.PutObjectRequest = { Bucket: bucket_name, Key: key_name, Body: fs.createReadStream(upload_file_path), ContentType: 'text/csv' } // await s3.putObject(uploadParam).promise() } catch(err) { console.log(err) throw err; } } /** * dynamodbにデータを書き込む関数 (データはテストデータを使用) * @param dynamodb dynamodbクライアント * @param table_name テーブル名 */ export const writeDynamodb = async (dynamodb: AWS.DynamoDB.DocumentClient, table_name: string) => { try { console.log('Start write dynamodb !') const testData = [ {id: 1, content: 'こんにちは', good: 0}, {id: 2, content: 'おはよう', good: 3}, {id: 3, content: 'おやすみ', good: 3}, {id: 4, content: 'good night', good: 9}, {id: 5, content: 'さようなら', good: 100}, {id: 11, content: 'こんにちは', good: 0}, {id: 12, content: 'おはよう', good: 3}, {id: 13, content: 'おやすみ', good: 3}, {id: 14, content: 'good night', good: 9}, {id: 15, content: 'さようなら', good: 100}, {id: 21, content: 'こんにちは', good: 0}, {id: 22, content: 'おはよう', good: 3}, {id: 23, content: 'おやすみ', good: 3}, {id: 24, content: 'good night', good: 9}, {id: 25, content: 'さようなら', good: 100}, {id: 31, content: 'こんにちは', good: 0}, {id: 32, content: 'おはよう', good: 3}, {id: 33, content: 'おやすみ', good: 3}, {id: 34, content: 'good night', good: 9}, {id: 35, content: 'さようなら', good: 100}, {id: 41, content: 'こんにちは', good: 0}, {id: 42, content: 'おはよう', good: 3}, {id: 43, content: 'おやすみ', good: 3}, {id: 44, content: 'good night', good: 9}, {id: 45, content: 'さようなら', good: 100}, {id: 51, content: 'こんにちは', good: 0}, {id: 52, content: 'おはよう', good: 3}, {id: 53, content: 'おやすみ', good: 3}, {id: 54, content: 'good night', good: 9}, {id: 55, content: 'さようなら', good: 100}, ]; // Dynamodbの仕様上、書き込みデータの最大は25個という制約がある // 書き込みデータが25個になるように調整 const chunkedTestData = chunk(testData, 25) // dynamodbのクエリを作成 const params: AWS.DynamoDB.DocumentClient.BatchWriteItemInput[] = chunkedTestData.map((testdata: object[]) => { return makeBatchWriteItemInput(table_name, testdata) }) console.log("Write dynamodb ...") // dynamodbへデータの書き込み for(const param of params) { await dynamodb.batchWrite(param).promise() } console.log("Success write dynamodb !") } catch(err) { console.log(err) throw err; } } /** * dynamodbのbatchWrite()を使用するときの引数を作成する関数 * @param table_name テーブル名 * @param data 書き込むデータ */ const makeBatchWriteItemInput = (table_name: string, data: object[]): AWS.DynamoDB.DocumentClient.BatchWriteItemInput => { // 書き込むデータごとにリクエストを生成 const writeRequests = data.map((item: object): AWS.DynamoDB.DocumentClient.WriteRequest => { return { PutRequest: { Item: item } } }) // どのテーブルに書き込むかという最終的なリクエストを生成 const batchWriteItemInput: AWS.DynamoDB.DocumentClient.BatchWriteItemInput = { RequestItems: { [table_name]: writeRequests } } return batchWriteItemInput } /** * 配列を指定の個数で区切る関数 * (lodash.chunk()をネイティブコードで実装した関数) * https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore#_chunk * @param input 対象配列 * @param size 指定サイズ */ const chunk = (input: any[], size: number) => { return input.reduce((arr, item, idx) => { return idx % size === 0 ? [...arr, [item]] : [...arr.slice(0, -1), [...arr.slice(-1)[0], item]]; }, []); }; // const processAll = async () => { // const dynamodb = new AWS.DynamoDB.DocumentClient({region: 'ap-northeast-1'}) // const table = "mail-stream-sample" // await writeDynamodb(dynamodb, "mail-stream-table") // await scanDynamodb(dynamodb, "mail-stream-table", "latest.csv") // } // processAll()
be7710b355f6b9cf20882ef78ec99f95428eeb34
TypeScript
RavivarmanPerinpanathan/web
/src/app/models/ChatMessage.ts
2.84375
3
import {User} from "./user"; import {Serialize} from "../interfaces/Serialize"; import {Chat} from "./chat"; export class ChatMessage implements Serialize<ChatMessage> { public id: number; public author: User; public chat: Chat; public message: string; public created_at: Date; public updated_at: Date; toString(): string { return `${this.author.username}: ${this.message} (${this.created_at.toLocaleString()})`; } deserialize(json: any): ChatMessage { this.id = json.id; this.message = json.message; this.created_at = new Date(json.created_at); this.updated_at = new Date(json.updated_at); this.author = new User().deserialize(json.author); this.chat = new Chat().deserialize(json.chat); return this; } }
ff6c9f7680354f3823398f37ceb3920925265e71
TypeScript
huhn511/iota.js
/packages/crypto/src/utils/arrayHelper.ts
3.390625
3
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 /** * Array helper methods. */ export class ArrayHelper { /** * Are the two array equals. * @param array1 The first array. * @param array2 The second array. * @returns True if the arrays are equal. */ public static equal(array1: ArrayLike<unknown> | undefined, array2: ArrayLike<unknown> | undefined): boolean { if (!array1 || !array2 || array1.length !== array2.length) { return false; } for (let i = 0; i < array1.length; i++) { if (array1[i] !== array2[i]) { return false; } } return true; } }
9ad9f2bb3d5b5c598d0c9bb4ab76363a66790201
TypeScript
NTSka/bot
/src/types/data.ts
2.734375
3
export type User = { id: string; username: string; } export type List = Array<User> export type Winners = { [key: string]: User; } export type Storage = { users: User[]; winners: Winners; } export type Top = { [key: string]: number }
8b99a57bb517da512f4e6d71dd60b9b5179e7fa6
TypeScript
benrosen/storytoy-cli
/src/functions/read-json-file/read-json-file.ts
3.40625
3
import { promises as fileSystem } from "fs"; /** * Parse a JSON file into a generically typed object. * * @param {string} path The path to the JSON file. * @returns {any} The object parsed from the JSON file. * * @todo {SHOULD} use generic return type instead of any */ export const readJsonFile = async <T>(path: string): Promise<T> => { try { return JSON.parse(await fileSystem.readFile(path, "utf8")) as T; } catch (error) { throw new Error(`Unable to read ${path}; ${error}`); } };
088a0e0b761057cd844d22be44b0c70dad7c0d39
TypeScript
tiagoarodrigues55/github-music-backend
/src/models/Follower.ts
2.578125
3
import { Model, Sequelize, DataTypes } from 'sequelize' const sequelize = new Sequelize('postgres://postgres:Tiago2003@localhost:5432/github-music'); class Follower extends Model{ public id!: number public user_id!: number public follow_id!: number | null public readonly createdAt!: Date; public readonly updatedAt!: Date; } Follower.init({ id: { type: DataTypes.INTEGER, // you can omit the `new` but this is discouraged autoIncrement: true, primaryKey: true, }, user_id: { type: DataTypes.INTEGER, allowNull: false, }, follow_id: { type: DataTypes.INTEGER, allowNull: true, } }, { sequelize, tableName: 'followers', }); export default Follower
52918dd28be86961ce3ca17d182759e1c53c1e0a
TypeScript
piku98/url_shortener
/src/models/urls.ts
2.8125
3
import { Connection, Schema, model, Document } from 'mongoose' export interface IURL extends Document { originalURL: string, uniqueCode: string, expiry: Date } export const URLSchema = new Schema({ originalURL: { type: String, required: true, unique: true, validate: { validator: (urlstring: string) => { let pattern = new RegExp("((http|https)://)(www.)?" + "[a-zA-Z0-9@:%._\\+~#?&//=]" + "{2,256}\\.[a-z]" + "{2,6}\\b([-a-zA-Z0-9@:%" + "._\\+~#?&//=]*)") return pattern.test(urlstring) }, message: 'invalid url' } }, uniqueCode: { type: String, required: true, unique: true }, expiry: { type: Date, required: true } }) export const URL = model<IURL>('url', URLSchema)
4e07d78aa13a4a3b8b9f8f0a2e3d38c2e744b132
TypeScript
jroets/simple-location-tracker-poc
/src/app/services/location-watcher.service.ts
2.734375
3
import { Injectable } from '@angular/core'; import { Geolocation, WatchPositionCallback } from '@capacitor/geolocation'; import { AppStateMonitor } from './app-state-monitor.service'; import * as EventEmitter from 'events'; /** * This is a singleton location watcher service. It encapsulates a single watcher. * Consumers simply register a callback. They don't need to worry about getting * the watcher started, or restarted, or any other management of it. * * The assumption is that we don't need multiple watchers. * * @todo Notify callbacks of changes to watcher status (starting, running, stopped) * @todo Consider implementing as an observable instead of callbacks * @todo Make the location options configurable at the app level * @todo Find easier/better way to monitor foreground/background transition */ @Injectable({ providedIn: 'root', }) export class LocationWatcherService { private watcherId: string; private callbacks: Map<number, WatchPositionCallback>; private options: PositionOptions; private nextId: number; private emitter: EventEmitter; constructor(private appStateMonitor: AppStateMonitor) { this.nextId = 1; this.callbacks = new Map(); // Default location options this.options = { timeout: 10000, enableHighAccuracy: true, maximumAge: 3600 } // Emitter for foreground/background events this.emitter = appStateMonitor.getEmitter(); // We don't get ngOnInit in service, so make our own init this.init(); } /** Initialize */ private init(): void { // Start the (one and only) watcher this.startInternalWatcher(); // We're going to restart whenever the app comes from the background // to deal with (what seems like) some quirks, like not detecting // a permission change. this.emitter.addListener("toForeground", this.onForeground.bind(this)); } /** * Tear down (angular will call this automatically) */ ngOnDestroy() { // Stop the watcher if it's running this.stopInternalWatcher(); } /** * Register a fn to be called with location updates * @param {WatchPositionCallback} callback - The callback fn * @returns {number} A unique id that can be used to deregister * @see deregister */ register(callback: WatchPositionCallback): number { const id = this.getUniqueId(); // Add the fn to the callbacks collection this.callbacks.set(id, callback); return id; } /** * Remove a registered callback from the watcher * @param {number} id - The id of the callback that was provided in the registration * @see register */ deregister(id: number): void { /** @todo Should we care about an unfound id? */ this.callbacks.delete(id); } /** * The callback that is called internally on location updates. * Forwards the location update to all registered callbacks. */ private internalCallback(position: GeolocationPosition, err?: GeolocationPositionError): void { // Log a few things if (position) console.log("Reported position:", position.coords.latitude, position.coords.longitude); if (err) console.log("Reported Error (" + err.code + ") " + err.message); // Loop through and call each registered callback this.callbacks.forEach(callback => callback(position, err)); } /** * Generate a unique id, to be give to registrants. * @returns {number} The id */ private getUniqueId(): number { return this.nextId++; } /** * Method to start the watcher */ private async startInternalWatcher() { console.log("Starting watcher"); this.watcherId = await Geolocation.watchPosition(this.options, this.internalCallback.bind(this)); } /** * Method to stop the watcher */ private async stopInternalWatcher() { if (this.watcherId) { console.log("Stopping watcher"); await Geolocation.clearWatch({id: this.watcherId}); } } /** * Method to restart (stop and start) the internal watcher */ private async restartInternalWatcher() { await this.stopInternalWatcher(); await this.startInternalWatcher(); } /** * Callback to handle transition from background to foreground */ private onForeground() { console.log("Restarting watcher on foreground"); this.restartInternalWatcher(); } }
687d215b2caf68bdb595a331deaa02a5b81c8465
TypeScript
hiNISAL/any-editor
/src/modules/Plug/Dropdown.plug.ts
2.59375
3
import { $create, $, $on, $show, $hide, hideClick } from '@/helpers/utils'; import { Plug, IPlug } from './Plug'; interface IDropItem { label: any, value: any, title?: string, }; interface IDetail { isTarget: boolean, el: any, value: string, label: string, }; class Dropdown extends Plug { private dropItems: IDropItem[] = []; private hoverShow: boolean = false; private maxHeight: number = 0; private labelKey: string = 'label'; private valueKey: string = 'value'; private constructor(config, ctx) { super(config, ctx); const { dropItems = [], maxHeight = 0, hoverShow = false, labelKey, valueKey } = config; this.dropItems = dropItems; this.maxHeight = maxHeight; this.hoverShow = hoverShow; this.labelKey = labelKey || 'label'; this.valueKey = valueKey || 'value'; this.createDOM(); this.setEvent(); } private createDOM() { this.beforeCreate(this.contexts); const { labelKey, valueKey } = this; const el = $create('div', { class: '__ae-menu', html: ` <div class="__ae-menu-item ${ this.id }"> <div class="__ae-menu-item-title" title="${ this.tip }"> <i class=""></i> <span>${ this.word }</span> </div> <div class="drop-items click-hide" style="display: none; ${ this.maxHeight > 0 ? `overflow: hidden; overflow-y: scroll; max-height: ${ this.maxHeight }px;` : 'height: auto' }"> ${ this.dropItems.map((item, index) => { return ` <div class="item " ${ item.title ? `title="${ item.title }"` : '' } data-value="${ item[valueKey] }" data-label="${ item[labelKey] }" data-index="${ index }" > ${ item[labelKey] } </div> `; }).join('') } </div> </div> `, }); this.dom = el; this.mounted(this.contexts); } private getDetail(target): IDetail { // 获取到塞在属性里的数据 const label = target.getAttribute('data-label'); const value = target.getAttribute('data-value'); let detail: IDetail = { el: null, isTarget: false, label: '', value: '' }; // item表示是否命中下拉框内的内容 if (label && value) { detail = { label, value, el: target, isTarget: true }; } else { detail = { el: target, isTarget: false, label: '', value: '' }; } return detail; } private setEvent() { const hoverShow = this.hoverShow; const dropWrap = $('.drop-items', this.dom); const menu = $('.__ae-menu-item', this.dom); // 带给事件 方便触发下拉框的主动关闭 const close = () => { $hide(dropWrap); }; const ctx = {...this.contexts, close}; const { click = () => {}, mouseover = () => {}, mouseout = () => {}, } = this.events; // 根据是否悬停就展开列表做不同的事件绑定 if (hoverShow) { // 悬停显示分别绑定两个鼠标事件 $on(menu, 'mouseover', (e) => { const res = mouseover({ ...ctx, e }); if (res !== false) { $show(dropWrap); } }); $on(menu, 'mouseout', (e) => { const res = mouseout({ ...ctx, e }); if (res !== false) { $hide(dropWrap); } }); // 选项要点击 所以还是要点的 $on(menu, 'click', (e) => { const { target } = e; const detail = this.getDetail(target); click({...ctx, detail, event: e}); }); } else { $on(menu, 'click', (e) => { e.stopPropagation(); hideClick(); const detail: IDetail = this.getDetail(e.target); const show = click({ ...ctx, detail, event: e }); // 如果return了false 则不展开下拉菜单 if (show !== false && !detail.isTarget) { $show(dropWrap); } }); } } } export default Dropdown;
fab8cb2c0addeed7ac9709c088d56fd5d74a390c
TypeScript
nosahama/nextui
/packages/nextui/src/pagination/styles.ts
2.9375
3
import { NormalSizes } from '../utils/prop-types'; type PaginationSize = { font: string; width: string; }; export const getPaginationSizes = (size: NormalSizes | number) => { const sizes: { [key in NormalSizes]: PaginationSize } = { mini: { font: '10px', width: '24px' }, small: { font: '12px', width: '28px' }, medium: { font: '14px', width: '34px' }, large: { font: '16px', width: '40px' }, xlarge: { font: '18px', width: '46px' } }; if (typeof size === 'number') return { font: `calc(${size}px / 2.55)`, width: `${size}px` }; return sizes[size]; };
7d547d6d258cb6899389778cad1aa0fb43ae66ee
TypeScript
danielcornock/recovqr-ui
/src/app/core/core-storage/services/storage/storage.service.ts
2.6875
3
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class StorageService { public getItem(key: string): string | null { return localStorage.getItem(key); } public setItem(key: string, payload: string): void { localStorage.setItem(key, payload); } public getObject<T>(key: string): T | undefined { const stringifiedObject = this.getItem(key); if (!stringifiedObject) { return; } return JSON.parse(stringifiedObject); } public setObject<T>(key: string, item: T): void { const stringifiedObject = JSON.stringify(item); this.setItem(key, stringifiedObject); } public removeItem(key: string): void { localStorage.removeItem(key); } }
d99ef1676faaccd682ff14b5a8816922d95c1a44
TypeScript
FontoXML/fontoxpath
/src/nodesFactory/INodesFactory.ts
2.59375
3
import { Document } from '../types/Types'; import ISimpleNodesFactory from './ISimpleNodesFactory'; /** * Defines the factory methods used in XQuery. Basically equivalent to the Document interface, but * with the 'createDocument' factory method added. * * @public */ export default interface INodesFactory extends ISimpleNodesFactory { createDocument(): Document; }
7a24429c01dd306937a1d29b69efec016a85c65b
TypeScript
sanchimenea/Todo-App
/backend/src/businessLogic/updateQueries.ts
2.578125
3
import { TodoUpdateParams } from "../models/TodoUpdateParam"; import { UpdateTodoRequest } from "../requests/UpdateTodoRequest"; export function paramsDoneOrImportant(updatedTodo: UpdateTodoRequest, userId: string, todoId: string) { const params: TodoUpdateParams = { Key: { "userId": userId, "todoId": todoId }, UpdateExpression: "set #n = :name, done = :done, #i = :important", ExpressionAttributeNames: { "#n": "name", "#i": "important" }, ExpressionAttributeValues: { ":name": updatedTodo.name, ":done": updatedTodo.done, ":important": updatedTodo.important } }; return params; } export function paramsUpdateDueDate(updatedTodo: UpdateTodoRequest, userId: string, todoId: string) { const params: TodoUpdateParams = { Key: { "userId": userId, "todoId": todoId }, UpdateExpression: "set #n = :name, dueDate = :dueDate, done = :done, #i = :important", ExpressionAttributeNames: { "#n": "name", "#i": "important" }, ExpressionAttributeValues: { ":name": updatedTodo.name, ":done": updatedTodo.done, ":important": updatedTodo.important, ":dueDate": updatedTodo.dueDate } }; return params; } export function paramsDeleteDueDate(userId: string, todoId: string) { const params: TodoUpdateParams = { Key: { "userId": userId, "todoId": todoId }, UpdateExpression: "remove #dd", ExpressionAttributeNames: { "#dd": "dueDate" } } return params; }
74a6440413d96039948bfb608f1fd13838413ac3
TypeScript
ovieokeh/contacts
/src/components/helpers.ts
3.15625
3
import { IContactDetails, IContactList, IGroupedContacts } from '../types' export const alphabet: string[] = Array.apply( undefined, Array(26) ).map((_, y) => String.fromCharCode(y + 65)) export const groupContacts = (contacts: IContactList): IGroupedContacts => { // to hold the contacts grouped by last name const groupedContacts = {} // initialise all possible groups alphabet.forEach(group => (groupedContacts[group] = [])) // for each contact contacts.forEach(contact => { // get the first letter of the last name const group = contact.name.last[0] if (groupedContacts[group]) { // add the contact to its group groupedContacts[group].push(contact) } }) return groupedContacts as IGroupedContacts } export const getName = (contact: IContactDetails) => `${contact.name.first}, ${contact.name.last.toUpperCase()}`
a048ca6d01cfd4b66b4f899091f02d59acace82c
TypeScript
Maaltijd-Maat/Maaltijd-Maat
/src/app/models/user.model.ts
2.765625
3
export interface IUser { readonly id?: string; readonly color?: string; firstname: string; lastname: string; email: string; secondEmail: string; password: string; avatar: string; guest: boolean; allergies: string[]; diets: string[]; } export class UserModel implements IUser{ readonly id?: string; firstname: string; lastname: string; email: string; secondEmail: string; password: string; avatar: string; guest: boolean; allergies: string[]; diets: string[]; constructor(firstname: string, lastname: string, email: string, password: string, avatar: string, guest: boolean, secondEmail?: string, allergies?: string[], diets?: string[], id?: string) { this.id = id; this.firstname = firstname; this.lastname = lastname; this.email = email; this.secondEmail = secondEmail || ''; this.password = password; this.avatar = avatar; this.guest = guest; this.allergies = allergies || []; this.diets = diets || []; } }
521cb6e8850e50c6f026865c3c0aa72f2ac61539
TypeScript
fossabot/kairo
/libs/kairo/src/lib/core/behavior.spec.ts
2.65625
3
import { Behavior, Computation, computed, Flag, lazy, mutable, runInTransaction, } from './behavior'; describe('core/behavior', () => { const noop = () => {}; function hasFlag(c: any, f: Flag) { return c['internal'].flags & f; } function numOfObserverNodes(c: any) { let last = c['internal'].last_observer; let count = 0; while (last !== null) { count++; last = last.prev_observer; } return count; } function numOfSourceNodes(c: any) { let last = (c['internal'] as Computation).last_source; let count = 0; while (last !== null) { count++; last = last.prev_source; } return count; } it('should establish a reactive relation', () => { const [a, setA] = mutable(0); const b = computed(() => a.value * 2); const c = computed(() => b.value * 2); expect(c.value).toBe(0); setA(1); expect(c.value).toBe(4); let result = 0; const stopWatch = c.watch((value) => { result = value; }); runInTransaction(() => { setA(2); setA(2); setA(3); }); expect(result).toBe(12); stopWatch(); }); it('should establish a reactive relation (static)', () => { const [a, setA] = mutable(0); const b = computed(() => a.value * 2, { static: true }); const c = computed(() => b.value * 2, { static: true }); expect(c.value).toBe(0); setA(1); expect(c.value).toBe(4); let result = 0; const stopWatch = c.watch((value) => { result = value; }); runInTransaction(() => { setA(2); setA(2); setA(3); }); expect(result).toBe(12); stopWatch(); expect(numOfObserverNodes(a)).toBe(1); setA(0); expect(numOfObserverNodes(a)).toBe(0); }); // it('should establish a reactive relation', () => {}); it('unused computation should be cleaned up', () => { const [a, setA] = mutable(0); const b = computed(() => a.value * 2); const c = computed(() => { if (a.value >= 0) { return b.value; } return 1; }); const stopWatch = c.watch(noop); setA(-1); expect(hasFlag(b, Flag.Stale)).toBeTruthy(); expect(numOfSourceNodes(b)).toBe(0); expect(numOfObserverNodes(b)).toBe(0); expect(numOfObserverNodes(a)).toBe(1); expect(numOfSourceNodes(c)).toBe(1); setA(1); expect(hasFlag(b, Flag.Stale)).toBeFalsy(); expect(numOfSourceNodes(b)).toBe(1); expect(numOfObserverNodes(b)).toBe(1); expect(numOfObserverNodes(a)).toBe(2); expect(numOfSourceNodes(c)).toBe(2); stopWatch(); }); it('unused computation should be cleaned up (2)', () => { const [a, setA] = mutable(0); const b1 = computed(() => a.value * 2); const b2 = computed(() => a.value * 4); const c = computed(() => { if (a.value >= 0) { return b1.value; } return b2.value; }); const stopWatch = c.watch(noop); setA(-1); expect(hasFlag(b1, Flag.Stale)).toBeTruthy(); expect(hasFlag(c, Flag.DepsUnstable)).toBeTruthy(); expect(numOfSourceNodes(b1)).toBe(0); expect(numOfObserverNodes(b1)).toBe(0); expect(numOfObserverNodes(a)).toBe(2); expect(numOfSourceNodes(c)).toBe(2); setA(1); expect(hasFlag(b1, Flag.Stale)).toBeFalsy(); expect(numOfSourceNodes(b1)).toBe(1); expect(numOfObserverNodes(b1)).toBe(1); expect(numOfObserverNodes(a)).toBe(2); expect(numOfSourceNodes(c)).toBe(2); stopWatch(); }); it('lazy', () => { const l = lazy<number>(); const [a, setA] = mutable(0); const b = computed(() => a.value * 2); let updated = false; l.watch(() => { updated = true; }); expect( l.execute(() => { return a.value + b.value; }) ).toBe(0); expect(numOfSourceNodes(l as any)).toBe(2); setA(1); expect(updated).toBeTruthy(); expect(hasFlag(l, Flag.Stale)).toBeTruthy(); expect( l.execute(() => { return a.value + b.value; }) ).toBe(3); expect(hasFlag(l, Flag.Stale)).toBeFalsy(); }); // TODO: it still fails: cyclic dependencies can not properly cleaned up. it('cyclic dependencies: sr latch', () => { const [S, setS] = mutable(false); const [R, setR] = mutable(false); const Q = computed(() => { const r = R.value, nq = NQ.value; return !(r || nq); }); const NQ = computed(() => { const s = S.value, q = Q.value; return !(s || q); }); expect(Q.value).toBeFalsy(); expect(NQ.value).toBeTruthy(); expect(numOfSourceNodes(Q)).toBe(2); //NQ R expect(numOfSourceNodes(NQ)).toBe(2); //Q S const stopWatch = Q.watch(noop); /** S _/‾\_ */ setS(true); setS(false); expect(Q.value).toBeTruthy(); expect(NQ.value).toBeFalsy(); /** R _/‾\_ */ setR(true); setR(false); expect(Q.value).toBeFalsy(); expect(NQ.value).toBeTruthy(); expect(numOfSourceNodes(Q)).toBe(2); //NQ R expect(numOfSourceNodes(NQ)).toBe(2); //Q S stopWatch(); expect(numOfSourceNodes(Q)).toBe(2); //NQ R expect(numOfSourceNodes(NQ)).toBe(2); //Q S setS(true); setS(false); // expect(numOfSourceNodes(Q)).toBe(2); //NQ R // expect(numOfSourceNodes(NQ)).toBe(0); //Q S expect(numOfObserverNodes(S)).toBe(0); }); });
7ba45cae2462500f051d3f6215bdbec5b04695a6
TypeScript
john-ko/simple-cache
/tests/fetch.spec.ts
2.828125
3
import SimpleCache from '../src' describe('spec (key)', () => { let simpleCache: SimpleCache let fakeCallback = () => new Promise((resolve, reject) => resolve('hello')) beforeEach(() => { simpleCache = new SimpleCache({}) }) it('creates a new value if it does not exist', async () => { const value = await simpleCache.fetch('/users/john', fakeCallback) expect(value).toBe('hello') }) it('returns value if key already exists', async () => { const value = await simpleCache.fetch('/users/john', fakeCallback) const sameValue = await simpleCache.fetch('/users/john', fakeCallback) expect(value).toBe(sameValue) }) it('re-fetches when expired', async () => { simpleCache = new SimpleCache({ ttl: -10 }) const callback1 = jest.fn() const callback2 = jest.fn() await simpleCache.fetch('/users/john', callback1) await simpleCache.fetch('/users/john', callback2) expect(callback1).toHaveBeenCalledTimes(1) expect(callback2).toHaveBeenCalledTimes(1) }) })
5fc31de3904321b39a440bec020b5bfa7b3abdb0
TypeScript
marcozam/os-ecommerce
/src/models/general/empresa.model.ts
2.546875
3
import { Field } from 'core/decorators'; import { BaseCatalog } from '../base-catalog.model'; export interface IEmpresa { nombre: any; } export class Empresa extends BaseCatalog implements IEmpresa { @Field('C1') nombre: string; constructor(key: number, _nombre: string) { super(key); this.nombre = _nombre; } }
8eb73626c7eee996e6516230e1c048fc79e89f5a
TypeScript
craby-c/MapboxTest
/src/Module/Models.ts
2.59375
3
// Input data model export interface ITripData { "tripduration": number, "starttime": string, "stoptime": string, "start station id": number, "start station name": string, "start station latitude": number, "start station longitude": number, "end station id": number, "end station name": string, "end station latitude": number, "end station longitude": number, "bikeid": number, "usertype": string, "birth year": number, "gender": number } // Any props model export interface IProps { [key: string]: any } export interface IViewport { height: string | number, width: string | number, latitude: number, longitude: number, zoom: number, mapboxApiAccessToken: string } // Changing style props model export interface IMarkerStyle { width?: TCSSProperty, height?: TCSSProperty, backgroundColor: string } // Any style prop model export type TCSSProperty = string | number | undefined; // Model of factors for modified durations export interface IDurationFactor { [key: number]: number } export interface IDuration { duration: number } export interface IPlace { point: [number, number], name: string } export type TActiveTrip = [number, number, IDuration];
f7b59d4b199e68b7260be3b793dd1fe3d35deaad
TypeScript
limlam/smart-home-local
/src/platform/execute.ts
2.65625
3
/** * Holds Execute stubs and helpers */ /// <reference types="@google/local-home-sdk" /> export const ExecuteStub: typeof smarthome.Execute = { Response: { Builder: class { private requestId: string = ''; private commands: smarthome.IntentFlow.ExecuteResponseCommands[] = []; public setRequestId(requestId: string): this { this.requestId = requestId; return this; } public setSuccessState(deviceId: string, state: unknown): this { this.commands.push({ ids: [deviceId], status: 'SUCCESS', states: state, }); return this; } public setErrorState( deviceId: string, errorCode: smarthome.IntentFlow.ExecuteErrors ): this { this.commands.push({ ids: [deviceId], status: 'ERROR', errorCode, }); return this; } public build() { return { requestId: this.requestId, payload: { commands: this.commands, }, }; } }, }, }; /** * A helper to build a simple `ExecuteRequestCommands` for sending * a single command to a single device * @param deviceId The id of the single device to send the command * @param command The single command to send to the device * @param params Parmeters for the command * @returns An `ExecuteRequestCommands` with the specified arguments */ export function createSimpleExecuteCommands( deviceId: string, command: string, params: object, customData: object ): smarthome.IntentFlow.ExecuteRequestCommands { return { devices: [{id: deviceId, customData}], execution: [{command, params}], }; } /** * Implementation of smarthome.DataFlow.UpdResponseData for testing DeviceManager */ export class UdpResponseData implements smarthome.DataFlow.UdpResponseData { constructor(requestId: string, deviceId: string) { this.requestId = requestId; this.deviceId = deviceId; } requestId: string; deviceId: string; protocol: smarthome.Constants.Protocol = smarthome.Constants.Protocol.UDP; }
8957e6c0b1ebf19a3f32c58e718c269705f4d9e9
TypeScript
ikbenignace/angular-ivy-qa3g3s
/src/services/base.service.ts
2.625
3
import { Injectable, Inject } from '@angular/core'; import { Observable, of } from 'rxjs'; import { HttpClient } from '@angular/common/http'; import { catchError } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class BaseService<T,TList> { constructor(protected http: HttpClient, @Inject('BASE_URL') protected baseUrl: string, protected controller: string) { } get(action: string): Observable<T> { return this.http.get<T>(this.baseUrl + this.controller + action) .pipe( catchError(this.handleError<T>()) ); } getCustomType<customT>(action: string): Observable<customT> { return this.http.get<customT>(this.baseUrl + this.controller + action) .pipe( catchError(this.handleError<customT>()) ); } getAll(action?: string): Observable<TList[]> { return this.http.get<TList[]>(this.baseUrl + this.controller + action) .pipe( catchError(this.handleError<TList[]>([])) ); } getAllCustomtype<customT>(action?: string): Observable<customT[]> { return this.http.get<customT[]>(this.baseUrl + this.controller + action) .pipe( catchError(this.handleError<customT[]>([])) ); } post(action: string, item: T) { return this.http.post(this.baseUrl + this.controller + action, item) .pipe( catchError(this.handleError<T>()) ); } /** * Handle Http operation that failed. * Let the app continue. * @param operation - name of the operation that failed * @param result - optional value to return as the observable result */ handleError<T>(result?: T) { return (error: any): Observable<T> => { // TODO: send the error to remote logging infrastructure console.error(error); // log to console instead // Let the app keep running by returning an empty result. return of(result as T); }; } }
9a96eaa4e3181d7bb9c8637995b47e998a4d8116
TypeScript
maoberlehner/node-sass-magic-importer
/packages/node-sass-magic-importer/src/functions/parse-selector-filters.ts
2.625
3
import { IParseSelectorFilters } from '../interfaces/IParseSelectorFilters'; import { IProcessRawSelectorFilters } from '../interfaces/IProcessRawSelectorFilters'; import { ISplitSelectorFilter } from '../interfaces/ISplitSelectorFilter'; export function parseSelectorFiltersFactory( processRawSelectorFilters: IProcessRawSelectorFilters, splitSelectorFilter: ISplitSelectorFilter, ): IParseSelectorFilters { return (url: string) => { const filterDivider = /[\s]+from[\s]+(?!.*from)/; if (!filterDivider.test(url)) { return []; } const selectorFiltersMatch = url .split(filterDivider)[0] .match(/{([\s\S]*)}/); if (!selectorFiltersMatch) { return []; } const rawSelectorFilters = selectorFiltersMatch[1].split(`,`) .map((x) => splitSelectorFilter(x.trim())); return processRawSelectorFilters(rawSelectorFilters); }; }
4f1a70cdd939101169197f6a3ae591169b94d3e7
TypeScript
pradnyatawale30/angularjs_training
/angularjs/typescript/manager.ts
3.890625
4
class Employee { private eid: number; private name: string; private status: boolean; // ? means optional parameter // default values will be undefined here..because its a javascript after compilation constructor(eid?: number, name?: string, status?: boolean) { this.eid = eid; this.name = name; this.status = status; } getEid(): number { return this.eid; } getName(): string { return this.name; } getStatus(): boolean { return this.status; } } // only single inheritance possible in TS class Manager extends Employee { private teamCount: number; private constructor(eid?: number, name?: string, status?: boolean, teamcount?: number) { super(eid, name, status); this.teamCount = teamcount; } getTeamCount(): number { return this.teamCount; } } let employee: Employee = new Employee(101, "John", true); console.log(employee.getEid()); console.log(employee.getName()); console.log(employee.getStatus()); let manager: Manager = new Manager(102, "Smith", true, 10); console.log(manager.getEid()); console.log(manager.getName()); console.log(manager.getStatus()); console.log(manager.getTeamCount()); // is static instance possible here? // or if we can make constructor as private?
3b6b9f0bc2bbc3bf8d8559f0692413c2f9979710
TypeScript
bart-haasbroek/video-upload
/src/app/store/wordpress/options/options.reducer.ts
2.875
3
import * as fromOptions from './options.actions'; export interface OptionsState { options: any; loaded: boolean; loading: boolean; } export const initialOptionsState: OptionsState = { options: {}, loaded: false, loading: false, }; export function optionsReducer( state = initialOptionsState, action: fromOptions.OptionsAction ): OptionsState { switch (action.type) { case fromOptions.LOAD_OPTIONS: { return { ...state, loading: true, }; } case fromOptions.LOAD_OPTIONS_SUCCESS: { const options = action.payload.reduce( (options: any, page: any) => { return { ...options, ...page }; }, { ...state.options, } ); return { ...state, options, loading: false }; } } return state; } export const getOptions = (state: any) => state.options; export const getOptionsLoadedState = (state: any) => state.loaded;
a6db7ccd88dede72a77d0626c405a8bb7172eb6a
TypeScript
fishedee/Demo
/typescript/other/src/auto_full_check.ts
3.828125
4
type Animal = 'dog' | 'cat' | 'fish' function getAnimalOrdal(input: Animal): number { // 这样写不好,会漏掉fish的常量 let number = 0 if (input === 'dog') { number = 1 } else if (input === 'cat') { number = 2 } return number } function getAnimalOrdal2(input: Animal): number { // 这样写是最好的,漏掉一个情况,都会报错 switch (input) { case 'dog': return 1 case 'cat': return 2 case 'fish': return 3 } } function testFullCheck() { getAnimalOrdal('dog') getAnimalOrdal2('cat') } export default testFullCheck
a53edbec7469fc481348f7a2c5b95568e97ce1c7
TypeScript
ParleyHub/Jupiter
/src/auth/auth.ts
2.703125
3
/* eslint-disable operator-linebreak */ /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable no-useless-return */ import { Request, Response, NextFunction } from 'express'; import jwt from 'jsonwebtoken'; import { v4 as uuidv4 } from 'uuid'; import redisClient from '../redis'; type GenericObject = { [key: string]: string }; const signToken = (payload: GenericObject): string => { const secretKey: string = process.env.SECRET_KEY || ''; const options = { expiresIn: '15m', }; return jwt.sign(payload, secretKey, options); }; const signRefreshToken = (payload: GenericObject): string => { const newPayload = { ...payload, string: uuidv4(), }; const secretKeyRefreshToken: string = process.env.SECRET_KEY_REFRESH_TOKEN || ''; const options = { expiresIn: '2h', }; return jwt.sign(newPayload, secretKeyRefreshToken, options); }; // eslint-disable-next-line @typescript-eslint/ban-types const verifyAccessToken = ( req: Request, res: Response, next: NextFunction ): void => { const authHeader: string = req.get('Authorization') || ''; if (!authHeader) { res.status(401).json({ message: 'No token provided.' }); return; } const token = authHeader.replace('Bearer ', ''); const secretKey: string = process.env.SECRET_KEY || ''; jwt.verify(token, secretKey, (error) => { if (error) { res.status(401).json({ message: 'Failed to authenticate.', }); return; } const decoded: any = jwt.decode(token); redisClient.get(`access-token:${decoded.id}`, (err, value) => { if (err || !value) { res.status(401).json({ message: 'Failed to authenticate.' }); return; } if (token === value) { next(); } }); }); }; export default { signToken, signRefreshToken, verifyAccessToken, };
6d8afe0d8d396951d395e758221ca78f97e1cd0c
TypeScript
Caballerog/blog
/factory-method-pattern/example1/index.ts
2.859375
3
import { ConcreteCreator1 } from "./concrete-creator1"; import { ConcreteCreator2 } from "./concrete-creator2"; import { Creator } from "./creator"; function client(creator: Creator) { console.log(`Client: I'm not aware of the creator's class`); console.log(creator.operation()); } const concreteCreator1 = new ConcreteCreator1(); const concreteCreator2 = new ConcreteCreator2(); client(concreteCreator1); console.log("----------"); client(concreteCreator2);
9e361aa120787082b426e47e9fff49b1cd27b2d8
TypeScript
G43riko/GTools
/src/math/simple-mat3.spec.ts
2.734375
3
import { expect } from "chai"; import "mocha"; import { Mat3 } from "./mat3"; describe("Mat3", () => { describe("init", () => { it("Test matrix creation", () => { const emptyMatrix = [ 1, 0, 0, 0, 1, 0, 0, 0, 1, ]; expect(Mat3.create().equalsArray(emptyMatrix)).to.be.true; expect(Mat3.create().equals(Mat3.create())).to.be.true; expect(Mat3.create().equals(null as any)).to.be.false; expect(Mat3.create().equals({} as any)).to.be.false; expect(Mat3.fromTranslation(0, 0).equals(Mat3.create())).to.be.true; expect(Mat3.fromScale(1, 1).equals(Mat3.create())).to.be.true; expect(Mat3.fromScale(1, 1)).to.deep.equal(Mat3.create()); expect(Mat3.fromTranslation(0, 0)).to.deep.equal(Mat3.create()); // // commented because error during comparison 0 and -0 // expect(Mat3.fromRotation(0)).to.deep.equal(Mat3.create()); }); }); });
83b35a91d63a9dd2824136dd257e27000c2a367c
TypeScript
fponticelli/tempo
/tools/docs/scripts/utils/markdown.ts
2.578125
3
import { Converter } from 'showdown' import { JSDOM } from 'jsdom' import fm from 'front-matter' import { trimChars } from 'tempo-std/lib/strings' import { highlight } from './highlight' const converter = new Converter({ parseImgDimensions: true, strikethrough: true, tables: true, tasklists: true }) const renameHtml = (path: string) => { const hasLeadingHash = path.startsWith('#') const parts = path.split('#').filter(a => !!a) if (!parts[0].endsWith('.html')) return path function processPart(part: string) { return part.split('.').map(p => trimChars(p, '_')).join('.') } const res = parts[0].split('/').map(processPart).join('/') return (hasLeadingHash ? [''] : []).concat([res].concat(parts.slice(1))).join('#') } function getComments(el: Element) { const arr = [] as Node[] for (const i in el.childNodes) { const n = el.childNodes[i] if (n.nodeType === 8) { arr.push(n) } else if (n.nodeType === 1) { arr.push(...getComments(n as Element)) } } return arr } export const markdown = (content: string, anchorMangler: (s: string) => string) => { const rawHtml = converter.makeHtml(content) const dom = new JSDOM(rawHtml) const codes = dom.window.document.querySelectorAll('.language-ts') for (let i = 0; i < codes.length; i++) { const code = codes[i] code.parentElement?.classList.add('language-ts') code.innerHTML = highlight(code.textContent || '') } const anchors = dom.window.document.querySelectorAll('a') for (let i = 0; i < anchors.length; i++) { const a = anchors[i] const href = a.href if (href.startsWith('http:') || href.startsWith('https:')) continue a.href = renameHtml(anchorMangler(href)) } const comments = getComments(dom.window.document.body) const toDelete = [] as Node[] for (let comment of comments) { let next: ChildNode | null = comment as ChildNode toDelete.push(next) while (next = next.nextSibling) { if (next != null && next.nodeType === Node.TEXT_NODE) { toDelete.push(next) } else { break } } } toDelete.forEach(n => { n.parentElement?.removeChild(n) }) let el = dom.window.document.body // while (el.childNodes.length === 1) { // if (!el.firstElementChild) break // el = el.firstElementChild as HTMLElement // } // console.log(el.nodeName) return el.innerHTML } export const markdownWithFM = (content: string, anchorMangler: (s: string) => string) => { const parsed = fm(content) const html = markdown(parsed.body, anchorMangler) return { html, data: parsed.attributes as any } }
a94ae9808a3a143ee193dfeed081f186a0165b51
TypeScript
joppe/apestaartje
/packages/lib/element/src/element.ts
2.953125
3
import { ElementConfig } from './ElementConfig'; export function element(config: ElementConfig): HTMLElement { const [tagName, attributes = {}, children] = config; const el = document.createElement(tagName); Object.keys(attributes).forEach((key) => { el.setAttribute(key, attributes[key]); }); if (Array.isArray(children)) { children.forEach((child) => { el.appendChild(element(child)); }); } else if (children !== undefined) { el.innerText = children; } return el; }
becfe7a1bc90f7398915a8a73091cbcd2664e65c
TypeScript
dbslate/dbslate
/src/utils/rand.ts
2.765625
3
import {random, sample} from 'lodash'; import * as ulid from 'ulid'; import {fillArray} from './array'; export const LOWER_ALPHA_CHARS = 'abcdefghijklmnopqrstuvwxyz'.split(''); export const UPPER_ALPHA_CHARS = LOWER_ALPHA_CHARS.map(c => c.toUpperCase()); export const ALPHA_CHARS = UPPER_ALPHA_CHARS.concat(LOWER_ALPHA_CHARS); export const NUM_CHARS = '0123456789'.split(''); export const ALPHA_NUM_CHARS = NUM_CHARS.concat(ALPHA_CHARS); export const ID_SEPARATOR = '_'; export const ID_RAND_SUFFIX_LENGTH = 12; export const id = ulid; export const int = (max: number = Number.MAX_SAFE_INTEGER): number => random(max); // tslint:disable-line:no-unnecessary-callback-wrapper (TODO tslint bug) export const num = (max: number = Number.MAX_VALUE): number => random(max); // tslint:disable-line:no-unnecessary-callback-wrapper (TODO tslint bug) export const char = (charSet: string[] = ALPHA_NUM_CHARS): string => sample(charSet) as string; export const str = ( minLength: number = 32, maxLength: number = minLength, charSet: string[] = ALPHA_NUM_CHARS, ): string => fillArray(random(minLength, maxLength), () => char(charSet)).join('');
fdf928cc7b99e55ddeaee7ddc7cc5658d69a5eb8
TypeScript
ariffadhillah/Game-Gewgly
/src/games/gewgly/objects/Eye/delegates/generator.service.ts
3.203125
3
import { CoordinateType, ConfigType } from '../schema'; export class Generator { public static generateEyePointPos( _ : ConfigType, direction: string ) : CoordinateType { // Position of eyes relative to EyeFrame const { eyesFrame, scale, eyeSpacing } = _; if( direction != "left" && direction != "right" ) { throw "generateEyePointPos Error"; } return { y : eyesFrame.y + eyesFrame.height, x : direction == "left" ? eyesFrame.x - eyeSpacing * scale : eyesFrame.x + eyesFrame.width + eyeSpacing * scale } } public static generateWhite( _ : ConfigType, direction: string ) : Phaser.Geom.Ellipse { const { height, width, w2h, scale, eyePointPosLeft, eyePointPosRight } = _; const eyePointPos = direction == "left" ? eyePointPosLeft : eyePointPosRight; return new Phaser.Geom.Ellipse( eyePointPos.x, eyePointPos.y, width * w2h * scale, height/w2h * scale ); } public static generatePupil( _ : ConfigType, direction: string ) : Phaser.Geom.Ellipse { const { pupilScale, scale, eyePointPosLeft, eyePointPosRight } = _; const eyePointPos = direction == "left" ? eyePointPosLeft : eyePointPosRight; return new Phaser.Geom.Ellipse( eyePointPos.x, eyePointPos.y, 4 * pupilScale * scale, 4 * pupilScale * scale); } public static generateBase( _ : ConfigType, direction: string ) : Phaser.Geom.Ellipse { const { left, right, leftWhite, pupilRotRadius } = _; const coor = direction == "left" ? left : right; return new Phaser.Geom.Ellipse( coor.x, coor.y, leftWhite.width * pupilRotRadius, leftWhite.height * pupilRotRadius); } // Circle for pupils to follow }
51e108f4cbb1f2718e9b0779e742e41089c69c31
TypeScript
zanozbot/mojedelo-virtualni-hekaton-2020-drugi-krog
/src/app/providers/paginator.provider.ts
2.578125
3
import { MatPaginatorIntl } from '@angular/material/paginator'; /** * Custom implementation for the Paginator to support Slovenian language */ export function PaginatorProvider() { const paginatorIntl = new MatPaginatorIntl(); paginatorIntl.itemsPerPageLabel = 'Število oddaj na strani:'; paginatorIntl.getRangeLabel = (page: number, pageSize: number, length: number) => { const start = page * pageSize + 1; const end = (page + 1) * pageSize; return `${start} - ${end} od ${length}`; }; return paginatorIntl; }
ff338fcf444d42994ca85d8280270ae268d0bc4f
TypeScript
Adrinalin4ik/world-of-warcraft
/client/src/game/network/webrtc/message.ts
2.53125
3
import { MessageType } from "./types"; export class Message { public type: MessageType = MessageType.none; constructor(type: MessageType) { this.type = type; } }
36da530b54d8d8bab071908cc844fd7491acec9d
TypeScript
mkazarnovskaya/checkers
/Game/Game/Scripts/checkers/position-hash.ts
3.046875
3
namespace Checkers { export class PositionHash<T> { hashObject: Object; constructor() { this.hashObject = new Object(); } hash(position: Position): string { let key0 = position.blackPlayer ? "1" : "2"; let key1 = 0; let key2 = 0; let key3 = 0; let index = 0; for (let row = 0; row < 8; ++row) { for (let col = 0; col < 4; ++col) { let cellValue = position.desk[row][col]; if (cellValue == 0) cellValue = 0b110; if (index < 10) { key1 = ((key1 << 3) | cellValue); } else if (index == 10) { key1 = ((key1 << 2) | (cellValue >> 1)); key2 = (cellValue & 1); } else if (index < 21) { key2 = ((key2 << 3) | cellValue); } else if (index == 21) { key2 = ((key2 << 1) | (cellValue & 1)); key3 = (cellValue >> 1); } else { key3 = ((key3 << 3) | cellValue); } ++index; } } return (key0 + "x" + new String(key1) + "x" + new String(key2) + "x" + new String(key3)); } getValue(position: Position): T { let hash = this.hash(position); return this.hashObject[hash]; } addValue(position :Position, value: T): void { let hash = this.hash(position); if (this.hashObject[hash]) throw new Error("Value was already added for this posion.") this.hashObject[hash] = value; } setValue(position: Position, value: T): void { let hash = this.hash(position); this.hashObject[hash] = value; } getAllValues(): T[] { return Object.keys(this.hashObject).map(nodeHash => this.hashObject[nodeHash]); } } }
3dfd73b99ae6bfbeb8abf4357b3c1c067aee8d0f
TypeScript
trojan8518/dragonEgg
/dragonEgg/src/Utils/SoundUtils.ts
2.65625
3
/** * 声音播放工具类 * @author zhangrui */ class SoundUtils { /** * 音频文件集合 */ private static soundMap: Map<string, egret.Sound>; private static soundChannelMap: Map<string, egret.SoundChannel>; /** * 背景音乐音量 */ private static _bg_sound_volume: number = 50; /** * 音效音量 */ private static _sound_volume: number = 50; public constructor() { } /** * 开始加载 */ public static startLoad(): void { if (!this.soundMap) this.soundMap = new Map<string, egret.Sound>(); if (!this.soundChannelMap) this.soundChannelMap = new Map<string, egret.SoundChannel>(); let bgType = "bg";//2个bgm随机 this.soundMap.set(SoundType.BACKGROUND, RES.getRes(SoundType.BACKGROUND + '_MP3')); this.soundMap.set(SoundType.BEHIT, RES.getRes(SoundType.BEHIT + '_MP3')); this.soundMap.set(SoundType.BOOM, RES.getRes(SoundType.BOOM + '_MP3')); this.soundMap.set(SoundType.BTN, RES.getRes(SoundType.BTN + '_MP3')); this.soundMap.set(SoundType.COIN, RES.getRes(SoundType.COIN + '_MP3')); this.soundMap.set(SoundType.CRITICAL, RES.getRes(SoundType.CRITICAL + '_MP3')); this.soundMap.set(SoundType.DIEBOOM, RES.getRes(SoundType.DIEBOOM + '_MP3')); this.soundMap.set(SoundType.ERROR, RES.getRes(SoundType.ERROR + '_MP3')); this.soundMap.set(SoundType.GIRL_SHOUTING, RES.getRes(SoundType.GIRL_SHOUTING + '_MP3')); this.soundMap.set(SoundType.HAMMER, RES.getRes(SoundType.HAMMER + '_MP3')); this.soundMap.set(SoundType.INTROMUSIC, RES.getRes(SoundType.INTROMUSIC + '_MP3')); this.soundMap.set(SoundType.LIGHTNING, RES.getRes(SoundType.LIGHTNING + '_MP3')); this.soundMap.set(SoundType.LVUP, RES.getRes(SoundType.LVUP + '_MP3')); this.soundMap.set(SoundType.MAN_SHOUTING, RES.getRes(SoundType.MAN_SHOUTING + '_MP3')); this.soundMap.set(SoundType.MONKEY_SHOUTING, RES.getRes(SoundType.MONKEY_SHOUTING + '_MP3')); this.soundMap.set(SoundType.MOVE, RES.getRes(SoundType.MOVE + '_MP3')); this.soundMap.set(SoundType.POPUP, RES.getRes(SoundType.POPUP + '_MP3')); this.soundMap.set(SoundType.STORY, RES.getRes(SoundType.STORY + '_MP3')); this.soundMap.set(SoundType.UPGRADE, RES.getRes(SoundType.UPGRADE + '_MP3')); this.soundMap.set(SoundType.YEAH, RES.getRes(SoundType.YEAH + '_MP3')); egret.lifecycle.onPause = () => { // this.soundMap.get(SoundType.BG).stop(); this.soundChannelMap.delete(SoundType.BACKGROUND) egret.ticker.pause(); // 关闭渲染和心跳 } egret.lifecycle.onResume = () => { this.play(SoundType.BACKGROUND, 0); egret.ticker.resume(); // 打开渲染和心跳 } } /** * 播放 * @param type 音乐类型 * @param loops 播放次数,默认值是 0,循环播放。 大于 0 为播放次数,如 1 为播放 1 次;小于等于 0,为循环播放。 */ public static play(type: string, loops: number) { // console.log("播放音效---名称:" + type); // console.log("音效当前音量---" + SoundUtils.sound_volume); // console.log("bgm当前音量---" + SoundUtils._bg_sound_volume); var sound: egret.Sound = this.soundMap.get(type); var channel: egret.SoundChannel; if (loops > 0) {//播放固定次数的音乐 if (!this.soundChannelMap.get(type)) { this.soundChannelMap.set(type, channel); } channel = sound.play(0, loops); channel.volume = 0.01 * this._sound_volume; } else {//循环播放的音乐 if (!this.soundChannelMap.get(type)) { channel = sound.play(0, loops); channel.volume = 0.01 * this._bg_sound_volume; this.soundChannelMap.set(type, channel); } } } /** * 播放 * @param type 音乐类型 */ public static stop(type: string) { let channel = this.soundChannelMap.get(type); if (channel) { channel.stop(); this.soundChannelMap.delete(type); } } /** * 设置背景音乐音量 */ public static set bg_sound_volume(value: number) { this._bg_sound_volume = value; if (this.soundChannelMap && this.soundChannelMap.get(SoundType.BACKGROUND)) { this.soundChannelMap.get(SoundType.BACKGROUND).volume = 0.01 * value; // this.soundChannelMap.get(SoundType.BG).stop(); } } /** * 获取背景音乐音量 */ public static get bg_sound_volume(): number { return this._bg_sound_volume; } /** * 设置音效音量 */ public static set sound_volume(value: number) { this._sound_volume = value; } /** * 获取音效音量 */ public static get sound_volume(): number { return this._sound_volume; } } class SoundType { /** * 背景音樂 */ public static BACKGROUND: string = "BACKGROUND"; /** * 背景音樂 */ public static BEHIT: string = "BEHIT"; /** * 背景音樂 */ public static BOOM: string = "BOOM"; /** * 背景音樂 */ public static BTN: string = "BTN"; /** * 背景音樂 */ public static COIN: string = "COIN"; /** * 背景音樂 */ public static CRITICAL: string = "CRITICAL"; /** * 背景音樂 */ public static DIEBOOM: string = "DIEBOOM"; /** * 背景音樂 */ public static ERROR: string = "ERROR"; /** * 背景音樂 */ public static GIRL_SHOUTING: string = "GIRL_SHOUTING"; /** * 背景音樂 */ public static HAMMER: string = "HAMMER"; /** * 背景音樂 */ public static INTROMUSIC: string = "INTROMUSIC"; /** * 背景音樂 */ public static LIGHTNING: string = "LIGHTNING"; /** * 背景音樂 */ public static LVUP: string = "LVUP"; /** * 背景音樂 */ public static MAN_SHOUTING: string = "MAN_SHOUTING"; /** * 背景音樂 */ public static MONKEY_SHOUTING: string = "MONKEY_SHOUTING"; /** * 背景音樂 */ public static MOVE: string = "MOVE"; /** * 背景音樂 */ public static POPUP: string = "POPUP"; /** * 背景音樂 */ public static STORY: string = "STORY"; /** * 背景音樂 */ public static UPGRADE: string = "UPGRADE"; /** * 背景音樂 */ public static YEAH: string = "YEAH"; }
94ec7907d305936d3e277a68c6ba2c0d7a0ec2b4
TypeScript
shahidur1/AngularClassesInForm
/src/app/app.component.ts
2.75
3
import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'angularclasses'; skill: string[] = ["R10", "R11", "R12"]; address: Address = new Address("Bashbari", "mohammadpur", "Dhaka", 1215); user: User = new User(this.address, "100", "sss", "ss@gmail.com", "R12", "female", false, true); public m1(data): void { console.log(data); } } export class User { address: Address; id: string; name: string; email: string; round: string; gender: string; skilljava: boolean; skillcs: boolean; constructor(addrress: Address, id: string, name: string, email: string, round: string, gender: string, skilljava: boolean, skillcs: boolean) { this.address = addrress; this.id = id; this.name = name; this.email = email; this.round = round; this.gender = gender; this.skilljava = skilljava; this.skillcs = skillcs; } } export class Address { street: string; city: string; state: string; postalcode: number; constructor(street: string, city: string, state: string, postalcode: number) { this.street = street; this.city = city; this.state = state; this.postalcode = postalcode; } }
aac218d23c00c2e63bf631670dab49fce1b91487
TypeScript
littletof/drashland_website
/drash/example_code/tutorials/requests/handling_url_query_params/home_resource.ts
2.640625
3
import { Drash } from "https://deno.land/x/drash/mod.ts"; export default class HomeResource extends Drash.Http.Resource { static paths = [ "/users" ]; public GET() { let userId = this.request.getUrlQueryParam("id"); if (!userId) { throw new Drash.Exceptions.HttpException( 400, "This resource requires the `id` URL query param." ); } userId = parseInt(userId); if (isNaN(userId)) { throw new Drash.Exceptions.HttpException( 400, "This resource requires the `id` URL query param to be a number." ); } this.response.body = `You passed in the following user ID as the URL query param: ${userId}`; return this.response; } }
5843f2400b71ea7456ee0d8cb648d8a8c0fe74bf
TypeScript
krasovsky22/aws-sam-example
/src/utils/common/alteration-helpers.ts
3.0625
3
const NUCLEOTIDE_COMPLIMENTS = { A: 'T', T: 'A', C: 'G', G: 'C', }; const complement = (nuc: string): string => { if (Object.keys(NUCLEOTIDE_COMPLIMENTS).includes(nuc)) { // @ts-ignore return NUCLEOTIDE_COMPLIMENTS[nuc]; } return ''; }; /** * Get reference and mutated nucleotide taking orientation into consideration. * @param orientation * @param original_nucleotide * @param replacement_nucleotide * @returns {{ref: *, alt: *}} */ export const getRefAlt = ({ orientation, original_nucleotide, replacement_nucleotide, }: { orientation: string; original_nucleotide: string; replacement_nucleotide: string; }) => { let ref, alt; if (orientation === '-') { ref = complement(original_nucleotide); alt = complement(replacement_nucleotide); } else { ref = original_nucleotide; alt = replacement_nucleotide; } return { ref, alt }; }; export const hasBayesDelScore = ({ original_nucleotide, replacement_nucleotide, }: { original_nucleotide: string; replacement_nucleotide: string; }): boolean => { const ref = original_nucleotide; const alt = replacement_nucleotide; return !!(ref && alt && ref.length === 1 && alt.length === 1 && complement(ref) && complement(alt)); };
f178ce51648e9e14a725ac12d1ee6aabecbb3285
TypeScript
esteban-w/angular-store-app
/src/app/checkout/services/cart.service.ts
2.546875
3
import { Injectable } from '@angular/core'; import { Product } from '../../catalog/models/product'; import { Cart, CartItem } from '../models/cart'; import { BehaviorSubject } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class CartService { cart: Cart = { items: {}, total: 0}; cartItems$: BehaviorSubject<object> = new BehaviorSubject<object>({}); cartCount$: BehaviorSubject<number> = new BehaviorSubject<number>(0); cartTotal$: BehaviorSubject<number> = new BehaviorSubject<number>(0); constructor() { this.cartItems$.subscribe((items: object) => { let cartTotal = 0; let cartCount = 0; Object.values(items).forEach((item: CartItem) => { const itemTotal = item.product.price * item.amount; cartTotal += itemTotal; cartCount += item.amount; }) this.cart.total = cartTotal; this.cartTotal$.next(this.cart.total); this.cartCount$.next(cartCount); }) } updateItem(product: Product, amount: number) { if (amount === 0) { return this.removeItem(product); } this.cart.items[product.id] = {product: product, amount: amount}; this.cartItems$.next(this.cart.items); return this.cart.items[product.id]; } addItem(product: Product, amount: number) { if (this.cart.items[product.id]) { this.cart.items[product.id].amount += amount; this.cartItems$.next(this.cart.items); return this.cart.items[product.id] } return this.updateItem(product, amount); } removeItem(product: Product) { if (this.cart.items[product.id]) { delete this.cart.items[product.id]; this.cartItems$.next(this.cart.items); } } emptyCart() { Object.values(this.cart.items).forEach(item => this.removeItem(item.product)) } }
ba306d4e3b3c1ba811312024d53364fb86cbdbdc
TypeScript
muellisa/EIA2
/Aufgabe5/snow.ts
3.34375
3
/* Name:Isabell Mller Matrikel:256034 Datum:19.11.17 Hiermit versichere ich, dass ich diesen Code selbst geschrieben habe. Er wurde nicht kopiert und nicht diktiert. */ namespace Aufgabe5 { export class Snow { x: number; y: number; color: string; g: number; /*new ruft constructor methode auf somit kann beim Konstruieren des Objektes Informationen uebergeben werden*/ constructor(_x: number, _y: number) { this.x = _x + Math.random() * 800; this.y = _y + Math.random() * 600; this.color = "#ffffff"; this.g = Math.random(); } sayHello(): void { console.log("Hello Snow"); } update(): void { this.move(); this.draw(); } move(): void { if (this.y > 600) { this.y = 0; } this.y += this.g; } draw(): void { crc2.beginPath(); crc2.arc(this.x, this.y, 2, 0, 2 * Math.PI); crc2.fillStyle = this.color; crc2.fill(); } } }
f667610115062d404d7f66430d8387165ecef1b1
TypeScript
bangbang93/BMCLJS
/src/main/service/game.ts
2.59375
3
/** * Created by bangbang93 on 2017/8/14. */ 'use strict'; import Launcher from '../launcher/launcher'; import { ipcMain } from 'electron'; import {mainWindow} from '../index' export interface IRunningGame { name: string, json: any, launcher: Launcher, id: GameIdentify } export interface IStartArguments { name: string, versionPath: string, minecraftPath: string, json: any, } class GameIdentify { constructor (private path: string, private version: string) {} valueOf() { return `${this.path}:${this.version}` } toString() { return this.valueOf() } } const running = new Map<GameIdentify, IRunningGame>(); export const start = async function (version: IStartArguments) { // TODO inheritsFrom const id = gameIdFactory({path: version.versionPath, name: version.name}) const launcher = new Launcher(version.versionPath, version.minecraftPath, {}, '/usr/bin/java', { json: version.json }); running.set(id, { name: version.name, json: version.json, launcher: launcher, id, }) const cp = await launcher.start(); cp.stdout.pipe(process.stdout); cp.stderr.pipe(process.stderr); cp.on('exit', () => { mainWindow.webContents.send('game:exit', {id: id.toString()}) running.delete(id) }) return launcher; } export function getRunning () { return running; } ipcMain.on('game:start', async (event, arg) => { console.log('game:start'); try { await start(arg.version); event.sender.send('game:started', { status: 'success', }); } catch (e) { switch (e.message) { case 'missing library': event.sender.send('game:started', { status: 'missing-library', missing: e.missing }); break; default: console.error(e); event.sender.send('game:started', { status: 'error', error: e.message, }); } } }) ipcMain.on('game:running', (event) => { console.log('game:running') event.returnValue = [...running.values()].map((p) => ({ name: p.name, launcher: p.launcher, id: p.id.toString(), })); }); const GAME_IDS = new Map<string, GameIdentify>() export function gameIdFactory({path, name}) { const id = `${path}/${name}` if (GAME_IDS.has(id)) { return GAME_IDS.get(id) } else { const GameId = new GameIdentify(path, name) GAME_IDS.set(id, GameId) return GameId } }
c02df902a1437cff1db554ddb00a21d412d697bb
TypeScript
Steady5063/steady5063.github.io
/common-ui/dist/common-ui/lib/core/functions/keyBy.d.ts
3.859375
4
/** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the last element responsible for generating the key. The * iteratee is invoked with one argument: (value). * * @param Array|Object collection The collection to iterate over. * @param Function iteratee The iteratee to transform keys. * @returns Object Returns the composed aggregate object. * @example * * const array = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ] * * keyBy(array, ({ code }) => String.fromCharCode(code)) * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } */ export declare function keyBy(array: any[], key: any): any;
447647a36141d37cb31f879f1e9587dd31d4b6b2
TypeScript
Toulix/gestion
/src/ue/ue.graphql.type.ts
2.59375
3
import { Field, Float, ID, ObjectType } from "@nestjs/graphql"; @ObjectType() export class Matiere { @Field(type => ID) id: string; @Field({nullable: true}) libelle?: string; @Field({nullable: true}) abbreviation?: string; @Field(type => Float, {nullable: true}) enseignementTheorique?: number; @Field(type => Float, {nullable: true}) enseignementDirige?: number; @Field(type => Float, {nullable: true}) enseignementPratique?: number; @Field(type => Float, {nullable: true}) credit?: number; @Field(type => Float, {nullable: true}) poids?: number; @Field({ nullable : true}) enseignant?: string; } @ObjectType() export class Unite { @Field(type => ID) id: string; @Field({nullable: true}) ueName?: string; @Field(type => [Matiere], {nullable: 'items'}) matieres?: Matiere[] } @ObjectType() export class Ue { @Field(type => ID) id: string; @Field({nullable: true}) niveau?: string; @Field({nullable: true}) parcours?: string; @Field({nullable: true}) anneeUniversitaire?: string; @Field({nullable: true}) semestreName?: string; @Field(type => [Unite], {nullable: 'items'}) ues?: Unite[] }
61668cb83417c9d437c01f1d0f26f86c088a3108
TypeScript
i-takuya/vscode-twitter
/src/controllers/service.ts
2.609375
3
import TwitterClient from '../twitter'; import MainController from './controller'; import * as vscode from 'vscode'; export enum LocalServiceEndpoint { User = 1, Search, Image, Refresh, Reply, Retweet, Like, Unlike, Follow, Unfollow, Css } export class LocalService { private app: any = require('express')(); private segments: string[] = []; private types: LocalServiceEndpoint[] = []; servicePort: string; addHandler(segment: string, type: LocalServiceEndpoint, handler: (req, res)=>void) { this.app.get(segment, handler); this.segments.push(segment); this.types.push(type); } start() { const port = this.app.listen(0).address().port; console.log('Local service listening on port ' + port); this.servicePort = port.toString(); } getSegment(type: LocalServiceEndpoint): string { var index = this.types.findIndex((value) => value == type); if (index != null) { var segment = this.segments[index]; if (segment != null) { var parts = segment.split('/'); if (parts.length > 1) { return parts[1]; } } } return null; } }
14711a92cfcd5ece8843b7ea1bc13aa4982785a8
TypeScript
leonadler/immutablets
/src/method-not-immutable-error.spec.ts
3.09375
3
import { expect } from 'chai'; import { MethodNotImmutableError, pathToString } from './method-not-immutable-error'; import { InputMutations } from './function-mutates-input'; describe('MethodNotImmutableError', () => { const emptyMutations: InputMutations = { args: { }, this: [ ] }; class PseudoClass { method() { } } it('can be constructed without errors', () => { new MethodNotImmutableError(emptyMutations, PseudoClass.prototype.method); new MethodNotImmutableError(emptyMutations, PseudoClass.prototype.method, PseudoClass); new MethodNotImmutableError(emptyMutations, PseudoClass.prototype.method, PseudoClass, 'pseudoMethod'); }); it('sets a "name" property', () => { const error = new MethodNotImmutableError(emptyMutations, PseudoClass.prototype.method); expect(error).to.have.property('name').which.equals('MethodNotImmutableError'); }); it('has the correct prototype chain', () => { const error = new MethodNotImmutableError(emptyMutations, PseudoClass.prototype.method); expect(error).to.be.an.instanceof(Error); expect(error).to.be.an.instanceof(MethodNotImmutableError); }); it('describes the changed <this> properties', () => { const mutations: InputMutations = { args: { }, this: [ { path: ['fruit', 'name'], oldValue: 'apple', newValue: 'banana' }, { path: ['newProp'], newValue: 'added' }, { path: ['oldProp'], oldValue: 'removed' } ] }; class ExampleClass1 { fruit: { name: string } = { name: 'apple' }; oldProp? = 'removed'; testMethod() { this.fruit.name = 'banana'; delete this.oldProp; } } const error = new MethodNotImmutableError(mutations, ExampleClass1.prototype.testMethod, ExampleClass1); expect(error.toString()).to.equal( unindent` MethodNotImmutableError: ExampleClass1.testMethod mutates properties. Changes: -this.fruit.name "apple" +this.fruit.name "banana" +this.newProp "added" -this.oldProp "removed" ` ); }); it('describes changed argument properties', () => { const mutations: InputMutations = { args: { 0: [ { path: ['color'], oldValue: 'red', newValue: 'green' } ] }, this: [] }; class ExampleClass2 { testMethod(fruit: { color: string }) { fruit.color = 'green'; } } const error = new MethodNotImmutableError(mutations, ExampleClass2.prototype.testMethod, ExampleClass2); expect(error.toString()).to.equal( unindent` MethodNotImmutableError: ExampleClass2.testMethod mutates properties. Changes: -fruit.color "red" +fruit.color "green" ` ); }); }); describe('pathToString (internal)', () => { it('joins a simple object property path by dots', () => { const path = ['document', 'body', 'firstChild']; expect(pathToString(path)).to.equal('.document.body.firstChild'); }); it('formats numeric indices as expected', () => { const path = ['items', '5', 'id']; expect(pathToString(path)).to.equal('.items[5].id'); }); it('formats string indices as expected', () => { const path = ['hash', 'some "rare" edge case']; expect(pathToString(path)).to.equal('.hash["some \\"rare\\" edge case"]'); }); }); describe('unindent (internal)', () => { it('strips whitespace as expected', () => { const result = unindent ` This should work. This too. and even this. `; expect(result).to.equal('This should work.\nThis too.\n and even this.'); }); }); function unindent(parts: TemplateStringsArray, ...params: any[]): string { const fullText = [parts[0]].concat(...params.map((p, i) => [String(p), parts[i + 1]])).join(''); const indent = (fullText.match(/^\n([\t ]+)/) || ['\n'])[0]; return fullText.trim().split(indent).join('\n'); }
3c66d9ab7f64a28bb0a77aec110972ab62c0d104
TypeScript
kgoggin/mindful
/data/notion.ts
2.609375
3
import { Client } from "@notionhq/client"; import { Page, RichTextPropertyValue, TitlePropertyValue, DatePropertyValue, } from "@notionhq/client/build/src/api-types"; import { randomColor } from "./colors"; export const notion = new Client({ auth: process.env.NOTION_TOKEN, }); export const DATABASE_ID = "7069361d473646b2ba6e3f7a664897b5"; type Quote = { id: string; content: string; backgroundColor: string; textColor: string; attribution: string | null; lastSeen: Date | null; }; const makeQuotes = (quotes: Page[]): Quote[] => { const result = []; for (const page of quotes) { const content = page.properties["Content"] as TitlePropertyValue; const attribution = page.properties["Attribution"] as RichTextPropertyValue; const lastSeen = page.properties["Last Seen"] as DatePropertyValue; const [backgroundColor, textColor] = randomColor(); if (content.title[0]) { result.push({ id: page.id, content: content.title[0].plain_text, attribution: attribution.rich_text[0]?.plain_text || null, lastSeen: lastSeen ? new Date(lastSeen.date.start) : null, backgroundColor, textColor, }); } } return result; }; export const getQuotes = async () => { const quotes = await notion.databases.query({ database_id: DATABASE_ID, }); return makeQuotes(quotes.results).sort((a, b) => { if (!a.lastSeen && !b.lastSeen) { return 0; } else if (!a.lastSeen) { return -1; } else if (!b.lastSeen) { return 1; } else { return 0; } }); }; export const getRandomQuote = async () => { const quotes = await getQuotes(); console.log(quotes); let quoteToShow = quotes[0]; if (quotes[0].lastSeen) { quoteToShow = quotes[Math.floor(Math.random() * quotes.length)]; } await updatePageLastSeen(quoteToShow.id); return quoteToShow; }; type CreateQuote = { content: string; attribution: string; }; export const createQuote = async ({ content, attribution }: CreateQuote) => { const res = await notion.pages.create({ parent: { database_id: DATABASE_ID, }, properties: { Content: { type: "title", title: [ { type: "text", text: { content, }, }, ], }, Attribution: { type: "rich_text", rich_text: [ { type: "text", text: { content: attribution, }, }, ], }, }, }); return makeQuotes([res as unknown as Page])[0]; }; export const updatePageLastSeen = async (pageId: string) => { const res = await notion.pages.update({ page_id: pageId, properties: { "Last Seen": { type: "date", date: { start: new Date().toISOString(), }, }, }, }); return res; };
8ab4b6dce5f5b81729c70dc73c3c4d25272405af
TypeScript
MrVhek/todolist
/functions/src/index.ts
2.65625
3
// // Start writing Firebase Functions // // https://firebase.google.com/docs/functions/typescript // // export const helloWorld = functions.https.onRequest((request, response) => { // response.send("Hello from Firebase!"); // }); import { Request, Response } from 'express'; const functions = require('firebase-functions'); const admin = require('firebase-admin'); import * as cors from 'cors'; const corsHandler = cors({origin: true}); admin.initializeApp(); const getAllUsers = (req: Request, res: Response) => { corsHandler(req, res, () => { const maxResults = 1000; // optional arg. const allUsers: any = []; admin.auth().listUsers(maxResults).then( (userRecords: { users: any[]; }) => { userRecords.users.forEach(userRecord => { // For each user allUsers.push({'email': userRecord.email, 'uid': userRecord.uid}); }); return res.status(200).send(JSON.stringify(allUsers)); }).catch((error: any) => { console.log("Error listing users:", error); return res.status(500).send(error); }); }) } module.exports = { api: functions.https.onRequest(getAllUsers), };
9d97e753b97dad82f9bea22142009ebf91673308
TypeScript
ThijsZijdel/Amsta-ErrorlessLearning
/app/src/app/admin/login/status.service.ts
2.796875
3
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import {isBoolean} from "util"; @Injectable() export class StatusService { public loggedInStatus:boolean = false; constructor() { } /** * Set the loggedInStatus * * @param {boolean} status * @author: Thijs Zijdel */ public changeLoggedInStatus(status: boolean):void { this.loggedInStatus = status; } /** * Get the actual login status * @returns {boolean} state * @author: Thijs Zijdel */ public getLoggedInStatus(): boolean { return this.loggedInStatus; } }