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
4857cd10ce1d389c60078777c0e0c7b7cad6bc20
TypeScript
StateFlex/StateFlex
/src/utils/htmlElements.util.ts
2.875
3
// HTML elements that the user can choose from interface htmlElementInt { width: number; height: number; attributes: Array<string>; } interface htmlElementsInt { [key: string]: htmlElementInt; } const HTMLelements: htmlElementsInt = { image: { width: 100, height: 100, attributes: ['className', 'id', 'src'], }, button: { width: 75, height: 28, attributes: ['className', 'id', 'text'], }, form: { width: 150, height: 150, attributes: ['className', 'id', 'text'], }, paragraph: { width: 250, height: 75, attributes: ['className', 'id', 'text'], }, list: { width: 75, height: 75, attributes: ['className', 'id', 'text'], }, link: { width: 50, height: 50, attributes: ['className', 'id', 'href', 'text'], }, }; export { HTMLelements };
3964688763e3e62bb0102841e4ffe51dd588cc0d
TypeScript
gfawcett22/ScheduleGraph
/FrontEnd/src/app/schedule/run.component.ts
2.515625
3
import {Component, Input, OnInit} from '@angular/core'; import {IRun} from "./run"; enum colors{ lightblue, lightgreen, lightred, lightgray, lightyellow } @Component({ selector: 'app-run', styles: ['.run {display:inline-block; border:1px solid black; height:60px; position:absolute}'], template: ` <div class="run" [style.width.%]="runWidthPercent" [style.left.%]="runLeftPercent" [style.background-color]="getRandomColor()" > <span class="runDetails">Run ID: {{runData.runID}}</span> <span *ngIf="runWidthPixels > 350" class="runDetails">Order No: {{runData.orderNo}}</span> <span *ngIf="runWidthPixels > 450" class="runDetails">Quantity: {{runData.quantity}} {{runData.quantityUom}}</span> <span *ngIf="runWidthPixels > 550" class="runDetails">Promise Date: {{runData.promiseDate | date:'shortDate'}}</span> <span *ngIf="runWidthPixels > 900" class="runDetails">Run Time: {{runData.runTime}} hrs</span> </div> ` }) export class RunComponent implements OnInit { @Input() runData: IRun; runWidthPercent: number; runWidthPixels: number; runLeftPercent: number; ngOnInit(): void { //the run percent is 100% divided by 24 hours in a day times the runtime this.runWidthPercent = ((100 / 24) * this.runData.runTime); this.runWidthPixels = window.screen.availWidth * (this.runWidthPercent / 100); let startTime = new Date(this.runData.startDate); this.runLeftPercent = ((100 / 24) * startTime.getHours()); console.log("run data start date: " + this.runData.startDate); console.log("start time: " + startTime); console.log("hours: " + startTime.getHours()); console.log(this.runLeftPercent); //console.log(this.runWidthPercent); //console.log(this.runWidthPixels); //console.log() } getRandomColor(): string { // let randomInt = Math.floor(Math.random() * 5); // console.log(randomInt); // return colors[randomInt]; return colors[this.runData.runID % 4]; } }
45c49803f140c605217f743ce6bcccd103c6289b
TypeScript
pagopa/io-dev-api-server
/src/features/fastLogin/nonceHandler.ts
2.828125
3
import { randomBytes } from "crypto"; import { pipe } from "fp-ts/lib/function"; import { Request } from "express"; import * as O from "fp-ts/lib/Option"; import { getDateMsDifference } from "../../utils/date"; export const NONCE_EXPYRING_MS = 30000; export type NonceInfo = { nonce: string; instantiationDate: Date; }; // eslint-disable-next-line functional/no-let let nonceInfo: NonceInfo; export const getNonceInfo = () => nonceInfo; const setNonceInfo = (nonce: string, instantiationDate: Date) => { nonceInfo = { nonce, instantiationDate }; }; export const generateNewNonce = () => pipe( randomBytes(16), str => str.toString("hex"), base64 => setNonceInfo(base64, new Date()) ); const extractNonceFromRequest = (request: Request): O.Option<string> => pipe( request.get("signature-input"), O.fromNullable, O.fold( () => O.none, sigInput => pipe( sigInput.match(/nonce="([^"]+)";/), O.fromNullable, O.map(matches => matches[1]) ) ) ); export const checkNonceFromRequest = (request: Request, nonceInfo: NonceInfo) => pipe( extractNonceFromRequest(request), O.fold( () => false, requestNonce => getDateMsDifference(new Date(), nonceInfo.instantiationDate) < NONCE_EXPYRING_MS && nonceInfo.nonce === requestNonce ) );
fa4dd84d5817c366d8d9cfd79c6b8370a7400fcd
TypeScript
NotWoods/color-breakdown
/src/db-worker/process-entry.ts
2.9375
3
import { HistoryEntry, PaletteEntry } from '../entry'; /** * Convert Data URI representing an image into a blob with the same data. * @see https://stackoverflow.com/questions/12168909/blob-from-dataurl */ export function dataUriToBlob(dataUri: string) { const [header, data] = dataUri.split(',', 2); // separate out the mime component const mimeType = header.split(':', 2)[1].split(';', 1)[0]; // convert base64 to raw binary data held in a string const byteString = atob(data); // write the bytes of the string to an ArrayBuffer const buffer = new ArrayBuffer(byteString.length); const intBuffer = new Uint8Array(buffer); // create a view into the buffer for (let i = 0; i < byteString.length; i++) { intBuffer[i] = byteString.charCodeAt(i); } return new Blob([buffer], { type: mimeType }); } /** * Convert blob to data uri * @throws DOMException if error when reading */ export function blobToDataUri(blob: Blob) { return new Promise<string>((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result as string); reader.onerror = () => reject(reader.error); reader.readAsDataURL(blob); }); } export function processEntry(entry: HistoryEntry): PaletteEntry; export function processEntry(entry: undefined): undefined; export function processEntry( entry: HistoryEntry | undefined, ): PaletteEntry | undefined; export function processEntry( entry: HistoryEntry | undefined, ): PaletteEntry | undefined { if (entry == undefined) { return undefined; } const timestamp = entry.id as number; const imgBlob = dataUriToBlob(entry.imgSrc); return { timestamp, imgSrc: URL.createObjectURL(imgBlob), colors: entry.colors, name: entry.name || new Date(timestamp).toLocaleString(), }; }
c11872286bdefc12c6f1ff8ece4571715e49177d
TypeScript
chronologic/automate-api
/src/middleware/authMiddleware.ts
2.578125
3
import { Response, NextFunction } from 'express'; import logger from '../logger'; import { UnauthorizedError } from '../errors'; import { RequestWithAuth } from '../models/Models'; import { UserService } from '../services/user'; export const authMiddleware = async (req: RequestWithAuth, res: Response, next: NextFunction) => { const token = decodeAuthHeader(req.headers.authorization); if (!token) { logger.debug('Auth token missing'); return next(new UnauthorizedError()); } let user; try { user = await UserService.validateApiKey(token); } catch (e) { logger.error(e); return next(e); } if (!user) { logger.debug('User not found'); return next(new UnauthorizedError()); } req.user = user; return next(); }; function decodeAuthHeader(header: string): string { try { const authToken = header.split(' ')[1]; return authToken; } catch (e) { logger.error(e); return null; } } export default authMiddleware;
1bc52c38afa500da309417bb703f62677cd71362
TypeScript
nihaux/yarec
/src/getToken.ts
2.59375
3
import { BadAuthorizationCodeError } from './errors'; import { ScopeEnum } from './types'; import { makePost } from './utils/makePost'; import { getBasicAuthHeader } from './utils/getBasicAuthHeader'; import { validateTokenResponse } from './utils/validateTokenResponse'; export type CommonGetAccessTokenArgs = { readonly redirect_uri: string; readonly client_id: string; readonly client_secret?: string; }; export type WithCodeGetAccessTokenArgs = { readonly code: string } & CommonGetAccessTokenArgs; export type AppOnlyGetAccessTokenArgs = CommonGetAccessTokenArgs; export type GetAccessTokenArgs = WithCodeGetAccessTokenArgs | AppOnlyGetAccessTokenArgs; export type GetAccessTokenResponse = { readonly access_token: string; readonly token_type: 'bearer'; readonly expires_in: number; readonly scope: ReadonlyArray<ScopeEnum>; readonly refresh_token?: string; }; const isWithCode = (params: GetAccessTokenArgs): params is WithCodeGetAccessTokenArgs => { return (params as any).code !== undefined; }; export const getToken = async (params: GetAccessTokenArgs): Promise<GetAccessTokenResponse> => { const { client_id, client_secret, redirect_uri } = params; const url = 'https://www.reddit.com/api/v1/access_token'; const extraHeaders = getBasicAuthHeader({ client_id, client_secret }); const response = await makePost({ url, body: { ...(isWithCode(params) ? { grant_type: 'authorization_code', code: params.code } : {}), ...(!isWithCode(params) && client_secret ? { grant_type: 'client_credentials' } : {}), ...(!isWithCode(params) && !client_secret ? { grant_type: 'https://oauth.reddit.com/grants/installed_client', device_id: 'DO_NOT_TRACK_THIS_DEVICE', } : {}), redirect_uri, }, extraHeaders, }); const jsonResponse = await response.json(); if (jsonResponse.error) { if (jsonResponse.error === 'invalid_grant') { throw new BadAuthorizationCodeError(); } throw new Error(jsonResponse.error); } validateTokenResponse({ jsonResponse }); return { ...jsonResponse, scope: jsonResponse.scope.split(' '), }; };
6106d22609d5c4dd37bb293e4197f05b12b35814
TypeScript
cadavidf/angular-cli
/packages/angular_devkit/schematics/src/rules/schematic.ts
2.5625
3
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { of as observableOf } from 'rxjs'; import { last, map } from 'rxjs/operators'; import { ExecutionOptions, Rule, SchematicContext } from '../engine/interface'; import { MergeStrategy, Tree } from '../tree/interface'; import { branch } from '../tree/static'; /** * Run a schematic from a separate collection. * * @param collectionName The name of the collection that contains the schematic to run. * @param schematicName The name of the schematic to run. * @param options The options to pass as input to the RuleFactory. */ export function externalSchematic<OptionT extends object>( collectionName: string, schematicName: string, options: OptionT, executionOptions?: Partial<ExecutionOptions>, ): Rule { return (input: Tree, context: SchematicContext) => { const collection = context.engine.createCollection(collectionName); const schematic = collection.createSchematic(schematicName); return schematic.call(options, observableOf(branch(input)), context, executionOptions); }; } /** * Run a schematic from the same collection. * * @param schematicName The name of the schematic to run. * @param options The options to pass as input to the RuleFactory. */ export function schematic<OptionT extends object>( schematicName: string, options: OptionT, executionOptions?: Partial<ExecutionOptions>, ): Rule { return (input: Tree, context: SchematicContext) => { const collection = context.schematic.collection; const schematic = collection.createSchematic(schematicName, true); return schematic.call(options, observableOf(branch(input)), context, executionOptions).pipe( last(), map(x => { // We allow overwrite conflict here because they're the only merge conflict we particularly // don't want to deal with; the input tree might have an OVERWRITE which the sub input.merge(x, MergeStrategy.AllowOverwriteConflict); return input; }), ); }; }
3353a9a1b611da8a95ee1214f6119f300fe178f4
TypeScript
elko-dev/nodejs-graphql-typescript-template
/src/service/user.service.ts
2.6875
3
import {UserEntity} from "../models/user.entity"; import { QueryGetUserArgs, MutationSignUpUserArgs, MutationSignUpAuthorizedUserArgs } from "../graphql/generated"; import {getRepository, Repository} from "typeorm"; import {Auth, AuthDetails} from "../auth/auth"; import {isValidEmail} from "../utils/validation.utils"; export default class UserService { private repo: Repository<UserEntity> = getRepository(UserEntity); private auth: Auth; constructor(auth: Auth) { this.auth = auth; } public async signUpUser(args: MutationSignUpUserArgs): Promise<UserEntity> { // create user const authUser: AuthDetails = await this.auth.registerUser(args.email, args.password); const user: UserEntity = new UserEntity(); user.authId = String(authUser.id); user.email = args.email; user.firstName = args.firstName; user.lastName = args.lastName; if (args.phoneNumber) { user.phoneNumber = args.phoneNumber; } if (!isValidEmail(args.email)) { throw new Error('Invalid email format'); } const newUser: UserEntity = await this.createUser(user); return newUser; } public async signUpAuthUser(args: MutationSignUpAuthorizedUserArgs): Promise<UserEntity> { const user: UserEntity = new UserEntity(); user.authId = String(args.authId); user.email = args.email; user.firstName = args.firstName; user.lastName = args.lastName; if (args.phoneNumber) { user.phoneNumber = args.phoneNumber; } if (!isValidEmail(args.email)) { throw new Error('Invalid email format'); } const newUser: UserEntity = await this.createUser(user); return newUser; } public async createUser(user: UserEntity): Promise<UserEntity> { return await this.repo.save(user); } public async getUser(args: QueryGetUserArgs): Promise<UserEntity> { const user: UserEntity = await this.queryUser(args); return user; } public async queryUser(args: QueryGetUserArgs): Promise<UserEntity> { const user: UserEntity | undefined = await this.repo.findOne(+args.id); if (user) { return user; } return Promise.reject("Not Found"); } public async getUserByFirebaseId(args: QueryGetUserArgs): Promise<UserEntity> { const user: UserEntity | undefined = await this.repo.findOne({ where: { authId: args.id, } }); if (user) { return user; } return Promise.reject("Not Found"); } public async updateUserProfilePhoto(id: string, userProfilePhotoUrl: string) { const user: UserEntity = await this.queryUser({id}); if (user) { user.profilePhotoUrl = userProfilePhotoUrl; await this.createUser(user); } } }
ed12bb6c5c6080c225a44618c273bf0eafb9410a
TypeScript
triptease/google-ads
/src/extract.ts
3.359375
3
import { isArray, forOwn } from "lodash"; import Long from "long"; type Primitives = string | number | undefined | null | Long; type CastPrimitive<V> = V extends Long ? number : V; type MapReturnType<X> = X extends Primitives ? CastPrimitive<X> : X extends { value?: infer V } ? CastPrimitive<V> : X extends Array<infer Y> ? Array<FlattenExtractObject<Y>> : FlattenExtractObject<X>; type FlattenExtractObject<X> = { [key in keyof X]: MapReturnType<X[key]> }; export type flatten<T> = MapReturnType<T>; function longToNumber(value: Long): number { return parseInt(value.toString(), 10); } export function flatten<T>(obj: T): MapReturnType<T> { const anyObj = obj as any; if (anyObj instanceof Object && "value" in anyObj) { if (Long.isLong(anyObj.value)) { return longToNumber(anyObj.value) as any; } return anyObj.value; } if (Long.isLong(anyObj)) { return longToNumber(anyObj) as any; } if (isArray(anyObj)) { return anyObj.map(flatten) as any; } if (anyObj instanceof Object) { const newObj = {} as any; Object.setPrototypeOf(newObj, Object.getPrototypeOf(anyObj)); forOwn(anyObj, (fieldValue, fieldName) => { newObj[fieldName] = flatten(fieldValue); }); return newObj; } return anyObj; } type Diff<T, U> = T extends U ? never : T; type NonNullable<T> = Diff<T, null | undefined>; type Require<Obj, Req extends keyof Obj | void> = { [P in Exclude<keyof Obj, Req>]?: Obj[P]; } & { [P in Extract<keyof Obj, Req>]-?: NonNullable<Obj[P]> }; export type extract<T, F extends keyof T | void = void> = Require< FlattenExtractObject<T>, F >; export function extract<T, F extends keyof T>( obj: T, requiredFields: F[] = [] ): Require<FlattenExtractObject<T>, F> { const flatObject: any = flatten(obj); requiredFields.forEach((field) => { const realValue = field in flatObject ? flatObject[field] : undefined; if (realValue == null || realValue === undefined) { throw new Error(`${field.toString()} does not exist on object`); } }); return flatObject as any as Require<FlattenExtractObject<T>, F>; }
c7f0ec8a4bca594549b3bd4c2684e957f2ac616a
TypeScript
CabbageSlices/KnN
/src/utils/__tests__/flatten-obj.test.ts
3.46875
3
import computePathsToNestedAttributes, { defaultPathFormatter } from 'utils/flatten-obj' it('default path formatter combines path and connects with a .', () => { const path = ['value', 'value2', 'depth3'] expect(defaultPathFormatter(path)).toBe('value.value2.depth3') const path2 = <string[]>[] expect(defaultPathFormatter(path2)).toBe('') const path3 = ['a'] expect(defaultPathFormatter(path3)).toBe('a') }) it('correctly flattens a nested object', () => { const object = { a: { b: [ { c: 1, }, {}, //not returned cuz empty [], //not returend cuz empty [true], 2, ], d: 3, e: null, f: 'hi', g: { h: -1, }, }, i: undefined, j: true, k: [], //empty value so shouldn't be returned l: {}, // same } expect(computePathsToNestedAttributes(object)).toEqual({ 'a.b.0.c': 1, 'a.b.3.0': true, 'a.b.4': 2, 'a.d': 3, 'a.e': null, 'a.f': 'hi', 'a.g.h': -1, i: undefined, j: true, }) }) it('correctly flattens a return a function with nested path', () => { const object = { a: { b: 3, c: () => { console.log('hi') }, d: [0, [], (x: number) => x], }, } const computed = computePathsToNestedAttributes(object) expect(typeof computed['a.c']).toBe('function') expect(typeof computed['a.d.2']).toBe('function') }) it('able to supply custom path function to flatten', () => { const object = { a: { b: [ { c: 1, }, 2, ], d: 3, e: null, }, } expect(computePathsToNestedAttributes(object, nestedPath => nestedPath.join('_'))).toEqual({ a_b_0_c: 1, a_b_1: 2, a_d: 3, a_e: null, }) }) it('able to prepend a base path', () => { const object = { a: { b: [ { c: 1, }, 2, ], }, } expect(computePathsToNestedAttributes(object, defaultPathFormatter, ['i', 'am', 'bass'])).toEqual( { 'i.am.bass.a.b.0.c': 1, 'i.am.bass.a.b.1': 2, } ) }) it('array nested path is returned as objects', () => { const object = [ { b: [ { c: 1, }, 2, ], d: 3, e: null, f: 'hi', g: { h: -1, }, }, { i: undefined }, true, [1, { a: 20, b: [] }, false, {}, 'hi'], ] expect(computePathsToNestedAttributes(object)).toEqual({ '0.b.0.c': 1, '0.b.1': 2, '0.d': 3, '0.e': null, '0.f': 'hi', '0.g.h': -1, '1.i': undefined, '2': true, '3.0': 1, '3.1.a': 20, '3.2': false, '3.4': 'hi', }) })
cdc146c617824202fb88def6eee518f181f4a21b
TypeScript
matt783/dex-react
/src/utils/validation.ts
3.0625
3
import { ValidationError, ObjectSchema } from '@hapi/joi' import { ValidationResolver } from 'react-hook-form' import { validInputPattern } from 'utils' export function preventInvalidChars(event: React.KeyboardEvent<HTMLInputElement>): void { if ( event.key !== 'Backspace' && event.key !== 'Delete' && !validInputPattern.test(event.currentTarget.value + event.key) && validInputPattern.test(event.currentTarget.value) ) { event.preventDefault() } } export function validatePositive(value: string, constraint = 0): true | string { return Number(value) > constraint || 'Invalid amount' } interface FormDataAsNumbers { [key: string]: number } /** * @name stringOrNumberResolverFactory * @description Factory function for form resolver using JOI validation * @param validationSchema joi.ObjectSchema<unknown> - Joi schema to check data * @param type [OPTIONAL] 'number' | undefined - sets casting use or straight FormData use */ export const stringOrNumberResolverFactory = <FormData, CustomContext = {}>( validationSchema: ObjectSchema<unknown>, type?: 'number', ) => (data: FormData): ReturnType<ValidationResolver<FormData, CustomContext>> => { const castedData: FormDataAsNumbers | FormData = type === 'number' ? Object.keys(data).reduce<FormDataAsNumbers>((acc, key) => { const oldValue = data[key] const castedValue = Number(oldValue) const castedObj = { ...acc, [key]: castedValue } return castedObj }, {}) : data const { error, value }: { value: typeof castedData | undefined; error?: ValidationError } = validationSchema.validate( castedData, ) return { values: error || !value ? {} : data, errors: error ? error.details.reduce((previous, currentError) => { return { ...previous, [currentError.path[0]]: currentError, } }, {}) : {}, } } export function formatSchemaErrorMessage(errorString?: string): string | undefined { if (!errorString) return undefined const cleanedString = errorString.replace(/"/g, '') return cleanedString[0].toUpperCase() + cleanedString.slice(1) }
5e6eaed2da16d4d7a4f73c7f062b4ce4c3daeb8f
TypeScript
achavez73/angularHello
/src/app/app.component.ts
2.8125
3
import { UsuariosService } from './usuarios.service'; import { Component, OnInit } from '@angular/core'; import { PostsService } from './posts.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers : [ UsuariosService ] }) export class AppComponent implements OnInit { mensaje = 'Curso de Angular'; nombre = 'Toño'; getNombre(){ return this.nombre; } //Property Binding imagenURL = "https://picsum.photos/420/320?image=0"; buttonStatus = false; //Class binding isActive = true; //Style Binding //Event Binding save(e){ console.log(e); } //Event Filtering onKeyUp(){ console.log("Enter fue presionado"); } //<!--Template variable--> /*onKeyUp(usuario){ console.log(usuario); }*/ //Two Way variable persona = { nombre: 'toño', edad: 20 } //decorator output info = ""; getMensaje(e){ alert(e); this.info = e; } //directiva ngif isValid = true; cursos = ['java', 'javascript', 'kotlin']; //for personas = ["Luis", "Mario", "Beto", "Manuel"]; personas2 = [ {id:1, nombre: "luis", edad: 23, hobby:"nadar"}, {id:2, nombre: "Mario", edad: 25, hobby:"correr"}, {id:3, nombre: "Beto", edad: 28, hobby:"escalar"}, {id:4, nombre: "Manuel", edad: 32, hobby:"leer"} ] onAgregar(){ this.personas2.push({id:5, nombre:"Steve", edad:21, hobby:"volar"}); } onBorrar(personaX){ let index = this.personas2.indexOf(personaX); this.personas2.splice(index,1); } onActualizar(personaX){ personaX.nombre = "Actualizado"; } getColor(hobby){ switch(hobby){ case 'nadar': return 'green'; case 'correr': return 'blue'; case 'escalar': return 'gray'; case 'leer': return 'yellow'; } } //safe navigation operator personaS = { nombre:"Pedro", apellido:"Perez", trabajo:undefined } //servicios personaSer : any =[]; /* constructor(){ let usuario = new UsuariosService(); usuario.getUsuarios(); this.personaSer = usuario.getUsuarios(); }*/ /* constructor(private usuariosservice : UsuariosService){ this.personaSer = usuariosservice.getUsuarios(); } */ listaDePosts : any = []; constructor(private postservice : PostsService){ } ngOnInit(){ //console.log('Componente inicializado'); this.postservice.getPost().subscribe(response => { this.listaDePosts = response; }); } }
bca976550dfb5a56840cb527af863ba8ba44845c
TypeScript
bobheadxi/seer
/web/src/math/aggregates/index.ts
2.96875
3
import { Participant } from '@/api/types'; // overviews export interface TeamOverview { aggs?: CompiledTeamAggregations, } export interface PlayerOverview { tier?: string; aggs?: CompiledPlayerAggregations; } export interface PlayerOverviews { [name: string]: PlayerOverview } export interface Overviews { team: TeamOverview, players: PlayerOverviews, } // aggregations export interface PlayerAggregations { // average, etc vision: number[], cs: number[], jungle: { friendly: number[], enemy: number[], }, dealt: number[], taken: number[], gold: number[], // take top 3 champs: number[], // take top 1 lanes: string[], roles: string[], } export function newPlayerAggregation(): PlayerAggregations { return { vision: [], cs: [], jungle: { friendly: [], enemy: [], }, dealt: [], taken: [], gold: [], champs: [], lanes: [], roles: [], }; } export function updatePlayerAggregation(agg: PlayerAggregations, part: Participant) { agg.vision.push(part.stats.visionScore); // minions + ungle agg.cs.push(part.stats.totalMinionsKilled); agg.cs.push(part.stats.neutralMinionsKilled); agg.jungle.friendly.push(part.stats.neutralMinionsKilledTeamJungle); agg.jungle.enemy.push(part.stats.neutralMinionsKilledEnemyJungle); agg.dealt.push(part.stats.totalDamageDealtToChampions); agg.taken.push(part.stats.totalDamageTaken); agg.gold.push(part.stats.goldEarned); agg.champs.push(part.championId); agg.lanes.push(part.timeline.lane); agg.roles.push(part.timeline.role); } export interface CompiledPlayerAggregations { avg: { // rounding turns numbers into... strings vision: string, cs: string, dealt: string, taken: string, gold: string, jungle: { friendly: string, enemy: string, }, } favourite: { champs: number[], lane: string, role: string, }, } export function getAvg(arr: number[]): string { const total = arr.reduce((acc, c) => acc + c, 0); return (total / arr.length).toFixed(2); } // this function drives me nuts. ts-ignore it all. TODO: use my brain export function getTop(arr: (string | number)[], count?: number): (string | number) | (string | number)[] { // @ts-ignore const counts = arr.reduce((m, v) => { // @ts-ignore m[v] = (m[v] || 0) + 1; // eslint-disable-line no-param-reassign return m; }, {}); // @ts-ignore const sorted = Object.keys(counts).sort((a, b) => counts[b] - counts[a]); if (!count) return sorted[0]; return sorted.slice(0, count); } // TODO: more aggregations export function compilePlayerAggregations(agg: PlayerAggregations): CompiledPlayerAggregations { return { avg: { vision: getAvg(agg.vision), cs: getAvg(agg.cs), dealt: getAvg(agg.dealt), taken: getAvg(agg.taken), gold: getAvg(agg.gold), jungle: { friendly: getAvg(agg.jungle.friendly), enemy: getAvg(agg.jungle.enemy), }, }, favourite: { champs: getTop(agg.champs, 5) as number[], lane: getTop(agg.lanes) as string, role: getTop(agg.roles) as string, }, }; } export interface TeamAggregations { matchTime: number[], wins: boolean[], towers: number[], dragons: number[], barons: number[], } export interface CompiledTeamAggregations { games: number, winRate: string, avg: { matchTime: string, towers: string, dragons: string, barons: string, }, } export function compileTeamAggregations(agg: TeamAggregations): CompiledTeamAggregations { const wins = agg.wins.filter(x => x).length; const avgGameTime = parseInt(getAvg(agg.matchTime), 10); return { games: agg.wins.length, winRate: (wins / agg.wins.length).toFixed(2), avg: { matchTime: `${Math.floor(avgGameTime / 60)}:${Math.floor(avgGameTime % 60)}`, towers: getAvg(agg.towers), dragons: getAvg(agg.dragons), barons: getAvg(agg.barons), }, }; }
93fc4e288d6613a5371fb273ecf3e8101818cdc9
TypeScript
jaybyron/melody
/packages/melody-idom/src/node_data.ts
2.578125
3
/** * Copyright 2015 The Incremental DOM Authors. * Copyright 2017 trivago N.V. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { createMap } from './util'; /** * Keeps track of information needed to perform diffs for a given DOM node. * @param {!string} nodeName * @param {?string=} key * @constructor */ function NodeData(nodeName, key) { /** * The attributes and their values. * @const {!Object<string, *>} */ this.attrs = createMap(); /** * An array of attribute name/value pairs, used for quickly diffing the * incomming attributes to see if the DOM node's attributes need to be * updated. * @const {Array<*>} */ this.attrsArr = []; /** * The incoming attributes for this Node, before they are updated. * @const {!Object<string, *>} */ this.newAttrs = createMap(); /** * The key used to identify this node, used to preserve DOM nodes when they * move within their parent. * @const */ this.key = key; /** * Keeps track of children within this node by their key. * {?Object<string, !Element>} */ this.keyMap = createMap(); /** * Whether or not the keyMap is currently valid. * {boolean} */ this.keyMapValid = true; /** * Whether or not the statics for the given node have already been applied. * * @type {boolean} */ this.staticsApplied = false; /** * Whether or not the associated node is or contains a focused Element. * @type {boolean} */ this.focused = false; /** * The node name for this node. * @const {string} */ this.nodeName = nodeName; /** * @type {?string} */ this.text = null; /** * The component instance associated with this element. * @type {Object} */ this.componentInstance = null; /** * The length of the children in this element. * This value is only calculated for raw elements. * @type {number} */ this.childLength = 0; } /** * Initializes a NodeData object for a Node. * * @param {Node} node The node to initialize data for. * @param {string} nodeName The node name of node. * @param {?string=} key The key that identifies the node. * @return {!NodeData} The newly initialized data object */ var initData = function(node, nodeName, key) { var data = new NodeData(nodeName, key); node['__incrementalDOMData'] = data; return data; }; /** * Retrieves the NodeData object for a Node, creating it if necessary. * * @param {Node} node The node to retrieve the data for. * @return {!NodeData} The NodeData for this Node. */ var getData = function(node) { if (process.env.NODE_ENV !== 'production') { if (!node) { throw new Error("Can't getData for non-existing node."); } } importNode(node); return node['__incrementalDOMData']; }; const importNode = function(node) { const stack = [node]; while (stack.length) { const node = stack.pop(); if (node['__incrementalDOMData']) { continue; } const isElement = node instanceof Element; const nodeName = isElement ? node.localName : node.nodeName; const key = isElement ? node.getAttribute('key') : null; const data = initData(node, nodeName, key); if (key) { const parentData = node.parentNode && node.parentNode['__incrementalDOMData']; if (parentData) { parentData.keyMap[key] = node; } } if (isElement) { const attributes = node.attributes; const attrs = data.attrs; const newAttrs = data.newAttrs; const attrsArr = data.attrsArr; for (let i = 0; i < attributes.length; i += 1) { const attr = attributes[i]; const name = attr.name; const value = attr.value; attrs[name] = value; newAttrs[name] = undefined; attrsArr.push(name); attrsArr.push(value); } for ( let child = node.firstChild; child; child = child.nextSibling ) { stack.push(child); } } else if (node.nodeType === 3) { data.text = node.data; } } }; /** */ export { getData, initData, importNode };
bcc25f170f75e07a49111c532709d9acc5ac9114
TypeScript
samchon/ecol
/src/linear/DequeCollection.ts
3.078125
3
import { Deque } from "tstl/container/Deque"; import { ICollection } from "../basic/ICollection"; import { IForwardIterator } from "tstl/iterator/IForwardIterator"; import { CollectionEvent } from "../basic/CollectionEvent"; import { EventDispatcher } from "../basic/EventDispatcher"; export class DequeCollection<T> extends Deque<T> implements ICollection<T, Deque<T>, Deque.Iterator<T>, Deque.ReverseIterator<T>> { /** * @hidden */ private dispatcher_: EventDispatcher<T, Deque<T>, Deque.Iterator<T>, Deque.ReverseIterator<T>> = new EventDispatcher(); /* --------------------------------------------------------- CONSTRUCTORS --------------------------------------------------------- */ // using super.constructor; public clear(): void { let first = this.begin(); let last = this.end(); this._Notify_erase(first, last); super.clear(); } /* ========================================================= ELEMENTS I/O - INSERT - ERASE - REFRESH ============================================================ INSERT --------------------------------------------------------- */ /** * @inheritdoc */ public push_front(val: T): void { super.push_front(val); this._Notify_insert(this.begin(), this.begin().next()); } /** * @inheritdoc */ public push_back(val: T): void { super.push(val); this._Notify_insert(this.end().prev(), this.end()); } /** * @hidden */ protected _Insert_by_range<U extends T, InputIterator extends Readonly<IForwardIterator<U, InputIterator>>> (pos: Deque.Iterator<T>, first: InputIterator, last: InputIterator): Deque.Iterator<T> { let n: number = this.size(); let ret = super._Insert_by_range(pos, first, last); n = this.size() - n; this._Notify_insert(ret, ret.advance(n)); return ret; } /* --------------------------------------------------------- ERASE --------------------------------------------------------- */ /** * @inheritdoc */ public pop_front(): void { this._Notify_erase(this.begin(), this.begin().next()); super.pop_front(); } /** * @inheritdoc */ public pop_back(): void { this._Notify_erase(this.end().prev(), this.end()); super.pop_back(); } /** * @hidden */ protected _Erase_by_range(first: Deque.Iterator<T>, last: Deque.Iterator<T>): Deque.Iterator<T> { this._Notify_erase(first, last); return super._Erase_by_range(first, last); } /* --------------------------------------------------------- REFRESH --------------------------------------------------------- */ /** * @inheritdoc */ public set(index: number, val: T): void { super.set(index, val); this.refresh(this.begin().advance(index)); } /** * @inheritdoc */ public refresh(): void; /** * @inheritdoc */ public refresh(it: Deque.Iterator<T>): void; /** * @inheritdoc */ public refresh(first: Deque.Iterator<T>, last: Deque.Iterator<T>): void; public refresh(first?: Deque.Iterator<T>, last?: Deque.Iterator<T>): void { if (first === undefined) { first = this.begin(); last = this.end(); } else if (last === undefined) last = first.next(); this.dispatchEvent(new CollectionEvent("refresh", first, last)); } /* ========================================================= EVENT DISPATCHER - NOTIFIERS - ACCESSORS ============================================================ NOTIFIERS --------------------------------------------------------- */ /** * @inheritdoc */ public dispatchEvent(event: DequeCollection.Event<T>): void { if (this.dispatcher_) this.dispatcher_.dispatchEvent(event); } /** * @hidden */ private _Notify_insert(first: Deque.Iterator<T>, last: Deque.Iterator<T>): void { this.dispatchEvent(new CollectionEvent("insert", first, last)); } /** * @hidden */ private _Notify_erase(first: Deque.Iterator<T>, last: Deque.Iterator<T>): void { this.dispatchEvent(new CollectionEvent("erase", first, last)); } /* --------------------------------------------------------- ACCESSORS --------------------------------------------------------- */ /** * @inheritdoc */ public hasEventListener(type: CollectionEvent.Type): boolean { return this.dispatcher_.hasEventListener(type); } /** * @inheritdoc */ public addEventListener(type: CollectionEvent.Type, listener: DequeCollection.Listener<T>): void { this.dispatcher_.addEventListener(type, listener); } /** * @inheritdoc */ public removeEventListener(type: CollectionEvent.Type, listener: DequeCollection.Listener<T>): void { this.dispatcher_.removeEventListener(type, listener); } } export namespace DequeCollection { export type Event<T> = CollectionEvent<T, Deque<T>, Deque.Iterator<T>, Deque.ReverseIterator<T>>; export type Listener<T> = CollectionEvent.Listener<T, Deque<T>, Deque.Iterator<T>, Deque.ReverseIterator<T>>; export const Event = CollectionEvent; export import Iterator = Deque.Iterator; export import ReverseIterator = Deque.ReverseIterator; } const old_swap = Deque.prototype.swap; Deque.prototype.swap = function <T>(obj: Deque<T>): void { old_swap.call(this, obj); if (this instanceof DequeCollection) this.refresh(); if (obj instanceof DequeCollection) obj.refresh(); };
a43c7bf00f16f0d06868235f978b6edd946f4d2d
TypeScript
asaleh267/exercises-in-programming-style
/chapter9/index.ts
3.765625
4
// This way using class import { write, readFile } from "fs"; class TFTheOne { value; constructor(v) { this.value = v; } bind(func) { this.value = func(this.value); return this; } // print data printMe(data) { console.log(data.slice(0, 25)) } // The functions // Takes a path to a file and returns the entire contents of the file as a string readFile(path: string) { return require('fs').readFileSync(path).toString().split(""); } // Takes a string and returns a copy with all nonalphanumeric chars replaced by white space filterChars(data: any[]) { for (let index = 0; index < data.length; index++) { if (isLetter(data[index])) { data[index] = data[index].toLowerCase(); } else { data[index] = ''; } } return data; } // scan and remove stop words scan(data: string[]) { let word = ""; let stopWords = require('fs').readFileSync("../data\\stop_words.txt").toString().split(","); let words = [] for (let index = 0; index < data.length; index++) { if (isLetter(data[index]) && data[index] != "") { word += data[index]; } else if (word != "" && !stopWords.includes(word)) { words.push(word); word = ""; } } return words; } // Takes a list of words and returns a dictionary associating words with frequencies of occurrence frequancies(words: string[]) { let words_count: [string, number][] = []; for (let word in words) { let found = false for (var index = 0; index < words_count.length; index++) { if (words[word] == words_count[i][0]) { words_count[index][1] += 1; found = true } } if (!found) { words_count.push([words[word], 1]); } } return words_count; } /* Takes a dictionary of words and their frequencies and returns a list of pairs where the entries are sorted by frequency */ sort(words_count: [string, number][]) { words_count.sort((a, b) => { return b[1] - a[1]; }); return words_count; } } function isLetter(str: string): Boolean { return str.length === 1 && Boolean(str.match(/^[0-9a-zA-Z]+$/)); } function main() { let item = new TFTheOne("../data\\dummy_data.txt"); item.bind(item.readFile) .bind(item.filterChars) .bind(item.scan) .bind(item.frequancies) .bind(item.sort) .bind(item.printMe); } main();
d36288de326830d38faa9c1b59a771046dcb0c17
TypeScript
Dirichi/football
/src/client/graphics/box_graphics.ts
2.671875
3
import { EVENTS } from "../../constants"; import { EventQueue } from "../../event_queue"; import { Field } from "../../game_objects/field"; import { IAnimationEngine } from "../../interfaces/ianimation_engine"; import { IBoxSchema } from "../../interfaces/ibox_schema"; export class BoxGraphics { public engine: IAnimationEngine; public queue: EventQueue; private boxes: IBoxSchema[]; private scale: number[]; constructor(engine: IAnimationEngine, queue: EventQueue) { this.engine = engine; this.boxes = []; this.queue = queue; this.scale = [0, 0, 1, 1]; this.configureListeners(); } public animate() { this.boxes.forEach((box) => this.engine.drawBox(box)); } public setScale(scale: number[]) { this.scale = scale; } private configureListeners() { this.queue.when(EVENTS.BOXES_DATA, (data) => { const deserializedData = data as IBoxSchema[]; this.boxes = deserializedData.map((box) => { return this.toScale(box); }); }); } private toScale(data: IBoxSchema): IBoxSchema { // TODO: Should scaling the gameObject also be a job of the serializer? const [xmin, ymin, xmax, ymax] = this.scale; const xrange = xmax - xmin; const yrange = ymax - ymin; return { x: (data.x * xrange) + xmin, xlength: (data.xlength * xrange), y: (data.y * yrange) + ymin, ylength: (data.ylength * yrange), } as IBoxSchema; } }
ff5de8fea5f0dd4938950fd82a00ccadac855e52
TypeScript
tarvyn/data-structures
/src/queue.ts
3.609375
4
import { LinkedList } from './linked-list'; export interface Queue<T> { enqueue: (value: T) => void; dequeue: () => T | undefined; isEmpty: () => boolean; toArray: () => T[]; } export class ArrayQueue<T = unknown> implements Queue<T> { private readonly list: T[] = []; enqueue(value: T): void { this.list.unshift(value); } dequeue(): T | undefined { return this.list.pop(); } isEmpty(): boolean { return !this.list.length; } toArray(): T[] { return this.list.slice(); } } export class LinkedListQueue<T = unknown> implements Queue<T> { private readonly list = new LinkedList(); enqueue(value: T): void { this.list.append(value); } dequeue(): T | undefined { return this.list.deleteHead()?.value as T | undefined; } isEmpty(): boolean { return !this.list.head; } toArray(): T[] { return this.list .toArray() .map((item) => item.value) .reverse() as T[]; } }
1bef5be6cf1a859e7528f7f628b65e0741a98a4f
TypeScript
AlexandrePereira0011/jogopw
/jogo/src/app/classes/weapons.ts
2.59375
3
export class Weapons { constructor(api: any){ this.name = api.nome; this.atk = api.Atk; this.TipoDeArma = api.TipoDeArma; this.Durabilidade = api.Durabilidade; this.idPersonagem = api.IDPersonagem; } name; Durabilidade; atk; idPersonagem; TipoDeArma; }
c1677f034a6f7c8edc21bb70895d56d049d254d5
TypeScript
anli/rna-scorebook
/src/screens/menu-add/use-menu-items.ts
2.640625
3
import R from 'ramda'; import {useState} from 'react'; type Group = { name: string; maxCount: number; items: [string, string][]; }; const useMenuItems = () => { const [pickedMap, setPickedMap] = useState<{ [key: string]: boolean; }>({}); const rolls = Object.entries(rollsMap); const specials = Object.entries(specialsMap); const appetizers = Object.entries(appetizersMap); const desserts = Object.entries(dessertsMap); const groups: Group[] = [ { name: 'rolls', maxCount: 1, items: rolls, }, { name: 'specials', maxCount: 2, items: specials, }, { name: 'appetizers', maxCount: 3, items: appetizers, }, { name: 'desserts', maxCount: 1, items: desserts, }, ]; const groupCountMap = getGroupCountMap(pickedMap); const groupIsValidMap = getGroupIsValidMap(groups, groupCountMap); const isValid = Object.values(groupIsValidMap).every(Boolean); const getIsPicked = (itemId: string) => { return pickedMap[itemId]; }; const toggle = (itemId: string) => { const newPickedState = !(pickedMap[itemId] || false); setPickedMap({...pickedMap, [itemId]: newPickedState}); }; const getGroupIsPickedCount = (group: string) => { return groupCountMap[group] || 0; }; return { rolls, specials, appetizers, desserts, toggle, pickedMap, getIsPicked, groups, getGroupIsPickedCount, isValid, }; }; export default useMenuItems; const itemGroupMap: {[key: string]: string} = { temaki: 'rolls', uramaki: 'rolls', maki: 'rolls', soySauce: 'specials', wasabi: 'specials', spoon: 'specials', chopsticks: 'specials', takeoutBox: 'specials', tea: 'specials', specialOrder: 'specials', menu: 'specials', onigiri: 'appetizers', edamame: 'appetizers', tempura: 'appetizers', misoSoup: 'appetizers', sashimi: 'appetizers', eel: 'appetizers', dumpling: 'appetizers', tofu: 'appetizers', pudding: 'desserts', fruit: 'desserts', greenTeaIceCream: 'desserts', }; const rollsMap = { temaki: 'TEMAKI', uramaki: 'URAMAKI', maki: 'MAKI', }; const specialsMap = { soySauce: 'SOY SAUCE', wasabi: 'WASABI', spoon: 'SPOON', chopsticks: 'CHOPSTICKS', takeoutBox: 'TAKEOUT BOX', tea: 'TEA', specialOrder: 'SPECIAL ORDER', menu: 'MENU', }; const appetizersMap = { onigiri: 'ONIGIRI', edamame: 'EDAMAME', tempura: 'TEMPURA', misoSoup: 'MISO SOUP', sashimi: 'SASHIMI', eel: 'EEL', dumpling: 'DUMPLING', tofu: 'TOFU', }; const dessertsMap = { pudding: 'PUDDING', fruit: 'FRUIT', greenTeaIceCream: 'GREEN TEA ICE CREAM', }; const getGroupCountMap = (pickedMap: {[key: string]: boolean}) => { const pickedItemIds = Object.keys(pickedMap).filter( (x) => pickedMap[x] === true, ); const groupNames = pickedItemIds.map((itemId) => itemGroupMap[itemId]); return groupNames.reduce( (acc: {[key: string]: number}, value) => ({ ...acc, [value]: (acc[value] || 0) + 1, }), {}, ); }; const getGroupIsValidMap = ( groups: Group[], groupCountMap: {[key: string]: number}, ) => { const groupMaxCountMap = groups.reduce((acc, group) => { return {...acc, [group.name]: group.maxCount}; }, {}); return R.mapObjIndexed<any, any>((value, key) => { return !R.isNil(groupCountMap[key]) && value === groupCountMap[key]; }, groupMaxCountMap); };
4186c9c843a938219643859f95b60c7daab8c60f
TypeScript
tom-hewitt/engine
/src/editor/utils/colorUtils.ts
2.546875
3
export function rgbToInt({ r, g, b }: rgb) { // 16^4 = 65536 // 16^2 = 256 return r * 65536 + g * 256 + b; }
1f2f4981ba5a6efe8f23cf686dee1c876dc86e7f
TypeScript
ablahsini/ematchit
/ematchitFront/src/app/resume.ts
2.859375
3
export class Resume { id:number; name:string; file:string; public static fromJson(json: Object): Resume { var resume = new Resume() resume.name = json['name'] resume.file = json['file'] return resume; } }
14f8a2da30030fe1ee057b75044321fa937df43a
TypeScript
l3miage-azizm/examen-2021-s6-8hk8iq
/src/app/games.service.ts
2.828125
3
import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { Game, newGame } from './Game'; interface GamesServiceInterface { readonly gamesObs: Observable<Game[]>; newGame(): void; play(id: number, col: number): void; } @Injectable({ providedIn: 'root' }) export class GamesService implements GamesServiceInterface { private gamesSubj = new BehaviorSubject<Game[]>([newGame()]); readonly gamesObs = this.gamesSubj.asObservable(); constructor() { } newGame(): void { this.gamesSubj.next( [...this.gamesSubj.value, newGame()] ); } play(id: number, col: number): void { const game = this.gamesSubj.value.find( g => g.id === id ); if (game) { const S = game.board.length - 1; const pos = S - [...game.board].reverse().findIndex( line => line[col] === 'EMPTY'); if (pos >= 0 && pos <= S) { game.board[pos][col] = game.turn; const newG: Game = { ...game, turn: game.turn === 'YELLOW' ? 'RED' : 'YELLOW' }; this.gamesSubj.next( this.gamesSubj.value.map( g => g === game ? newG : g) ); } } } }
c602b7f2d941e86f73b00a68ed48c17a6f09a801
TypeScript
yanche/compiler
/src/language/RegEx/astprocess.ts
2.75
3
import { IdGen, flatten, CharCode, NodeId } from "../../utility"; import { ASTNode } from "../../compile"; import { createNFA, NFA, Transition } from "../../automata"; export abstract class ASTNode_REGEX extends ASTNode { public toNFATransition(idGen: IdGen, start: NodeId, terminal: NodeId): ReadonlyArray<Transition> { throw new Error(`not implemented`) } public toNFA(): NFA { const idGen = new IdGen(); const start = idGen.next(); const end = idGen.next(); const trans = this.toNFATransition(idGen, start, end); return createNFA(trans, [start], [end]); } }; export class ASTNode_OR extends ASTNode_REGEX { constructor(public readonly children: ReadonlyArray<ASTNode_REGEX>) { super(); } public toNFATransition(idGen: IdGen, start: NodeId, terminal: NodeId): ReadonlyArray<Transition> { return flatten<Transition>(this.children.map(c => c.toNFATransition(idGen, start, terminal))); } } export class ASTNode_Concat extends ASTNode_REGEX { constructor(public readonly children: ReadonlyArray<ASTNode_REGEX>) { super(); } public toNFATransition(idGen: IdGen, start: NodeId, terminal: NodeId): ReadonlyArray<Transition> { const len = this.children.length; let prevend = start; return flatten<Transition>(this.children.map((c, idx) => { const t = idx === (len - 1) ? terminal : idGen.next(); const ret = c.toNFATransition(idGen, prevend, t); prevend = t; return ret; })); } } export class ASTNode_RStar extends ASTNode_REGEX { constructor(public readonly child: ASTNode_REGEX) { super(); } public toNFATransition(idGen: IdGen, start: NodeId, terminal: NodeId): ReadonlyArray<Transition> { return this.child.toNFATransition(idGen, start, terminal).concat(new Transition(start, terminal, ""), new Transition(terminal, start, "")); } } export class ASTNode_RPlus extends ASTNode_REGEX { constructor(public readonly child: ASTNode_REGEX) { super(); } public toNFATransition(idGen: IdGen, start: NodeId, terminal: NodeId): ReadonlyArray<Transition> { return this.child.toNFATransition(idGen, start, terminal).concat(new Transition(terminal, start, "")); } } export class ASTNode_RQues extends ASTNode_REGEX { constructor(public readonly child: ASTNode_REGEX) { super(); } public toNFATransition(idGen: IdGen, start: NodeId, terminal: NodeId): ReadonlyArray<Transition> { return this.child.toNFATransition(idGen, start, terminal).concat(new Transition(start, terminal, "")); } } export class ASTNode_Range extends ASTNode_REGEX { constructor(public readonly lower: CharCode, public readonly upper: CharCode) { super(); } public toNFATransition(idGen: IdGen, start: NodeId, terminal: NodeId): ReadonlyArray<Transition> { const lower = this.lower; const upper = this.upper; if (lower > upper) throw new Error(`invalid range expression: ${String.fromCharCode(lower)}-${String.fromCharCode(upper)}`); const ret = new Array<Transition>(upper - lower + 1); for (let i = lower; i <= upper; ++i) { ret[i - lower] = new Transition(start, terminal, String.fromCharCode(i)); } return ret; } } export class ASTNode_Single extends ASTNode_REGEX { constructor(public readonly ch: CharCode) { super(); } public toNFATransition(idGen: IdGen, start: NodeId, terminal: NodeId): ReadonlyArray<Transition> { return [new Transition(start, terminal, String.fromCharCode(this.ch))]; } }
d84c61e683c5c7644c407dbb2573ac029ea01a07
TypeScript
leandrosineriz/LaboratorioIII
/Clase4/htdocs/Clase4/javascript/validaciones.ts
2.5625
3
namespace Test{ let xhttp:XMLHttpRequest=new XMLHttpRequest(); export function ValidarUsuario() { var usuario:string=(<HTMLInputElement>document.getElementById("txtUsu")).value; var contraseña=(<HTMLInputElement>document.getElementById("txtPass")).value; xhttp.open("GET","backend/validar.php?usu="+usuario+"&&pass="+contraseña,true); xhttp.send(); xhttp.onreadystatechange = () => { console.log(xhttp.readyState); if (xhttp.readyState == 4 && xhttp.status == 200) { var $respuesta:string=xhttp.responseText; document.bgColor = $respuesta; alert(xhttp.responseText); } }; } }
5c10098dde3224183ade3000416130354be50e94
TypeScript
Sergyus/pwa
/src/api/generated/types.d.ts
2.796875
3
export type Maybe<T> = T | null; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K]; }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; /** The `Upload` scalar type represents a file upload. */ Upload: any; }; export type PostInput = { userId: Scalars['Int']; title: Scalars['String']; body: Scalars['String']; }; export type PostUpdateInput = { userId?: Maybe<Scalars['Int']>; title?: Maybe<Scalars['String']>; body?: Maybe<Scalars['String']>; }; export type CommentInput = { postId: Scalars['Int']; userId: Scalars['Int']; body: Scalars['String']; }; export type CommentUpdateInput = { body?: Maybe<Scalars['String']>; }; export type PaginationInput = { limit?: Maybe<Scalars['Int']>; page?: Maybe<Scalars['Int']>; }; export type PostWithPagination = { __typename?: 'PostWithPagination'; count: Scalars['Int']; currentPage: Scalars['Int']; totalPages: Scalars['Int']; data?: Maybe<Array<Post>>; }; export type UserWithPagination = { __typename?: 'UserWithPagination'; count: Scalars['Int']; currentPage: Scalars['Int']; totalPages: Scalars['Int']; data?: Maybe<Array<User>>; }; export type CommentWithPagination = { __typename?: 'CommentWithPagination'; count: Scalars['Int']; currentPage: Scalars['Int']; totalPages: Scalars['Int']; data?: Maybe<Array<Comment>>; }; export type Query = { __typename?: 'Query'; user: User; users: UserWithPagination; post: Post; posts: PostWithPagination; comment: Comment; comments: CommentWithPagination; }; export type QueryUserArgs = { userId: Scalars['Int']; }; export type QueryUsersArgs = { pagination?: Maybe<PaginationInput>; }; export type QueryPostArgs = { postId: Scalars['ID']; }; export type QueryPostsArgs = { pagination?: Maybe<PaginationInput>; }; export type QueryCommentArgs = { commentId: Scalars['ID']; }; export type QueryCommentsArgs = { pagination?: Maybe<PaginationInput>; }; export type Mutation = { __typename?: 'Mutation'; addPost: Post; updatePost: Post; deletePost: Post; addComment: Comment; updateComment: Comment; deleteComment: Comment; }; export type MutationAddPostArgs = { data: PostInput; }; export type MutationUpdatePostArgs = { postId: Scalars['ID']; data: PostUpdateInput; }; export type MutationDeletePostArgs = { postId: Scalars['ID']; }; export type MutationAddCommentArgs = { data: CommentInput; }; export type MutationUpdateCommentArgs = { commentId: Scalars['ID']; data: CommentUpdateInput; }; export type MutationDeleteCommentArgs = { commentId: Scalars['ID']; }; export type Post = { __typename?: 'Post'; id: Scalars['ID']; title: Scalars['String']; body: Scalars['String']; author: User; comments: Array<Comment>; }; export type Comment = { __typename?: 'Comment'; id: Scalars['ID']; body: Scalars['String']; post: Post; author: User; }; export type User = { __typename?: 'User'; id: Scalars['ID']; name: Scalars['String']; username: Scalars['String']; email: Scalars['String']; address?: Maybe<Address>; phone: Scalars['String']; website: Scalars['String']; company: Company; posts: Array<Post>; }; export type Company = { __typename?: 'Company'; name: Scalars['String']; catchPhrase: Scalars['String']; bs: Scalars['String']; }; export type Address = { __typename?: 'Address'; street: Scalars['String']; suite: Scalars['String']; city: Scalars['String']; zipcode: Scalars['String']; geo: Geo; }; export type Geo = { __typename?: 'Geo'; lat: Scalars['Float']; lng: Scalars['Float']; }; export enum CacheControlScope { Public = 'PUBLIC', Private = 'PRIVATE', }
b8f909ff0c82553480000368d1acf060f8e855c7
TypeScript
catull/calendariale
/src/calendar/RomanCalendar.ts
2.984375
3
import { amod, mod } from '../Astro'; import { INVALID_COUNT, INVALID_LEAP_DAY, INVALID_MONTH, Month, ROMAN_MONTH_MAX_DAYS, RomanEvent } from '../Const'; import { JulianCalendar } from './JulianCalendar'; import type { JulianDate } from './JulianDate'; import { RomanDate } from './RomanDate'; import { CalendarDateValidationException } from './core/index'; export class RomanCalendar { // Calculate Roman calendar date from Julian day number (JDN) public static fromJdn(jdn: number): RomanDate { const date: JulianDate = JulianCalendar.fromJdn(jdn); let year: number = date.getYear(); let month: number = date.getMonth(); let count: number = date.getDay(); let event: RomanEvent = RomanEvent.KALENDS; let leap = false; if (count === 1) { event = RomanEvent.KALENDS; } else if (count <= this.nonesOfMonth(month)) { event = RomanEvent.NONES; count = this.nonesOfMonth(month) - count + 1; } else if (count <= this.idesOfMonth(month)) { event = RomanEvent.IDES; count = this.idesOfMonth(month) - count + 1; } else if (month !== Month.FEBRUARY || !JulianCalendar.isLeapYear(year)) { const m = amod(month + 1, 12); const y = m !== 1 ? year : year !== -1 ? year + 1 : 1; const kalends1 = this.toJdn(y, m, RomanEvent.KALENDS, 1, false); year = y; month = m; event = RomanEvent.KALENDS; count = kalends1 - jdn + 1; } else if (count < 25) { month = Month.MARCH; event = RomanEvent.KALENDS; count = 30 - count; } else { month = Month.MARCH; event = RomanEvent.KALENDS; count = 31 - count; leap = count === 6; } return new RomanDate(jdn, year, month, event, count, leap); } // Determine Julian day number (JDN) from Roman calendar date public static toJdn(year: number, month: number, event: RomanEvent, count: number, leap: boolean): number { this.validate(year, month, event, count, leap); const day: number = event === RomanEvent.KALENDS ? 1 : event === RomanEvent.NONES ? this.nonesOfMonth(month) : this.idesOfMonth(month); let jdn: number = JulianCalendar.toJdn(year, month, day) - count; if (leap) { jdn += 1; } if ( !JulianCalendar.isLeapYear(year) || month !== Month.MARCH || event !== RomanEvent.KALENDS || count < 6 || count > 16 ) { jdn += 1; } return jdn; } /** * Return the date of the Ides in Roman month. * @param {number} month the month * @result {number} either the 15th or 13th */ private static idesOfMonth(month: number): number { if (month === Month.MARCH || month === Month.MAY || month === Month.JULY || month === Month.OCTOBER) { return 15; } return 13; } /** * Return the date of the Nones in Roman month. * @param {number} month the month * @result {number} either the 7th or 5th */ private static nonesOfMonth(month: number): number { return this.idesOfMonth(month) - 8; } private static validate(year: number, month: number, event: RomanEvent, count: number, leap: boolean): void { if (month < 1 || month > 12) { throw new CalendarDateValidationException(INVALID_MONTH); } const previousMonth: number = mod(month - 1, 12); const maxKalends: number = ROMAN_MONTH_MAX_DAYS[mod(month - 2, 12)] - this.idesOfMonth(previousMonth) + 1; const maxCount: number = event === RomanEvent.IDES ? 8 : event === RomanEvent.NONES ? this.nonesOfMonth(month) - 1 : maxKalends; if (count < 1 || count > maxCount) { throw new CalendarDateValidationException(INVALID_COUNT); } // In a leap year, the 6th day before the Kalends of March appears twice, once leap and once non-leap. // The Romans distingiushed them as // - 'a.d. VI Kal. Mart.', written out 'ante diem sextum Kalendas Martii' -> non-leap day // - 'a.d. bis VI Kal. Mart.', similarly as 'ante diem bis sextum Kalendas Martii' -> LEAP day // Here is the correspondance to the days in the Julian calendar: // 0004-02-25 [Julian Calendar] === 0004 a.d. bis VI Kal. Mart. [Roman Calendar] LEAP // 0004-02-24 [Julian Calendar] === 0004 a.d. VI Kal. Mart. [Roman Calendar] // 0004-02-23 [Julian Calendar] === 0004 a.d. VII Kal. Mart. [Roman Calendar] // In a non-leap year, the correspondance is: // 0003-02-24 [Julian Calendar] === 0003 a.d. VI Kal. Mart. [Roman Calendar] // 0003-02-23 [Julian Calendar] === 0003 a.d. VII Kal. Mart. [Roman Calendar] // In other words, the 6th day before the Kalends of March is the only date that may be used twice IN A LEAP YEAR. // Thus, leap days were inserted between the 6th and 7th day originally (Feb. 25th). if ( leap && (event !== RomanEvent.KALENDS || month !== Month.MARCH || count !== 6 || !JulianCalendar.isLeapYear(year)) ) { throw new CalendarDateValidationException(INVALID_LEAP_DAY); } } }
85d08a2dc836eedd926cd6fde8a3ff9dc2243a29
TypeScript
molvqingtai/yunzhixin-official
/src/hooks/useDebounce.ts
3.046875
3
import { useState } from 'react' const useDebounce = (func: Function, delay: number): (() => void) => { const [prevTime, setPrevTime] = useState(+new Date()) return (...args: []) => { const nowTime = +new Date() console.log('prevTime', nowTime - prevTime) if (nowTime - prevTime >= delay) { setPrevTime(nowTime) func(...args) } } } export default useDebounce // import { useEffect, useState } from 'react' // const useDebounce = (value: any, delay: number): any => { // const [debounceValue, setDebunceValue] = useState(value) // useEffect(() => { // const timer = setTimeout(() => setDebunceValue(value), delay) // return () => clearTimeout(timer) // }, [value, delay]) // return debounceValue // } // export default useDebounce
9ee06d6ae5219329417673b05b7bf113785e912b
TypeScript
marcokam/Nudge
/Nudge.ClientSDK/Util/fp/Instances/Compare.test.ts
3.53125
4
import { Compare } from "./Compare"; import { propOr } from "../object"; import { Comparator } from "../function"; const flipDir = <A>(f: Comparator<A>) => (a: A, b: A) => f(a, b) === 0 ? 0 : f(a, b) === -1 ? 1 : -1; const ascNum = (a: number, b: number) => a === b ? 0 : a < b ? -1 : 1; const ascString = (a: string, b: string) => a.localeCompare(b) === 0 ? 0 : a.localeCompare(b) === -1 ? -1 : 1; describe("Compare", () => { it("wraps a comparator to be run with run", () => { const numCompare = Compare.of(ascNum); expect(numCompare.run(1, 2)).toEqual(-1); expect(numCompare.run(0, 0)).toEqual(0); expect(numCompare.run(700, 70)).toEqual(1); }); it("acts as a monoid", () => { const c1 = Compare.of(ascNum).concat(Compare.empty<number>()); const c2 = Compare.empty<number>().concat(Compare.of(ascNum)); expect(c1.run(5, 4)).toEqual(c2.run(5, 4)); expect(c1.run(80, 80)).toEqual(c2.run(80, 80)); expect(c1.run(999, -5)).toEqual(c2.run(999, -5)); }); it("can transform the input before running", () => { expect( [{ name: "one", value: 1 }, { name: "two", value: 2 }, { name: "three", value: 3 }] .sort(Compare.of(flipDir(ascNum)) .contramap(propOr("value", 0)) .run) ).toEqual([{ name: "three", value: 3 }, { name: "two", value: 2 }, { name: "one", value: 1 }]) }); it("can combine comparators together (falls through if 0)", () => { interface T { name: string; age: number; }; const ts: T[] = [{ name: "Donny", age: 2 }, { name: "Leo", age: 2 }, { name: "Raph", age: 3 }, { name: "Mikey", age: 3 }]; expect( ts.sort(Compare.of(flipDir(ascNum)) .contramap((t: T) => t.age) .concat(Compare.of(ascString) .contramap((t: T) => t.name)) .run) ).toEqual([{ name: "Mikey", age: 3 }, { name: "Raph", age: 3 }, { name: "Donny", age: 2 }, { name: "Leo", age: 2 }]); }); });
c081a59b8849020c6109c2ebfe359b903513f80d
TypeScript
vuestorefront/storefront-ui
/packages/sfui/shared/utils/browser.ts
2.546875
3
export const isBrowser = typeof window !== 'undefined'; export const isReduceMotionEnabled = isBrowser && window?.matchMedia('(prefers-reduced-motion: reduce)').matches; declare global { interface Navigator { userAgentData?: { platform: string; brands: { brand: string; version: string; }[]; }; } } function testPlatform(re: RegExp) { return typeof window !== 'undefined' && window.navigator != null ? re.test(window.navigator['userAgentData']?.platform || window.navigator.platform) : false; } function testUserAgent(re: RegExp) { if (typeof window === 'undefined' || window.navigator == null) { return false; } return ( window.navigator['userAgentData']?.brands.some((brand: { brand: string; version: string }) => re.test(brand.brand), ) || re.test(window.navigator.userAgent) ); } export const isMac = testPlatform(/^Mac/i); export const isAndroid = testUserAgent(/Android/i); export const isSafari = testUserAgent(/^((?!chrome|android).)*safari/i);
45db8c9502b3bb2a7a027f321dca713f72494155
TypeScript
vold-io/stellium
/src/@stellium-common/tools/sort_functions.ts
3.09375
3
export const sortByKey = (collection: Array<any>, key: string): Array<any> => { return collection.sort((a, b) => { if (a[key] < b[key]) return -1; if (a[key] > b[key]) return 1; return 0; }); };
6d58fc89f1c0c32afd2f84351aa6072b01335731
TypeScript
corefunc/corefunc
/array/search/search-linear.ts
3.4375
3
export function arraySearchLinear(array: number[], target: number): number { for (let index = 0; index < array.length; index++) { if (array[index] === target) { return index; } } return -1; }
5c93b15241874b0d81e73c708ec6665d3979e9b4
TypeScript
mickielreid/Auth0-Spring-Angular
/Angular/src/app/shared/SortingTypesHolder.ts
3.015625
3
import { Student } from 'src/app/classes/student'; // this class holds all the interface and types needed to sort the student and admin tables export type SortColumn = keyof Student | '' ; export type SortDirection = 'asc' | 'desc' | ''; export const rotate: {[key: string]: SortDirection} = { 'asc': 'desc', 'desc': '', '': 'asc' }; export const compare = (v1: string | number, v2: string | number) => v1 < v2 ? -1 : v1 > v2 ? 1 : 0; export interface SortEvent { column: SortColumn; direction: SortDirection; }
d1a3cd5a62bbd2a65e78d784b639111823861d9e
TypeScript
chewtoys/api-1
/app/Models/HouseType/index.ts
2.546875
3
/** * @description Тип дома */ export default (sequelize: any, Sequelize: any) => { const HouseType = sequelize.define("house_type", { house_type_id: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, allowNull: false, notEmpty: true }, name: { type: Sequelize.STRING(50), allowNull: false, notEmpty: true } }, { freezeTableName: true, tableName: "house_types", underscored: true }); return HouseType; }
06a6148654d69157cb79432f63308b2d8d8d35e2
TypeScript
cotsell/-Ang-OldNote-Cli
/src/app/service/gater.service.ts
2.515625
3
import { Injectable, EventEmitter } from '@angular/core'; // 이 서비스는 Give And Take하는 용도의 중개자 서비스에요. // 한번에 여러개의 구독자가 생기는 경우에는 어떻게 할 지 고민을 해봐야 겠어요. // 배열을 막 이렇게 끼얹나? @Injectable() export class GaterService { giveEvent: EventEmitter<any> = new EventEmitter(); takeEvent: EventEmitter<any> = new EventEmitter(); constructor() { // console.log('Gater Service!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!'); } }
9f9173de27ddd3b7d0fced08364d803d16b24595
TypeScript
ryoboua/starship_royal
/game/classes/Game.ts
2.609375
3
import Lobby from "../../shared/classes/Lobby" import AsteroidField from "./AsteroidField" import { ClientModel, GameModel, Level, PlayerPositionUpdate, GameActionContext as GameFrontEndContext, GameState, PlayerScores } from "../../shared/interfaces"; import { GRID_SIZE, ROUND_TIME, GAME_OVER_REASONS } from "../constants" import Vector from './Vector'; export default class Game extends Lobby implements GameModel { level: number levels: Level[] asteroidField: AsteroidField gridsize: number timer: number _context: GameFrontEndContext | undefined constructor() { super() this.level = 0 this.levels = [] this.asteroidField = new AsteroidField() this.gridsize = GRID_SIZE this.timer = ROUND_TIME this._context } static createGameState(players: ClientModel[], context: GameFrontEndContext): Game { const game = new Game() players.forEach(player => game.addPlayer(player)) game.setFrontEndContext(context) return game } get type() { return this._context?.rootState.game.type || 'single' } resetState() { this.timer = ROUND_TIME this.asteroidField = new AsteroidField() Object.values(this.players).forEach((player) => player.reset()) } setFrontEndContext(context: GameFrontEndContext) { this._context = context } dispatch(eventName: string, data?: any) { this._context?.dispatch(eventName, data) } commit(eventName: string, data?: any) { this._context?.commit(eventName, data) } gameLoop(): GAME_OVER_REASONS | undefined { this.asteroidField.updatePosition() Object.values(this.players).forEach((player) => { if (player.isAlive) { player.updatePosition(this.asteroidField, this.isLocal(player.socketId)) if (!player.isAlive) { this.dispatch("playerDead", player.socketId) } } }) if (!Object.values(this.players).some((player) => player.isAlive)) { return GAME_OVER_REASONS["ALL_DEAD"] } // if (!this.timer) { // return GAME_OVER_REASONS["TIMER"] // } return } getGameState(): GameState { return { players: this.players, asteroidField: this.asteroidField, gridsize: this.gridsize, timer: this.timer, playerScores: this.playerScores, } } get playerScores(): PlayerScores { return Object.values(this.players) .map((player) => ({ name: player.name, score: player.score, color: player.color })) .sort((a, b) => b.score - a.score) } addLevel(level: Level) { this.levels.push(level) } decrementTimer() { if (!this.timer) { return } this.timer-- } getCurrentLevel(): number { return this.levels.length } destroyShip(socketId: string) { const player = this.players[socketId] if (!player) { return } player.selfDestruct() } isLocal(socketId: string): boolean { return this._context?.rootState.client.socketId === socketId } getPlayerWithHighestScore() { const { name, score } = Object.values(this.players).sort((a, b) => b.score - a.score)[0] return { name, score } } getPlayerPosition(socketId: string): Vector { return this.players[socketId].pos } broadcastPosition() { if (!this._context) { return } const { socketId } = this._context.rootState.client const { pos } = this.players[socketId] const payload: PlayerPositionUpdate = { socketId, pos } this.dispatch("broadcastPosition", payload) } }
294fb817b933354f2f17803aae83998668f5b466
TypeScript
anselmstordeur/myTsChess
/Pieces/Rook.ts
2.859375
3
/** * Created by Anselm Stordeur on 11/24/16. */ import {Piece} from "../Piece"; import {Player} from "../Player"; import {Vector} from "../Primitives/Vector"; export class Rook extends Piece { /** * Creates a new Rook * @param {Vector} position * @param {Player} player * @param {object} options * @param {boolean} options.captured * @param {boolean} options.moved */ constructor(position: Vector, player: Player, options?) { super('Rook', position, player, options); } public isValidMove(): boolean { // TODO: implement validation of move return false; } }
6a0badbf27ea276d9cb195c8c40e9356092cdd51
TypeScript
sourvinos/transfers-v3.9
/ClientApp/src/app/shared/pipes/format-number.pipe.ts
2.703125
3
import { Pipe, PipeTransform } from '@angular/core' import { HelperService } from '../services/helper.service' @Pipe({ name: 'formatNumber' }) export class FormatNumberPipe implements PipeTransform { //#region variables private language = '' private seperators = [] private regEx = /(\d)(?=(\d{3})+(?!\d))/g //#endregion constructor(private helperService: HelperService) { this.language = this.getLanguage() this.seperators = this.setSeperators() } //#region public methods public transform(value: number, fractionDigits = 0, addSymbol = false): string { switch (true) { case (value == 0): return value.toFixed(fractionDigits) .replace(this.seperators[0], this.seperators[1]) .replace(this.regEx, '$1' + this.seperators[0]) + (addSymbol ? '% ––' : '') case (value < 0): return value.toFixed(fractionDigits) .replace(this.seperators[0], this.seperators[1]) .replace(this.regEx, '$1' + this.seperators[0]) + (addSymbol ? '% ▼' : '') case (value > 0): return value.toFixed(fractionDigits) .replace(this.seperators[0], this.seperators[1]) .replace(this.regEx, '$1' + this.seperators[0]) + (addSymbol ? '% ▲' : '') } } //#endregion //#region private methods private getLanguage(): string { return this.helperService.readItem("language") == '' ? 'en-GB' : this.helperService.readItem("language") } private setSeperators(): string[] { switch (this.language) { case 'cs-CZ': return [',', '.'] case 'de-DE': return ['.', ','] case 'el-GR': return ['.', ','] case 'en-GB': return [',', '.'] } } //#endregion }
4395154257cf975e407df2e6306ef0067a149e78
TypeScript
smeup/ketchup
/packages/ketchup/src/managers/kup-debug/kup-debug-declarations.ts
3.0625
3
/** * Interface for the logs of KupDebug. */ export interface KupDebugLog { category: KupDebugCategory; date: Date; id: string; element: string | Object; message: string; } /** * Interface for printed logs. */ export interface KupDebugLogPrint { [index: string]: { date: string; element: string | Object; message: string; }[]; } /** * Category of debug logs. */ export enum KupDebugCategory { INFO = 'Informational', WARNING = 'Warning', ERROR = 'Error', } /** * Colors associated with every type of log to be printed. */ export enum KupDebugLogColor { 'Load' = 'green', 'Render' = 'green', 'Resize' = 'green', 'Misc' = 'blue', 'Total' = 'teal', }
406e10f8aa93097290c7042541e12350d2a8d97d
TypeScript
ucll-algoritmisch-denken/testing-framework
/src/animation/number-animation-builder.ts
3.171875
3
import { IAnimation } from './animation'; import { constant } from './constant'; import { sequence } from './sequence'; import { linear } from './linear-animation'; function appendJump<T>(animation : IAnimation<T>, value : T) : IAnimation<T> { const appended = constant(value, 0); return sequence(animation, appended); } function appendConstant<T>(animation : IAnimation<T>, duration : number) : IAnimation<T> { const value = animation.endValue; const appended = constant(value, duration); return sequence(animation, appended); } function appendLinear(animation : IAnimation<number>, to : number, duration : number) : IAnimation<number> { const from = animation.endValue; const appended = linear(from, to, duration); return sequence(animation, appended); } export class NumberAnimationBuilder { private animation : IAnimation<number>; constructor(initial : number) { this.animation = constant<number>(initial, 0); } relativeTo(delta : number, duration : number) { this.absoluteTo(this.animation.at(this.animation.duration) + delta, duration); } absoluteTo(to : number, duration : number) { this.animation = appendLinear(this.animation, to, duration); } constant(duration : number) { this.animation = appendConstant(this.animation, duration); } jump(to : number) { this.animation = appendJump(this.animation, to); } build() : IAnimation<number> { return this.animation; } }
9be8dbc922b0de9945024618428599624ce3913c
TypeScript
maziac/asm-api-doc-tool
/src/labelsfile.ts
3.234375
3
import { readFileSync } from 'fs'; import { HierarchyEntry } from './hierarchyentry'; /** * Class to represent the list file. */ export class LabelsFile { /// All the lines of text read from the file. public lines: Array<string>; /** * Reads the labels file. * @param filename */ constructor(filename: string) { this.lines = readFileSync(filename).toString().split('\n'); } /** * Returns all labels with line numbers that are included in the * 'exports'. * Parses the list file lines, searches for "EXPORT" and creates a hierarchy map out of it. * The map is a map-of-maps. * E.g. text.layer2.print_string, text.ula.print_string, text.layer2.print_char, will become: * text - layer2 - print_string * +- ula - print_string * +- print_char * @return A hierarchy with */ public getExports(): HierarchyEntry { // Create map const hierarchyMap = new HierarchyEntry(); // Parse all lines for(const line of this.lines) { // Parsing: A list file line looks like this: // "math.udiv_hl_e: EQU 0x00000059" // or // "label: equ $4000" const match = /^([a-z_][\w\.]*):?\s*equ\s+(.*)/i.exec(line); if(match) { // Get label const label = match[1]; // Divide dots and put all parts in an own map const labelParts = label.split('.'); let map = hierarchyMap; let subLabel; for(const part of labelParts) { subLabel = (subLabel) ? subLabel+'.'+part : part; // Check if label already exists in map let nextMap = map.elements.get(part); if(!nextMap) { // Create new entry nextMap = new HierarchyEntry(subLabel); map.elements.set(part, nextMap); } // Next map = nextMap; } // Add value to last map const value = this.parseValue(match[2]); map.labelValue = value; } } // Return return hierarchyMap; } /** * Converts a string into a number. If string starts with "0x" or "$" * it is interpreted as hexadecimal, otherwise decimal. * @param valueString The string to convert. * @return The value of the string. */ protected parseValue(valueString: string) { if(valueString.startsWith('$')) return parseInt('0x' + valueString.substr(1)); // Skip first character return parseInt(valueString); } }
f1f86980d5737f826465af62a89c2d970991cfce
TypeScript
taoyuan/biner
/src/encoding-length.ts
2.96875
3
import {isUserType, isType} from './util'; import * as symbols from './internal/symbols'; import {Metadata} from './internal/meta'; /** * Get the number of bytes to encode `obj` using `schema`. * @param {*} obj Any valid js object. * @param {Object} schema * @returns {number} */ export function encodingLength(obj, schema) { const context = new Metadata(); encodingLengthCommon(obj, schema, context); Metadata.clean(context); return context.bytes; } /** * @param {any} item * @param {Object} typeOrSchema * @param {Metadata} context */ export function encodingLengthCommon(item, typeOrSchema, context) { if (isType(typeOrSchema) && typeOrSchema.encodingLength) { context[symbols.bytes] += typeOrSchema.encodingLength.call(context, item); } else { encodingLengthSchema(item, typeOrSchema, context); } } /** * @param {any} item * @param {Object} schema * @param {Metadata} context */ function encodingLengthSchema(item, schema, context) { if (!isUserType(schema)) { throw new TypeError('Argument `schema` should be a plain object.'); } if (context.node === undefined) { context.node = item; context.current = item; } else { context.current = item; } const keys = Object.keys(schema); for (let i = 0; i < keys.length; i += 1) { const key = keys[i]; const type = schema[key]; const value = item[key]; if (!isType(type)) { encodingLengthSchema(value, type, context); context.current = item; continue; // eslint-disable-line no-continue } if (type.encodingLength) { context[symbols.bytes] += type.encodingLength.call(context, value); } } }
800f7918d93456c202c67749885ffa2344dabf00
TypeScript
SSmJaE/cxmooc-tools
/src/internal/app/mooc.ts
2.734375
3
import {CxPlatform} from "../../mooc/chaoxing/platform"; import {ZhsPlatform} from "../../mooc/zhihuishu/platform"; import {Course163Platform} from "../../mooc/course163/platform"; import {IEventListener} from "@App/internal/utils/event"; import {Task} from "@App/internal/app/task"; // 事件 export type MoocEvent = "complete" | "reload" | "error" | "taskComplete"; // 单个Mooc任务,可能会被抛弃 export interface Mooc { Init(): any } // Mooc任务集,未来更倾向于使用此接口 export interface MoocTaskSet extends Mooc, IEventListener<MoocEvent> { // 初始化 Init(): Promise<any> // 停止 Stop(): Promise<any> // 返回下一个任务点 Next(): Promise<Task> // 设置任务点位置 SetTaskPointer(index: number): void; } // Mooc工厂,可以根据页面url等数据,来返回对应的mooc任务 // 未来返回值Mooc可能会换为MoocTaskSet export interface MoocFactory { CreateMooc(): Mooc } // 默认工厂 export class DefaultMoocFactory implements MoocFactory { public CreateMooc(): Mooc { let mooc = new CxPlatform().CreateMooc(); if (mooc == null) { mooc = new ZhsPlatform().CreateMooc(); } if (mooc == null) { mooc = new Course163Platform().CreateMooc(); } return mooc; } }
27bfa9dd37f34136c226313d9deb5bd3e95863c0
TypeScript
AkashSDas/typescript_code_snippets
/01_basic_types/basic_types.ts
4.4375
4
// ****** Basic types ****** // =================== // Boolean // =================== let isDone: boolean = true; let isAlive: boolean = false; // =================== // Number // =================== // As in JavaScript, all numbers in TypeScript are either floating point values or BigIntegers. // These floating point numbers get the type number, while BigIntegers get the type bigint. let decimal: number = 6; let hex: number = 0xffffff; let binary: number = 0b01010; let octal: number = 0o744; let big: bigint = 100n; // =================== // String // =================== let color: string = "black"; let firstName: string = "james"; // =================== // Array // =================== let friends: string[] = ["james", "bond", "ethan", "hunt"]; let nums: Array<number> = [1, 2, 3, 4]; // =================== // Tuple // =================== // Tuple types allow you to express an array with a fixed number of elements // whose types are known, but need not be the same. // For example, you may want to represent a value as a pair of a string and a number let tuple: [string, number]; tuple = ["james", 7]; // OK // tuple = [7, 'james'] // Error // =================== // Enum // =================== // An enum is a way of giving more friendly names to sets of numeric values. enum Color1 { Red, Green, Blue, } let c1: Color1 = Color1.Green; // By default, enums begin numbering their members starting at 0. // You can change this by manually setting the value of one of its members. // For example, we can start the previous example at 1 instead of 0: enum Color2 { Red = 1, Green, Blue, } let c2: Color2 = Color2.Green; // Or, even manually set all the values in the enum: enum Color3 { Red = 1, Green = 2, Blue = 4, } let c3: Color3 = Color3.Green; // A handy feature of enums is that you can also go from a numeric value to the name // of that value in the enum. For example, if we had the value 2 but weren’t sure what // that mapped to in the Color enum above, we could look up the corresponding name: enum Color4 { Red = 1, Green, Blue, } let colorName: string = Color4[2]; // Displays 'Green' console.log(colorName); // =================== // Unknown // =================== // We may need to describe the type of variables that we do not know when we are writing an application. // These values may come from dynamic content – e.g. from the user – or we may want to intentionally // accept all values in our API. In these cases, we want to provide a type that tells the compiler and // future readers that this variable could be anything, so we give it the unknown type. let notSure: unknown = 4; notSure = "maybe a string instead"; notSure = false; // If you have a variable with an unknown type, you can narrow it to something more specific by doing // typeof checks, comparison checks, or more advanced type guards declare const maybe: unknown; // 'maybe' could be a string, object, boolean, undefined, or other types // const aNumber: number = maybe; // Type 'unknown' is not assignable to type 'number' if (maybe === true) { // TypeScript knows that maybe is a boolean now const aBoolean: boolean = maybe; // So, it cannot be a string // const aString: string = maybe; // Type 'boolean' is not assignable to type 'string'. } if (typeof maybe === "string") { // TypeScript knows that maybe is a string const aString: string = maybe; // So, it cannot be a boolean // const aBoolean: boolean = maybe; // Type 'string' is not assignable to type 'boolean'. } // =================== // Any // =================== // In some situations, not all type information is available or its declaration would take an // inappropriate amount of effort. These may occur for values from code that has been written // without TypeScript or a 3rd party library. In these cases, we might want to opt-out of type // checking. To do so, we label these values with the any type: declare function getValue(key: string): any; // OK, return value of 'getValue' is not checked const str: string = getValue("myString"); // The any type is a powerful way to work with existing JavaScript, // allowing you to gradually opt-in and opt-out of type checking during compilation. // Unlike unknown, variables of type any allow you to access arbitrary properties, // even ones that don’t exist. These properties include functions and TypeScript will not check // their existence or type: let looselyTyped: any = 4; // OK, ifItExists might exist at runtime looselyTyped.ifItExists(); // OK, toFixed exists (but the compiler doesn't check) looselyTyped.toFixed(); let strictlyTyped: unknown = 4; // strictlyTyped.toFixed(); // Object is of type 'unknown'. // The any will continue to propagate through your objects: let looselyTyped$: any = {}; let d = looselyTyped$.a.b.c.d; // ^ = let d: any // After all, remember that all the convenience of any comes at the cost of losing type safety. // Type safety is one of the main motivations for using TypeScript and you should try to avoid // using any when not necessary. // =================== // Void // =================== // void is a little like the opposite of any: the absence of having any type at all. You may // commonly see this as the return type of functions that do not return a value: function greeting(): void { console.log("Hello"); } // Declaring variables of type void is not useful because you can only assign null // (only if --strictNullChecks is not specified, see next section) or undefined to them: let unusable: void = undefined; // OK if `--strictNullChecks` is not given unusable = null; // =================== // Null and Undefined // =================== // Much like void, they’re not extremely useful on their own: let u: undefined = undefined; let n: null = null; // =================== // Never // =================== // The never type represents the type of values that never occur. // For instance, never is the return type for a function expression or an arrow function // expression that always throws an exception or one that never returns. // Variables also acquire the type never when narrowed by any type guards that can never be true. // The never type is a subtype of, and assignable to, every type; however, no type is a subtype of, // or assignable to, never (except never itself). Even any isn’t assignable to never. // Function returning never must not have a reachable end point function error(message: string): never { throw new Error(message); } // Inferred return type is never function fail() { return error("Something failed"); } // Function returning never must not have a reachable end point function infiniteLoop(): never { while (true) {} } // =================== // Object // =================== // object is a type that represents the non-primitive type, // i.e. anything that is not number, string, boolean, bigint, symbol, null, or undefined. // With object type, APIs like Object.create can be better represented. For example: declare function create(o: object | null): void; create({ props: 0 }); create(null); // assigning any other data type will give error // =================== // Type assertions // =================== // A type assertion is like a type cast in other languages, but it performs no special checking // or restructuring of data. It has no runtime impact and is used purely by the compiler. // TypeScript assumes that you, the programmer, have performed any special checks that you need. // Type assertions have two forms. let someValue: unknown = "this is a string"; // 1. as-syntax let strLength: number = (someValue as string).length; // 2. angle-bracket syntax let strAnotherLength: number = (<string>someValue).length; // =================== // About Number, String, Boolean, Symbol and Object // =================== // It can be tempting to think that the types Number, String, Boolean, Symbol, or Object // are the same as the lowercase versions recommended above. These types do not refer to // the language primitives however, and almost never should be used as a type. // function reverse(s: String): String { // return s.split("").reverse().join(""); // } // reverse("hello world"); // Instead, use the types number, string, boolean, object and symbol. function reverse(s: string): string { return s.split("").reverse().join(""); } reverse("hello world");
5292b1f76eb34cafd7343baf97ee9677cc512bcf
TypeScript
JSProxy/tooldir
/设计模式/share/src/factory.ts
3.96875
4
//简单工厂 interface IComputer { opend(): void } class IntelComputer implements IComputer { public opend(){ console.log('这是 intel 的电脑') } } class AmdComputer implements IComputer { public opend(){ console.log('这是 amd 的电脑') } } class ComputerFactory { public produce(type: String): IComputer { if(type === 'intel'){ return new IntelComputer() }else if(type === 'amd'){ return new AmdComputer() }else { console.log('请填写正确的品牌') } } } const cf = new ComputerFactory() cf.produce('intel').opend() // 多方法工厂 class ComputerFactoryMulty { public produceIntel(): IComputer { return new IntelComputer() } public produceAmd(): IComputer { return new AmdComputer() } } const cfm = new ComputerFactoryMulty() cfm.produceAmd().opend(); //静态工厂 class ComputerFactoryStatic { public static produceIntel(): IComputer { return new IntelComputer() } public static produceAmd(): IComputer { return new AmdComputer() } } ComputerFactoryStatic.produceAmd().opend()
c70167eb8525c751e8de209bded95f9e7c444093
TypeScript
Richardowsky/remme-client-js
/packages/remme-transaction-service/src/index.ts
2.5625
3
import { RemmeMethods, IRemmeApi } from "remme-api"; import { IRemmeAccount } from "remme-account"; import { sha512, NodeConfigRequest } from "remme-utils"; import * as protobuf from "remme-protobuf"; import { IRemmeTransactionService } from "./interface"; import { BaseTransactionResponse, IBaseTransactionResponse, CreateTransactionDto, SendTransactionDto, } from "./models"; /** * Class for creating and sending transactions * @example * ```typescript * const remme = new Remme.Client(); * const familyName = "pub_key"; * const familyVersion = "0.1"; * const inputs = []; * const outputs = []; * const payloadBytes = new Buffer("my transaction"); * const createDto = new CreateTransactionDto( * familyName, * familyVersion, * inputs, * outputs, * payloadBytes, * ); * const transaction = await remme.transaction.create(createDto); * const sendResponse = await remme.transaction.send(transaction); * ``` */ class RemmeTransactionService implements IRemmeTransactionService { // index signature [key: string]: any; private readonly _remmeApi: IRemmeApi; private readonly _remmeAccount: IRemmeAccount; /** * @example * Usage without remme main package * ```typescript * const remmeApi = new RemmeApi(); // See RemmeRest implementation * const remmeAccount = new RemmeAccount(); // See RemmeAccount implementation * const remmeTransaction = new RemmeTransactionService(remmeApi, remmeAccount); * ``` * @param {IRemmeApi} remmeApi * @param {IRemmeAccount} remmeAccount */ public constructor(remmeApi: IRemmeApi, remmeAccount: IRemmeAccount) { this._remmeApi = remmeApi; this._remmeAccount = remmeAccount; } /* tslint:disable */ /** * Documentation for building transactions * https://sawtooth.hyperledger.org/docs/core/releases/latest/_autogen/sdk_submit_tutorial_js.html#building-the-transaction * @example * ```typescript * const familyName = "pub_key"; * const familyVersion = "0.1"; * const inputs = []; * const outputs = []; * const payloadBytes = Uint8Array.from("my transaction"); * const createDto = new CreateTransactionDto( * familyName, * familyVersion, * inputs, * outputs, * payloadBytes, * ); * const transaction = await remmeTransaction.create(createDto); * ``` * @param {CreateTransactionDto} settings * @returns {Promise<string>} */ /* tslint:enable */ public async create(settings: CreateTransactionDto): Promise<string> { const { familyName, familyVersion, inputs, outputs, payloadBytes, } = settings; const { node_public_key: batcherPublicKey, } = await this._remmeApi.sendRequest<NodeConfigRequest>(RemmeMethods.nodeConfig); const transactionHeaderBytes = protobuf.TransactionHeader.encode({ familyName, familyVersion, inputs: [ ...inputs, this._remmeAccount.address ], outputs: [ ...outputs, this._remmeAccount.address ], signerPublicKey: this._remmeAccount.publicKeyHex, nonce: sha512(Math.floor(Math.random() * 1000).toString()), batcherPublicKey, payloadSha512: sha512(payloadBytes), }).finish(); const signature = this._remmeAccount.sign(transactionHeaderBytes); let transaction = protobuf.Transaction.encode({ header: transactionHeaderBytes, headerSignature: signature, payload: payloadBytes, }).finish(); try { // @ts-ignore transaction = btoa(String.fromCharCode(...transaction)); } catch (e) { // @ts-ignore transaction = transaction.toString("base64"); } // @ts-ignore return transaction; } /** * @example * ```typescript * const sendResponse = await remmeTransaction.send(transaction); * console.log(sendRequest.batchId); * ``` * @param {string} transaction * @returns {Promise<IBaseTransactionResponse>} */ public async send(transaction: string): Promise<IBaseTransactionResponse> { const requestPayload = new SendTransactionDto(transaction); const batchId = await this._remmeApi .sendRequest<SendTransactionDto, string>(RemmeMethods.transaction, requestPayload); return new BaseTransactionResponse( this._remmeApi.networkConfig, batchId, ); } } export { RemmeTransactionService, IRemmeTransactionService, BaseTransactionResponse, IBaseTransactionResponse, CreateTransactionDto, SendTransactionDto, };
65ce3d6fd2147c380bdb34eabbac1e37c0e12a32
TypeScript
juniorpb/r3-ts-cli
/src/lib/route.ts
2.640625
3
import chalk from 'chalk'; import fs from 'fs'; import CLI from 'clui'; // Libs const Spinner = CLI.Spinner; class Route { private setImport(file: any, importStr: string) { const data = fs.readFileSync(file, 'utf-8'); const result = data.replace(/\/\* Routes \*\//g, importStr); fs.writeFileSync(file, result, 'utf-8'); } private setRoute(file: any, routeStr: string) { const data = fs.readFileSync(file, 'utf-8'); const result = data.replace(/<Switch>/g, routeStr); fs.writeFileSync(file, result, 'utf-8'); } private setMenu(name: string, choise: any) { const file = `./src/redux/ducks/menu/index.js`; let link; if (choise.option == 'internal') { link = `/in/${name}`; } else { link = `/${name}`; } const data = fs.readFileSync(file, 'utf-8'); const content = `}\n { id: '${name}', name: '${name.charAt(0).toUpperCase() + name.slice(1)}', link: '${link}', icon: 'fa-circle', submenu: [], active: false, show: true, } /* r3-cli-menu-tag */,`; const result = data.replace(/} \/\* r3-cli-menu-tag \*\/,/g, content); fs.writeFileSync(file, result, 'utf-8'); } public createRoute(name: string, choise: any) { const status = new Spinner('Implementing a new Route, please wait...'); status.start(); try { const container = name.charAt(0).toUpperCase() + name.slice(1) + 'Container'; const component = name.charAt(0).toUpperCase() + name.slice(1); let file; const importStr = `/* Routes */\nimport ${component} from '../pages/${name}/${container}';`; let routeStr; if (choise.routerOption == 'internal') { file = `./src/app/view/templates/In.tsx`; routeStr = `<Switch>\n <Route exact key="${name}" path="/in/${name}" component={${component}} />`; } else { file = `./src/app/view/templates/Out.tsx`; routeStr = `<Switch>\n <Route exact key="${name}" path="/${name}" component={${component}} />`; } try { this.setImport(file, importStr); this.setRoute(file, routeStr); // TODO: this.setMenu(name, choise); } catch (err) { console.error(chalk.red(`\n \u2715 Error creating Route ${name.toUpperCase()}!`)); console.error(err); } console.info(chalk.green(' \u2713 Successful Route creation')); } catch (err) { throw err; } finally { setTimeout(() => { status.stop(); }, 500); } } } export default Route;
8a3b4ceea3dd497a3754b3c79b43b0599b1eb652
TypeScript
uber/baseweb
/src/helpers/responsive-helpers.ts
2.703125
3
/* Copyright (c) Uber Technologies, Inc. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. */ import type { Breakpoints, Theme } from '../styles'; import type { Responsive } from '../layout-grid'; import type { MediaQueryPageMargins, PageMargins } from './types'; /** * Helper function that generates media queries based on breakpoint, e.g. * getMediaQuery(720) => '@media screen and (min-width: 720px)' */ export const getMediaQuery = (breakpoint: number): string => `@media screen and (min-width: ${breakpoint}px)`; export const getMediaQueries = (breakpoints: Breakpoints): string[] => Object.keys(breakpoints) // @ts-ignore .map((key) => breakpoints[key]) .sort((a, b) => a - b) .map(getMediaQuery); export const getMinimumPageMargins = (margins: Responsive<number>): PageMargins => { const margin = Array.isArray(margins) ? margins[0] : margins; return { paddingInlineStart: `${margin}px`, paddingInlineEnd: `${margin}px`, }; }; export const getMediaQueryPageMargins = (theme: Theme): MediaQueryPageMargins => { const result = {} as MediaQueryPageMargins; const mediaQueries = getMediaQueries(theme.breakpoints); for (const [index, query] of mediaQueries.entries()) { // There is no guarantee grid.margins will have enough margins to satisfy // each breakpoint. const margin = Array.isArray(theme.grid.margins) ? theme.grid.margins[index] ?? theme.grid.margins.at(-1) : theme.grid.margins; result[query] = { paddingInlineStart: `${margin}px`, paddingInlineEnd: `${margin}px` }; } return result; };
f03f971b9e90334449f99b4e3b448e2b55610957
TypeScript
eirikhm/smokeJs
/src/math/Vector2D.ts
3.8125
4
class Vector2D { public x:number; public y:number; constructor(x = 0, y = 0) { this.x = x; this.y = y; } public add(vector:Vector2D):void { this.x += vector.x; this.y += vector.y; } get magnitude():number { return Math.sqrt(this.x * this.x + this.y * this.y); } get angle():number { return Math.atan2(this.y, this.x); } public static fromAngle(angle:number, magnitude:number):Vector2D { return new Vector2D(magnitude * Math.cos(angle), magnitude * Math.sin(angle)); } }
9342215f83d44c4caacf1b362f7eb35858aca6fe
TypeScript
lowcodeunit/lcu-hamburger-menu
/projects/common/src/lib/models/hamburger-menu.model.ts
3.0625
3
export class HamburgerMenuModel { public Label:string; public Url:string; public Disabled:string; public Icon?:string; public Param?:string; /** * * @param label The string to be displayed in the menu * * @param icon The icon that accompanies the menu string * * @param url the link associated with the menu item * * @param disabled is the button disabled string = true or false * * @param param this is what can be passed to the routerLink in the insatnce of opening a modal */ constructor(label: string, url: string, disabled: string, icon?: string, param?: string){ this.Label = label; this.Icon = icon; this.Url = url; this.Disabled = disabled; this.Param = param; } }
0aa2ad58501c872431fa9bb8baa056d3c6706f86
TypeScript
chapagain/neon-dash
/src/app/services/visualization.service.ts
2.5625
3
/* * Copyright 2017 Next Century Corporation * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ import { Injectable } from '@angular/core'; import * as _ from 'lodash'; import { NeonGridItem } from '../neon-grid-item'; import { BaseNeonComponent } from '../components/base-neon-component/base-neon.component'; import { BaseLayeredNeonComponent } from '../components/base-neon-component/base-layered-neon.component'; /** * Basic information about a visualization */ export interface VisualizationAdapter { id: string; gridData: NeonGridItem; component: BaseNeonComponent | BaseLayeredNeonComponent; } /** * This provides an Angular service for registering and unregistering visualizations on a page. * * @class neonDemo.services.VisualizationService * @constructor */ @Injectable() export class VisualizationService { private widgets: VisualizationAdapter[]; constructor() { this.widgets = []; } /** * Registers a function to this service, so that it can be executed as part of a bulk operation. Should be called by visualization * widgets upon being created. * @param {String} visualizationId The unique id for the visualization. * @param {Function} bundleFunction The function to register. */ registerBindings(visualizationId: string, component: BaseNeonComponent | BaseLayeredNeonComponent) { let widget = _.find(this.widgets, (item) => { return item.id === visualizationId; }); // If the widget was found, add the binding function if (widget) { widget.component = component; } else { this.widgets.push({ id: visualizationId, gridData: null, component: component }); } } /** * Register the grid data for a visualization * @param {string} visualizationId * @param {NeonGridItem} gridData */ registerGridData(visualizationId: string, gridData: NeonGridItem) { let widget = _.find(this.widgets, (item) => { return item.id === visualizationId; }); // If the widget was found, add the binding function if (widget) { widget.gridData = gridData; } else { this.widgets.push({ id: visualizationId, gridData: gridData, component: null }); } } /** * Unregisters a function with the given ID from this service. Should be called by visualization widgets upon being destroyed. * @param {String} visualizationId The unique ID of the function being unregistered. */ unregister(visualizationId) { let index: number = _.findIndex(this.widgets, { id: visualizationId }); if (index >= 0) { this.widgets.splice(index, 1); } } /** * Returns a list of all objects currently registered to this service, so the functions they have references to can * be used for bulk operations. * @return {Array} The list of objects subscribed to this service. */ getWidgets(): NeonGridItem[] { let widgetList: NeonGridItem[] = []; // Build the list of widgets for (let item of this.widgets) { // Clone everything let gridItem: NeonGridItem = _.cloneDeep(item.gridData); // Move the row/col/sizes up to the root let gridItemConfig = gridItem.gridItemConfig; gridItem.sizex = gridItemConfig.sizex; gridItem.sizey = gridItemConfig.sizey; gridItem.row = gridItemConfig.row; gridItem.col = gridItemConfig.col; // Re-build the bindings gridItem.bindings = item.component.getBindings(); widgetList.push(gridItem); } return widgetList; } }
ae40d1e866af50407606c9d4879e076f55b84289
TypeScript
Modern-Knowledge/serious-game-backend
/src/util/mail/Recipient.ts
2.90625
3
/* * https://nodemailer.com/message/addresses/ */ export class Recipient { public readonly name: string; public readonly address: string; /** * @param name name of the recipient * @param address email of the recipient */ constructor(name: string, address: string) { this.name = name; this.address = address; } }
bf18556f2e32d1d1c67daa9964d61ffa71b1c29e
TypeScript
lennyferrell/terminus-ui
/terminus-ui/src/validators/validators/numbers/numbers.spec.ts
2.96875
3
// tslint:disable: no-non-null-assertion import { FormControl } from '@angular/forms'; import { numbersValidator } from './numbers'; describe(`numbersValidator`, () => { beforeEach(() => { this.validatorFn = numbersValidator(2); }); describe(`if the control is invalid`, () => { test(`should return null`, () => { const values = [undefined, {}]; for (const val of values) { expect(this.validatorFn(val as any)).toEqual(null); } }); }); describe(`if number length is correct`, () => { test(`should return null`, () => { const val = '23ab'; expect(this.validatorFn(new FormControl(val))).toEqual(null); }); }); describe(`if number length is incorrect`, () => { test(`should return error`, () => { const val = '2CD'; const result = this.validatorFn(new FormControl(val)); expect(result!.numbers.valid).toEqual(false); expect(result!.numbers.actual).toEqual(val); }); }); describe(`if the number is missing`, () => { test(`should return response as default number 1`, () => { this.validatorFn2 = numbersValidator(); expect(this.validatorFn2(new FormControl('6'))).toEqual(null); }); }); });
3ba07857e259c323e901d497a749e0b2b5924759
TypeScript
kmccullough/recipe-book
/src/app/component/view/collection/collection-item.service.ts
3.078125
3
export interface ItemValue { key: string; itemValue: any; } /** * Store and access registered view components */ export class CollectionItemService { values = new Map<string, ItemValue>(); constructor() { } /** * Register view component by key with optional predicate * @param key Unique key to register component under * @param itemValue Component to register * @returns Self reference */ add(key, itemValue) { this.values.set(key, { key, itemValue }); return this; } /** * Get registered component by key or default component * @param key Unique key of expected component * @returns Registered component by key or default component */ get(key) { // Get registered component from node component service by layout name const component = this.values.get(key); return component && component.itemValue; } }
7f3c8bb29b8f18c8e00a67a3bcd975b5075f2f4a
TypeScript
lgmf/ng-rxjs-store
/src/app/contact/components/contact-list.component.ts
2.53125
3
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { Contact } from '../store'; export interface ClickedEvent { id: number; } @Component({ selector: 'app-contact-list', template: ` <h1 class="title">{{ title }}</h1> <ul class="list-group"> <li *ngFor="let item of data" class="item"> <div class="info"> <span class="title">{{ item.name }}</span> <span class="description">{{ item.email }}</span> </div> <div class="actions"> <button class="btn" (click)="onClick(item.id)">{{ actionIcon }}</button> </div> </li> </ul> `, styles: [ ` :host { display: grid; grid-gap: 12px; } :host > .title { font-size: 1.75rem; font-weight: bolder; } ` ] }) export class ContactListComponent { @Input() title: string; @Input() data: Contact[]; @Input() actionIcon: string; @Output() clicked = new EventEmitter<ClickedEvent>(); onClick(id: number) { this.clicked.emit({ id }); } }
5b95a5c7af78b8d742a63388612a49e55c44a192
TypeScript
BiloCode/Food-Proyect
/packages/web/src/application/core/puntuaction/UpdateUserDataInPuntuactions.ts
2.5625
3
import firebase from "firebase"; import { FirebaseCollectionNames } from "config/constans"; type UpdatedData = { _id: string; fullName: string; profileImageUrl: string; }; class UpdateUserDataInPuntuactions { public static exec = async (userData: UpdatedData) => { const db = firebase.firestore(); const clientDocRef = db .collection(FirebaseCollectionNames.client) .doc(userData._id); try { db.runTransaction(async (transaction) => { const client = await transaction.get(clientDocRef); const clientData = client.data(); const clientBranchOfficeIds = [ ...clientData.puntuaction.branchOfficeIds, ]; const requestPuntuactions = []; clientBranchOfficeIds.forEach((_id) => { const branchDocRef = db .collection(FirebaseCollectionNames.branchOffice) .doc(_id); const updatedData = () => { return transaction.get(branchDocRef).then((doc) => { const branchData = doc.data(); const puntuactions = branchData.puntuactions.map( (puntuactionData) => { if (puntuactionData.userId === userData._id) { return { ...puntuactionData, client: { fullName: userData.fullName, profileImage: userData.profileImageUrl, }, }; } return puntuactionData; } ); transaction.update(branchDocRef, { puntuactions }); return true; }); }; requestPuntuactions.push(updatedData()); }); await Promise.all(requestPuntuactions); }); } catch (error) { console.log(error); } }; } export default UpdateUserDataInPuntuactions;
56aac75371122c0febd814bca8f6a7c7c04394eb
TypeScript
HenriSup/DabTheWave
/assets/Scripts (5)/RythmBorderBehavior (31)/script.ts
2.734375
3
class RythmBorderBehavior extends Sup.Behavior { private timeAlive:number private isPlayerBorder:boolean=false awake() { this.timeAlive=0 this.actor.spriteRenderer.setOpacity(-1) } update() { this.setSprite() if (this.actor.spriteRenderer.getOpacity()==-1){ this.actor.spriteRenderer.setOpacity(1) } this.timeAlive+=1 this.actor.spriteRenderer.setOpacity(this.actor.spriteRenderer.getOpacity()-0.05) if (this.actor.spriteRenderer.getOpacity()<=0){ this.actor.destroy() } } setIsPlayerBorder(){ this.isPlayerBorder=true } setSprite(){ if(this.isPlayerBorder && this.actor.spriteRenderer.getAnimation()!="PlayerTurn"){ this.actor.spriteRenderer.setAnimation("PlayerTurn",false) } if(!this.isPlayerBorder && this.actor.spriteRenderer.getAnimation()!="ParrotTurn") { this.actor.spriteRenderer.setAnimation("ParrotTurn",false) } } } Sup.registerBehavior(RythmBorderBehavior);
3bb043ee43afedf68864d922c2fe6a304310f8b3
TypeScript
SmartCampus/ecoknowledge
/backend/src/TimeBox.ts
2.796875
3
/// <reference path="../typings/node/node.d.ts" /> /// <reference path="../typings/moment/moment.d.ts" /> /// <reference path="../typings/moment-timezone/moment-timezone.d.ts" /> var moment = require('moment'); var moment_timezone = require('moment-timezone'); import Clock = require('./Clock'); class TimeBox { private startDate:moment.Moment; private endDate:moment.Moment; constructor(starDate:moment.Moment, endDate:moment.Moment) { this.startDate = starDate; this.endDate = endDate; } public isDateInMillisInTimeBox(currentDateInMillis:number):boolean{ var currentInMillis:moment.Moment = moment(currentDateInMillis); return currentInMillis.isAfter(this.startDate) && currentInMillis.isBefore(this.endDate); } public isDateInTimeBox(currentDate:moment.Moment):boolean{ return this.isDateInMillisInTimeBox(currentDate.valueOf()); } public getStartDate():moment.Moment { return this.startDate; } public getStartDateInMillis():number { return this.startDate.valueOf(); } public getEndDate():moment.Moment { return this.endDate; } public getEndDateInMillis():number { return this.endDate.valueOf(); } public getStartDateInStringFormat():string { return this.convertTimeForMiddlewareAPI(this.startDate); } public getEndDateInStringFormat():string { return this.convertTimeForMiddlewareAPI(this.endDate); } /** * * @returns {{startDate: string, endDate: string}} */ public getRequired():any { var startDateStr = this.convertTimeForMiddlewareAPI(this.startDate); var endDateStr = this.convertTimeForMiddlewareAPI(this.endDate); return { 'startDate':startDateStr, 'endDate':endDateStr } } /** * This method is needed because API of SmartCampus middleware wants * dates in the following format : YYYY-MM-DD hh:mm:ss</br> * We wanted to isolated this behavior in a specific method. * @param aDateInMillis * The date in millis to convert * @returns {string} * The given date in the following format : YYYY-MM-DD hh:mm:ss</br> * Uses Date#toISOString method. */ public convertTimeForMiddlewareAPI(aMoment:moment.Moment):string { //console.log("Conversion du moment pour matcher avec le middleware"); var date:string=aMoment.format(); /* console.log("date à convertir", date); console.log("date à convertir au format iso", aMoment.toISOString()); */ var dateWithoutTimeZone:string[] = date.split('+'); var dateWithoutTail:string[] = dateWithoutTimeZone[0].split('.'); var headOfDate:string = dateWithoutTail[0]; //console.log("head of date", headOfDate); var arrayOfHeadOfDate:string[] = headOfDate.split('T'); var properDate:string= arrayOfHeadOfDate[0] + " " + arrayOfHeadOfDate[1]; //console.log("new date", properDate); return properDate; } } export = TimeBox;
2768e5e45407310b8bbb9546e3112f6c631e04e8
TypeScript
alexander-shipilov/positron
/utils/observer/types/ObserverCallback.ts
2.96875
3
import { ObserverInterface } from "./Observer.interface"; import { ObserverRecord } from "./ObserverRecord"; /** * Callback function to call when observer event occurred */ export type ObserverCallback< Record extends ObserverRecord<unknown>, Observer extends ObserverInterface<unknown, unknown, Record> > = (records: Record[], observer: Observer) => void;
21e3aa26af0ed29ee6829c6a36b970636b1c44f9
TypeScript
tryguba/form_service
/src/source/patterns/singleton/decorators/constructor-parameter/functional.ts
3
3
import { ConstantConstructorParameter, FunctionConstructorParameter } from '../../constructor-parameter'; import { getMetadataStorage } from '../../singleton.metadata.storage'; import { SingletonStorage } from '../../singleton.storage'; export function Functional<Type>(operator: (storage: SingletonStorage) => Type): ParameterDecorator & PropertyDecorator { return (target: Object, propertyKey?: string | symbol, parameterIndex?: number) => { if (typeof target === 'function' && propertyKey === undefined && typeof parameterIndex === 'number') { /// Constructor parameter decorator const storage = getMetadataStorage(target.prototype); storage.setConstructorArgument(parameterIndex, new FunctionConstructorParameter(operator)); } else if (propertyKey !== undefined && parameterIndex === undefined) { /// Property decorator const storage = getMetadataStorage(target); storage.setProperty(propertyKey, new FunctionConstructorParameter(operator)); } else { throw new Error('Illegal usage'); } } }
3c908b17db2de4cfc7f8a2aa7ccb1f2bfd3b1ddb
TypeScript
lovefcaaa/abc
/examples/ultra_cat_app/cat/cat.ts
2.625
3
export class Cat { id?: number; name?: string; age?: number; } export interface CatDTO { name: string; age: number; }
9d01fb022a04a3ae5182dc05fc2cfab840db9580
TypeScript
Kamiapp-fr/kami-flash
/dist/types/enum/ColorProgressBar.d.ts
2.78125
3
/** * Determine the progress bar color should be used which each type. * @enum ColorProgressBar */ declare enum ColorProgressBar { OK = "#008e72", ERROR = "#ff0056", WARNING = "#ff3000", INFO = "#0081ff" } export default ColorProgressBar;
cde44e473e0c81e3370b7919c4e98e8e4e9cf1c0
TypeScript
iBhavesh/expo-template-redux_tookit-typescript
/src/features/counter/counter.ts
2.734375
3
import { createSlice } from "@reduxjs/toolkit"; type InitialState = { count: number; }; const initialState: InitialState = { count: 0, }; const counter = createSlice({ name: "counterSlice", initialState, reducers: { increment: (state) => { state.count++; }, decrement: (state) => { state.count--; }, }, }); export const { decrement, increment } = counter.actions; export default counter.reducer;
3468b4483bd7628d3dbc3862ebcb7ecc8b4b3893
TypeScript
ConfidentCannabis/react-query
/src/core/queryInstance.ts
2.75
3
import { uid, isServer, isDocumentVisible, Console } from './utils' import { Query, QueryState } from './query' import { BaseQueryConfig } from './types' // TYPES export type OnStateUpdateFunction<TResult, TError> = ( state: QueryState<TResult, TError> ) => void // CLASS export class QueryInstance<TResult, TError> { id: number config: BaseQueryConfig<TResult, TError> onStateUpdate?: OnStateUpdateFunction<TResult, TError> private query: Query<TResult, TError> private refetchIntervalId?: number constructor( query: Query<TResult, TError>, onStateUpdate?: OnStateUpdateFunction<TResult, TError> ) { this.id = uid() this.onStateUpdate = onStateUpdate this.query = query this.config = {} } clearInterval(): void { if (this.refetchIntervalId) { clearInterval(this.refetchIntervalId) this.refetchIntervalId = undefined } } updateConfig(config: BaseQueryConfig<TResult, TError>): void { const oldConfig = this.config // Update the config this.config = config if (!isServer) { if (oldConfig?.refetchInterval === config.refetchInterval) { return } this.query.clearIntervals() const minInterval = Math.min( ...this.query.instances.map(d => d.config.refetchInterval || Infinity) ) if ( !this.refetchIntervalId && minInterval > 0 && minInterval < Infinity ) { this.refetchIntervalId = setInterval(() => { if ( this.query.instances.some(_ => this.config.enabled) && (isDocumentVisible() || this.query.instances.some( _ => this.config.refetchIntervalInBackground )) ) { this.query.fetch() } }, minInterval) } } } async run(): Promise<void> { try { // Perform the refetch for this query if necessary if ( this.query.config.enabled && // Don't auto refetch if disabled !this.query.wasSuspended && // Don't double refetch for suspense this.query.state.isStale && // Only refetch if stale (this.query.config.refetchOnMount || this.query.instances.length === 1) ) { await this.query.fetch() } this.query.wasSuspended = false } catch (error) { Console.error(error) } } unsubscribe(): void { this.query.instances = this.query.instances.filter(d => d.id !== this.id) if (!this.query.instances.length) { this.clearInterval() this.query.cancel() if (!isServer) { // Schedule garbage collection this.query.scheduleGarbageCollection() } } } }
f19238acda088bdc96596611b3539ee595b3e83c
TypeScript
kaoengine/kao-blog-react-ssr-yaml
/src/server/index.ts
2.78125
3
import * as http from "http"; import app from "./app"; import { parse } from "path"; // Look for Markdown files in /posts non-recursively const context = require.context("/posts", false, /\.md$/); const posts = context.keys().map((filePath) => { const slug = parse(filePath).name; const post = context(filePath); return { ...post, slug }; }); function normalizePort(val: number | string): number | string | boolean { const port = typeof val === "string" ? parseInt(val, 10) : val; if (isNaN(port)) { // named pipe return val; } if (port >= 0) { // port number return port; } return false; } // Create an app given its posts const mode = process.env.NODE_ENV; const server = http.createServer(app(posts, mode)); // Attempt to normalize the port const port = normalizePort(process.env.PORT || 8080); function onError(error: NodeJS.ErrnoException): void { if (error.syscall !== "listen") { throw error; } const bind = typeof port === "string" ? `Pipe ${port}` : `Port ${port}`; // Handle specific listen errors with friendly messages switch (error.code) { case "EACCES": console.error(`${bind} requires elevated privileges`); process.exit(1); break; case "EADDRINUSE": console.error(`${bind} is already in use`); process.exit(1); break; default: throw error; } } function onListening(): void { const addr = server.address(); const bind = typeof addr === "string" ? `pipe ${addr}` : `port ${addr.port}`; console.debug(`Express server listening on ${bind}`); } // Listen on provided port, on all network interfaces server.listen(port); server.on("error", onError); server.on("listening", onListening);
35356b746401afb59e7aafd457f11da8929cb84a
TypeScript
slooi/AntSimulation
/src/client/main.ts
2.90625
3
import Game from "./Game"; console.log("Main.ts loaded"); /* DEPENDENCIES */ const canvas = document.getElementById("canvas") as HTMLCanvasElement; /* MAIN CODE */ const game = new Game({ canvas }); window.addEventListener("keydown", (e) => { // Note pheromones dissapear only in render stage // game.speed does NOT make the rander stage run more. So pheromones won't be reduced as much per tick if (e.key === "w") { if (game.speed === 1) { game.speed = 100; console.log("FAST FORWARDS!"); } else { game.speed = 1; console.log("BACK TO NORMAL"); } } });
bd69c82ede7c325234b51b73dddaaf6e4e6a7797
TypeScript
ymolists/polyhedra-viewer
/src/math/operations/__tests__/prismOps.test.ts
2.71875
3
import { elongate, gyroelongate, shorten, turn } from "../prismOps" import { Polyhedron } from "math/polyhedra" describe("elongate", () => { describe("canApplyTo", () => { function expectApplyTo(name: string, value: boolean = true) { expect(elongate.canApplyTo(Polyhedron.get(name))).toEqual(value) } it("works on capstones", () => { // only works on shortened capstones expectApplyTo("tetrahedron") expectApplyTo("square cupola") expectApplyTo("pentagonal rotunda") expectApplyTo("pentagonal bipyramid") expectApplyTo("triangular orthobicupola") expectApplyTo("pentagonal orthocupolarotunda") expectApplyTo("elongated triangular pyramid", false) expectApplyTo("gyroelongated pentagonal bicupola", false) // doesn't work on fastigium expectApplyTo("triangular prism", false) expectApplyTo("gyrobifastigium", false) }) }) }) describe("gyroelongate", () => { describe("canApplyTo", () => { function expectApplyTo(name: string, value: boolean = true) { expect(gyroelongate.canApplyTo(Polyhedron.get(name))).toEqual(value) } it("works on capstones", () => { expectApplyTo("square cupola") expectApplyTo("pentagonal rotunda") expectApplyTo("pentagonal bipyramid") expectApplyTo("triangular orthobicupola") expectApplyTo("pentagonal orthocupolarotunda") expectApplyTo("elongated triangular pyramid", false) expectApplyTo("gyroelongated pentagonal bicupola", false) // doesn't work on fastigium expectApplyTo("triangular prism", false) expectApplyTo("gyrobifastigium", false) // doesn't work on tetrahedra expectApplyTo("tetrahedron", false) expectApplyTo("triangular bipyramid", false) }) }) describe("hasOptions", () => { function expectHasOptions(name: string, value: boolean = true) { expect(gyroelongate.hasOptions(Polyhedron.get(name))).toEqual(value) } describe("works on capstones", () => { // only works on bicupolae/birotundae expectHasOptions("square orthobicupola") expectHasOptions("icosidodecahedron") expectHasOptions("pentagonal orthocupolarotunda") // false cases expectHasOptions("pentagonal bipyramid", false) expectHasOptions("pentagonal cupola", false) }) }) }) describe("shorten", () => { function expectApplyTo(name: string, value: boolean = true) { expect(shorten.canApplyTo(Polyhedron.get(name))).toEqual(value) } function expectHasOptions(name: string, value: boolean = true) { expect(shorten.hasOptions(Polyhedron.get(name))).toEqual(value) } describe("canApplyTo", () => { it("works on nonshortened capstones", () => { // elongated and gyroelongated capstones expectApplyTo("elongated square pyramid") expectApplyTo("elongated triangular cupola") expectApplyTo("gyroelongated pentagonal cupolarotunda") // invalid on prisms and shortened capstones expectApplyTo("decagonal prism", false) expectApplyTo("square antiprism", false) expectApplyTo("pentagonal cupola", false) expectApplyTo("pentagonal bipyramid", false) }) }) describe("hasOptions", () => { it("true only if gyroelongated bicupola", () => { // true only if gyroelongated bicupola expectHasOptions("gyroelongated square bicupola") expectHasOptions("gyroelongated pentagonal cupolarotunda") // false for everything else expectHasOptions("gyroelongated square cupola", false) expectHasOptions("gyroelongated square bipyramid", false) expectHasOptions("elongated square gyrobicupola", false) }) }) }) describe("turn", () => { function expectApplyTo(name: string, value: boolean = true) { expect(turn.canApplyTo(Polyhedron.get(name))).toEqual(value) } function expectHasOptions(name: string, value: boolean = true) { expect(turn.hasOptions(Polyhedron.get(name))).toEqual(value) } describe("canApplyTo", () => { it("works on prismatics", () => { expectApplyTo("cube") expectApplyTo("octahedron") expectApplyTo("pentagonal prism") expectApplyTo("octagonal antiprism") // false on digonal antiprism expectApplyTo("tetrahedron", false) }) it("works on nonshortened capstones", () => { expectApplyTo("gyroelongated pentagonal pyramid") expectApplyTo("elongated square bipyramid") expectApplyTo("elongated square cupola") // false cases expectApplyTo("square pyramid", false) expectApplyTo("pentagonal orthocupolarotunda", false) // false on elongated triangular pyramid expectApplyTo("elongated triangular pyramid", false) expectApplyTo("elongated triangular bipyramid", false) }) }) describe("hasOptions", () => { it("is true only on bicupolae", () => { expectHasOptions("elongated square gyrobicupola") expectHasOptions("gyroelongated triangular bicupola") expectHasOptions("elongated pentagonal gyrobirotunda") expectHasOptions("gyroelongated pentagonal cupolarotunda") expectHasOptions("pentagonal antiprism", false) expectHasOptions("elongated square bipyramid", false) expectHasOptions("gyroelongated square cupola", false) }) }) })
1444f0910d355e85e0b41e2761b96051709fe832
TypeScript
jolocom/jolocom-lib
/tests/recovery/socialRecovery.test.ts
2.59375
3
import { SocialRecovery } from '../../ts/recovery/socialRecovery' import { expect } from 'chai' import { testDID32, testSecret32, testShares } from '../data/recovery.data' describe('Social Recovery', () => { it('should create and combine', function() { const amount = 255 const threshold = 50 const shards = SocialRecovery.createShards( testDID32, testSecret32, amount, threshold, ) const { did, secret } = SocialRecovery.combineShard( shards.slice(0, threshold), ) expect(did).to.equal(testDID32.replace('did:jolo:', '')) expect(secret.toString('hex')).to.equal(testSecret32) }) it('should create shares correctly', () => { const shards = SocialRecovery.createShards(testDID32, testSecret32, 5, 3) expect(shards.length).to.equal(5) }) it('should combine shares correctly', () => { const { did, secret } = SocialRecovery.combineShard(testShares.slice(0, 3)) expect(secret.toString('hex')).to.equal(testSecret32) expect(did).to.equal(testDID32.replace('did:jolo:', '')) }) it('should fail if not enough shares are presented', () => { expect(() => SocialRecovery.combineShard([testShares[0], testShares[1]]), ).to.throw() }) it('should validate a shard', () => { const result = SocialRecovery.validateShard(testShares[0]) expect(result).to.be.true }) it('should fail validating a wrong shard', () => { const result = SocialRecovery.validateShard('not a correct shard') expect(result).to.be.false }) })
80e887e312d5ebc5f63b8f9237b63c3e4638d137
TypeScript
ProgramowanieZespoloweIS2021/frontend
/src/state/_redux/user/module.ts
2.71875
3
export type User = { id: number; email: string; firstName: string; surname: string; }; export type UserModule = { authorized: boolean | null; id: number | null; email: string | null; }; export const initialState: UserModule = { authorized: null, id: null, email: null, };
ae8322230947d7c749bdaab8efb16e060457efcc
TypeScript
RoTour/robin-tourne-cvsite-client
/src/app/models/post.model.ts
2.75
3
export class Post { id!: number; ownerName!: string; text!: string; createdAt!: Date; updatedAt!: Date; constructor(id: number, text: string, createdAt: Date, updatedAt: Date, ownerName: string) { this.id = id; this.text = text; this.createdAt = createdAt; this.updatedAt = updatedAt; this.ownerName = ownerName; } }
9cd51da30ef2f36d4ff5c3c0b7eb6de796d8cfdc
TypeScript
Zoweb/Buildr
/packages/Client/src/ts/logging/LogLevel.ts
3.109375
3
import {LogColour} from "./LogColour"; export enum LogLevel { LEMON, DEBUG, INFO, WARN, ERROR } export function getLevelColour(level: LogLevel): LogColour { switch (level) { case LogLevel.LEMON: return LogColour.PURPLE; case LogLevel.DEBUG: return LogColour.BLUE; case LogLevel.INFO: return LogColour.CYAN; case LogLevel.WARN: return LogColour.ORANGE; case LogLevel.ERROR: return LogColour.RED; default: return LogColour.DEFAULT; } } export function getLevelName(level: LogLevel): string { switch (level) { case LogLevel.LEMON: return "lemon"; case LogLevel.DEBUG: return "debug"; case LogLevel.INFO: return "info"; case LogLevel.WARN: return "warn"; case LogLevel.ERROR: return "error"; default: return "unknown"; } } export function isLevelEnabled(test: LogLevel, max: LogLevel): boolean { return max <= test; }
49b1801e9c773c88e48135baee6355a7a216b042
TypeScript
westvo/q-a-site
/src/questions/questions.service.ts
2.53125
3
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { CreateQuestionDto } from './dto/create-question.dto'; import { UpdateQuestionDto } from './dto/update-question.dto'; import { Question } from './entities/question.entity'; @Injectable() export class QuestionsService { constructor( @InjectRepository(Question) private readonly questionRepository: Repository<Question>, ) {} create(createQuestionDto: CreateQuestionDto): Promise<Question> { const question = new Question(); question.title = createQuestionDto.title; question.content = createQuestionDto.content; question.postTime = new Date(); return this.questionRepository.save(question); } async update(id: number, updateQuestionDto: UpdateQuestionDto): Promise<Question> { const question = await this.questionRepository.findOne(id); question.title = updateQuestionDto.title; question.content = updateQuestionDto.content; return this.questionRepository.save(question); } findAll() { return this.questionRepository.find(); } findOne(id: number) { return this.questionRepository.findOne(id); } remove(id: number) { return this.questionRepository.delete(id); } }
c31af09b68ef67d7bb537334165b3313d5b4c7ed
TypeScript
sandialabs/common
/src/COMMONWeb/app/classes/applications.ts
2.828125
3
interface IApplicationInfo { name: string; version: string; } export interface IDeviceApplications { deviceID: number; applications: IApplicationInfo[]; timestamp: string; } class DeviceApplications { deviceID: number; applications: IApplicationInfo[]; timestamp: Date; constructor(data: IDeviceApplications) { this.deviceID = data.deviceID; this.applications = data.applications; this.timestamp = new Date(data.timestamp); } } interface ISnapshot { version: string; timestamp: string; } export interface IApplicationHistory { name: string; history: ISnapshot[]; } interface IApplicationsMap { [app: string]: IApplicationHistory; } class Snapshot { version: string; timestamp: Date; constructor(data: ISnapshot) { this.version = data.version; this.timestamp = new Date(data.timestamp); } } // See Database/Models.cs class ApplicationHistory { name: string; history: Snapshot[]; constructor() { this.name = ""; this.history = []; } update(data: IApplicationHistory) { this.name = data.name; this.history = []; for (var i = 0; i < data.history.length; ++i) { var snapshot = new Snapshot(data.history[i]); this.history.push(snapshot); } } } export interface IApplicationsHistoryMap { [name: string]: IApplicationHistory; } interface IApplicationsHistory { [name: string]: ApplicationHistory; } class ApplicationsHistoryMap { history: IApplicationsHistory; constructor(map: IApplicationsHistoryMap) { this.history = {}; var keys = Object.keys(map); for (var i = 0; i < keys.length; ++i) { let name = keys[i]; let history: IApplicationHistory = map[name]; let appHistory = new ApplicationHistory(); appHistory.update(history); this.history[name] = appHistory; } } } export interface IAllApplicationsHistory { history: IApplicationsMap; } export class AllApplicationsHistory { history: ApplicationsHistoryMap; apps: string[]; constructor(history: IAllApplicationsHistory) { this.history = new ApplicationsHistoryMap(history.history); this.apps = Object.keys(this.history.history); this.apps.sort(); } } export class ApplicationManager { applications: DeviceApplications; //values: any[]; dataService: any; applicationHistory: ApplicationHistory; constructor(data: IDeviceApplications, dataService: any) { this.applications = new DeviceApplications(data); this.dataService = dataService; //this.values = []; this.applicationHistory = null; } public onSelectApplication(app: string) { var t = this; this.dataService.getAppHistory(this.applications.deviceID, app) .then((data: IApplicationHistory) => { if (!t.applicationHistory) t.applicationHistory = new ApplicationHistory(); t.applicationHistory.update(data); }); } }
be4e5e383807142d178ece173b275401a2a341e2
TypeScript
lucianoadan/mumablue-challenge
/front/src/app/core/models/api-response.ts
2.59375
3
export interface ApiResponse<T> { errors: string[]; message: string; payload: T; }
f9b22201927b7ebb8ea2fba8f5fb1bf6d9b09012
TypeScript
taikeguluer/dapp-boilerplate
/src/Translation/Translation.ts
2.78125
3
import { env, utils } from 'decentraland-commons' import * as flat from 'flat' import * as fs from 'fs' import * as path from 'path' export interface TranslationData { [key: string]: string } export interface TranslationCache { locale?: TranslationData } export class Translation { static DEFAULT_LOCALE = 'en' localesPath: string cache: TranslationCache constructor() { this.localesPath = env.get( 'LOCALES_PATH', path.resolve(__dirname, './locales') ) this.cache = {} // {locale: translations} } async fetch(locale: string): Promise<TranslationData> { if (!this.cache[locale]) { const availableLocales = await this.getAvailableLocales() if (availableLocales.includes(locale)) { this.cache[locale] = this.parse(await this.readFile(locale)) } } return this.cache[locale] || {} } async getAvailableLocales(): Promise<string[]> { const files = await utils.promisify<string[]>(fs.readdir)(this.localesPath) return files.map(filePath => path.basename(filePath, path.extname(filePath)) ) } parse(fileContents: string): TranslationData { // The translation lib ( https://github.com/yahoo/react-intl ) doesn't support nested values // So instead we flatten the structure to look like `{ 'nested.prop': 'value' }` const translations = JSON.parse(fileContents) return flat(translations) } async readFile(locale: string): Promise<string> { return utils.promisify<string>(fs.readFile)( path.resolve(this.localesPath, `${locale}.json`), 'utf8' ) } }
872df9cc5812eb2d7e8d32febfd5ded73e61b25c
TypeScript
North-West-Wind/NWWbot
/src/commands/information/role-info.ts
2.859375
3
import { PermissionResolvable, Role } from "discord.js"; import { NorthClient, NorthInteraction, NorthMessage, FullCommand } from "../../classes/NorthClient.js"; import * as Discord from "discord.js"; import { color } from "../../function.js"; class RoleInfoCommand implements FullCommand { name = "role-info" description = "Displays information of a role." aliases = ["ri"] usage = "<role>" category = 6 args = 1 options = [{ name: "role", description: "The role's information to display.", required: true, type: "ROLE" }]; async execute(interaction: NorthInteraction) { if (!interaction.guild) return await interaction.reply("This command only works on server."); const role = <Role>interaction.options.getRole("role"); await interaction.reply({ embeds: [this.createRoleEmbed(role, interaction.client)] }); } async run(message: NorthMessage, args: string[]) { const roleID = args[0].replace(/<@&/g, "").replace(/>/g, ""); if (isNaN(parseInt(roleID)) || args.length > 1) { var role = message.guild.roles.cache.find(x => x.name.toLowerCase() === args.join(" ").toLowerCase()); if (!role) return message.channel.send("No role was found with the name " + args.join(" ")); } else { var role = await message.guild.roles.fetch(roleID); if (!role) return message.channel.send("No role was found!"); } const Embed = this.createRoleEmbed(role, message.client); message.channel.send({ embeds: [Embed] }); } createRoleEmbed(role: Role, client: NorthClient) { const guild = role.guild; const userMember = role.members; const userMemberCount = []; const botMemberCount = []; for (const user of userMember.values()) { if (user.user.bot === false) userMemberCount.push(user.id); if (user.user.bot) botMemberCount.push(user.id); } const memberCount = role.members.size; let permissions = []; for (const flag of Object.keys(Discord.PermissionsBitField.Flags)) if (role.permissions.has(<PermissionResolvable>flag)) permissions.push(flag); if (role.permissions.has(Discord.PermissionsBitField.Flags.Administrator)) permissions = ["ADMINISTRATOR"]; const Embed = new Discord.EmbedBuilder() .setColor(color()) .setTitle("Information of " + role.name) .setDescription("In server **" + guild.name + "**") .addFields([ { name: "ID", value: role.id, inline: true }, { name: "Name", value: role.name, inline: true }, { name: "Member Count", value: `Members: \`${memberCount}\`\nUsers: \`${userMemberCount.length}\`\nBots: \`${botMemberCount.length}\``, inline: true }, { name: "Hoist? (Separated)", value: role.hoist ? "Yes" : "No", inline: true }, { name: "Position", value: role.position.toString(), inline: true }, { name: "Color", value: (!role.hexColor.startsWith("#") ? "#" : "") + role.hexColor.toUpperCase(), inline: true }, { name: "PermissionsBitField", value: "`" + (permissions.length > 0 ? permissions.join("`, `").replace(/_/g, " ") : "N/A") + "`" } ]) .setTimestamp() .setFooter({ text: "Have a nice day! :)", iconURL: client.user.displayAvatarURL() }); return Embed; } } const cmd = new RoleInfoCommand(); export default cmd;
b6939ee20ad9a20b04f94bcc888b915e9bc926bf
TypeScript
iorveth/hydra
/substrate-query-framework/cli/src/generate/RelationshipGenerator.ts
2.703125
3
import { WarthogModel, Field, ObjectType, makeRelation } from '../model'; import { generateJoinColumnName, generateJoinTableName } from './utils'; import { camelCase } from 'lodash'; export class RelationshipGenerator { private _visited: string[]; model: WarthogModel; constructor(model: WarthogModel) { this.model = model; this._visited = []; } addMany2Many(field: Field, relatedField: Field, currentObject: ObjectType, relatedObject: ObjectType): void { field.relation = makeRelation('mtm', field.type, relatedField.name); field.relation.joinTable = { tableName: generateJoinTableName(currentObject.name, relatedObject.name), joinColumn: generateJoinColumnName(currentObject.name), inverseJoinColumn: generateJoinColumnName(relatedObject.name), }; relatedField.relation = makeRelation('mtm', relatedField.type, field.name); this.addToVisited(...[currentObject.name.concat(field.name), relatedObject.name.concat(relatedField.name)]); } addOne2Many(field: Field, relatedField: Field, currentObject: ObjectType, relatedObject: ObjectType): void { field.relation = makeRelation('otm', field.type, relatedField.name); relatedField.relation = makeRelation('mto', relatedField.type, field.name); this.addToVisited(...[currentObject.name.concat(field.name), relatedObject.name.concat(relatedField.name)]); } addMany2One(field: Field, currentObject: ObjectType, relatedObject: ObjectType, relatedField: Field): void { if (!relatedField.type) { // Additinal field for field resolver const fname = camelCase(currentObject.name).concat('s'); relatedField = new Field(fname, relatedObject.name, field.nullable, false, true); relatedField.relation = makeRelation('otm', currentObject.name, field.name); relatedObject.fields.push(relatedField); } else { relatedField.relation = makeRelation('otm', currentObject.name, field.name); } field.relation = makeRelation('mto', field.type, relatedField.name); this.addToVisited(...[currentObject.name.concat(field.name), relatedObject.name.concat(relatedField.name)]); } addOne2One(field: Field, relatedField: Field, currentObject: ObjectType, relatedObject: ObjectType): void { field.relation = makeRelation('oto', field.type, relatedField.name); field.relation.joinColumn = true; relatedField.relation = makeRelation('oto', relatedField.type, field.name); this.addToVisited(...[currentObject.name.concat(field.name), relatedObject.name.concat(relatedField.name)]); } addToVisited(...args: string[]): void { this._visited.push(...args); } isVisited(f: Field, o: ObjectType): boolean { return this._visited.includes(o.name.concat(f.name)); } listTypeWithNoDerivedDirective(field: Field, currentObject: ObjectType): void { const relatedObject = this.model.lookupEntity(field.type); const relatedFields = relatedObject.fields.filter(f => f.type === currentObject.name && f.isList); if (relatedFields.length !== 1) { throw new Error(`Incorrect ManyToMany relationship detected! ${currentObject.name} -> ${field.name} found ${relatedFields.length} fields on ${relatedObject.name} of list type`); } if (!relatedFields[0].derivedFrom) { throw new Error(`Incorrect ManyToMany relationship detected! @derived directive for ${relatedObject.name}->${relatedFields[0].name} not found`); } this.addMany2Many(field, relatedFields[0], currentObject, relatedObject); } listTypeWithDerivedDirective(field: Field, currentObject: ObjectType): void { // Shoud never happen! if (!field.derivedFrom) throw new Error(`No derivedFrom found on ${currentObject.name}->${field.name}`); const relatedObject = this.model.lookupEntity(field.type); const relatedField = this.model.lookupField(field.type, field.derivedFrom.argument); if (relatedField.derivedFrom) { throw new Error( `${relatedObject.name}->${relatedField.name} derived field can not reference to another derived field!` ); } relatedField.isList ? this.addMany2Many(field, relatedField, currentObject, relatedObject) : this.addOne2Many(field, relatedField, currentObject, relatedObject); } typeWithDerivedDirective(field: Field, currentObject: ObjectType): void { // Shoud never happen! if (!field.derivedFrom) throw new Error(`No derivedFrom found on ${currentObject.name}->${field.name}`); const relatedObject = this.model.lookupEntity(field.type); const relatedField = this.model.lookupField(field.type, field.derivedFrom.argument); if (relatedField.derivedFrom) { throw new Error( `${relatedObject.name}->${relatedField.name} derived field can not reference to another derived field!` ); } if (relatedField.isList) { throw new Error(`${relatedObject.name}->${relatedField.name} can not reference to another a list field`); } this.addOne2One(field, relatedField, currentObject, relatedObject); } typeWithNoDerivedDirective(field: Field, currentObject: ObjectType): void { const relatedObject = this.model.lookupEntity(field.type); const relatedFields = relatedObject.fields.filter(f => f.type === currentObject.name); if (relatedFields.length === 0) { return this.addMany2One(field, currentObject, relatedObject, {} as Field); } const derivedFields = relatedFields.filter(f => f.derivedFrom?.argument === field.name); if (derivedFields.length === 1) { return !derivedFields[0].isList ? this.addOne2One(field, derivedFields[0], currentObject, relatedObject) : this.addMany2One(field, currentObject, relatedObject, derivedFields[0]); } // Errors throw derivedFields.length === 0 ? new Error( `Incorrect relationship. '${relatedObject.name}' should have a derived field with @derivedFrom(field: "${field.name}") directive maybe?` ) : new Error(`Found multiple derived fields with same argument -> @derivedField(field:"${field.name}")`); } generate(): void { const entityNames = this.model.entities.map(t => t.name); this.model.entities.forEach(currentObject => { for (const field of currentObject.fields) { if (!entityNames.includes(field.type) || this.isVisited(field, currentObject)) continue; if (field.isList) { return field.derivedFrom ? this.listTypeWithDerivedDirective(field, currentObject) : this.listTypeWithNoDerivedDirective(field, currentObject); } else { return field.derivedFrom ? this.typeWithDerivedDirective(field, currentObject) : this.typeWithNoDerivedDirective(field, currentObject); } } }); } }
4109a9c741d7de331ebb33cb002510778fd09ad6
TypeScript
LLehtola/pokemon-trainer-angular
/src/app/components/signup/signup.component.ts
2.515625
3
import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, AbstractControl, } from '@angular/forms'; import { AuthService } from '../../services/auth.service'; /** * Renders the signup. * User's name gets stored in localstorage and authService updates its observable user. */ @Component({ selector: 'app-signup', templateUrl: './signup.component.html', styleUrls: ['./signup.component.scss'], }) export class SignupComponent implements OnInit { user = new FormGroup({ name: new FormControl('', [Validators.required, Validators.minLength(3)]), }); get name(): AbstractControl { return this.user.get('name'); } signupUser() { if (!this.name.invalid) { this.authService.storeUserInLocalStorage(this.name.value); } } constructor(private authService: AuthService) {} ngOnInit(): void {} }
f68c88e5780339e8f2b94e2a32355425811f8efc
TypeScript
AzureCloudMonk/breakout
/index.ts
3.140625
3
let canvasElem = document.getElementById("canvas") as HTMLCanvasElement; let canvasBounds = canvasElem.getBoundingClientRect(); const POWER_UP_RADIUS = 10; interface PowerUpType { color(): string; execute(x: number, y: number): void; } class ExtraBall implements PowerUpType { color() { return "grey"; } execute(x: number, y: number) { balls.push(new Ball(x, y, 10, 2 * Math.random(), -3)); } } class FlamingBall implements PowerUpType { color() { return "blue"; } execute(x: number, y: number) { balls.push(new Ball(x, y, 10, 2 * Math.random(), -3, -1)); } } class PaddleSize implements PowerUpType { color() { return "green"; } execute(x: number, y: number) { bat.increaseSize(); } } class PaddleSpeed implements PowerUpType { color() { return "red"; } execute(x: number, y: number) { bat.increaseSpeed(); } } class Explosion implements PowerUpType { color() { return "#710193"; } execute(x: number, y: number) { let num = ~~(Math.random() * 5) + 5; for (let i = 0; i < num; i++) balls.push( new Ball( x, y, 3, 3 * Math.cos((Math.PI / (num + 1)) * (i + 1)), -3 * Math.sin((Math.PI / (num + 1)) * (i + 1)), 3 ) ); } } const powerUpTypes = [ new ExtraBall(), new PaddleSize(), new PaddleSpeed(), new Explosion(), new FlamingBall(), ]; function randomPowerUp() { return powerUpTypes[~~(powerUpTypes.length * Math.random())]; } class PowerUp { private taken = false; constructor( private x: number, private y: number, private type: PowerUpType ) {} update(bat: Paddle) { this.y += 1; let coll = this.collidesWith(bat); if (coll !== CollisionDir.NONE) { this.type.execute(this.x, this.y); this.taken = true; } } isAlive() { return !this.taken && this.y - POWER_UP_RADIUS < canvasBounds.height; } collidesWith(bat: Collider) { return bat.collidesWith(this.x, this.y, POWER_UP_RADIUS); } draw(ctx: CanvasRenderingContext2D) { ctx.fillStyle = this.type.color(); ctx.beginPath(); ctx.arc(this.x, this.y, POWER_UP_RADIUS, 0, 2 * Math.PI); ctx.fill(); ctx.fillStyle = "black"; } } interface Collider { collidesWith(x: number, y: number, r: number): CollisionDir; } class Ball { constructor( private x: number, private y: number, private r: number, private vx: number, private vy: number, private hitPoint?: number ) {} getX() { return this.x; } update(bat: Paddle, wall: Brick[]) { this.x += this.vx; this.y += this.vy; if ( 0 > this.x + this.vx - this.r || this.x + this.vx + this.r >= canvasBounds.width ) { this.vx = -this.vx; } if (0 > this.y + this.vy - this.r) { this.vy = -this.vy; } if (this.y + this.vy + this.r >= canvasBounds.height) { // TODO: // this.vy = -this.vy; } if (this.hitPoint !== -1) { let coll = this.collidesWith(bat); if (coll === CollisionDir.SIDE) { this.vx = -this.vx; } else if (coll === CollisionDir.TOP) { this.vy = -this.vy; } if (coll !== CollisionDir.NONE && swing > 0) { this.vx *= 1.1; this.vy *= 1.1; } if (this.hitPoint && coll !== CollisionDir.NONE) this.hitPoint--; } wall.forEach((x) => { let coll = this.collidesWith(x); if (this.hitPoint !== -1) { if (coll === CollisionDir.SIDE) { this.vx = -this.vx; } else if (coll === CollisionDir.TOP) { this.vy = -this.vy; } if (this.hitPoint !== undefined && coll !== CollisionDir.NONE) this.hitPoint--; } }); } isAlive() { return ( (this.hitPoint === undefined || this.hitPoint != 0) && this.y - POWER_UP_RADIUS < canvasBounds.height ); } draw(ctx: CanvasRenderingContext2D) { if (this.hitPoint === -1) ctx.fillStyle = "#cc0000"; ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI); ctx.fill(); ctx.fillStyle = "black"; } collidesWith(bat: Collider) { return bat.collidesWith(this.x + this.vx, this.y + this.vy, this.r); } } enum CollisionDir { TOP, SIDE, NONE, } const PADDLE_HEIGHT = 20; const INIT_PADDLE_WIDTH = 100; class Paddle implements Collider { private x = (canvasBounds.width - INIT_PADDLE_WIDTH) / 2; private y = canvasBounds.height - 2 * PADDLE_HEIGHT; private w = INIT_PADDLE_WIDTH; private speed = 1; increaseSize() { this.w += 10; } increaseSpeed() { this.speed += 0.1; } update(ball: Ball) { if (!playerControlled) { let d = this.x + this.w / 2 - ball.getX(); if (d < -10) this.x += this.speed * 1.5; else if (d > 10) this.x -= this.speed * 1.5; } else { if (leftDown) this.x -= this.speed * 1.5; if (rightDown) this.x += this.speed * 1.5; if (swing > 0) swing--; } } draw(ctx: CanvasRenderingContext2D) { if (swing > 0) ctx.strokeStyle = "red"; ctx.strokeRect(this.x, this.y, this.w, PADDLE_HEIGHT); if (swing > 0) ctx.strokeStyle = "black"; } collidesWith(x: number, y: number, r: number) { let testX = x; let testY = y; let dir = CollisionDir.NONE; // which edge is closest? if (x < this.x) { testX = this.x; dir = CollisionDir.SIDE; } else if (x > this.x + this.w) { testX = this.x + this.w; // right edge dir = CollisionDir.SIDE; } // top edge if (y < this.y) { testY = this.y; dir = CollisionDir.TOP; } let distX = x - testX; let distY = y - testY; let distance = Math.hypot(distX, distY); if (distance <= r) { return dir; } else { return CollisionDir.NONE; } } } const BRICK_SPACING = 10; const BRICK_WIDTH = 40; const BRICK_HEIGHT = 15; class Brick implements Collider { private hitPoints; constructor(private x: number, private y: number, private color: string[]) { this.hitPoints = color.length - 1; } draw(ctx: CanvasRenderingContext2D) { ctx.fillStyle = this.color[this.hitPoints]; ctx.fillRect(this.x, this.y, BRICK_WIDTH, BRICK_HEIGHT); ctx.fillStyle = "black"; } collidesWith(x: number, y: number, r: number) { let testX = x; let testY = y; let dir = CollisionDir.NONE; if (x < this.x) { testX = this.x; dir = CollisionDir.SIDE; } else if (x > this.x + BRICK_WIDTH) { testX = this.x + BRICK_WIDTH; dir = CollisionDir.SIDE; } if (y < this.y) { testY = this.y; dir = CollisionDir.TOP; } else if (y > this.y + BRICK_HEIGHT) { testY = this.y + BRICK_HEIGHT; dir = CollisionDir.TOP; } let distX = x - testX; let distY = y - testY; let distance = Math.hypot(distX, distY); if (distance <= r) { this.hitPoints--; if (this.hitPoints < 0 && Math.random() < 0.75) powerUps.push( new PowerUp(this.x + BRICK_WIDTH / 2, this.y, randomPowerUp()) ); return dir; } else { return CollisionDir.NONE; } } isAlive() { return this.hitPoints >= 0; } } let ball = new Ball( canvasBounds.width / 2, canvasBounds.height - 100, 10, 2 * Math.random(), 3 ); let balls = [ball]; let bat = new Paddle(); let wall: Brick[] = []; let powerUps: PowerUp[] = [ new PowerUp( canvasBounds.width / 2, canvasBounds.height - 100, new Explosion() ), ]; let wx = ~~(canvasBounds.width / (BRICK_WIDTH + BRICK_SPACING)); let offset = (canvasBounds.width - wx * (BRICK_WIDTH + BRICK_SPACING) + BRICK_SPACING) / 2; for (let x = 0; x < wx; x++) for (let y = 0; y < 13; y++) wall.push( new Brick( (BRICK_SPACING + BRICK_WIDTH) * x + offset, (BRICK_SPACING + BRICK_HEIGHT) * y + BRICK_SPACING, ["#cc0000", "#ffcc00", "#00aa00"] ) ); function draw() { let ctx = canvasElem.getContext("2d")!; ctx.clearRect(0, 0, canvasBounds.width, canvasBounds.height); balls.forEach((x) => x.draw(ctx)); bat.draw(ctx); wall.forEach((w) => w.draw(ctx)); powerUps.forEach((w) => w.draw(ctx)); } function update() { bat.update(ball); powerUps.forEach((w) => w.update(bat)); powerUps = powerUps.filter((x) => x.isAlive()); balls.forEach((x) => x.update(bat, wall)); balls = balls.filter((x) => x.isAlive()); wall = wall.filter((x) => x.isAlive()); } const FPS = 60; const SLEEP = 1000 / FPS; function gameLoop() { let before = Date.now(); update(); draw(); let after = Date.now(); let sleep = SLEEP - (after - before); if (sleep < 5) console.log("Stayed up all night!"); setTimeout(() => gameLoop(), sleep); } let playerControlled = false; let leftDown = false; let rightDown = false; let swing = -1; const LEFT_KEY = 37; const UP_KEY = 38; const RIGHT_KEY = 39; const DOWN_KEY = 40; window.addEventListener("keydown", (e) => { playerControlled = true; if (e.keyCode === LEFT_KEY || e.key === "a") { leftDown = true; } else if (e.keyCode === RIGHT_KEY || e.key === "d") { rightDown = true; } else if (e.key === " " && swing < 0) { swing = 10; } }); window.addEventListener("keyup", (e) => { if (e.keyCode === LEFT_KEY || e.key === "a") { leftDown = false; } else if (e.keyCode === RIGHT_KEY || e.key === "d") { rightDown = false; } else if (e.key === " ") { swing = -1; } }); gameLoop();
a527d6e21c2a873453c8dcf557b1994cec20e37f
TypeScript
mrjasonweaver/list-organizer
/clientapp/src/app/models/contacts.ts
2.609375
3
// state export interface IContact { id: number; firstName: string; lastName: string; email: string; role: string; organization: string; phone: string; status: boolean; } export interface IContactsState { page: number; contacts: IContact[]; } export interface IContactsListState { contacts: IContact[]; } export interface IContactsPageState { page: number; } export interface IContactState { contact: IContact; } export interface IFirstNameState { firstName: string; } export interface ILastNameState { lastName: string; } export interface IEmailState { email: string; } export interface IRoleState { role: string; } export interface IOrganizationState { organization: string; } export interface IPhoneState { phone: string; } export interface IStatusState { status: boolean; } export const InitialContactsState: IContactsState = { page: 1, contacts: [{ id: 0, firstName: '', lastName: '', email: '', role: '', organization: '', phone: '', status: false }] }; export const InitialContactState: IContactState = { contact: { id: 0, firstName: '', lastName: '', email: '', role: '', organization: '', phone: '', status: false} };
36881b1fc6302875f5da04258dd0232d413ad63b
TypeScript
vladyslav/Jira-like-app
/client/src/app/SwitchModes.ts
2.609375
3
import { defaultQueryParams } from './Config'; import Initialize from './interfaces/Initialize'; import RenderTickets from './RenderTickets'; import TicketService from './services/TicketService'; export default class SwitchModes implements Initialize { storage: void; checkbox: HTMLInputElement | null; backlog: HTMLElement | null; dragAndDrop: HTMLElement | null; state: string | null; constructor(private ticketService: TicketService, private renderTickets: RenderTickets) { this.checkbox = document.querySelector('.toggle-state'); this.backlog = document.querySelector('.backlog-section'); this.dragAndDrop = document.querySelector('.drag-and-drop'); this.state = localStorage.getItem('checked'); this.checkbox!.addEventListener('click', (): void => { this.toggleModes(); this.setState(this.checkbox!.checked); }); } private async toggleModes(): Promise<void> { if (this.state === 'true') { this.backlog!.classList.toggle('hide'); this.dragAndDrop!.classList.toggle('hide'); this.renderTickets.renderTickets( (await this.ticketService.getTickets(defaultQueryParams)).data, ); } else { this.dragAndDrop!.classList.toggle('hide'); this.backlog!.classList.toggle('hide'); this.renderTickets.renderTickets( (await this.ticketService.getTickets(defaultQueryParams)).data, ); } } private setState(state: boolean) { this.storage = localStorage.setItem('checked', (state as unknown) as string); } initialize(): void { if (this.state === 'true') { this.checkbox!.checked = true; this.toggleModes(); } } }
c9e9b201e1c8c1d99be3be6062176a4fa8dd1d0d
TypeScript
lizhenheng0203/express_ts
/src/utils/result.ts
2.671875
3
// import { CODE_SUCCESS,CODE_ERROR } from "./constant" export class Result { private data: any private msg: string private code: number constructor(data: any = undefined, msg: string = '操作成功', code: number = 0) { this.data = data this.code = code this.msg = msg } }
d16944ed3d53dc836a3f5f752b3573b9802a7c01
TypeScript
DeusDaSilva/php-react-to-do-app
/frontend/src/context/Reducer.ts
2.953125
3
import { ToDoState } from "typings"; import { Actions, ActionType } from "./Actions"; export const getInitialState = (): ToDoState => ({ todos: [] }) export const todoReducer = (state: ToDoState, action: Actions): ToDoState => { switch (action.type) { case ActionType.AddToDo: return { todos: [...state.todos, action.todo] } case ActionType.UpdateToDo: return { todos: state.todos.map((todo) => { return (todo.id === action.todo.id) ? action.todo : todo }) }; case ActionType.SetToDos: return { todos: action.todos }; } }
ce985081cc7e2c9d47b364a5b541f29fef0e93c4
TypeScript
crowcl52/examen_front
/src/app/redux/user.reducers.ts
2.671875
3
import * as fromUser from './user.actions'; import { User } from '../models/user.model'; export interface USerState { data: User; } const initState: USerState = { data: null } export function userReducer( state = initState, action: fromUser.actions ): USerState{ switch(action.type){ case fromUser.ACTIVATED_USER: return {data: {... action.user} }; case fromUser.DEACTIVATED_USER: return {data: null}; default: return state; } }
984cb05ce7c5768db8beb73500239d657f54d4ee
TypeScript
mosure/ci-webex-bot
/src/interfaces/bots.ts
2.671875
3
export interface Bot { say(message: string): void; } export interface IBots { getBot(id: string): Bot | undefined; }
ff5e04da71863afbadcf872422b28eee85a3e17e
TypeScript
pedroalvesbatista/hinkskalle
/frontend/tests/_data.ts
2.5625
3
import axios from 'axios'; import { Container, plainToContainer, Upload, plainToUpload, User, plainToUser, Collection, plainToCollection, Entity, plainToEntity, SearchResult, plainToSearchResult } from '@/store/models'; import { map as _map } from 'lodash'; export function makeTestUser() { return { id: "1", username: 'test.hase', email: 'test@ha.se', firstname: 'Test', lastname: 'Hase', isAdmin: false, } } export function makeTestUserObj(from: any=null): User { return plainToUser(from || makeTestUser()); } export function makeTestContainers() { return [ { id: "1", name: "testhippo", collectionName: "oinktion", entityName: "oinktity", description: 'Nilpferd', createdAt: new Date(), stars: 0, type: 'singularity' }, { id: "2", name: "testzebra", collectionName: "muhtion", entityName: "muhtity", description: 'Streifig', createdAt: new Date(), stars: 0, type: 'mixed' }, ] } export function makeTestContainersObj(from: any=null): Container[] { return _map(from || makeTestContainers(), plainToContainer); } export function makeTestLatest() { return [ { tags: ['eins', 'zwei'], container: { name: 'testhase', createdAt: new Date(), collectionName: 'oinkton', entityName: 'oinktity', }, }, { tags: ['drei', 'vier'], container: { name: 'testnilpferd', createdAt: new Date(), collectionName: 'muhton', entityName: 'muhtity', }, } ]; } export function makeTestLatestObj(from: any=null): Upload[] { return _map(from || makeTestLatest(), plainToUpload); } export function makeTestCollections() { return [ { id: '1', name: 'esel', description: 'eyore', createdAt: new Date(), entityName: 'oinktity', }, { id: '2', name: 'schaf', description: 'shawn', createdAt: new Date(), entityName: 'wooftity', } ]; } export function makeTestCollectionsObj(from: any=null): Collection[] { return _map(from || makeTestCollections(), plainToCollection); } export function makeTestEntities() { return [ { id: '1', name: 'esel', description: 'eyore', createdAt: new Date(), }, { id: '2', name: 'schaf', description: 'shawn', createdAt: new Date(), } ]; } export function makeTestEntitiesObj(from: any=null): Entity[] { return _map(from || makeTestEntities(), plainToEntity); } export function makeTestSearchResult() { return { entity: makeTestEntities(), collection: makeTestCollections(), container: makeTestContainers(), image: [] } } export function makeTestSearchResultObj(from: any=null): SearchResult { return plainToSearchResult(from || makeTestSearchResult()); }
a8a58a1b733478665050f234ae160c56dd1f01fd
TypeScript
kingOfQj/webgpu-renderer
/src/core/Light.ts
2.734375
3
/** * Light.ts * * @Author :dtysky(dtysky@outlook.com) * @Date : 6/11/2021, 9:57:52 PM */ import { mat4, vec3 } from 'gl-matrix'; import geometries from '../buildin/geometries'; import Material from './Material'; import Mesh from './Mesh'; import Node from './Node'; export enum ELightType { INVALID = 0, Area, Directional, Point, Spot } export enum EAreaLightMode { Rect, Disc } export interface IDirectionalLightOptions {} export interface IAreaLightOptions { mode: EAreaLightMode; size: [number, number]; } export default class Light extends Node { public static CLASS_NAME: string = 'Light'; public static IS(value: any): value is Light{ return !!(value as Light).isLight; } public isLight: boolean = true; protected _areaMode: EAreaLightMode; protected _areaSize: Float32Array; protected _color: Float32Array; protected _worldPos: Float32Array = new Float32Array(3); protected _worldDir: Float32Array = new Float32Array(3); protected _ubInfo: Float32Array; protected _mesh: Mesh; get ubInfo() { return this._ubInfo; } constructor( protected _type: ELightType, color: [number, number, number], otherOptions: IAreaLightOptions | IDirectionalLightOptions ) { super(); this._color = new Float32Array(color); this._ubInfo = new Float32Array(40); const u32View = new Uint32Array(this._ubInfo.buffer); u32View[0] = _type; if (_type === ELightType.Area) { this._areaMode = (otherOptions as IAreaLightOptions).mode; this._areaSize = new Float32Array((otherOptions as IAreaLightOptions).size); u32View[1] = this._areaMode; this._ubInfo.set(this._areaSize, 2); } } public setColor(r: number, g: number, b: number) { this._color.set(new Float32Array([r, g, b])); } public requireLightMesh(material: Material) { if (this._type !== ELightType.Area) { throw new Error('Light mesh only support area!'); } if (!this._mesh) { this._mesh = new Mesh( this._areaMode === EAreaLightMode.Rect ? geometries.rectLight : geometries.discLight, material ); } return this._mesh; } public updateMatrix() { super.updateMatrix(); mat4.getTranslation(this._worldPos, this._worldMat); vec3.transformMat4(this._worldDir, [0, 0, 1], this._worldMat); if (this._mesh) { this._mesh.scale.set(this._areaMode === EAreaLightMode.Disc ? [this._areaSize[0], this._areaSize[0], 0] : [this._areaSize[0], this._areaSize[1], 0] ); this._mesh.updateWorldMatrix(this); this._mesh.material.setUniform('u_lightColor', this._color); } this._ubInfo.set(this._color, 4); this._ubInfo.set(this._worldMat, 8); this._ubInfo.set(mat4.invert(new Float32Array(16), this._worldMat), 24); } }
993b12fb2e4a335fb1523d2a2744814f67b757ce
TypeScript
mukeshsoni/deepnotes-editor
/src/Editor/decorators.ts
2.625
3
import linkify from 'linkify-it'; import memoizeOne from 'memoize-one'; import { ContentBlock, CompositeDecorator } from 'draft-js'; import escapeStringRegexp from 'escape-string-regexp'; import Hashtag from './components/Hashtag'; import SearchHighlight from './components/SearchHighlight'; import Link from './components/Link'; const linkifyInstance = linkify(); const HASHTAG_REGEX = /#[\w\u0590-\u05ff]+/g; type Callback = (start: number, end: number) => void; function findWithRegex( regex: RegExp, contentBlock: ContentBlock, callback: Callback ) { const text = contentBlock.getText(); let matchArr, start; while ((matchArr = regex.exec(text)) !== null) { start = matchArr.index; callback(start, start + matchArr[0].length); } } function hashtagStrategy(contentBlock: ContentBlock, callback: Callback) { findWithRegex(HASHTAG_REGEX, contentBlock, callback); } function findLinkEntities( contentBlock: ContentBlock, callback: (start: number, end: number) => void ) { const links = linkifyInstance.match(contentBlock.getText()); if (links) { links.forEach((link: any) => callback(link.index, link.lastIndex)); } } export const createDecorators = memoizeOne((searchText = '') => { const regex = new RegExp(escapeStringRegexp(searchText), 'gi'); return new CompositeDecorator([ { strategy: hashtagStrategy, component: Hashtag, }, { strategy: (contentBlock, callback) => { if (searchText) { findWithRegex(regex, contentBlock, callback); } }, component: SearchHighlight, }, { strategy: findLinkEntities, component: Link }, ]); });
c86842d2db28eb2852d33c0fe6bd7f4ca11292c3
TypeScript
jonathanlingnau/EIA-2
/Aufgabe 9/aufgabe9.ts
2.578125
3
//Aufgabe: Aufgabe 9 //Name: Jonathan Lingnau //Matrikel: 255645 //Datum: 30.05.17 // //Hiermit versichere ich, dass ich diesen Code selbst geschrieben habe. //Er wurde nicht kopiert und auch nicht diktiert. namespace Form { window.addEventListener("load", init); let eissorten: string[] = ["Vanille", "Schokolade", "Erdbeere", "Himbeere", "Zitrone", "Banane", "Mocca", "Cookies", "Mango", "Haselnuss", "Straciatella", "Nougat", "Kirsche", "Joghurt", "Pistazie"]; let toppings: string[] = ["Sahne", "Schokostreusel", "Bunte Zuckerstreusel", "Erdbeersoße", "Schokosoße"]; let cups: string[] = ["Waffel", "Becher"]; let iceInput: HTMLInputElement[] = []; let toppingsInput: HTMLInputElement[] = []; let cupsInput: HTMLInputElement[] = []; let Eissorten: HTMLElement; let Toppings: HTMLElement; let Behaelter: HTMLElement; let Ausgabe: HTMLElement; let Button: HTMLElement; function init(_event: Event): void { Eissorten = document.getElementById("sorten"); Toppings = document.getElementById("toppings"); Behaelter = document.getElementById("cups"); Ausgabe = document.getElementById("ausgabe"); createInputs(); Eissorten.addEventListener("change", change); Toppings.addEventListener("change", change); Behaelter.addEventListener("change", change); } function createInputs(): void { for (let i: number = 0; i < eissorten.length; i++) { createCounter(eissorten[i]); } for (let i: number = 0; i < toppings.length; i++) { createCheckbox(toppings[i]); } for (let i: number = 0; i < cups.length; i++) { createRadio(cups[i]); } } function createCounter(_eis: string): void { let input: HTMLInputElement = document.createElement("input"); let label: HTMLLabelElement = document.createElement("label"); label.innerText = _eis; label.appendChild(input); input.type = "number"; input.min = "0"; input.value = "0"; Eissorten.appendChild(label); iceInput.push(input); } function createCheckbox(_topping: string): void { let input: HTMLInputElement = document.createElement("input"); let label: HTMLLabelElement = document.createElement("label"); label.innerText = _topping; label.appendChild(input); input.type = "checkbox"; Toppings.appendChild(label); toppingsInput.push(input); } function createRadio(_behaelter: string): void { let input: HTMLInputElement = document.createElement("input"); let label: HTMLLabelElement = document.createElement("label"); label.innerText = _behaelter; label.appendChild(input); input.type = "radio"; input.required = true; Behaelter.appendChild(label); cupsInput.push(input); } function change(): void { let summe: number = 0; for (let i: number = 0; i < iceInput.length; i++) { summe += parseInt(iceInput[i].value); } for (let i: number = 0; i < toppingsInput.length; i++) { if(toppingsInput[i].checked) {summe += 0.8;} } show(summe); } function show(_summe: number): void { document.getElementById("selectedIce").innerText = ""; document.getElementById("selectedToppings").innerText = ""; document.getElementById("selectedFruits").innerText = ""; document.getElementById("SelectedCup").innerText = ""; for (let i: number = 0; i < iceInput.length; i++) { if (parseInt(iceInput[i].value) > 0) { document.getElementById("selectedIce").innerText += eissorten[i] + " " + ": " + (parseInt(iceInput[i].value) * 1) + "\n"; } } for (let i: number = 0; i < toppingsInput.length; i++) { if(toppingsInput[i].checked) { document.getElementById("selectedToppings").innerText += toppings[i] + " 0.80 Euro" + "\n"; } } for (let i: number = 0; i < cupsInput.length; i++) { if(cupsInput[i].checked) { document.getElementById("SelectedCup").innerText += cups[i] + "\n"; } } //Anzeigen der Gesamtsumme document.getElementById("Summe").innerText = _summe.toString() + " Euro"; } }
7ce80100fa7dc45fde993257b6012b8e79e21125
TypeScript
fasterthanlime/bamb
/game/src/ai/compute-score.ts
2.921875
3
import { GameState, CellState } from "../types"; import { GameBase } from "../game-base"; export function computeScore( game: GameBase, state: GameState, player: number, ): number { let valueOwned = 0; let countCell = (cell: CellState) => { if (!cell.cardId) { return; } let card = game.cardSpecs[cell.cardId]; if (card.player == player && typeof card.value === "number") { valueOwned += card.value; } }; for (const cell of state.board.cells) { countCell(cell); } return valueOwned; }
bbd11385ef6bb0214ef1b03afd8358b1efadab6a
TypeScript
milangstojkovic/servicebook
/src/Containers/DataProvider/DataProvider.reducer.ts
2.6875
3
import ACTION_TYPE from '../../Store/actionTypes'; import { IDataProviderActions } from './DataProvider.actions'; import { IDataProviderState } from './DataProvider.state'; const initState: IDataProviderState = { users: { data: null, error: false, loading: false }, vehicles: { data: null, error: false, loading: false }, records: { data: null, error: false, loading: false }, selectedUser: null, selectedVehicle: null } export default (state = initState, action: IDataProviderActions): IDataProviderState => { switch (action.type) { case ACTION_TYPE.FETCH_USER_DATA_INIT: { return { ...state, users: { ...initState.users, loading: true } } } case ACTION_TYPE.FETCH_USER_DATA_SUCCESS: { return { ...state, users: { ...initState.users, data: action.payload } } } case ACTION_TYPE.FETCH_USER_DATA_ERROR: { return { ...state, users: { ...initState.users, error: true, errorMessage: action.payload } } } case ACTION_TYPE.FETCH_USER_VEHICLES_INIT: { return { ...state, vehicles: { ...initState.vehicles, loading: true } } } case ACTION_TYPE.FETCH_USER_VEHICLES_SUCCESS: { return { ...state, vehicles: { ...initState.vehicles, data: action.payload } } } case ACTION_TYPE.FETCH_USER_VEHICLES_ERROR: { return { ...state, vehicles: { ...initState.vehicles, error: true, errorMessage: action.payload } } } case ACTION_TYPE.FETCH_VEHICLE_RECORDS_INIT: { return { ...state, records: { ...initState.records, loading: true } } } case ACTION_TYPE.FETCH_VEHICLE_RECORDS_SUCCESS: { return { ...state, records: { ...initState.records, data: action.payload } } } case ACTION_TYPE.FETCH_VEHICLE_RECORDS_ERROR: { return { ...state, records: { ...initState.records, error: true, errorMessage: action.payload } } } case ACTION_TYPE.SELECT_USER: { return { ...state, selectedUser: action.payload } } case ACTION_TYPE.SELECT_VEHICLE: { return { ...state, selectedVehicle:action.payload } } default: return state; } }
9b814b2459a0223cd5e40278f261d74a9e1b21eb
TypeScript
stugen/uhb-live
/src/ui/utils/clientId.ts
2.515625
3
import randomstring from 'randomstring' export const getClientId = (): string => { return window.sessionStorage.getItem('client') || '' } export const setClientId = (): void => { const clientId = getClientId() if (clientId === '') { window.sessionStorage.setItem('client', randomstring.generate()) } }
332cfddb269cddeea825b084a98dc7faa848a31c
TypeScript
JeongGeun/YoutubeClone-fe
/src/components/reducer/ui_reducer.ts
2.703125
3
import { TOGGLE_DRAWER } from '../actions/home/type'; const initialState = { open: false, }; export default function Toggle(state = initialState, action) { switch (action.type) { case TOGGLE_DRAWER: return { ...state, open: !state.open }; default: return state; } }
202b6064c07ef8fad308d1daef610c8e06551f9e
TypeScript
yu3211/studyCode
/mordanSample/source/ts/google/unknownkey/app2.ts
2.90625
3
async function executeAjax() { try { return new Promise( ( resolve:(result:Array<json>) => void , reject) => { let result = $.ajax({type: 'GET' , url: 'https://maps.googleapis.com/maps/api/geocode/json' , dataType: 'json' , data: { key: 'keyを設定する', address: $('#zip').val(), language: 'ja'} }) console.log('asyncとawaitで非同期処理を実装中') console.log(result) resolve(result) }) } catch (error) { console.error(error) } } async function exec() { // awaitで待つ関数は、必ずPromiseオブジェクトを生成して返す await executeAjax().then( function(data) { if (data.status == "OK") { var components = data.results[0].address_components; if (components.length == 5) { $('#state').val(components[3].long_name); $('#city').val(components[2].long_name); $('#address1').val(components[1].long_name); } else if (components.length == 6) { $('#state').val(components[4].long_name); $('#city').val(components[3].long_name); $('#address1').val(components[2].long_name); $('#address2').val(components[1].long_name); } } }) } $(() => { $('#btn').click((e) => { console.log(`郵便番号::${$('#zip').val()}`) console.log('asyncとawaitで非同期処理を実装') exec() console.log('asyncとawaitで非同期処理を実装完了') }) })
38b5f7d5cde3411fcaabd7bd92c244dac7769624
TypeScript
moses0072/myFlix-Angular-Client
/src/app/fetch-api-data.service.ts
2.75
3
import { Injectable } from '@angular/core'; import { catchError } from 'rxjs/internal/operators'; import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { map } from 'rxjs/operators'; //import { Router } from '@angular/router'; //Declaring the api url that will provide data for the client app const apiUrl = 'https://mytopfilms.herokuapp.com/'; //User Registration @Injectable({ providedIn: 'root' }) /** * This service will enable communication with the movie API * and enable CRUD operations to be performed. */ export class FetchApiDataService { /** * The constructor Injects the HttpClient module to the constructor params. * This will provide HttpClient to the entire class, making it available via this.http. */ constructor(private http: HttpClient) { } /** * This method will make the api call to the user registration endpoint. * @param userDetails User name, password, email and date of birth. */ userRegistration(userDetails: any): Observable<any> { return this.http.post(apiUrl + 'users', userDetails).pipe( catchError(this.handleError) ); } /** * This method will make the api call to the user login endpoint. * @param username Username of type string. * @param password Password of type string. * @returns object with username and bearer token */ userLogin(username: string, password:string): Observable<any> { return this.http.post(apiUrl + 'login', { Username: username, Password: password, }) .pipe( map(this.extractResponseData), catchError(this.handleError)); } /** * This method will make the api call to the movies endpoint. * @returns array of movie objects. */ getAllMovies(): Observable<any> { const token = localStorage.getItem('token'); return this.http.get(apiUrl + 'movies', { headers: new HttpHeaders( { Authorization: 'Bearer ' + token, }) }).pipe( map(this.extractResponseData), catchError(this.handleError) ); } /** * This method will make the api call to the movie title endpoint. * @returns movie object. */ getMovieByTitle(): Observable<any> { const token = localStorage.getItem('token'); return this.http.get(apiUrl + 'movies/:Title', {headers: new HttpHeaders( { Authorization: 'Bearer ' + token, }) }).pipe( map(this.extractResponseData), catchError(this.handleError) ); } /** * This method will make the api call to the director name endpoint. * @param directorName name of movie director of type string. * @returns director object. */ getDirector(directorName: string): Observable<any> { const token = localStorage.getItem('token'); return this.http.get(apiUrl + 'movies/director/' + directorName, { headers: new HttpHeaders( { Authorization: 'Bearer ' + token, }) }).pipe( map(this.extractResponseData), catchError(this.handleError) ); } /** * This method will make the api call to the genre name endpoint. * @param genre name of genre of type string. * @returns genre object. */ getGenre(genre: string): Observable<any> { const token = localStorage.getItem('token'); return this.http.get(apiUrl + 'movies/genre/' + genre, {headers: new HttpHeaders( { Authorization: 'Bearer ' + token, }) }).pipe( map(this.extractResponseData), catchError(this.handleError) ); } /** * This method will make the api call to the User endpoint. * @returns user object. */ getUser(): Observable<any> { const user = localStorage.getItem('user'); const token = localStorage.getItem('token'); return this.http.get(apiUrl + `users/${user}`, { headers: new HttpHeaders({ Authorization: 'Bearer ' + token, }), }).pipe( map(this.extractResponseData), catchError(this.handleError)); } /** * This method will make the api call to the movie ID endpoint * in order to add the movie ID to the FavoriteMovies array in the user object. * @param movieID of type string. */ addFavoriteMovie(movieID: string): Observable<any> { const token = localStorage.getItem('token'); const user = localStorage.getItem('user'); return this.http.post(apiUrl + `users/${user}/favorites/${movieID}`, movieID, {headers: new HttpHeaders( { Authorization: 'Bearer ' + token, }) }).pipe(catchError(this.handleError)); } /** * This method will make the api call to the movie ID endpoint * in order to delete the movie ID from the FavoriteMovies array in the user object. * @param movieID of type string. */ deleteFavoriteMovie(movieID: string): Observable<any> { const token = localStorage.getItem('token'); const user = localStorage.getItem('user'); return this.http.delete(apiUrl + `users/${user}/favorites/${movieID}`, {headers: new HttpHeaders( { Authorization: 'Bearer ' + token, }) }).pipe( catchError(this.handleError) ); } /** * This method will make the api call to the User endpoint * in order to edit the user data. * @param userDetails object of user name, password, email and date of birth. * @returns user object. */ editUser(userDetails: any): Observable<any> { const token = localStorage.getItem('token'); const user = localStorage.getItem('user'); return this.http.put(apiUrl + `users/${user}`, userDetails, {headers: new HttpHeaders( { Authorization: 'Bearer ' + token, }) }).pipe( map(this.extractResponseData), catchError(this.handleError) ); } /** * This method will make the api call to the User endpoint * in order to delete the user data. * @returns user object. */ deleteUser(): Observable<any> { const token = localStorage.getItem('token'); const user = localStorage.getItem('user'); return this.http.delete(apiUrl + `users/${user}`, {headers: new HttpHeaders( { Authorization: 'Bearer ' + token, }) }).pipe( map(this.extractResponseData), catchError(this.handleError) ); } private extractResponseData(res: Object): any { const body = res; return body || { }; } private handleError(error: HttpErrorResponse): any{ if (error.error instanceof ErrorEvent) { console.error('Some error occurred:', error.error.message); } else { console.error( `Error Status code ${error.status}, ` + `Error body is: ${error.error}`); } return throwError( 'Something bad happened'); } }
b2d0e772ca02e8177f6aea79f09fdf70bac427b3
TypeScript
sakibrahmanchy/storefront
/src/entities/customer.entity.ts
2.515625
3
import { Column, Entity, JoinColumn, OneToMany, PrimaryGeneratedColumn, } from 'typeorm'; import { BaseEntity } from './base.entity'; import { Sale } from './sale.entity'; @Entity() export class Customer extends BaseEntity { @PrimaryGeneratedColumn() id: number; @Column() customer_name: string; @Column() customer_contact: number; @Column() customer_email: string; @Column('datetime', { nullable: true }) last_bill_on: string; @Column('double', { nullable: true }) last_bill_amount: number; @OneToMany(() => Sale, (sale) => sale.customer) @JoinColumn() sales: Sale[]; }
d354e7b8081ee33dba2900e0a6320e85c0d7aee0
TypeScript
kylejlin/fitview
/src/axes.ts
2.625
3
const axes: Axes = {} as Axes; export default axes; updateAxes(); window.addEventListener("resize", updateAxes); window.addEventListener("orientationchange", updateAxes); function updateAxes() { if (window.innerWidth > window.innerHeight) { axes.major = window.innerWidth; axes.minor = window.innerHeight; } else { axes.major = window.innerHeight; axes.minor = window.innerWidth; } } interface Axes { major: number; minor: number; }
17d5925ee811442c1a8f2835959156ba59049dc5
TypeScript
kdechant/eamon
/client/adventures/cliffs-of-fire/commands.ts
2.8125
3
import Game from "../../core/models/game"; import {Monster} from "../../core/models/monster"; import {CommandException} from "../../core/utils/command.exception"; declare let game: Game; export var custom_commands = []; custom_commands.push({ name: "wave", verbs: ["wave"], description: "Waves something in the air.", examples: ['WAVE WAND'], run: function(verb: string, arg: string): void { // this command is really just a wrapper around the "use" command const artifact = game.artifacts.getLocalByName(arg); if (artifact) { if (artifact.id === 3) { // black wand. "wave x" is just a synonym for "use x" artifact.use(); } else { throw new CommandException("Nothing happens."); } } else { throw new CommandException("Nothing happens."); } }, });
4555226844b7d40b808b16b8dff7a011c95cee68
TypeScript
Santiagovar/Proyecto_eventos
/proyecto_nuevo/src/providers/UsuarioService.ts
2.578125
3
import {Injectable} from '@angular/core'; //UrlSearchParams sirve para mandar parametros import {Http,URLSearchParams } from '@angular/http'; import {URL_SERVICIOS} from "../config/url.servicios"; import {AlertController,Platform } from "ionic-angular"; import {Storage} from '@ionic/storage'; @Injectable() export class UsuarioService { token:string; id_usuario:string; constructor(public http: Http,private alertCtrl: AlertController, private plataform : Platform, private storage: Storage) { this.cargar_storage(); } activo():boolean{ //funion para saber si la sesion está activa if(this.token){ return true; } else{ return false; } } ingresar(correo:string, contrasena:string){ let data = new URLSearchParams(); //envia los datos data.append("correo", correo); data.append("contrasena", contrasena); let url = URL_SERVICIOS + "/login"; //respuesta mientras se espera return this.http.post( url, data ) .map(resp =>{ let data_resp = resp.json(); console.log(data_resp); if( data_resp.error){ this.alertCtrl.create({ title : "error al iniciar", subTitle : data_resp.mensaje, buttons : ["OK"] }).present(); }else{ this.token = data_resp.token; this.id_usuario = data_resp.id_usuario; //guardar Storage this.guardar_storage(); } }) } cerrar_sesion(){ this.token = null; this.id_usuario = null; this.guardar_storage(); } private guardar_storage(){ if(this.plataform.is("cordova")){ //dispositivos this.storage.set('token',this.token); this.storage.set('id_usuario',this.id_usuario); }else{ //computador if(this.token){ localStorage.setItem("token", this.token); localStorage.setItem("id_usuario", this.id_usuario); }else{ localStorage.removeItem("token"); localStorage.removeItem("id_usuario"); } } } cargar_storage(){ let promesa = new Promise((resolve, reject) =>{ if(this.plataform.is("cordova")){ //dispositivo this.storage.ready() //revisa si el almacenamiento del dispositivo está bien .then( ()=>{ this.storage.get("token").then( token => { if( token ){ //revisa si no llega nada nulo this.token = token; } }) this.storage.get("id_usuario").then( id_usuario => { if( id_usuario ){ //revisa si no llega nada nulo this.id_usuario = id_usuario; } resolve(); }) }) }else{ //computador if(localStorage.getItem("token")){ this.token = localStorage.getItem("token") ; this.id_usuario = localStorage.getItem("id_usuario") ; } resolve(); } }); return promesa; } }
69312575c102a04fb987cf25320e9cce43d0eea7
TypeScript
lanemt/definitelytyped.github.io
/types/amap-js-api/lngLat.d.ts
3.03125
3
declare namespace AMap { class LngLat { /** * 构造一个地理坐标对象 * @param lng 经度 * @param lat 纬度 * @param noAutofix 是否自动修正 */ constructor(lng: number, lat: number, noAutofix?: boolean); /** * 移动当前经纬度坐标得到新的坐标 * @param east 移动经度,向右为正值 * @param north 移动维度,向上为正值 */ offset(east: number, north: number): LngLat; /** * 当前经纬度和传入经纬度或者经纬度数组连线之间的地面距离,单位为米 * @param lnglat 对比目标 */ distance(lnglat: LngLat | LngLat[]): number; /** * 获取经度值 */ getLng(): number; /** * 获取纬度值 */ getLat(): number; /** * 判断当前坐标对象与传入坐标对象是否相等 * @param lnglat 判断目标 */ equals(lnglat: LngLat): boolean; /** * 以字符串的形式返回 */ toString(): string; // internal add(lnglat: LngLat, noAutofix?: boolean): LngLat; subtract(lnglat: LngLat, noAutofix?: boolean): LngLat; divideBy(num: number, noAutofix?: boolean): LngLat; multiplyBy(num: number, noAutofix?: boolean): LngLat; } }