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
b9a8057c2d94f27708bc713c68ff31623f648958
TypeScript
zachowj/node-red-contrib-home-assistant-websocket
/src/common/errors/HomeAssistantError.ts
2.625
3
import { RED } from '../../globals'; interface HaError { code: string; message: string; } export function isHomeAssistantApiError(error: any): error is HaError { return error.code !== undefined && error.message !== undefined; } export default class HomeAssistantError extends Error { readonly #statusMessage: string; constructor( haError: HaError, statusMessage = 'home-assistant.error.error' ) { super(haError.message); this.name = 'HomeAssistantError'; this.#statusMessage = RED._(statusMessage); } }
06882ca2ef89dc4e5f5af8a0ca5b74ce1785ed92
TypeScript
kkumari27/Assngmnt6
/assignment6-master/src/app/book.ts
2.65625
3
export class Book { id:number; name:string; price:number; author:string; image:string; details:string; constructor(id,name,price,author,image,details){ this.id=id; this.name=name; this.price=price; this.author=author; this.image=image; this.details=details; } }
06d1fcc05085c8e2ef1b2faa51ea5f08ccd9aa75
TypeScript
rahulagarwal10895/angular
/src/app/shared/model/Student.ts
2.515625
3
export class Student{ public id:number; public studentName:string; public category:string; public dob:Date; public fname:string; public mname:string; public score:number; public email:string; public contact:string; public documents:Document; constructor(){ this.documents=new Document(); } } export class Document{ public domicileCertificate:boolean; public birthCertificate:boolean; public previousMarksheets:boolean; public policeClearance:boolean; public passport:boolean; public signedDeclaration:boolean; } export class AvailableDocuments{ public name:string; public isRequired:boolean; }
ccdd25d82f2842cdf5dd6783fb1f9a0f8f844ac5
TypeScript
desktop/desktop
/app/test/unit/octicon-test.ts
2.53125
3
import { iconForRepository } from '../../src/ui/octicons' import * as OcticonSymbol from '../../src/ui/octicons/octicons.generated' import { CloningRepository } from '../../src/models/cloning-repository' import { Repository } from '../../src/models/repository' import { gitHubRepoFixture } from '../helpers/github-repo-builder' describe('octicon/iconForRepository', () => { it('shows download icon for cloning repository', () => { const repository = new CloningRepository( 'C:/some/path/to/repo', 'https://github.com/desktop/desktop' ) const icon = iconForRepository(repository) expect(icon).toEqual(OcticonSymbol.desktopDownload) }) it('shows computer icon for non-GitHub repository', () => { const repository = new Repository('C:/some/path/to/repo', 1, null, false) const icon = iconForRepository(repository) expect(icon).toEqual(OcticonSymbol.deviceDesktop) }) it('shows repo icon for public GitHub repository', () => { const gitHubRepository = gitHubRepoFixture({ owner: 'me', name: 'my-repo', isPrivate: false, }) const repository = new Repository( 'C:/some/path/to/repo', 1, gitHubRepository, false ) const icon = iconForRepository(repository) expect(icon).toEqual(OcticonSymbol.repo) }) it('shows lock icon for private GitHub repository', () => { const gitHubRepository = gitHubRepoFixture({ owner: 'me', name: 'my-repo', isPrivate: true, }) const repository = new Repository( 'C:/some/path/to/repo', 1, gitHubRepository, false ) const icon = iconForRepository(repository) expect(icon).toEqual(OcticonSymbol.lock) }) it('shows fork icon for forked GitHub repository', () => { const gitHubRepository = gitHubRepoFixture({ owner: 'me', name: 'my-repo', isPrivate: false, parent: gitHubRepoFixture({ owner: 'you', name: 'my-repo' }), }) const repository = new Repository( 'C:/some/path/to/repo', 1, gitHubRepository, false ) const icon = iconForRepository(repository) expect(icon).toEqual(OcticonSymbol.repoForked) }) })
b778b39fc6896d4acc2eea7b60259c085bf6ffb5
TypeScript
kryptonian41/mytry-next-app
/pages/api/users/authenticate.ts
2.640625
3
import type { NextApiRequest, NextApiResponse } from "next"; import axios from "axios"; export const authenticateUser = async (body = {}) => { const { email, password } = body as any; let response; try { response = await axios.post(process.env.WCOMM_DOMAIN, null, { params: { rest_route: `${process.env.JWT_NAMESPACE}/auth`, email, password, }, }); response.status = 201; } catch (error) { response = error.response; } return response; }; // TODO - if request is made without proper request body, respond with 400 export default async (req: NextApiRequest, res: NextApiResponse) => { if (req.method === "POST") { const response = await authenticateUser(req.body); res.status(response.status).json(response.data); } else res.status(405).json(""); };
c83d3bf6e79b784b94867e77a3a5e862c6a57c1d
TypeScript
JRoman-brug/newFirebasePage
/src/app/services/firestore/firestore.service.ts
2.515625
3
import { Injectable } from '@angular/core'; import { AngularFirestore, AngularFirestoreCollection } from '@angular/fire/compat/firestore'; // Observables library import { map } from 'rxjs/operators'; import { Observable, pipe } from 'rxjs'; // Intefaces import { IProduct, IProductId } from '../../interfaces/product/product' import { ICategoria } from "../../interfaces/product/categoria"; @Injectable({ providedIn: 'root' }) export class FirestoreService { productos: Observable<IProductId[]>; private collection: AngularFirestoreCollection<any> constructor(private dbFireStore: AngularFirestore) { this.collection = this.dbFireStore.collection<IProduct>('Productos') // Llena el array con los documentos de la coleccion this.productos = this.collection.snapshotChanges().pipe( map(a => a.map(a => { const producto: IProductId = { id: a.payload.doc.id, producto: a.payload.doc.data().producto, precio: a.payload.doc.data().precio, image: a.payload.doc.data().imagen, categoria:"" } return producto })) ) } // Obtiene todos los documentos de la base de datos getProductos() { return this.productos } // Obtenien un producto en especifico getProducto(id: string) { return this.collection.doc(id).snapshotChanges().pipe( map(a => { const producto: IProductId = { id: a.payload.id, producto: a.payload.data().producto, precio: a.payload.data().precio, image: a.payload.data().imagen, categoria:'' } return producto }) ) } // Agrega un producto addProductos(data: IProduct) { return this.collection.add(data) } updateProducto(id:string, data:IProduct){ this.collection.doc(id).update(data) } // Elimina un documento de la base de datos deleteProducto(id: string): Promise<any> { return this.collection.doc(id).delete() } }
951049a5a152b1da0ea8d9140ba458559f8948cb
TypeScript
m-mik/ipa-trainer
/common/hooks/useKey.ts
2.640625
3
import { useCallback, useEffect } from 'react' function useKey(targetKey: string, handler: (e: KeyboardEvent) => void) { const keyDownHandler = useCallback( (e: KeyboardEvent) => { if (e.key === targetKey) { handler(e) } }, [handler, targetKey] ) useEffect(() => { window.addEventListener('keydown', keyDownHandler) return () => window.removeEventListener('keydown', keyDownHandler) }, [keyDownHandler]) } export default useKey
61e15ad73e94c07c75c040c4bc5e43feb0802cf7
TypeScript
MrZhouZh/awesome-validator
/test/rules/full-width.ts
3.078125
3
import { assert } from 'chai'; import { AbstractRule } from '../../src/rules/abstract-rule'; import { FullWidth } from '../../src/rules/full-width'; describe('FullWidth', () => { let fullWidth: FullWidth; beforeEach(() => { fullWidth = new FullWidth(); }); it('is rule', () => { assert.instanceOf(fullWidth, AbstractRule); }); it('values is valid with additional characters', () => { assert.isTrue(new FullWidth('!@#$%^&*(){}').validate('!@#$%^&*(){} test@example.com')); assert.isTrue(new FullWidth('[]?+=/\\-_|"\',<>.').validate('[]?+=/\\-_|"\',<>. \t \n test@example.com')); assert.isTrue(new FullWidth(undefined).validate('ひらがな')); }); it('values is valid', () => { assert.isTrue(fullWidth.validate('ひらがな・カタカナ、.漢字')); assert.isTrue(fullWidth.validate('3ー0 a@com')); assert.isTrue(fullWidth.validate('Fカタカナ゙ᆲ')); assert.isTrue(fullWidth.validate('Good=Parts')); }); it('values is not valid', () => { assert.isFalse(fullWidth.validate('abc')); assert.isFalse(fullWidth.validate('abc123')); assert.isFalse(fullWidth.validate('!"#$%&()<>/+=-_? ~^|.,@`{}[]')); assert.isFalse(fullWidth.validate(Boolean())); assert.isFalse(fullWidth.validate(Number())); assert.isFalse(fullWidth.validate(String())); assert.isFalse(fullWidth.validate(null)); assert.isFalse(fullWidth.validate(undefined)); assert.isFalse(fullWidth.validate(true)); assert.isFalse(fullWidth.validate(false)); assert.isFalse(fullWidth.validate(0)); assert.isFalse(fullWidth.validate(0.0)); assert.isFalse(fullWidth.validate(-0.0)); assert.isFalse(fullWidth.validate('')); assert.isFalse(fullWidth.validate('0')); assert.isFalse(fullWidth.validate(' ')); assert.isFalse(fullWidth.validate(' ')); assert.isFalse(fullWidth.validate({})); assert.isFalse(fullWidth.validate(new Object())); assert.isFalse(fullWidth.validate(Object.create(null))); assert.isFalse(fullWidth.validate(Boolean(true))); assert.isFalse(fullWidth.validate(Number(1))); assert.isFalse(fullWidth.validate(String('fooBar'))); assert.isFalse(fullWidth.validate('foo')); assert.isFalse(fullWidth.validate({foo: 'bar'})); assert.isFalse(fullWidth.validate(1)); assert.isFalse(fullWidth.validate(-1)); assert.isFalse(fullWidth.validate(1.0)); assert.isFalse(fullWidth.validate(-1.0)); assert.isFalse(fullWidth.validate(1)); assert.isFalse(fullWidth.validate(1.0)); assert.isFalse(fullWidth.validate(1.1)); assert.isFalse(fullWidth.validate(new Object({foo: 'bar'}))); class Foo {} assert.isFalse(fullWidth.validate(new Foo())); }); });
34b6dfb1d46682bf765888cf7190ef987e987644
TypeScript
oscarmelara/datalink
/src/utils/alerts.ts
2.53125
3
import Swal from 'sweetalert2' const colors: { [x: string]: string } = { confirmButtonColor: '#212754', blackButton: '#333333', } interface SweetAlertProps { title?: string html?: string icon?: 'success' | 'error' | 'warning' | 'info' | 'question' | undefined } export const confirmAlert = ({ title = '', html = '', icon = 'question', }: SweetAlertProps) => { return Swal.fire({ title, html, icon, showCancelButton: true, confirmButtonColor: colors.confirmButtonColor, cancelButtonColor: colors.blackButton, confirmButtonText: 'Yes', }) } export const simpleAlert = ({ title = '', html = '', icon = 'info', }: SweetAlertProps) => { return Swal.fire({ title, html, icon, confirmButtonColor: colors.blackButton, confirmButtonText: 'Close', }) } export const loaderAlert = ({ title = '', html = '', }: SweetAlertProps): void => { Swal.fire({ title, html, onBeforeOpen: () => { Swal.showLoading() }, }) }
ab0ee6e8244cd3d665eadf7342edbaeb6912bf0c
TypeScript
marcmrf/ts-auto-mock
/src/transformer/descriptor/enum/enumDeclaration.ts
2.5625
3
import * as ts from 'typescript'; import { TypeChecker } from '../../typeChecker/typeChecker'; import { RandomPropertyAccessor } from '../random/random'; import { IsTsAutoMockRandomEnabled } from '../../../options/random'; export function GetEnumDeclarationDescriptor(node: ts.EnumDeclaration): ts.Expression { const typeChecker: ts.TypeChecker = TypeChecker(); const typesList: ts.LiteralType[] = node.members.map((it: ts.EnumMember) => typeChecker.getTypeAtLocation(it)) as ts.LiteralType[]; if (IsTsAutoMockRandomEnabled()) { const nodesList: ts.Expression[] = typesList.map((type: ts.LiteralType, index: number) => { if (type.hasOwnProperty('value')) { return ts.createLiteral(type.value); } return ts.createLiteral(index); }); return ts.createCall(RandomPropertyAccessor('enumValue'), [], [...nodesList]); } if (typesList[0].hasOwnProperty('value')) { return ts.createLiteral(typesList[0].value); } return ts.createLiteral(0); }
8fe1018048fadbbacd444660a5d1957dc0140e90
TypeScript
andretimm/flash
/src/modules/Message/MessageController.ts
2.578125
3
import { Request, Response } from "express"; import { validationResult } from "express-validator"; import { Errors } from "../../entities/Error"; import { Message } from "../../entities/Message"; import { MessageService } from "./MessageService"; class MessageController { constructor(private messageService: MessageService) {} async getMessageByID(req: Request, res: Response) { const { messageID } = req.params; try { return res.json(await this.messageService.findOne(messageID)); } catch (error) { return res.status(400).send(new Errors({ msg: error.message })); } } async createNewMessage(req: Request, res: Response) { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } let message = req.body; message.created_date = new Date().toDateString(); try { return res.json(await this.messageService.createMessage(message)); } catch (error) { return res.status(400).send(new Errors({ msg: error.message })); } } isExpired(message: Message) { const { created_date, timer } = message; created_date.setMilliseconds(created_date.getMilliseconds() + timer); return created_date < new Date(); } } export { MessageController };
2b0e2a0c56c3b87799191ae7199e7b9b6521267e
TypeScript
netoudi/won-games-client
/src/utils/filter/index.ts
2.625
3
import { ParsedUrlQueryInput } from 'querystring' import { ItemProps } from 'components/ExploreSidebar' export type ParseArgs = { queryString: ParsedUrlQueryInput filterItems: Pick<ItemProps, 'type' | 'name'>[] } export const parseQueryStringToWhere = ({ queryString, filterItems, }: ParseArgs) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const obj: any = {} Object.keys(queryString).forEach((key) => { if (key === 'sort') return const item = filterItems.find((el) => el.name === key) obj[key] = item?.type === 'checkbox' ? { name_contains: queryString[key] } : queryString[key] }) return obj } export const parseQueryStringToFilter = ({ queryString, filterItems, }: ParseArgs) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const obj: any = {} Object.keys(queryString).forEach((key) => { const item = filterItems.find((el) => el.name === key) obj[key] = item?.type === 'checkbox' && !Array.isArray(queryString[key]) ? [queryString[key]] : queryString[key] }) return obj }
ef57f92e34c76369c3385aa721925c3689702dd3
TypeScript
modelmap/a1-notation
/dist/noObject/converters/A1-Col-2.d.ts
2.8125
3
/** * @fileOverview Converts column letter to number * @author Flambino * @see https://codereview.stackexchange.com/questions/90112/a1notation-conversion-to-row-column-index * @param {string} col * * @return {number} */ export default function (col: string): number;
2b3a6fe2a23389bf27d00866af990e246d35cccc
TypeScript
elkarouani/my-angular-demo
/src/app/courses.service.ts
2.578125
3
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class CoursesService { _courses: string[]; constructor() { this._courses = ['item1', 'item2', 'item3']; } get courses() { return this._courses; } addCourse() { this._courses.push('item') } removeCourse(course: string) { this._courses = this._courses.filter(item => item !== course); } updateCourse(course: string) { this._courses[this._courses.indexOf(course)] += "-updated"; } }
2c735189519b70498bd187470bf7cdaea24b28e3
TypeScript
nexttiereducation/mobile-upgrade
/src/app/pipes/gerundize.pipe.ts
3.09375
3
import { Pipe, PipeTransform } from '@angular/core'; import { endsWith, join, trimEnd, words } from 'lodash'; @Pipe({ name: `gerundize` }) export class GerundizePipe implements PipeTransform { /** * Takes a string of words and transforms one of them into a gerund. */ public transform(val: string, wordIndex: number = 0) { const wordArray = words(val); let word = wordArray[wordIndex]; if (endsWith(word, `e`)) { word = trimEnd(word, `e`); } word += `ing`; wordArray.splice(0, 1, word); const newVal = join(wordArray, ` `); return newVal; } }
7fcdc2987561aeea913755883eb95a9e9f72cde6
TypeScript
isabelADev/ray-tracing-css
/src/app/ray-trace-graph/utils/ray-trace-utils.ts
2.796875
3
import {Coord} from '../models/coord'; export class RayTraceUtils { public static calculateTransformForBulletToCoord(coord: Coord) { return `translate(${coord.xPos}px, ${coord.yPos}px)`; } public static calculateVectorWidth(dX: number, dY: number, offsetWidth: number): number { return Math.sqrt(Math.pow(dX, 2) + Math.pow(dY, 2)) - offsetWidth / 2; } public static calculateAngleDegreesForVector(dX: number, dY: number): number { const radiansAngle = dX === 0 ? 1 : Math.atan(dY / dX); return radiansAngle * (180 / Math.PI); } public static calculateLeftMidPoint(elem: HTMLElement): Coord { const absPosRectangle = elem.getBoundingClientRect(); const xPos = absPosRectangle.x; const yPos = absPosRectangle.y; const height = elem.offsetHeight; return new Coord(xPos, yPos + height / 2); } }
63e6ec12ca6defb656ead672825373dcb1bca2ad
TypeScript
cichya/Angular.Learning.SPA
/src/app/features/ngrx/store/ngrx.actions.ts
2.515625
3
import { Data } from './../models/data'; import { Action } from '@ngrx/store'; export const FETCH_DATA = '[Ngrx] Fetch Data'; export const SET_DATA = '[Ngrx] Set Data'; export const ADD_DATA = '[Ngrx] Add Data'; export const DELETE_DATA = '[Ngrx] Delete Data'; export class FetchData implements Action { readonly type = FETCH_DATA; } export class SetData implements Action { readonly type = SET_DATA; constructor(public payload: Data[]) {} } export class AddData implements Action { readonly type = ADD_DATA; constructor(public payload: Data) {} } export class DeleteData implements Action { readonly type = DELETE_DATA; constructor(public index: number) {} } export type NgrxActions = | AddData | DeleteData | FetchData | SetData;
4a5c4f98d64328ee142d3bc7e69e2e577385370c
TypeScript
emmaofori20/myPhpBlog
/src/app/models/Categories.model.ts
2.625
3
export class Categories { public id: number; public CategoriesName:string; constructor(Name:string, date:string, id:number){ this.CategoriesName=Name; this.id=id; } }
ccae0956230fa633f87bb55f48ce502f563ba5e8
TypeScript
njirem95/cah-clone
/src/networking/GameServerHandler.ts
2.546875
3
import { Connection } from "./Connection"; import * as socketio from "socket.io"; import { Event } from "../events/Event"; export class GameServerHandler implements Connection { constructor( private _server: socketio.Server, private _events: Map<string, Event> ) { } public handle(): void { this._server.on('connection', (session: socketio.Socket) => { console.log("A user connected"); this._events.forEach(function(event: Event, id: string) { session.on(id, function(data) { event.handle(session, data); }); }); }); } }
c49acb064fe65b2986ae1d9e358ad1d491603d9d
TypeScript
MisterMard/picklefinance-core
/src/database/DatabaseUtil.ts
2.515625
3
import { ethers } from "ethers"; import { JarDefinition } from "../model/PickleModelJson"; /** * This file is not used currently. Might be deleted. */ export const CURRENT = 0; export const ONE_DAY = 48; export const THREE_DAYS = ONE_DAY * 3; export const SEVEN_DAYS = ONE_DAY * 7; export const THIRTY_DAYS = ONE_DAY * 30; export const SAMPLE_DAYS = THIRTY_DAYS + 1; export const ONE_YEAR_MS = 365 * 24 * 60 * 60 * 1000; export interface AssetDatabaseEntry { asset:string, balance:number, height:number, ratio:number, supply:number, timestamp:number, value:number, } export interface FarmDatabaseEntry { apy: number, valuePerHour: number address: string, valueBalance: number, valuePerBlock: number, tokenAddress: string, allocShare: number, gaugeAddress: string, valuePerDay: number, tokenBalance: number, picklePerBlock: number, picklePerHour: number, picklePerDay: number, } export interface XY { x: number, y: number, } /* export async function getJarAssetSingleDataSingle(asset: JarDefinition, before: number) : Promise<AssetDatabaseEntry> { let params : any; if( before ) { params = { TableName: "asset", KeyConditionExpression: "asset = :asset", FilterExpression : '#tskey <> :tsval', ExpressionAttributeValues: { ":asset": asset.details.apiKey.toLowerCase(), ":tsval": before, }, ExpressionAttributeNames: { "#tskey": "timestamp" }, Limit: SAMPLE_DAYS, PageSize: 1, ScanIndexForward: false }; } else { params = { TableName: "asset", KeyConditionExpression: "asset = :asset", ExpressionAttributeValues: { ":asset": asset.details.apiKey.toLowerCase() }, Limit: 1, ScanIndexForward: false, }; } const data = await ddb.query(params).promise(); // @ts-ignore return data.Items; }; export async function getJarAssetData(asset: JarDefinition, count: number = SAMPLE_DAYS) : Promise<AssetDatabaseEntry[]> { let params : any; if( count ) { params = { TableName: "asset", KeyConditionExpression: "asset = :asset", ExpressionAttributeValues: { ":asset": asset.details.apiKey.toLowerCase() }, Limit: count, ScanIndexForward: false }; } else { params = { TableName: "asset", KeyConditionExpression: "asset = :asset", ExpressionAttributeValues: { ":asset": asset.details.apiKey.toLowerCase() } }; } const data = await ddb.query(params).promise(); // @ts-ignore return count ? data.Items.reverse() : data.Items; }; export async function getFarmDatabaseEntry (definition: JarDefinition) : Promise<FarmDatabaseEntry> { let params = { TableName: "farm", KeyConditionExpression: "address = :address", ExpressionAttributeValues: { ":address": ethers.utils.getAddress(definition.contract.toLowerCase()) }, Limit: 1, ScanIndexForward: false }; const data = await ddb.query(params).promise(); // @ts-ignore return data.Items.reverse()[0]; }; export async function getIndexedBlock(table: string, asset : string, createdBlock: number) : Promise<number> { const params = { TableName: table, KeyConditionExpression: "asset = :asset", ExpressionAttributeValues: { ":asset": asset }, ScanIndexForward: false, Limit: 1 }; let result = await ddb.query(params).promise(); return result.Items.length > 0 ? result.Items[0].height : createdBlock; }; export async function getJarPerformance(asset: JarDefinition, count?: number ) : Promise<XY[]> { let data : any[] = await getJarAssetData(asset, count); // Is this code valid? if (asset.details.apiKey === "cdai") { const diffRatio = data[0].ratio - 1; data = data.map(d => { d.ratio -= diffRatio; return d; }); } return data.map(item => ({x: item.timestamp, y: parseFloat(item.ratio)})); } */
fb5e4f85824fe1616e4728064cb90794c8e8ccbf
TypeScript
gsapkar/user-likes-nodejs-api
/src/validators/schemas.ts
2.6875
3
import * as Joi from "joi"; // the password must have be more than 5 chars and at least one number and at least one uppercase char const passwordRegex = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{5,}$/; export const schemas = { signup: Joi.object().keys({ username: Joi.string().required(), password: Joi.string().regex(passwordRegex).required(), }), login: Joi.object().keys({ username: Joi.string().required(), password: Joi.string().regex(passwordRegex).required(), }), updatePassword: Joi.object().keys({ oldPassword: Joi.string().regex(passwordRegex).required(), newPassword: Joi.string().regex(passwordRegex).required(), }), id: Joi.object({ id: Joi.number().required() }), };
85b76861810a77c39ba397cc56f5253d4e0b15b0
TypeScript
tcgdex/cards-database
/data/Sun & Moon/Ultra Prism/157.ts
2.703125
3
import { Card } from '../../../interfaces' import Set from '../Ultra Prism' const card: Card = { name: { en: "Leafeon GX", fr: "Phyllali GX", es: "Leafeon GX", it: "Leafeon GX", pt: "Leafeon GX", de: "Folipurba GX" }, illustrator: "5ban Graphics", rarity: "Secret Rare", category: "Pokemon", set: Set, dexId: [ 470, ], hp: 200, types: [ "Grass", ], evolveFrom: { en: "Eevee", fr: "Évoli", }, suffix: "GX", abilities: [ { type: "Ability", name: { en: "Breath of the Leaves", fr: "Souffle du Feuillage", es: "Respiro de las Hojas", it: "Alito di Foglie", pt: "Hálito de Folhas", de: "Atem der Blätter" }, effect: { en: "If this Pokémon is your Active Pokémon, once during your turn (before your attack), you may heal 50 damage from 1 of your Pokémon that has any Energy attached to it.", fr: "Si ce Pokémon est votre Pokémon Actif, une seule fois pendant votre tour (avant votre attaque), vous pouvez soigner 50 dégâts à l’un de vos Pokémon auquel de l’Énergie est attachée.", es: "Si este Pokémon es tu Pokémon Activo, una vez durante tu turno (antes de tu ataque), puedes curar 50 puntos de daño a 1 de tus Pokémon que tenga alguna Energía unida a él.", it: "Una sola volta durante il tuo turno, se questo Pokémon è il tuo Pokémon attivo, prima di attaccare, puoi curare da 50 danni uno dei tuoi Pokémon che ha Energie assegnate.", pt: "Se este Pokémon for o seu Pokémon Ativo, uma vez durante a sua vez de jogar (antes de atacar), você poderá curar 50 pontos de dano de 1 dos seus Pokémon que tiver alguma Energia ligada a ele.", de: "Wenn dieses Pokémon dein Aktives Pokémon ist, kannst du einmal während deines Zuges (bevor du angreifst) 50 Schadenspunkte bei 1 deiner Pokémon heilen, an das mindestens 1 Energie angelegt ist." }, }, ], attacks: [ { cost: [ "Grass", "Colorless", "Colorless", ], name: { en: "Solar Beam", fr: "Lance-Soleil", es: "Rayo Solar", it: "Solarraggio", pt: "Raio Solar", de: "Solarstrahl" }, damage: 110, }, { cost: [ "Grass", ], name: { en: "Grand Bloom GX", fr: "Efflorescence-GX", es: "Gran Floración GX", it: "Fioritura Formidabile-GX", pt: "Floração Grandiosa GX", de: "Blütezeit GX" }, effect: { en: "For each of your Benched Basic Pokémon, search your deck for a card that evolves from that Pokémon and put it onto that Pokémon to evolve it. Then, shuffle your deck. (You can’t use more than 1 GX attack in a game.)", fr: "Pour chacun de vos Pokémon de Banc de base, cherchez dans votre deck une carte Évolution de ce Pokémon et placez-la sur ce Pokémon pour le faire évoluer. Mélangez ensuite votre deck. (Vous ne pouvez utiliser qu’une attaque GX par partie.)", es: "Por cada uno de tus Pokémon Básicos en Banca, busca en tu baraja 1 carta que evolucione de ese Pokémon y ponla sobre ese Pokémon para hacerlo evolucionar. Después, baraja las cartas de tu baraja. (No puedes usar más de 1 ataque GX en una partida).", it: "Per ogni Pokémon Base nella tua panchina, cerca nel tuo mazzo una carta che si evolve da quel Pokémon e metticela sopra per farlo evolvere. Poi rimischia le carte del tuo mazzo. Non puoi usare più di un attacco GX a partita.", pt: "Para cada um dos seus Pokémon Básicos no Banco, procure por 1 carta no seu baralho que evolua daquele Pokémon e coloque-a sobre aquele Pokémon para evoluí-lo. Em seguida, embaralhe o seu baralho (você não pode usar mais de 1 ataque GX por partida).", de: "Durchsuche pro Basis-Pokémon auf deiner Bank dein Deck nach 1 Karte, die sich aus jenem Pokémon entwickelt, und lege sie auf jenes Pokémon, um es zu entwickeln. Mische anschließend dein Deck. (Du kannst pro Spiel nur 1 GX-Attacke einsetzen.)" }, }, ], weaknesses: [ { type: "Fire", value: "×2" }, ], retreat: 2, } export default card
c948be3a7e718de2bf328be7eab219f490aa9d8a
TypeScript
TrungDucMai/MD5-Bai3-Angular-Simple-Calculator
/src/app/calculator/calculator.component.ts
2.640625
3
import {Component, OnInit} from '@angular/core'; @Component({ selector: 'app-calculator', templateUrl: './calculator.component.html', styleUrls: ['./calculator.component.scss'] }) export class CalculatorComponent implements OnInit { public firstNumber: any; public secondNumber: any; public operators = ['Cong', 'Tru', 'Nhan', 'Chia']; public result =0; op: any; constructor() {} ngOnInit(): void {} public operating(){ switch (this.op){ case 'Cong': this.result = this.firstNumber + this.secondNumber; break; case 'Tru': this.result = this.firstNumber - this.secondNumber; break; case 'Nhan': this.result = this.firstNumber * this.secondNumber; break; case 'Chia': this.result = this.firstNumber / this.secondNumber; break; } } }
dcc572439209378dec106b00ed1bce81d048333e
TypeScript
do7be/lgtm-hub
/src/actions/index.ts
2.546875
3
import { Dispatch } from 'redux' import { RootState } from '../reducers' import * as types from '../constants/ActionTypes' export const loadRandom = () => { return async function (dispatch: Dispatch<RootState>, _getState: any) { const data: { imageUrl: string }[] = await (await fetch('/random')).json() const imageData = data.map(image => image.imageUrl) return dispatch({ type: types.RandomActionNames.LOAD_RANDOM, payload: imageData }) } } export const addHistory = (data: string) => { return { type: types.HistoryActionNames.ADD_HISTORY, payload: data } } export const loadHistory = () => { return async function (dispatch: Dispatch<RootState>, _getState: any) { const data: ReadonlyArray<string> = await (await fetch('/recommend')).json() return dispatch({ type: types.HistoryActionNames.LOAD_HISTORY, payload: data }) } } export const selectImage = (data: { img: string }) => { return async function (dispatch: Dispatch<RootState>, _getState: any) { const method = 'POST' const body = JSON.stringify(data) const headers = { 'Content-Type': 'application/json' } const options = { method, headers, body } await fetch('/select', options) return dispatch({ type: types.ImageActionNames.SELECT_IMAGE }) } }
3fb042e2537c6b6f79d6ee475f51e40178ffc7f0
TypeScript
GodGee/ts-gg
/webpack/src/index.ts
3.625
4
// 需要在webpack.config.js中配置resolve属性 // 告诉webpack以.ts结尾的文件可以被认为是一个模块 import { hi } from './m1' console.log(hi) function sum(a: number, b: number): number { return a + b } console.log(sum(123, 456)) // 如果配置babel时,不指定版本运行环境,生成的不变 // 而如果指定了IE 11,则const会被代替为var(IE 11不支持ES6!) const obj = { name: '孙悟空', age: 33 } console.log(obj) obj.age = 18 console.log(obj) // 使用ES6中的Promise webpack自动使用箭头函数,需要配置,否则IE11报错 console.log(Promise) // 使用ES6中的箭头函数 let fn = (a: number, b: number) => a + b fn(123, 456) fn(77, 22)
1deafd1f48ad0f9e5c0382bfc704e9178d9b26ce
TypeScript
martinjirak/phone-contacts
/src/helpers/factory.ts
3.015625
3
import { Contact } from "../types"; import * as R from "ramda"; export const normalizePhoneNumber = (value: string) => { let phoneNumber; if (!value.trim()) return undefined; let digits = value.replace(/\D/g, ""); if (digits.length !== 9 && digits.length !== 12) return undefined; let digitsArray = digits.match(/.{1,3}/g); if (!!digitsArray && digitsArray.length === 4) { phoneNumber = `+${R.join(" ", digitsArray)}`; } if (!!digitsArray && digitsArray.length === 3) { phoneNumber = `+420 ${R.join(" ", digitsArray)}`; } return phoneNumber; }; export const getId = (value: string, contacts: Contact[]) => { const sanitizedName = R.pipe( (val: string) => val.normalize("NFD").replace(/[\u0300-\u036f]/g, ""), R.toUpper, R.split(" "), R.join("_") )(value); const escape = (s: string) => s.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); const createRe = (s: string) => new RegExp(`^${escape(s)}(-(\\d+))?$`); const count = R.pipe( R.filter(R.propSatisfies(R.test(createRe(sanitizedName)), "id")), R.length as any )(contacts) as number; if (count === 0) { return sanitizedName; } return `${sanitizedName}-${count + 1}`; };
894b1093995b3fac32309a35f3ddef1eeab14587
TypeScript
timvandam/coding-challenges
/src/LeetCode/2. Add Two Numbers/index.test.ts
3.1875
3
import { addTwoNumbers, ListNode, ListNodeOrNull } from './index' function createLinkedList(...args: number[]): ListNodeOrNull { if (!args.length) return null return new ListNode(args[0], createLinkedList(...args.slice(1))) } it('one', () => { expect(addTwoNumbers(createLinkedList(2, 4, 3), createLinkedList(5, 6, 4))).toEqual( createLinkedList(7, 0, 8) ) }) it('two', () => { expect(addTwoNumbers(createLinkedList(5), createLinkedList(5))).toEqual(createLinkedList(0, 1)) }) it('three', () => { expect(addTwoNumbers(createLinkedList(1, 8), createLinkedList(0))).toEqual(createLinkedList(1, 8)) })
f39f4d62ee8bbb24b7dbdf8dc9fb419d7779da1c
TypeScript
JGrenet/EIP-Pinty-Web
/src/app/core/Api/Model/PlaceInfo.ts
2.515625
3
export class FriendsPassage { id: string; name: string; pp: string; } export class PlaceInfo { constructor(_id: string, _placeId: string, _name: string, _formattedAddress: string, _location: number[], _phone: string, _priceLevel: number, _rating: number, _googleRating: number, _url: string, _website: string, _lastRequest: string, _types: string, _openingHours: string[], _compatibility: number, _subs: string[], _image: string, _friends: FriendsPassage[]) { this.id = _id; this.placeID = _placeId; this.name = _name; this.formattedAddress = _formattedAddress; this.location = _location; this.phone = _phone; this.priceLevel = _priceLevel; this.rating = _rating; this.googleRating = _googleRating; this.url = _url; this.website = _website; this.lastRequest = _lastRequest; this.types = _types; this.openingHours = _openingHours; this.compatibility = _compatibility; this.subs = _subs; this.image = _image; this.friends = _friends; } id: string; placeID: string; name: string; formattedAddress: string; location: number[]; phone: string; priceLevel: number; rating: number; googleRating: number; url: string; website: string; lastRequest: string; types: string; openingHours: string[]; compatibility: number; subs: string[]; image: string; friends: FriendsPassage[]; }
02e9f6a05cc8db18653062c3236f1a6c083b6b4c
TypeScript
ErYaminiPal/RecruitmentApp
/src/main/webapp/app/entities/applicant/applicant.model.ts
2.90625
3
import { IApplication } from 'app/entities/application/application.model'; export interface IApplicant { id?: number; firstName?: string | null; lastName?: string | null; email?: string | null; phone?: string | null; summary?: string | null; cTC?: number | null; eCTC?: number | null; highestEducation?: string | null; applications?: IApplication[] | null; } export class Applicant implements IApplicant { constructor( public id?: number, public firstName?: string | null, public lastName?: string | null, public email?: string | null, public phone?: string | null, public summary?: string | null, public cTC?: number | null, public eCTC?: number | null, public highestEducation?: string | null, public applications?: IApplication[] | null ) {} } export function getApplicantIdentifier(applicant: IApplicant): number | undefined { return applicant.id; }
2ed682382c24023f0af046f1938aa261930baba6
TypeScript
ytmfdw/Test
/code/code/src/utils/CommonUtils.ts
2.78125
3
/** * 生成指定位数的随机码 * @param num */ function createOneyCode(num?: number): string { return 'FN_' + uuid(isNaN(num) ? 8 : num, 16); } function uuid(len, radix) { var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''); var uuid = [], i; radix = radix || chars.length; if (len) { // Compact form for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix]; } else { // rfc4122, version 4 form var r; // rfc4122 requires these characters uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-'; uuid[14] = '4'; // Fill in random data. At i==19 set the high bits of clock sequence as // per rfc4122, sec. 4.1.5 for (i = 0; i < 36; i++) { if (!uuid[i]) { r = 0 | Math.random() * 16; uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r]; } } } return uuid.join(''); } /** * 分转换成元,保留两位小数点 * @param money */ function fenToYuan(money: number): string { if (isNaN(money)) { return '0.00'; } return (money / 100.00).toFixed(2); } /** * 检查版本更新 */ function checkForUpdate(): void { if (!isWX) return; if (typeof wx.getUpdateManager === 'function') { const updateManager = wx.getUpdateManager(); updateManager.onCheckForUpdate(function (res) { // 请求完新版本信息的回调 Log.d("版本更新信息:"); Log.d(res.hasUpdate); }); updateManager.onUpdateReady(function () { // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 showModal({ title: '更新提示', content: '新版本已经准备好,重启应用以使用', cancelText: "知道了", showCancel: true, confirmText: "重启", success: function (res) { if (res.confirm) { // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 updateManager.applyUpdate(); } } }) }); } } //弹出提示框 function showModal(data: any): void { if (isWX) { let showData = { title: data.title ? data.title : "温馨提示", content: data.content ? data.content : "", cancelText: data.cancelText ? data.cancelText : "取消", confirmText: data.confirmText ? data.confirmText : "确定", showCancel: data.showCancel ? data.showCancel : data.cancelText, success: data.success ? data.success : null, confirmColor: data.confirmColor ? data.confirmColor : "#576B95", fail: data.fail ? data.fail : null, complete: data.complete ? data.complete : null, cancelColor: data.cancelColor ? data.cancelColor : "#000000" }; UiManager.getSelf(Index.getApp()).showModal(showData); } } function showToast(data: any): void { if (isWX) { /* wx.showToast({ title: data.title ? data.title : '^_^', icon: data.icon ? data.icon : 'none', duration: data.duration ? data.duration : 1500 });*/ let showData = { title: data.title ? data.title : '^_^', duration: data.duration ? data.duration : 1500 }; UiManager.getSelf(Index.getApp()).showToast(showData.title, showData.duration); } } function showLoading(data?: any): void { UiManager.getSelf().showLoading(data); } function hideLoading(): void { UiManager.getSelf().hideLoading(); } /** * 数组复制 * @param src 源数组; * @param srcPos 源数组要复制的起始位置; * @param dest 目的数组; * @param destPos 目的数组放置的起始位置; * @param length 复制的长度。 * src and dest都必须是同类型或者可以进行转换类型的数组. */ function arraycopy(src: Array<any>, srcPos: number, dest: Array<any>, destPos: number, length: number): void { var srcLen = src.length; var endPos = Math.min(srcLen, srcPos + length); for (var i = srcPos, j = destPos; i < endPos; i++ , j++) { dest[j] = src[i]; } } /** * 日期格式化函数 * 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * * yyyy-MM-dd hh:mm:ss.S ==> 2006-07-02 08:09:04.423 * yyyy-M-d h:m:s.S ==> 2006-7-2 8:9:4.18 * * @param date 要格式化的日期 * @param fmt 格式字符串 */ function formatDate(date: Date, fmt: string) { var o = { "M+": date.getMonth() + 1, //月份 "d+": date.getDate(), //日 "h+": date.getHours(), //小时 "m+": date.getMinutes(), //分 "s+": date.getSeconds(), //秒 "q+": Math.floor((date.getMonth() + 3) / 3), //季度 "S": date.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; } /**获取星期一的日期 */ function getFirstDayOfWeek(date?: Date) { var tmpDate = date ? date : new Date(); var day = tmpDate.getDay() || 7; return new Date(tmpDate.getFullYear(), tmpDate.getMonth(), tmpDate.getDate() + 1 - day); }; /** * 震动时间 * @param time 毫秒数 */ function vibrate(time: number) { if (isNoVirbate) return; // Log.d('virbrate time:' + time); let count = time / 15; let index = 0; let obj = { count: count, index: index }; Laya.timer.loop(15, obj, function () { // Log.d('virbrate loop index:' + index); wx.vibrateShort(); index++; if (index > count) { Laya.timer.clearAll(obj); obj = null; } }); } function vibrateLong() { if (isNoVirbate) return; wx.vibrateLong(); } function vibrateShort() { if (isNoVirbate) return; wx.vibrateShort(); } /** * 显示骨骼动画 * * @param {string} aniPath 动画路径 * @param {string} [aniName] 可选,动画名称 * @param {Laya.Sprite} [father] 可选,动画加载父控件 * @param {Function} [callBack] 播放结束回调 * @param {number} [x] 可选,位置 * @param {number} [y] * @param {number} [scale] 可选,缩放 */ function showOverAni(aniPath: string, aniName?: string, father?: Laya.Sprite, callBack?: Function, x?: number, y?: number, scale?: number) { //显示升官动画 let resPath = aniPath; // var ske: Laya.Skeleton = new Laya.Skeleton(); let thiz = this; let mTemplet = new Laya.Templet(); mTemplet.on(Laya.Event.COMPLETE, this, function () { // Log.d('动画加载完成~~~~~~~~~'); let mArmature = mTemplet.buildArmature(1); if (aniName) { mArmature.play(aniName, false); } else { let aniNum = mArmature.getAnimNum(); let names = []; for (let i = 0; i < aniNum; i++) { var name = mTemplet.getAniNameByIndex(i); // Log.d('动画名:' + name); names.push(name); } // Log.d('动画个数:' + aniNum); mArmature.play(names[0], false); } // mArmature.scale(1.5, 1.5); // mArmature.pos(thiz.imgHouse.width / 2, thiz.imgHouse.height); // mArmature.pos(thiz.heroShadow.width / 2, 0); mArmature.pos(x ? x : 0, y ? y : 0); if (scale) { mArmature.scale(scale, scale); } if (father) { father.addChild(mArmature); } else { Laya.stage.addChild(mArmature); } // thiz.play(); mArmature.on(Laya.Event.STOPPED, this, function () { // Log.d('fix 播放完成 ======='); mArmature.destroy(); mTemplet.destroy(); Laya.loader.clearRes(resPath); //播放结束 回调 if (callBack) { callBack(); } }); }); mTemplet.on(Laya.Event.ERROR, this, function () { Log.d('加载出错~~~~~~~~'); }); mTemplet.loadAni(resPath); } /** * 随机生成一个汉字 * * @returns {string} */ function randomStr(): string { // let str = '\\u' + (Math.round(Math.random() * 20901) + 19968).toString(16); let str = '\\u' + (Math.round(Math.random() * 3000) + 19968).toString(16); return (decode(str)); } /**将汉字 \u编码解码 */ function decode(s) { isNaN return unescape(s.replace(/\\(u[0-9a-fA-F]{4})/gm, '%$1')); } function encode1(s) { return escape(s).replace(/%(u[0-9A-F]{4})|(%[0-9A-F]{2})/gm, function ($0, $1, $2) { return $1 && '\\' + $1.toLowerCase() || unescape($2); }); } /**判断两点是否相邻 */ function isNear(p1, p2): boolean { return (((p1.y === p2.y) && Math.abs(p1.x - p2.x) === 1) || (p1.x === p2.x && Math.abs(p1.y - p2.y) === 1)); } //从point1移动到point2,转过的角度 function getPointAngle(point1, point2): number { if (point2.x == point1.x && point2.y == point1.y) { return 0; } if (point2.x > point1.x && point2.y > point1.y) {//第一象限 return Math.atan((point2.y - point1.y) / (point2.x - point1.x)) / Math.PI * 180 } else if (point2.x < point1.x && point2.y > point1.y) { return Math.atan((point1.x - point2.x) / (point2.y - point1.y)) / Math.PI * 180 + 90 } else if (point2.x < point1.x && point2.y < point1.y) { return Math.atan((point1.y - point2.y) / (point1.x - point2.x)) / Math.PI * 180 + 180 } else if (point2.x > point1.x && point2.y < point1.y) { return Math.atan((point2.x - point1.x) / (point1.y - point2.y)) / Math.PI * 180 + 270 } if (point2.x == point1.x && point2.y > point1.y) { return 90;//下 } else if (point2.x == point1.x && point2.y < point1.y) { return 270;//上 } else if (point2.x > point1.x && point2.y == point1.y) { return 360;//右 } else { return 180;//左 } } /** * 根据索引值,获取该索引所在的二维数组位置 * @param col * @param index */ function getPointByIndex(index: number, col: number): any { var point = { x: 0, y: 0 }; point.x = index % col; point.y = Math.floor(index / col); return point; } /** * 根据点坐标,获取该点的索引 * @param col * @param index */ function getIndexByPoint(x: number, y: number, col: number): number { var index = -1; index = y * col + x; return index; } /** * 存储分数到微信开放域,只有更大分值时才存储 * @param {Number} score * @param {function} callback */ function saveScoreToWxCloudStorage(score: number, callback?: Function) { Log.d('saveScoreToWxCloudStorage=============score=' + score); var kvDataList = []; var maxScore = wx.getStorageSync(SCORE_KEY); if (maxScore == null || maxScore == "" || score > maxScore) { wx.setStorageSync(SCORE_KEY, score); let date = Math.round(new Date().getTime() / 1000); var scoreValue = JSON.stringify({ "wxgame": { "score": score, "update_time": date, } }); //总分数 kvDataList.push({ key: SCORE, value: scoreValue }); } if (kvDataList.length > 0) { wx.setUserCloudStorage({ KVDataList: kvDataList, success: res => { Log.d('wx cloud storage save done: ' + res); Log.d(res); callback(1); }, fail: res => { Log.d('wx cloud storage save failed: ' + res); callback(0); } }); } else { callback(1); } } /** * 单位转换 * @param num */ function num2size(num: number): string { if (num === 0) return '0'; if (num < 1000) { return num + ''; } var k = 1000, // or 1024 sizes = ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'], i = Math.floor(Math.log(num) / Math.log(k)); return (num / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i]; } /** * 灰化控件 * @param view */ function grayView(view: Laya.Sprite): void { var grayMat: Array<number> = [ .3086, .6094, .082, 0, 0, .3086, .6094, .082, 0, 0, .3086, .6094, .082, 0, 0, 0, 0, 0, 1, 0 ]; //创建一个颜色滤镜对象,红色 var grayFilter: Laya.ColorFilter = new Laya.ColorFilter(grayMat); view.filters = (view.filters ? (view.filters.push(grayFilter), view.filters) : [grayFilter]); }
81816646b4e83f672a40238e4bb97605bd646624
TypeScript
ghoul007/events
/src/app/pages/event/events.service.ts
2.53125
3
import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { Observable, throwError as observableThrowError } from 'rxjs'; import { catchError, map, tap } from 'rxjs/operators'; import { Event } from './event'; @Injectable({ providedIn: 'root' }) export class EventsService { private eventesUrl = 'api/events'; // URL to web api constructor(private http: HttpClient) {} getEvents() { return this.http .get<Event[]>(this.eventesUrl) .pipe(map(data => data), catchError(this.handleError)); } getEvent(id: number): Observable<Event> { return this.getEvents().pipe( map(eventes => eventes.find(event => event.id === id)) ); } save(event: Event) { if (event.id) { return this.put(event); } return this.post(event); } delete(event: Event) { const headers = new Headers(); headers.append('Content-Type', 'application/json'); const url = `${this.eventesUrl}/${event.id}`; return this.http.delete<Event>(url).pipe(catchError(this.handleError)); } // Add new Event private post(event: Event) { const headers = new Headers({ 'Content-Type': 'application/json' }); return this.http .post<Event>(this.eventesUrl, event) .pipe(catchError(this.handleError)); } // Update existing Event private put(event: Event) { const headers = new Headers(); headers.append('Content-Type', 'application/json'); const url = `${this.eventesUrl}/${event.id}`; return this.http.put<Event>(url, event).pipe(catchError(this.handleError)); } private handleError(res: HttpErrorResponse | Event) { console.error(res['error'] || res['body'].error); return observableThrowError(res['error'] || 'Server error'); } }
b1fbe72117014c0dffa4999a8f2d211fcd9fb195
TypeScript
bfv/xrefcli
/src/commands/switch.ts
2.8125
3
import { Config } from './../config'; import { Executable } from './../executable'; import { Help } from '../help'; export class SwitchCommand implements Executable { private config: Config; private reponame = ''; constructor(config: Config) { this.config = config; } execute(params: any): Promise<void> { const promise = new Promise<void>(resolve => { if (this.reponame !== undefined) { this.config.data.current = this.reponame; } console.log(this.config.data.current); resolve(); }); return promise; } validate(params: any) { const options = params['options']; if (<boolean>options['help'] === true) { const help = new Help(); help.switchCommand(); process.exit(0); } const name = <string>options['name']; if (name !== undefined) { if (!this.config.repoExists(name)) { console.error(`Error: repo ${name} doesn't not exist`); return false; } } this.reponame = name; return true; } }
bdedda8c5ebea0e6c05d452fe6efc999a1f97f6f
TypeScript
IoTSharp/IoTSharp
/ClientApp/src/stores/keepAliveNames.ts
2.640625
3
import { defineStore } from 'pinia'; import { KeepAliveNamesState } from './interface'; /** * 路由缓存列表 * @methods setCacheKeepAlive 设置要缓存的路由 names(开启 Tagsview) * @methods addCachedView 添加要缓存的路由 names(关闭 Tagsview) * @methods delCachedView 删除要缓存的路由 names(关闭 Tagsview) * @methods delOthersCachedViews 右键菜单`关闭其它`,删除要缓存的路由 names(关闭 Tagsview) * @methods delAllCachedViews 右键菜单`全部关闭`,删除要缓存的路由 names(关闭 Tagsview) */ export const useKeepALiveNames = defineStore('keepALiveNames', { state: (): KeepAliveNamesState => ({ keepAliveNames: [], cachedViews: [], }), actions: { async setCacheKeepAlive(data: Array<string>) { this.keepAliveNames = data; }, async addCachedView(view: any) { if (this.cachedViews.includes(view.name)) return; if (view.meta.isKeepAlive) this.cachedViews.push(view.name); }, async delCachedView(view: any) { const index = this.cachedViews.indexOf(view.name); index > -1 && this.cachedViews.splice(index, 1); }, async delOthersCachedViews(view: any) { if (view.meta.isKeepAlive) this.cachedViews = [view.name]; else this.cachedViews = []; }, async delAllCachedViews() { this.cachedViews = []; }, }, });
e49d8bf0ea9b0aa0366caef0d771b6ede9f1fe75
TypeScript
protolambda/ssz
/src/types/index.ts
3.328125
3
/** * SSZ is a type system that defines: * - efficient serialization / deserialization * - stable merkleization * - default constructor * * Along with these standardized operations, we provide: * - equality * - valid value assertion * - copy / clone * - serialized byte length (for serialization) * - chunk count (for merkleization) * * This library operates on values of several kinds of 'backings', or underlying representations of data. * Each backing has runtime tradeoffs for the above operations that arise from the nature of the underlying * representation. Effort has been made to minimize the differences between backings for the core API, which * includes the above operations, property getter/setters, and iteration (value iteration for vectors/lists * and enumerable key iteration for containers). * * We support the following backings, which correspond to the core operations of serialization and merkleization: * * - Structural - This backing has a native javascript type representation. * Containers are constructed as js Objects, vectors and lists as Arrays (or TypedArrays) * Within operations, property access is performed using js getter notation, with gets * corresponding to the structure of the value's type. Because structural non-constructor operations do not * assume the underlying representation of values, all backings can be operated on in this context. * * - Tree - This backing has an immutable merkle tree representation. * The data is always represented as a tree, and within operations, the tree * structure is harnessed as much as possible. Property getters return subtrees except for basic types, * when the native value corresponding th that type is returned. * Values backed by a tree are wrapped in an ES6 Proxy object to provide a convenient, 'structural' interface * for property getters/setters. * * - ByteArray - This backing has a byte array representation. * The data is always represented as a Uint8Array, and within operations, * the serialized structure is harnessed as much as possible. * Property getters return sub-arrays except for basic types, when the native value * corresponding to that type is returned. * Values backed by an array are wrapped in an ES6 Proxy object to provide a convenient, 'structural' interface * for property getters/setters. */ export * from "./basic"; export * from "./composite"; export * from "./type";
7cd077a3a7a4366c2425bac539272dede58c1aee
TypeScript
esbjornlarsen/SP2015
/JavascriptPromise/JavascriptPromise/Scripts/CallBack.ts
3
3
namespace main { export class TestCallBack { static init() { TestCallBack.doHelloWorld(TestCallBack.myCallBackFunction); TestCallBack.doHelloWorld(TestCallBack.myCallBackFunctionLog); } static doHelloWorld(callback: (str : string, str2 : string) => any) { // Call the callback callback('Hello', "World"); } static myCallBackFunction (text1, text2) { alert(text1 + " " + text2); } static myCallBackFunctionLog(text1, text2) { console.log(text1 + " " + text2); } } }
0bc7dfc3fbd7b3d7ebabe738a3729cfa34409ff2
TypeScript
cheminfo/database-aggregator
/src/source/__tests__/driver-errors.test.ts
2.546875
3
import { getDriverPath } from '../../../test/util'; import { copy } from '../copy'; describe('source copy errors', () => { it('shoud fail when driver config is missing', () => { // @ts-ignore return expect(copy({ driver: undefined })).rejects.toThrow( /^driver must be a string or object$/ ); }); it('should fail to get inexistant driver', () => { // @ts-ignore return expect(copy({ driver: 'notfound' })).rejects.toThrow( /^could not resolve driver location: notfound$/ ); }); it('should fail if driver throws on load', () => { return expect( // @ts-ignore copy({ driver: getDriverPath('source-error/throw') }) ).rejects.toThrow(/^bad driver$/); }); it('should fail if driver does not export an object', async () => { await expect( // @ts-ignore copy({ driver: getDriverPath('source-error/number') }) ).rejects.toThrow(/^driver module must be an object$/); await expect( // @ts-ignore copy({ driver: getDriverPath('source-error/null') }) ).rejects.toThrow(/^driver module must be an object$/); }); it('should fail if driver forgets to export methods', async () => { await expect( // @ts-ignore copy({ driver: getDriverPath('source-error/missing-getdata') }) ).rejects.toThrow(/^driver must provide a method named "getData"$/); // @ts-ignore await expect(copy({ driver: {} })).rejects.toThrow( /^driver must provide a method named "getData"$/ ); await expect( // @ts-ignore copy({ driver: getDriverPath('source-error/missing-getids') }) ).rejects.toThrow(/^driver must provide a method named "getIds"$/); }); it('should throw if collection is not in config', () => { return expect( // @ts-ignore copy({ driver: getDriverPath('source-copy'), collection: null }) ).rejects.toThrow(/^collection must be a string$/); }); });
8f6dba09cd1e1c0cd839f9b45e7118d102f36667
TypeScript
junior5/ecommerce
/frontend/src/app/ecommerce/models/produto.model.ts
2.5625
3
export class Produto { id: number; nome: string; descricao: string; custoCompra: number; urlImagem: string; constructor(id: number, nome: string, descricao:string, custoCompra: number, urlImagem: string) { this.id = id; this.nome = nome; this.descricao = descricao; this.urlImagem = urlImagem; } }
656cf68a3465403335441fc0bad498aa4f4e668a
TypeScript
tenbot/tenbot
/packages/cipher/__tests__/pkcs7.spec.ts
2.640625
3
import { decrypt, encrypt } from '@tenbot/cipher'; describe('@tenbot/cipher > pkcs7', () => { describe('decrypt', () => { it('should get correct pkcs7 decrypted buffer', () => { const size = 32; const input = Buffer.concat([ Buffer.from([1, 2, 3, 4]), Buffer.alloc(28, 28), ]); const output = Buffer.from([1, 2, 3, 4]); expect(decrypt(input, size).equals(output)).toBe(true); }); it('should return as is if the padding is not correct', () => { const size = 32; const input = Buffer.from([1, 2, 3, 99]); expect(decrypt(input, size).equals(input)).toBe(true); }); }); describe('encrypt', () => { it('should get correct pkcs7 encrypted buffer', () => { const size = 32; const input = Buffer.from([1, 2, 3, 4]); const output = Buffer.concat([ Buffer.from([1, 2, 3, 4]), Buffer.alloc(28, 28), ]); expect(encrypt(input, size).equals(output)).toBe(true); }); }); });
8ee671eabd97dd3d94659cf7f465800b71e25f44
TypeScript
a707843858/courierCach
/src/packages/tasks.ts
2.90625
3
export class Task { private queue: Map<Request, any> = new Map(); get(original: Request) { return this.queue.get(original); } set(original: Request, controller: any) { this.queue.set(original, controller); return true; } delete(original: Request) { return this.queue.delete(original); } size() { return this.queue.size; } clear() { this.queue = new Map(); return true; } }
1ed6c9a60b81e5721bf5dbc361544533499e6ef9
TypeScript
Yama-Tomo/json2typescript
/test/model/json/i-employee.ts
2.546875
3
export interface ISkill { id: number; skill_name: string; description: string|null; } export interface IEmployee { id: number; first_name: string; last_name: string; branch_name: string; age: number; hobby?: string; description: { length_of_service: number, position: string, sub_position: string }; skill_lists: ISkill[]; }
d45ab883c5128b3c5f9337dd3264100e163c20ff
TypeScript
honnix/flyteconsole
/src/common/formatters.ts
2.96875
3
import cronstrue from 'cronstrue'; import { Admin, Protobuf } from 'flyteidl'; import * as moment from 'moment-timezone'; import { subSecondString, unknownValueString, zeroSecondsString } from './constants'; import { timezone } from './timezone'; import { durationToMilliseconds, isValidDate } from './utils'; /** Formats a date into a standard string with a moment-style "from now" hint * ex. 12/21/2017 8:19:36 PM (18 days ago) */ export function dateWithFromNow(input: Date) { if (!isValidDate(input)) { return unknownValueString; } const date = moment.utc(input); return `${date.format('l LTS')} UTC (${date.fromNow()})`; } /** Formats a date into a moment-style "from now" value */ export function dateFromNow(input: Date) { if (!isValidDate(input)) { return unknownValueString; } const date = moment(input); return `${date.fromNow()}`; } /** Formats a date into a standard format used throughout the UI * ex 12/21/2017 8:19:36 PM */ export function formatDate(input: Date) { return isValidDate(input) ? moment(input).format('l LTS') : unknownValueString; } /** Formats a date into a standard UTC format used throughout the UI * ex 12/21/2017 8:19:36 PM UTC */ export function formatDateUTC(input: Date) { return isValidDate(input) ? `${moment.utc(input).format('l LTS')} UTC` : unknownValueString; } /** Formats a date into a standard local format used throughout the UI * ex 12/21/2017 8:19:36 PM PDT */ export function formatDateLocalTimezone(input: Date) { return isValidDate(input) ? moment(input) .tz(timezone) .format('l LTS z') : unknownValueString; } /** Outputs a value in milliseconds in (H M S) format (ex. 2h 3m 30s) */ export function millisecondsToHMS(valueMS: number): string { if (valueMS < 0) { return unknownValueString; } if (valueMS === 0) { return zeroSecondsString; } if (valueMS < 1000) { return `${valueMS}ms`; } const duration = moment.duration(valueMS); const parts = []; // Using asHours() because if it's greater than 24, we'll just show the total if (duration.asHours() >= 1) { parts.push(`${Math.floor(duration.asHours())}h`); } if (duration.minutes() >= 1) { parts.push(`${duration.minutes()}m`); } if (duration.seconds() >= 1) { parts.push(`${duration.seconds()}s`); } return parts.length ? parts.join(' ') : unknownValueString; } /** Converts a protobuf Duration value to (H M S) format (ex. 2h 3m 30s)*/ export function protobufDurationToHMS(duration: Protobuf.IDuration) { return millisecondsToHMS(durationToMilliseconds(duration)); } /** Calculates the difference between two Dates and outputs it in (H M S) format (ex. 2h 3m 30s) */ export function dateDiffString(fromDate: Date, toDate: Date) { if (!isValidDate(fromDate) || !isValidDate(toDate)) { return unknownValueString; } return millisecondsToHMS(moment(toDate).diff(fromDate)); } const fixedRateUnitStrings = { [Admin.FixedRateUnit.DAY]: 'days', [Admin.FixedRateUnit.HOUR]: 'hours', [Admin.FixedRateUnit.MINUTE]: 'minutes' }; /** Converts a IFixedRate value into a human-readable string ('Every x minutes/hours/days') */ export function fixedRateToString({ value, unit }: Admin.IFixedRate): string { if (unit == null || !(unit in Admin.FixedRateUnit) || !value) { return ''; } return `Every ${value} ${fixedRateUnitStrings[unit]}`; } export function getScheduleFrequencyString(schedule?: Admin.ISchedule) { if (schedule == null) { return ''; } if (schedule.cronExpression) { // Need to add a leading 0 to get a valid CRON expression, because // ISchedule is using AWS-style expressions, which don't allow a `seconds` position return cronstrue.toString(`0 ${schedule.cronExpression}`); } if (schedule.rate) { return fixedRateToString(schedule.rate); } return ''; } /** Ensures that a given string has a protocol prefix. If not, will add https:// to the beginning */ export function ensureUrlWithProtocol(url: string): string { if (url.indexOf('http') !== 0) { return `https://${url}`; } return url; } /** Formats a number into a string with leading zeros to ensure a consistent * width. * Example: 1 will be '01' * 10 will be '10' */ export function leftPaddedNumber(value: number, length: number): string { return value.toString().padStart(length, '0'); }
0d851549bb4b2530f917a4d5663e7eb6d735af3e
TypeScript
idettman/idettman.github.io
/examples/js/story-graph-master/src/components/actor.ts
3
3
import { SOURCE, TARGET } from './constants' import Type from './type' export default class Actor { id: number type: Type name: string location: string | null locations: string[] entryTime: number lifeTime: number // callback: () => void members: Actor[] parentId?: number; constructor(data, world, actorOne?: Actor, actorTwo?: Actor) { this.type = data.type; this.name = data.name; this.members = []; if (data.locations) { this.location = data.location || data.locations[0]; this.locations = data.locations; } else { this.locations = []; this.location = null; } this.lifeTime = data.lifeTime || 999; // this.callback = data.callback || null; if (data.members) { this.fetchMembers(world, data.members, actorTwo, actorTwo); } if (data.initializeName) { this.name = data.initializeName(this, world); } } fetchMembers(world, members, actorOne, actorTwo) { members.forEach((member, idx) => { if (member === SOURCE) { this.members[idx] = actorOne } else if (member === TARGET) { this.members[idx] = actorTwo } }); } hasMember(id: number): boolean { let found: boolean = false; for (let i = 0; i < this.members.length; i++) { if (this.members[i].id === id) { found = true break } } return found } getTypes() { return this.type.get(); } setEntryTime(time) { this.entryTime = time; } }
35267ea258bf493703e5aa21ecaf5cc109d1b350
TypeScript
chenchunfeng/ts-axios
/examples/cancel/app.ts
2.734375
3
import axios from '../../src/index' let cancel; const CancelToken = axios.CancelToken; axios({ url: '/config/test', method: 'post', headers: { test: '321' }, CancelToken: new CancelToken(c => { cancel = c; }) }).then((res) => { console.log(res.data) }).catch(e => { console.log(e, axios.isCancel(e)) }) cancel('haha'); cancel('bbq'); const source = axios.CancelToken.source(); axios({ url: '/config/test', method: 'post', headers: { test: '2222' }, CancelToken: source.token }).then((res) => { console.log(res.data) }).catch(e => { console.log(e, axios.isCancel(e)) }) source.cancel('nini'); const CancelToken1 = axios.CancelToken const source1 = CancelToken1.source() axios.get('/cancel/get', { cancelToken: source1.token }).catch(function(e) { debugger if (axios.isCancel(e)) { console.log('Request canceled', e.message) } }) setTimeout(() => { source1.cancel('Operation canceled by the user.') axios.post('/cancel/post', { a: 1 }, { cancelToken: source1.token }).catch(function(e) { if (axios.isCancel(e)) { console.log(e.message) } }) }, 100)
1e6a38072bd636ac7131b99d53c55431acd73e56
TypeScript
huyhoangtb/nodejs-reactjs-core-project
/server/src/core/responseable/ResponseData.ts
2.625
3
export default class ResponseData { protected _success: boolean; protected _result: object; protected _message: string; protected _detail: object; protected _trace: any; protected _error: { code: string, desc: string }; constructor(data?: any) { if(!data) { return; } this._success = data.success; this._result = data.result; this._message = data.message; this._error = data.error; this._detail = data.detail; } set success(value: boolean) { this._success = value; } set trace(value: any) { this._trace = value; } set result(value: object) { this._result = value; } set message(value: string) { this._message = value; } set detail(value: object) { this._detail = value; } set error(value: { code: string; desc: string }) { this._error = value; } get trace(): any { return this._trace; } get success(): boolean { return this._success; } get result(): object { return this._result; } get message(): string { return this._message; } get detail(): object { return this._detail; } get error(): { code: string; desc: string } { return this._error; } }
7a1fde57f8dfa6e5b0baeec871edc9ee2aacb253
TypeScript
mattmazzola/draft-js-sample
/src/ToolbarExample/classes.ts
2.8125
3
export interface IWordType { id: string name: string multivalue: boolean } const wordTypes: IWordType[] = [ { id: "0", name: 'noun', multivalue: true }, { id: "1", name: 'verb', multivalue: false }, { id: "2", name: 'adjective', multivalue: false }, { id: "3", name: 'punctuation', multivalue: true } ]; export default wordTypes
70d33074e9fe9127c808c44454e7f483c89862ce
TypeScript
begin29/rad_task
/orders/controllers/lib/paymentService.ts
2.578125
3
const axios = require('axios'); const models = require('../../../models'); const { PaymentProcessError, OrderUpdateError } = require('../../helpers/errors'); export class PaymentService { readonly orderId: number; readonly orderSum: number; readonly paymentUrl = 'http://payments_api:3000/pay'; constructor(id: number, sum: number) { this.orderId = id; this.orderSum = sum || 0; } pay(token){ return axios.post( this.paymentUrl, { sum: this.orderSum }, { headers: { 'x-access-token': token } } ).then( response => { models.Order.update( { status: response.data.status }, { where: { id: this.orderId }, returning: true } ).then( ([ updatedCount, [updatedOrder] ]) => { if (updatedCount > 0){ setTimeout(() => { this.deliverOrCancelOrder(updatedOrder).catch(err => { throw err; }) }, 3000); } }).catch( err => { throw new OrderUpdateError(err); }); }).catch( err => { throw new PaymentProcessError(err); }); } private deliverOrCancelOrder(order){ let nextOrderStatus = order.status == 'confirmed' ? 'delivered' : 'canceled'; return models.Order.update( { status: nextOrderStatus }, { where: { id: order.id }, returning: true } ).then( ([ updatedCount, [updatedOrder] ]) => { //can do something more with updated order }).catch( err => { throw new OrderUpdateError(err); }); } }
241f84c85a0808f44a75f0e2073f7362002d1afa
TypeScript
AntonShilin/eshop
/src/Reducers/MainStateReducer.ts
2.90625
3
import { IMainState, MainStateActions, GetFableResultsTypes, GetBiographyResultsTypes, GetStoryResultsTypes, GetBestsellersResultsTypes, GetFictionResultsTypes, GetArtResultsTypes, GetLifestyleResultsTypes, } from "../Types/MainStateTypes"; const mainState: IMainState = { allGenresData: [], isLoading: false, genresName: ["fairytales", "biography", "story", "bestsellers", "fiction", "art", "lifestyle"] }; export const mainStateReducer = ( state: IMainState = mainState, action: MainStateActions ): IMainState => { switch (action.type) { case GetFableResultsTypes.GETFABLERESULTS: { let newarr: any[] = []; if (action.results !== null) { newarr = [...state.allGenresData, action.results]; } return { ...state, allGenresData: newarr, }; } case GetBiographyResultsTypes.GETBIOGRAPHYRESULTS: { let newarr: any[] = []; if (action.results !== null) { newarr = [...state.allGenresData, action.results]; } return { ...state, allGenresData: newarr, }; } case GetStoryResultsTypes.GETSTORYRESULTS: { let newarr: any[] = []; if (action.results !== null) { newarr = [...state.allGenresData, action.results]; } return { ...state, allGenresData: newarr, }; } case GetBestsellersResultsTypes.GETBESTSELLERSRESULTS: { let newarr: any[] = []; if (action.results !== null) { newarr = [...state.allGenresData, action.results]; } return { ...state, allGenresData: newarr, }; } case GetFictionResultsTypes.GETFICTIONRESULTS: { let newarr: any[] = []; if (action.results !== null) { newarr = [...state.allGenresData, action.results]; } return { ...state, allGenresData: newarr, }; } case GetArtResultsTypes.GETARTRESULTS: { let newarr: any[] = []; if (action.results !== null) { newarr = [...state.allGenresData, action.results]; } return { ...state, allGenresData: newarr, }; } case GetLifestyleResultsTypes.GETLIFESTYLERESULTS: { let newarr: any[] = []; if (action.results !== null) { newarr = [...state.allGenresData, action.results]; } return { ...state, allGenresData: newarr, }; } default: return state; } };
9cf11075bbfc82c2a86908e96923445a4f10275c
TypeScript
Ernyoke/algorithms-ts
/src/sort/quickSort.ts
3.859375
4
/** * In place Quick-sort algorithm * @param {T[]} values: array to be sorted * @param {(a:T, b:T) => boolean } comparator: function which takes to elements of T and returns true if a < b */ import partition from "../array/partition"; export default function quickSort<T>(values: T[], comparator: (a: T, b: T) => boolean = (a: T, b: T) => a < b) { const quickSortRecursive = (startPosition: number, endPosition: number) => { if (startPosition < endPosition) { const pivot = values[startPosition + Math.floor((endPosition - startPosition) / 2)]; const lowerPartitionPosition = partition(values, (a: T) => comparator(a, pivot), startPosition, endPosition); const upperPartitionPosition = partition(values, (a: T) => !comparator(pivot, a), lowerPartitionPosition, endPosition); quickSortRecursive(startPosition, lowerPartitionPosition - 1); quickSortRecursive(upperPartitionPosition, endPosition); } }; quickSortRecursive(0, values.length - 1); };
b67a073316add5e5ecd1ac5bb4036172aa57622d
TypeScript
pasta04/oengs-submission-viewer
/src/types/oengus.d.ts
2.65625
3
export type MarathonGameAPI = Game[]; export type MarathonSubmissionAPI = { id: number; user: User; games: Omit<Game, 'user'>[]; availabilities: { from: string; to: string; }[]; answers: { id: number; question: Questions; /** * 回答 * @description チェックボックスの場合は、文字列で"true"になる。 */ answer: string | null; /** 必須項目か */ answerRequired: boolean; }[]; opponents: null; opponentDtos: null; user: User; }[]; export type MarathonListAPI = { next: MarathonInfo[]; open: MarathonInfo[]; live: MarathonInfo[]; }; export type MarathonAPI = { /** * イベントのID * @example "rtaij2019" */ id: string; /** イベント名 */ name: string; /** イベント作成者 */ creater: User; /** * 開始日時 * @example "2019-12-27T03:00:27Z" */ startDate: string; /** 終了日時 */ endDate: string; /** 説明 */ description: string; /** オフライン開催か */ onsite: false; /** 開催地 */ location: string | null; /** * 言語 * @example "ja" */ language: string; /** 走者ごとに応募できる最大ゲーム数 */ maxGamesPerRunner: number; /** ゲームごとに応募できる最大カテゴリ数 */ maxCategoriesPerGame: number; /** レースや協力プレイを応募できるか */ hasMultiplayer: boolean; /** レースや協力プレイでの最大走者数 */ maxNumberOfScreens: number; /** イベントのTwitchID */ twitch: string; /** イベントのTwitter ScreenName */ twitter: string; /** DiscordID */ discord: string; /** * 国 * @example "JP" */ country: string | null; discordPrivacy: boolean; /** 応募受付中 */ submitsOpen: boolean; /** @example "PT10M" */ defaultSetupTime: string; /** 選考が完了していたらtrue */ selectionDone: boolean; /** スケジュールが公開されていたらtrue */ scheduleDone: boolean; isPrivate: boolean; /** モデレータ */ moderators: User[]; hasIncentives: boolean; /** 応募を編集できるか */ canEditSubmissions: boolean; /** 追加項目 */ questions: Questions[]; hasDonations: boolean; payee: null; supportedCharity: null; /** ISO-4217 format for Paypal */ donationCurrency: null; donationWebhook: null; donationsTotal: null; hasSubmitted: null; }; export type SelectionAPI = { [categoryId: number]: { /** 選考結果ID */ id: number; /** カテゴリID */ categoryId: number; /** * 選考結果 * - TODO: 保留 * - VALIDATED: 当選 * - REJECTED: 落選 * - BONUS: ボーナス */ status: SelectionStatus; }; }; export type SelectionStatus = 'TODO' | 'VALIDATED' | 'REJECTED' | 'BONUS' | 'BACKUP'; export type MarathonInfo = Pick<MarathonAPI, 'id' | 'name' | 'startDate' | 'endDate' | 'onsite' | 'location' | 'country' | 'language'>; type Game = { /** ゲームID */ id: number; /** ゲーム名 */ name: string; /** ゲームの説明 */ description: string; /** 機種 */ console: string; /** アスペクト比 */ ratio: string; /** エミュレータ使用か */ emulated: boolean; /** カテゴリ */ categories: Category[]; /** ユーザ */ user: User; }; type Category = { /** カテゴリID */ id: number; /** カテゴリ名 */ name: string; /** * 予定時刻 * @description PTの後に時、分が続く。 * @example "PT47M" * @example "PT1H" * @example "PT4H30M" */ estimate: string; /** カテゴリ説明 */ description: string; /** 動画URL */ video: string; /** シングルかレースか */ type: CategoryType; /** レース用のコード。シングルならnull */ code: string; /** たぶんレース相手の動画情報 */ opponents: { /** レース参加者ID(ユーザIDではない) */ id: number; /** 動画URL */ video: string; }[]; /** (不明)たぶんレース相手のなにか */ opponentDtos: { /** レース参加者ID(ユーザIDではない) */ id: number; /** ユーザ情報 */ user: User; /** 動画URL */ video: string; /** 参加可能時刻 */ availabilities: { from: string; to: string; }[]; }[]; }; type CategoryType = 'SINGLE' | 'RACE' | 'COOP' | 'COOP_RACE'; type User = { /** ユーザID */ id: number; /** ユーザ名(英) */ username: string; /** ユーザ名(日) */ usernameJapanese: string; /** 有効なアカウントか */ enabled: boolean; /** マラソンにおける権限 */ roles: string[]; /** Twitterのscreen_name。@なし */ twitterName: string; /** TwitchID */ twitchName: string; /** Speedrun.comのユーザ名 */ speedruncomName: string; /** アカウント連携しているか */ atLeastOneAccountSynchronized: boolean; emailPresentForExistingUser: boolean; }; type Questions = { id: number; label: string; /** * フィールド種別 * - TEXT: 1行テキスト * - SELECT: セレクトボックス * - CHECKBOX: チェックボックス * - FREETEXT: 選択項目ではなく、単純にテキストとして何か表示する。マークダウンが使える。 */ fieldType: 'TEXT' | 'SELECT' | 'TEXTAREA' | 'CHECKBOX' | 'FREETEXT'; /** 選択肢 */ options: string[]; questionType: 'SUBMISSION'; /** FREETEXT用の文章 */ description: string | null; position: number; }; export type ScheduleAPI = { id: number; lines: { categoryId: number; categoryName: string; console: string; customRun: boolean; date: string; emulated: boolean; estimate: string; gameName: string; id: number; position: number; ratio: string; runners: User[]; setupBlock: boolean; setupBlockText: string | null; setupTime: string; type: CategoryType; }[]; };
9e7dfe5ea69d8d3b157e6263641b27518bb44e9e
TypeScript
JamesHDuffield/fate
/functions/src/services/db.ts
2.71875
3
import { User } from '../models/user'; import { Moment, Option } from '../models/moment'; import { Location } from '../models/location'; // tslint:disable-next-line: no-implicit-dependencies import { DocumentReference } from '@google-cloud/firestore'; import { Zone } from '../models/zone'; import { Flag } from '../models/flag'; const RESPAWN_LOCATION = '/zones/lPtHuBdQJZ1DRONwtBIH' export class DatabaseService { respawnPoint: DocumentReference; constructor(public firestore: FirebaseFirestore.Firestore) { this.respawnPoint = this.firestore.doc(RESPAWN_LOCATION); } // Util async getRef<T>(docRef: DocumentReference): Promise<T> { const ref = await docRef.get(); return ref.data() as T; } // Move user async userToMoment(userRef: DocumentReference, momentRef: DocumentReference): Promise<void> { await userRef .set({ moment: momentRef }, { merge: true }); } async userToLocation(userRef: DocumentReference, locationRef: DocumentReference): Promise<void> { const location = await locationRef.get(); await userRef .set({ moment: location.data().moment}, { merge: true }); } async getDefaultMomentRefFromZoneRef(zoneRef: DocumentReference): Promise<DocumentReference> { const zone = await zoneRef.get(); const location: FirebaseFirestore.DocumentSnapshot = await zone.data().location.get(); return location.data().moment; } async userToZone(userRef: DocumentReference, zoneRef: DocumentReference): Promise<void> { const momentRef = await this.getDefaultMomentRefFromZoneRef(zoneRef); await userRef .set({ moment: momentRef }, { merge: true }); } async clearNonPermanentFlags(userRef: DocumentReference): Promise<void> { const user = await userRef.get(); if (!user.exists) { throw new Error('User does not exist'); } const flags: DocumentReference[] = user.data().flags; if (!flags) { return } const newFlags = []; for (const flag of flags) { const result = await flag.get(); if (result.data().permanent) { newFlags.push(flag); } } await user.ref.update({ flags: newFlags }); } // Creation async createUser(uid: string, username: string): Promise<void> { const ref = this.firestore.doc(`/users/${uid}`) const doc = await ref.get(); if (doc.exists) { return; } const momentRef = await this.getDefaultMomentRefFromZoneRef(this.respawnPoint); const user: User = { admin: false, username, moment: momentRef, flags: [], }; await ref.set(user); } async createMoment(locationRef: DocumentReference, moment: Moment): Promise<DocumentReference> { return locationRef.collection('moments').add(moment); } async createLocation(zoneRef: DocumentReference, location: Partial<Location>, moment: Moment): Promise<[DocumentReference, DocumentReference]> { const locationRef = await zoneRef.collection('locations').add(location); const momentRef = await this.createMoment(locationRef, moment); await locationRef.set({ moment: momentRef }, { merge: true }); return [locationRef, momentRef]; } async createZone(zone: Zone): Promise<DocumentReference> { return this.firestore.collection('zones').add(zone); } async addOption(currentRef: DocumentReference, option: Partial<Option>): Promise<void> { const current = await this.getRef<Moment>(currentRef); option.id = Math.max(-1, ...current.options.map((opt)=> opt.id)) + 1; current.options.push(option as Option); await currentRef.set(<any>{ options: current.options }, { merge: true }) } // Find users async cleanUsers(): Promise<void> { const query = await this.firestore.collection('users') .where('username', '==', 'Nameless') .get(); console.log(`Cleaning ${query.size} user(s)`); for (const data of query.docs) { await data.ref.delete(); } } }
c8533ffbe5095215ffcf927bd2d54227a1b088e3
TypeScript
tus-alpine-team/scrapbox-notification-bot
/src/index.ts
2.578125
3
import { ScrapboxProjectResponse } from './scrapboxProjectResponse'; import { sendToLine } from './sendToLine'; const project_name = 'tus-alpine'; // 更新情報をLINEに投げる // eslint-disable-next-line @typescript-eslint/no-unused-vars function postMessage(): void { const yesterday = new Date(); yesterday.setDate(yesterday.getDate() - 1); yesterday.setHours(20); yesterday.setMinutes(0); const urls = getModifiedURLs(yesterday); if (urls.length == 0) return; const hr = '\n------------'; const result = [ hr, '本日は以下の記事が更新されました。', ...urls.map((url) => ` ・ ${url}`), `詳細は https://scrapbox.io/stream/${project_name}/ を御覧ください`, ]; sendToLine(result.join('\n')); } // 大体20:00に更新情報を投げるように設定する // eslint-disable-next-line @typescript-eslint/no-unused-vars function setTrigger(): void { //作成済みのtriggerがあったら全て消す ScriptApp.getProjectTriggers() .filter((trigger) => trigger.getHandlerFunction() == 'postMessage') .forEach((trigger) => ScriptApp.deleteTrigger(trigger)); const now = new Date(); now.setHours(20); now.setMinutes(0); ScriptApp.newTrigger('postMessage').timeBased().at(now).create(); } // 特定の時間以降に更新されたページのURLを取得する function getModifiedURLs(from: Date): string[] { const response = UrlFetchApp.fetch( `https://scrapbox.io/api/pages/${project_name}` ).getContentText('UTF-8'); const json = JSON.parse(response) as ScrapboxProjectResponse; return ( json.pages // 更新日時順にsortする .sort((a, b) => b.updated - a.updated) // 指定した時刻以降に更新されたpageのみ抽出する .filter((page) => page.updated * 1000 >= from.getTime()) .map( (page) => `https://scrapbox.io/${project_name}/${page.title.replace( /\s/g, '_' )}` ) ); }
a8714d28263e2dcd3266e896e6003da4f08019b5
TypeScript
PixoDev/pammy-api
/src/services/recipe.service.ts
2.65625
3
import { NewRecipePayload } from "@interfaces/recipe"; import { RecipeModel } from "@models/recipe.model"; export const getRecipe = async (recipeId: string) => { return RecipeModel.findById(recipeId).lean().exec(); }; interface RecipesParams { params: any; } export const getRecipes = async ({ params }: RecipesParams) => { const query = buildQuery(params); const count = parseInt(params.count) || 20; const page = parseInt(params.page); console.log("PARAMS", query); return RecipeModel.find(query) .limit(count) .skip((page - 1) * count) .lean() .exec(); }; const FILTERS = ["cookingTime"]; const buildQuery = (filters: { [key: string]: any }) => { const init: any = {}; Object.keys(filters).forEach((key: string) => { if (FILTERS.includes(key)) { init[key] = { $lte: filters[key] }; } if (key === "query") { init["$text"] = { $search: filters[key], }; } }); return init; }; export const createRecipe = async (payload: NewRecipePayload) => { const recipe = new RecipeModel(payload); return recipe.save(); }; export const updateRecipe = async ( recipeId: string, payload: Partial<NewRecipePayload> ) => { return await RecipeModel.findByIdAndUpdate( recipeId, { $set: payload }, { new: true } ) .lean() .exec(); };
4f4bf1916e4bb0d6a0d5d88dbfc890f2c4bdc62b
TypeScript
villevauhkonen/node-ts
/src/index.ts
2.75
3
import Express from 'express' import returnName from './returnName' const app = Express() const port = 8081; // define a route handler for the default home page app.get( "/", ( req: Express.Request, res: Express.Response ) => { const name = returnName('Ville') res.send(name); } ); // start the Express server app.listen( port, () => { console.log( `server started at http://localhost:${ port }` ); } );
758b38e97519e9cb9253c78b23511770ee37998e
TypeScript
LBHackney-IT/NCC
/ng-ncc-app/src/app/common/components/current-caller/current-caller.component.ts
2.53125
3
import { Component, Input } from '@angular/core'; import { CallService } from '../../services/call.service'; @Component({ selector: 'app-current-caller', templateUrl: './current-caller.component.html', styleUrls: ['./current-caller.component.scss'] }) export class CurrentCallerComponent { @Input() withPrefix: boolean; @Input() allowAnonymous: boolean; constructor(private Call: CallService) { } /** * */ getCallerName(): string | null { if (this.Call.hasCaller()) { return this.Call.getCaller().getName(); } return null; } /** * */ hasCaller(): boolean { return this.Call.hasCaller(); } /** * Returns TRUE if the current caller is anonymous (but NOT a non-tenant). */ isCallerAnonymous() { return !this.isCallerIdentified() && !this.Call.isCallerNonTenant(); } /** * Returns TRUE if the current caller is identified. */ isCallerIdentified() { return this.Call.hasCaller() && this.Call.isCallerIdentified(); } }
25bf91f0cca63eebd331d9073e933f27e6e1a748
TypeScript
Supinic/charlestonbieber
/src/commands/RandomLyrics.ts
2.859375
3
import { Lyrics } from './types'; import { Command, Platform, randomItem } from '../modules'; import { Supi, supi, someRandomAPI } from '../modules/GotInstances'; export class RandomLyrics extends Command { name = 'randomlyrics'; aliases = null; permission = Command.Permissions.EVERYONE; cooldown = 7500; syntax = ['song?']; description = 'Fetches the lyrics of the specified song, then returns a random line from the lyrics.'; data = null; async execute({ channel, platform }: Command.Input, ...args: string[]): Promise<Command.Output> { let usingCurrent = false; let title: string; if ( args.length === 0 && channel.name === 'supinic' && platform.name === Platform.Names.TWITCH ) { const { data: queue }: Supi.Response<Supi.SongRequest.Queue[]> = await supi('bot/song-request/queue').json(); const current = queue.find(({ status }) => status === Supi.SongRequest.Status.CURRENT); if (!current) { return { reply: 'No song is playing right now', success: false, cooldown: 5000, }; } usingCurrent = true; title = current.name; } else if (args.length === 0) { return { reply: 'A song must be specified', success: false, cooldown: 2500, }; } if (!title) { title = args.join(' '); } const data: Lyrics = await someRandomAPI({ url: 'lyrics', searchParams: { title }, }).json(); if (data.error) { return { reply: 'Could not find that song', success: false, cooldown: usingCurrent ? 5000 : 2500, }; } const lyrics = randomItem([...new Set( data.lyrics .split('\n') .filter((line) => !(line.startsWith('[') && line.endsWith(']'))), )]); return { reply: `${lyrics} (${data.author} - ${data.title})`, cooldown: usingCurrent ? 10000 : this.cooldown, }; } }
ee413bc6569621938071cf76189bde65d599ae13
TypeScript
kerlos1256/socialMedia-server
/src/utils/check_Auth.ts
2.546875
3
require('dotenv') const jwt = require('jsonwebtoken'); const key = process.env.SECRET_KEY export default (headers) => { if (headers) { if (headers.authorization) { const token = headers.authorization.split('Bearer ')[1]; if (token) { try{ const user = jwt.verify(token, key); return user } catch(err){ throw new Error('Invalid/Expired Token') } } throw new Error('Authentication token must be \'Bearer [token]') } throw new Error('Authorization header must be provied') } throw new Error('Headers must be provieded') }
c71eaf04af7fb9b2746d96baa808989e0c2a5a87
TypeScript
nikoladimitroff/Zmey
/Prototypes/Overmind/src/utils.ts
2.9375
3
export function checkAndSet(target: any, donor: any, prop: string): void { if(donor[prop] !== undefined) { target[prop] = donor[prop]; } else { console.assert(false); } } export async function fetchJSON(url: string): Promise<any> { let promise = new Promise(resolve => { let req = new XMLHttpRequest(); req.overrideMimeType("application/json"); req.open('GET', url, true); req.onload = function() { //console.log( req.responseText); resolve(eval("new Object(" + req.responseText + ")")); }; req.send(null); }); return await promise; }
70cbeedd2229181e867a22b4209c967fa3524554
TypeScript
pl4st3/SingleInstanceBrowser
/app/src/renderer/RendererApplication.ts
2.6875
3
import { ipcRenderer, remote } from "electron"; import * as $Settings from "../shared/Settings"; import * as $URLItem from "../shared/URLItem"; import * as $ShortCuts from "mousetrap"; /** * The class for the renderer application part. Each window will have only one instamce. */ export class CRendererApplication { private settings: $Settings.Settings; private addressBar: HTMLDivElement; private goBackButton: HTMLButtonElement; private goForwardButton: HTMLButtonElement; private urlField: HTMLInputElement; private webView: Electron.WebviewTag; /** * Creates the user interface, the web content part and handles all events. */ constructor() { // Unfortunately sendSync is declared as returning void so a hacky workaround is used... // tslint:disable-next-line:no-any this.settings = (ipcRenderer.sendSync("IPC", ["getSettings"]) as any) as $Settings.Settings; const fragment: DocumentFragment = new DocumentFragment(); this.webView = this.getWebView(); this.addressBar = this.getAddressBar(); this.addressBar.appendChild(this.getNavigationButtons()); this.addressBar.appendChild(this.getURLField()); fragment.appendChild(this.addressBar); fragment.appendChild(this.webView); document.body.appendChild(fragment); remote.getCurrentWindow().webContents.session.setPermissionRequestHandler(this.onPermissionRequest.bind(this)); ipcRenderer.on("IPC", this.onIPC.bind(this)); this.bindShortCuts(); this.queryInitialURLItem(); } /** * Get the initial URL to be loaded via an IPC call from the main process. */ private queryInitialURLItem(): void { // tslint:disable-next-line:no-any const urlItem: $URLItem.URLItem = (ipcRenderer.sendSync("IPC", ["queryURLItem"]) as any) as $URLItem.URLItem; if ((urlItem && urlItem.DoLoad)) { this.loadURL(urlItem.URL); } else { if (this.settings.Homepage !== "") { this.loadURL(this.settings.Homepage); } else { this.addressBar.style.display = ""; this.urlField.focus(); } } } /** * Bind keyboard shortcut(s) to a function. * @param shortcut A single keyboard shortcut ar on array of shortcuts. * @param func The function to be executed if the given keyboard shortcut is used. */ private bindShortCut(shortcut: string | string[], func: Function): void { $ShortCuts.bind(shortcut, (_event: ExtendedKeyboardEvent, _combo: string): boolean => { func.call(this); return false; }); } /** * Bind all keyboard shortcut(s) from the app settings to the respective function. */ private bindShortCuts(): void { this.bindShortCut(this.settings.ShortCuts.ToggleAddressBar, () => { this.addressBar.style.display === "none" ? this.addressBar.style.display = "" : this.addressBar.style.display = "none"; }); this.bindShortCut(this.settings.ShortCuts.ToggleInternalDevTools, () => { const devToolsOpened = remote.getCurrentWindow().webContents.isDevToolsOpened(); devToolsOpened ? remote.getCurrentWindow().webContents.closeDevTools() : remote.getCurrentWindow().webContents.openDevTools(); }); this.bindShortCut(this.settings.ShortCuts.ToggleDevTools, () => { this.webView.isDevToolsOpened() ? this.webView.closeDevTools() : this.webView.openDevTools(); }); this.bindShortCut(this.settings.ShortCuts.FocusLocationBar, () => { if (this.addressBar.style.display === "none") { this.addressBar.style.display = ""; } this.urlField.focus(); this.urlField.select(); }); this.bindShortCut(this.settings.ShortCuts.InternalReload, () => { remote.getCurrentWindow().webContents.reload(); }); this.bindShortCut(this.settings.ShortCuts.Reload, () => { this.webView.reload(); }); this.bindShortCut(this.settings.ShortCuts.GoBack, () => { this.webView.goBack(); }); this.bindShortCut(this.settings.ShortCuts.GoForward, () => { this.webView.goForward(); }); this.bindShortCut(this.settings.ShortCuts.ExitHTMLFullscreen, () => { this.webView.executeJavaScript("document.webkitExitFullscreen();", true); }); this.bindShortCut(this.settings.ShortCuts.ToggleWin32Menu, () => { ipcRenderer.send("IPC", ["toggleWin32Menu"]); }); } /** * Load a URL in the webview tag. * @param url The URL string to be loaded. */ private loadURL(url: string): void { this.webView.setAttribute("src", $URLItem.getURLItem(url).URL); } /** * Go back one step in the browser history. * @param _event A mouse event. */ private goBack(_event: MouseEvent): void { this.webView.goBack(); } /** * Go forward one step in the browser history. * @param _event A mouse event. */ private goForward(_event: MouseEvent): void { this.webView.goForward(); } /** * Called when the user clicks the Go button or presses Enter in the URL field. * @param event A mouse or keyboard event. */ private loadURLItemListener(event: MouseEvent | KeyboardEvent): void { if ((event.type === "keypress") && ((event as KeyboardEvent).key !== "Enter")) { return; } this.loadURL(this.urlField.value); } /** * Handles all IPC calls from the main process. * @param event An Electron event. * @param args The arguments sent by the calling main process. */ // tslint:disable-next-line:no-any private onIPC(_event: Electron.Event, ...args: any[]): void { if ((args.length === 0) || (!this.webView)) { return; } switch (args[0][0]) { case "loadURLItem": if (args[0].length === 2) { this.loadURL((args[0][1] as $URLItem.URLItem).URL); } break; default: break; } } /** * Called when the page has finished loading. * Sets the focus to the webview tag to enable keyboard navigation in the page. * @param _event An Electron event. */ private onDidFinishLoad(_event: Electron.Event): void { if (!this.webView.getWebContents().isFocused()) { this.webView.focus(); } } /** * Called when the title of the current page has been updated. * @param event An Electron PageTitleUpdatedEvent. */ private onPageTitleUpdated(event: Electron.PageTitleUpdatedEvent): void { remote.getCurrentWindow().setTitle(event.title); } /** * Called when a web page logs something to the browser console. * Default handling for the event is prevented, enhanced with additional * infos and again written to the console. In future versions this should * be redirected/copied to a log file. * @param event An Electron ConsoleMessageEvent. */ private onConsoleMessage(event: Electron.ConsoleMessageEvent): void { console.log("LOG from %s: [Level %d] %s (Line %d in %s)", this.webView.getURL(), event.level, event.message, event.line, event.sourceId); event.preventDefault(); event.stopImmediatePropagation(); } /** * Handles permission requests from web pages. * Permissions are granted based on app settings. * @param _webContents The calling Electron webContents. * @param permission The requested permission. * @param callback A callback called with the boolean result of the permission check. */ private onPermissionRequest(_webContents: Electron.WebContents, permission: string, callback: (permissionGranted: boolean) => void): void { const grant: boolean = (this.settings.Permissions.indexOf(permission) > -1); console.info(`Permission '${permission}' requested, ${grant ? "granting." : "denying."}`); callback(grant); } /** * Called when the navigaion to a URL has finished. * Used to update parts of the user interface. * @param _event An Electron DidNavigateEvent. */ private onDidNavigate(_event: Electron.DidNavigateEvent) { this.urlField.value = this.webView.getURL(); this.goBackButton.disabled = !this.webView.canGoBack(); this.goForwardButton.disabled = !this.webView.canGoForward(); } /** * Called when the user clicks on a link in a page which should be opened in another window/tab. * @param event An Electron NewWindowEvent. */ private onNewWindow(event: Electron.NewWindowEvent) { if (this.settings.AllowNewWindows) { // Excluding `save-to-disk` for now if (["default", "foreground-tab", "background-tab", "new-window", //"save-to-disk", "other"].indexOf(event.disposition) !== -1) { ipcRenderer.send("IPC", ["openWindow", event.url]); } } } /** * Build the address bar. * @returns The DOM element(s) for the address bar. */ private getAddressBar(): HTMLDivElement { const addressBar: HTMLDivElement = document.createElement("div"); addressBar.setAttribute("id", "addressBar"); // Initially hidden; made visible depending on command line params addressBar.style.display = "none"; return addressBar; } /** * Build the navigation buttons. * @returns The DOM element(s) for the navigation buttons. */ private getNavigationButtons(): HTMLDivElement { const navigationButtonsContainer: HTMLDivElement = document.createElement("div"); navigationButtonsContainer.setAttribute("id", "navigationButtonsContainer"); this.goBackButton = document.createElement("button"); this.goBackButton.setAttribute("id", "goBack"); this.goBackButton.disabled = true; this.goBackButton.title = "Go back"; this.goBackButton.disabled = true; this.goBackButton.appendChild(document.createTextNode("<")); this.goBackButton.addEventListener("click", this.goBack.bind(this), false); navigationButtonsContainer.appendChild(this.goBackButton); this.goForwardButton = document.createElement("button"); this.goForwardButton.setAttribute("id", "goForward"); this.goForwardButton.disabled = true; this.goForwardButton.title = "Go forward"; this.goForwardButton.appendChild(document.createTextNode(">")); this.goForwardButton.addEventListener("click", this.goForward.bind(this), false); navigationButtonsContainer.appendChild(this.goForwardButton); const goButton: HTMLButtonElement = document.createElement("button"); goButton.setAttribute("id", "goButton"); goButton.title = "Open URL"; goButton.appendChild(document.createTextNode("Go")); goButton.addEventListener("click", this.loadURLItemListener.bind(this), false); navigationButtonsContainer.appendChild(goButton); return navigationButtonsContainer; } /** * Build the URL text field. * @returns The DOM element(s) for the URL text field. */ private getURLField(): HTMLDivElement { const urlFieldContainer: HTMLDivElement = document.createElement("div"); urlFieldContainer.setAttribute("id", "urlFieldContainer"); this.urlField = document.createElement("input"); this.urlField.setAttribute("id", "urlField"); this.urlField.setAttribute("type", "text"); if (this.settings.ShortCuts.Global) { this.urlField.setAttribute("class", "mousetrap"); } this.urlField.addEventListener("keypress", this.loadURLItemListener.bind(this), false); urlFieldContainer.appendChild(this.urlField); return urlFieldContainer; } /** * Build the webview tag. * @returns A completely configured Electron.WebviewTag. */ private getWebView(): Electron.WebviewTag { const webView: Electron.WebviewTag = document.createElement("webview"); webView.setAttribute("id", "webView"); webView.setAttribute("autosize", ""); if (this.settings.AllowPopups) { webView.setAttribute("allowpopups", ""); } webView.setAttribute("plugins", ""); webView.setAttribute("useragent", this.settings.UserAgent); webView.addEventListener("did-navigate", this.onDidNavigate.bind(this), false); webView.addEventListener("did-finish-load", this.onDidFinishLoad.bind(this), false); webView.addEventListener("page-title-updated", this.onPageTitleUpdated.bind(this), false); webView.addEventListener("console-message", this.onConsoleMessage.bind(this), false); webView.addEventListener("new-window", this.onNewWindow.bind(this), false); return webView; } }
ca885fc085e142ebf6fc1726320942e8b143a852
TypeScript
gristlabs/ts-interface-builder
/test/fixtures/ignore-generics.ts
2.65625
3
export interface ITest { myGeneric: IMyType<string>; } export interface IMyType<T> { value: T; }
91c67b9dc1b9057458e3aef3a13dc101b2c71859
TypeScript
Blubtastic/angularShoppwingWebsite
/client/app/google-maps/google-maps.component.ts
2.578125
3
/* Component for the google map on the products page that displays user locations, show a selected product's location, and can be used to filter the list of products based on the selected user */ import { Component, OnInit } from '@angular/core'; import { UserService } from '../services/user.service'; import { MessageService } from '../services/message.service'; import { Subscription } from 'rxjs/Rx'; @Component({ selector: 'app-google-maps', templateUrl: './google-maps.component.html', styleUrls: ['./google-maps.component.scss'] }) export class GoogleMapsComponent implements OnInit { subscription: Subscription; init_lat = 63.428024; init_lng = 10.393186; zoom = 4; users = []; isLoading = true; constructor(private userService: UserService, private messageService: MessageService) { this.subscription = this.messageService.getMessage(). subscribe(msg => { this.init_lat = msg.text[0]; this.init_lng = msg.text[1]; this.zoom = 10; }); } ngOnInit() { this.getUsers(); } // Updates the zoom level when the user zooms the map updateMapZoom($event) { this.zoom = $event; } // Updates center of map when it changes (i.e. user drags the map) updateMapCenter($event) { this.init_lat = $event.lat; this.init_lng = $event.lng; } // Used to filter products by user id, sends id to products component filterByUser(id) { this.messageService.sendID(id); } // Used to load the list of users, will then plot markers on the map getUsers() { this.userService.getUsers().subscribe( users => { this.users = users; }, error => console.log(error), () => { this.isLoading = false; } ); } }
cc4b5c1af310c6f24518543c53d7b34c7ed94292
TypeScript
skcotnam062/TypeScript30
/src/10 - Hold Shift and Check Checkboxes/main.ts
2.890625
3
(function() { const checkboxes = document.querySelectorAll( '.inbox input[type="checkbox"]' ) as NodeListOf<HTMLInputElement>; let lastChecked: HTMLInputElement; function handleCheck(this: HTMLInputElement, e: MouseEvent): void { // Check if they had the shift key down // AND check that they are checking it let inBetween: boolean = false; if (e.shiftKey && this.checked) { // go ahead and do what we please // loop over every single checkbox checkboxes.forEach( (checkbox: HTMLInputElement): void => { console.log(checkbox); if (checkbox === this || checkbox === lastChecked) { inBetween = !inBetween; console.log('Starting to check them inbetween!'); } if (inBetween) { checkbox.checked = true; } } ); } lastChecked = this; } checkboxes.forEach(checkbox => checkbox.addEventListener('click', handleCheck) ); })();
863bf40abd2025227a0e0cc823a532df8bd55d19
TypeScript
eyaleizenberg/doom_minesweeper
/src/redux/reducers/game.ts
2.578125
3
import { handleActions } from 'redux-actions'; import { IGameState } from '../../interfaces/gameInterface'; import * as ACTIONS from '../../constants/actionTypes'; export const defaultState = { isGameOver: false, gameInProgress: false, newGameDialogShown: false, customGameDialogShown: false, isGameWon: false, saveDialogShown: false, loadDialogShown: false, timer: 0 }; export const getTimer = (state: IGameState): number => state.timer; export const getIsGameOver = (state: IGameState): boolean => state.isGameOver; export const getIsGameWon = (state: IGameState): boolean => state.isGameWon; export const getNewGameDialogShown = (state: IGameState): boolean => state.newGameDialogShown; export const getGameInProgress = (state: IGameState): boolean => state.gameInProgress; export const getCustomGameDialogShown = (state: IGameState): boolean => state.customGameDialogShown; export const getSaveDialogShown = (state: IGameState): boolean => state.saveDialogShown; export const getLoadDialogShown = (state: IGameState): boolean => state.loadDialogShown; export default handleActions( { [ACTIONS.GAME_OVER]: (state: IGameState) => { return { ...state, isGameOver: true }; }, [ACTIONS.TOGGLE_NEW_GAME_DIALOG]: (state: IGameState) => { return { ...state, loadDialogShown: false, saveDialogShown: false, newGameDialogShown: !state.newGameDialogShown }; }, [ACTIONS.MATRIX_CREATED]: (state: IGameState) => { return { ...defaultState, gameInProgress: true }; }, [ACTIONS.SHOW_CUSTOM_GAME_DIALOG]: (state: IGameState) => { return { ...state, customGameDialogShown: true, newGameDialogShown: false }; }, [ACTIONS.GAME_WON]: (state: IGameState) => { return { ...state, isGameWon: true }; }, [ACTIONS.TIMER_TICK]: (state: IGameState) => { return { ...state, timer: state.timer + 1 }; }, [ACTIONS.SAVE_DIALOG_TOGGLED]: (state: IGameState) => { return { ...state, newGameDialogShown: false, loadDialogShown: false, saveDialogShown: !state.saveDialogShown }; }, [ACTIONS.LOAD_DIALOG_TOGGLED]: (state: IGameState) => { return { ...state, newGameDialogShown: false, saveDialogShown: false, loadDialogShown: !state.loadDialogShown }; } }, defaultState );
803607ff202a6ef5fe9dd1012a376429a2bff531
TypeScript
netgum/archanova
/packages/cli/src/services/TemplateService.ts
2.546875
3
import { resolve, join } from 'path'; import { readdir, readFile, writeFile, stat, ensureDir, pathExists } from 'fs-extra'; import { SdkService } from './SdkService'; export class TemplateService { private static SRC_DIR = resolve(__dirname, '../../template'); constructor(private workingPath: string) { // } public templateExists(): Promise<boolean> { return pathExists( join(this.workingPath, 'package.json'), ); } public async createTemplate(app: SdkService.IApp): Promise<void> { const fileNames = await readdir(TemplateService.SRC_DIR); const copyMap: { src: string; dest: string; }[] = []; for (const fileName of fileNames) { const filePath = join(TemplateService.SRC_DIR, fileName); const fileStat = await stat(filePath); if (fileStat.isDirectory()) { const subFileNames = await readdir(filePath); await ensureDir(join(this.workingPath, fileName)); for (const subFileName of subFileNames) { const subFilePath = join(filePath, subFileName); const subFileStat = await stat(subFilePath); if (!subFileStat.isDirectory()) { copyMap.push({ src: subFilePath, dest: join(this.workingPath, fileName, subFileName), }); } } } else { copyMap.push({ src: filePath, dest: join(this.workingPath, fileName), }); } } for (const { src, dest } of copyMap) { let content = await readFile(src, 'utf8'); if (app) { content = content.replace( new RegExp('\\$\\{([a-zA-Z\\.]+)\\}', 'ig'), (result: string, found: string) => { switch (found) { case 'app.name': result = app.name; break; case 'app.description': result = app.description || ''; break; case 'app.alias': result = app.alias; break; } return result; }, ); } await writeFile(dest, content, 'utf8'); } } }
7fb7da0283b5b7f99c6f86ab2d7040f486d5ec44
TypeScript
Tamareg/BlankExpressAsyncTesting
/BlankExpressAsyncTesting/mylib_express.ts
2.640625
3
const os = require('os'); const fs = require('fs'); const express = require('express'); const hbs = require('hbs'); var bUseMainten = false; var app = express(); hbs.registerPartials(__dirname + '/views/partials') app.set('view engine', 'hbs'); /* bUseMainten */ if (bUseMainten) { //---------------------------------------------- app.use app.use((req, res, next) => { res.render('mainten.hbs'); }); } else { //---------------------------------------------- app.use app.use((req, res, next) => { var now = new Date().toString(); var sLog = `${now}: ${req.method} ${req.url}` console.log(sLog); myAppendLog(sLog); next(); }); } app.use(express.static(__dirname + '/public')); //console.log(__dirname); //---------------------------------------------- myAppendLog var myAppendLog = (psText) => { var oUser = os.userInfo(); var sUName = oUser.username; fs.appendFile('mylib_express.log', `\r\n ${psText} for ${sUName}`, function (err) { if (err) { console.log(err); if (err) throw err; //console.log('Unable to append to server.log.') } }); } //---------------------------------------------- myCallBacks module.exports.myCallBacks = () => { var iAction = 1; switch (iAction) { case 0: //var app = require('./app'); app.server.close(); break; case 1: console.log("command to listen"); setListenAll(); break; default: console.log("Please set iAction"); } } //---------------------------------------------- setListenAll var setListenAll = () => { /* app.get('/views/partials', (req, res) => { //res.send('HtmlUsefulColors.html'); res.render('footer.hbs', { }); }); */ //---------------------------------------------- hbs Helpers hbs.registerHelper('myCurrentYear', () => { return new Date().getFullYear() }); hbs.registerHelper('myUpper', (text) => { return text.toUpperCase(); }); app.get('/', (req, res) => { // res.send('<h1>Listening on port 3000</h1>'); //res.send({ name: 'Powell Electronics', items: ['Connectors', 'Cables'] res.render('home.hbs', { pageTitle: 'Page: Initial', welcomeMessage: 'Testing Initial', //currentYear: new Date().getFullYear() }) }); app.get('/about', (req, res) => { //res.send('HtmlUsefulColors.html'); res.render('about.hbs', { pageTitle: 'Page: About', welcomeMessage: 'Testing About', //currentYear: '2000-' + new Date().getFullYear() }); }); app.get('/bad', (req, res) => { res.send({ errorMessage: 'Unable to handle request' }); }); app.listen(3000, () => { console.log('Server is up on port 3000'); }); }
86e13a4142bbdf807f67bc73dc755c65e12d1854
TypeScript
AnupriyaGola/Typescript
/youtube.ts
2.875
3
//defining a class class Youtube{ //fields or properties private videoTitle : string; private publisher : string; private publishDate : any; private views : number; private subscribe : number; private no_of_likes : number; private no_of_dislikes : number; private category : string; private license : string; private music : string; //a constructor which is used to initialize a class filelds. constructor(videoTitle:string,publisher:string,publishDate:any,views:number,subscribe:number,no_of_likes:number,no_of_dislikes:number,category:string,license?:string,music?:string){ this.videoTitle = videoTitle; this.publisher = publisher; this.publishDate = publishDate; this.views = views; this.subscribe = subscribe; this.no_of_likes = no_of_likes; this.no_of_dislikes = no_of_dislikes; this.category = category; this.license = license; this.music = music; } //end constructor getNumberofViews =()=>{ return this.views; } getVideoTitle=()=>{ return this.videoTitle; } getPublishedDate=()=>{ return this.publishDate; } getRating=()=>{ if((this.no_of_likes) > (this.no_of_dislikes)) { return (this.videoTitle +" has rating 5"); } else{ return (this.videoTitle +" has below rating 5") } } getPublisher=()=>{ return this.publisher; } getCategory=()=>{ return this.category; } getlicense=()=>{ return this.license; } getRelatedVideos=()=>{ return ("Will be shown soon") } getNoOfLikes=()=>{ return this.no_of_likes; } getNoOfDislikes=()=>{ return this.no_of_dislikes; } getComments=()=>{ return ("Loading") } setNoOfViews =(newview : number)=>{ this.views = (newview) + 1; } setPublisherName=(NameP : string)=>{ this.publisher = NameP; } } //end class let video1 = new Youtube("Rings","Paramount Pictures International","Aug 24 2016",5082933,380000,16000,19000,"Entertainment","Standard Youtube License") let video2 = new Youtube("Sinter 2","JUJU MANUEL","Dec 14 2015",336962,2000,14800,1000,"People & Blogs") let cat = video1.getCategory() let title =video1.getVideoTitle() let date = video1.getPublishedDate() let License =video1.getlicense() let ratings = video1.getRating() let like = video1.getNoOfLikes() let dislike = video1.getNoOfDislikes() let comment = video1.getComments() let views = video1.getNumberofViews() video1.setNoOfViews(views) let newviews = video1.getNumberofViews() let Publish = video1.getPublisher() let cat2 = video2.getCategory() let views2 = video2.getNumberofViews() let title2 =video2.getVideoTitle() let date2 = video2.getPublishedDate() let License2 =video2.getlicense() let ratings2 = video2.getRating() let like2 = video2.getNoOfLikes() let dislike2 = video2.getNoOfDislikes() let comment2 = video2.getComments() let publishername = video2.getPublisher() video2.setPublisherName("Anupriya Gola") let newpublisher = video2.getPublisher() console.log("Category: " +cat +"\nVideo Title: " +title +"\nPublished Date: " +date +"\nLicense: " +License +"\nRatings: " +ratings +"\nNo Of Likes: " +like +"\nNo Of Dislikes: " +dislike +"\nComments: " +comment +"\nViews: " +views +"\nUpdated No of Views: " +newviews +"\nPublisher: " +Publish) console.log("\nCategory: " +cat2 +"\nVideo Title: " +title2 +"\nPublished Date: " +date2 +"\nViews: " +views2 +"\nLicense: " +License2 +"\nRatings: " +ratings2 +"\nNo Of Likes: " +like2 +"\nNo Of Dislikes: " +dislike2 +"\nComments: " +comment2 +"\nPublisher: " +publishername +"\nUpdated Publisher: " +newpublisher)
04e1533dab8e05ba2409225c3aa6d8a3af089043
TypeScript
zuramai/denovel
/config/database.ts
2.734375
3
import { config } from "https://deno.land/x/dotenv/mod.ts"; /* |-------------------------------------------------------------------------- | Database Connection Interfaces |-------------------------------------------------------------------------- | | It will let you know available databases | for this framework. | */ interface mysql { hostname: string; username: string; password: string; db: string; port: number; } interface postgres { host: string; user: string; password: string; port: number; database: string; } interface mongo { hostname: string; username: string; //optional db: string; password: string; //optional port: string; } /* |-------------------------------------------------------------------------- | Database Connections |-------------------------------------------------------------------------- | | Here are each of the database connections setup for your application. | Of course, examples of configuring each database platform that is | supported by Denovel is shown below to make development simple. | | | All database work in Denovel is done through the Typescript ORM facilities | so make sure you have the driver for your particular database of | choice installed on your machine before you begin development. | */ export const Mysql: mysql = { hostname: config().DB_HOST || 'localhost', username: config().DB_USER || 'root', password: config().DB_PASS || '', db: config().DB_NAME || 'denovel', port: 3306, } export const Postgres: postgres = { host: config().DB_HOST || 'localhost', user: config().DB_USER || 'root', password: config().DB_PASS || '', port: parseInt(config().DB_PORT) || 5432, database: config().DB_NAME || 'denovel', } export const Mongo: mongo = { hostname: config().DB_HOST || 'mongodb://localhost', username: config().DB_USER, //optional db: config().DB_NAME || 'denovel', password: config().DB_PASS, //optional port: config().DB_PORT || '27107', } /** * Export connection name * * */ export const Connection = config().DB_CONNECTION;
572cec362cda2f915dd8f457d1ae2682e7847def
TypeScript
webdev0415/Estack-backend
/src/merchant/dto/create-otp.dto.ts
2.546875
3
import { IsEmail, IsNotEmpty, IsString } from 'class-validator'; import { ApiProperty } from '@nestjs/swagger'; /** input for create Otp endpoint */ export class CreateOtpDto { /** email */ @ApiProperty({ description: 'Email', required: true, format: 'string', }) @IsString() @IsNotEmpty() @IsEmail() email: string; }
f9acf98d9458ebb0d59a5d04da441b72ddc9d88d
TypeScript
wilfredlopez/color-converter
/test/methods/tints.test.ts
3.328125
3
import { ColorConverter } from "../../src"; function equal(value: any, expected: any) { expect(value).toEqual(expected); } const defaultWeight = (w?: any) => { it(`${w} should default to 10% weight tints`, () => { const { length } = new ColorConverter("hsl(0 100% 50%)").tints(w); equal(length, 10); }); }; describe("methods / tints", () => { defaultWeight(); defaultWeight(""); defaultWeight("foo"); defaultWeight(NaN); defaultWeight(null); defaultWeight(undefined); // eslint-disable-line no-undefined it("should calculate tints", () => { const tints = new ColorConverter("#00ffff").tints(); equal(tints.length, 10); equal(tints[0].hexString(), "#19ffff"); equal(tints[2].hexString(), "#4dffff"); equal(tints[4].hexString(), "#80ffff"); equal(tints[6].hexString(), "#b3ffff"); equal(tints[8].hexString(), "#e6ffff"); equal(tints[9].hexString(), "#ffffff"); }); it("should include tints weight", () => { const tints = new ColorConverter("#00ffff").tints(); equal(tints[0].weight, 10); equal(tints[2].weight, 30); equal(tints[4].weight, 50); equal(tints[6].weight, 70); equal(tints[8].weight, 90); equal(tints[9].weight, 100); }); });
57fb8e69607ded35b7b66ea700924a24fc0d3b92
TypeScript
ravunana/manda-negocio
/src/main/webapp/app/shared/model/retencao-fonte.model.ts
2.625
3
export interface IRetencaoFonte { id?: number; motivoRetencao?: string; valor?: string; porcentagem?: boolean; detalheId?: number; impostoCodigoImposto?: string; impostoId?: number; } export class RetencaoFonte implements IRetencaoFonte { constructor( public id?: number, public motivoRetencao?: string, public valor?: string, public porcentagem?: boolean, public detalheId?: number, public impostoCodigoImposto?: string, public impostoId?: number ) { this.porcentagem = this.porcentagem || false; } }
72960b0b2627fc194738f876e04e958e2a0188a7
TypeScript
NativeScript/NativeScript
/apps/automated/src/ui/core/weak-event-listener/weak-event-listener-tests.ts
2.8125
3
import * as TKUnit from '../../../tk-unit'; import { Observable, EventData } from '@nativescript/core'; import { addWeakEventListener, removeWeakEventListener } from '@nativescript/core/ui/core/weak-event-listener'; import { forceGC } from '../../../ui-helper'; class Target { public counter: number = 0; public onEvent(data: EventData) { this.counter++; } } export function test_addWeakEventListener_throwsWhenCalledwitnInvalid_source() { TKUnit.assertThrows(() => { addWeakEventListener(undefined, 'eventName', emptyHandler, {}); }); } export function test_addWeakEventListener_throwsWhenCalledwitnInvalid_target() { TKUnit.assertThrows(() => { addWeakEventListener(new Observable(), 'eventName', emptyHandler, undefined); }); } export function test_addWeakEventListener_throwsWhenCalledwitnInvalid_handler() { TKUnit.assertThrows(() => { addWeakEventListener(new Observable(), 'eventName', undefined, {}); }); } export function test_addWeakEventListener_throwsWhenCalledwitnInvalid_name() { TKUnit.assertThrows(() => { addWeakEventListener(new Observable(), undefined, emptyHandler, {}); }); } export function test_addWeakEventListener_listensForEvent() { const source = new Observable(); const target = new Target(); addWeakEventListener(source, Observable.propertyChangeEvent, target.onEvent, target); source.set('testProp', 'some value'); TKUnit.assertEqual(target.counter, 1, 'Handler not called.'); } export function test_addWeakEventListener_listensForEven_multipleTargetst() { const source = new Observable(); const target1 = new Target(); const target2 = new Target(); addWeakEventListener(source, Observable.propertyChangeEvent, target1.onEvent, target1); addWeakEventListener(source, Observable.propertyChangeEvent, target2.onEvent, target2); source.set('testProp', 'some value'); TKUnit.assertEqual(target1.counter, 1, 'Handler not called.'); TKUnit.assertEqual(target2.counter, 1, 'Handler not called.'); } export function test_removeWeakEventListener_StopsListeningForEvent() { const source = new Observable(); const target = new Target(); addWeakEventListener(source, Observable.propertyChangeEvent, target.onEvent, target); removeWeakEventListener(source, Observable.propertyChangeEvent, target.onEvent, target); source.set('testProp', 'some value'); TKUnit.assertEqual(target.counter, 0, 'Handler should not be called.'); } export function test_handlerIsCalled_WithTargetAsThis() { const source = new Observable(); const target = new Object(); let callbackCalled = false; const handler = function (args: EventData) { TKUnit.assertEqual(this, target, 'this should be the target'); callbackCalled = true; }; addWeakEventListener(source, Observable.propertyChangeEvent, handler, target); source.set('testProp', 'some value'); TKUnit.assert(callbackCalled, 'Handler not called.'); } function getSourceAsWeakRef(): WeakRef<Observable> { return new WeakRef(new Observable()); } function getTargetAsWeakRef(): WeakRef<Target> { return new WeakRef(new Target()); } // commented out tests because the latest v8 runtime uses the built-in WeakRef implementation // which does not guarantee releases after a GC call - it uses heuristics to determine when // a WeakRef should be released - so we don't really need to test this. // export function test_listenerDoesNotRetainTarget(done) { // const sourceRef = getSourceAsWeakRef(); // const targetRef = getTargetAsWeakRef(); // // with the v8 6.5 the GC does not release WeakRefs so fast if you pass them to a method // // that's why we are making the call to the addWeakEventListener in a closure so that the WeakRef will be easier released // (function () { // addWeakEventListener(sourceRef.get(), Observable.propertyChangeEvent, emptyHandler, targetRef.get()); // })(); // forceGC(); // try { // TKUnit.assert(!targetRef.get(), 'Target should be released after GC'); // done(null); // } catch (e) { // done(e); // } // } // export function test_listenerDoesNotRetainSource(done) { // const sourceRef = getSourceAsWeakRef(); // const targetRef = getTargetAsWeakRef(); // // with the v8 6.5 the GC does not release WeakRefs so fast if you pass them to a method // // that's why we are making the call to the addWeakEventListener in a closure so that the WeakRef will be easier released // (function () { // addWeakEventListener(sourceRef.get(), Observable.propertyChangeEvent, targetRef.get().onEvent, targetRef.get()); // })(); // forceGC(); // try { // TKUnit.assert(!sourceRef.get(), 'Source should be released after GC'); // done(null); // } catch (e) { // done(e); // } // } export function test_handlerIsDetached_WhenAllListenersAreRemoved() { const source = new Observable(); const target1 = new Target(); const target2 = new Target(); addWeakEventListener(source, Observable.propertyChangeEvent, target1.onEvent, target1); addWeakEventListener(source, Observable.propertyChangeEvent, target2.onEvent, target2); removeWeakEventListener(source, Observable.propertyChangeEvent, target1.onEvent, target1); removeWeakEventListener(source, Observable.propertyChangeEvent, target2.onEvent, target2); TKUnit.assert(!source.hasListeners(Observable.propertyChangeEvent), 'All events should be detached'); } export function test_autoDetachingOfDeadReferences(done) { const source = new Observable(); for (let i = 0; i < 100; i++) { addListenerWithSource(source); } try { const target = new Target(); addWeakEventListener(source, Observable.propertyChangeEvent, emptyHandler, target); removeWeakEventListener(source, Observable.propertyChangeEvent, emptyHandler, target); forceGC(); const testPass = (<any>source)._observers[Observable.propertyChangeEvent] ? (<any>source)._observers[Observable.propertyChangeEvent].length <= 1 : true; TKUnit.assert(testPass, 'All events should be detached'); done(null); } catch (e) { done(e); } } function addListenerWithSource(source: Observable) { const target = new Target(); addWeakEventListener(source, Observable.propertyChangeEvent, target.onEvent, target); } function emptyHandler(data: EventData) { // Do nothing. }
4f1d5d9fe081929a972d0714608818bb75936298
TypeScript
abdelrahmanabdo/AdvancedCareClinics-app
/src/services/DepartmentsService.ts
2.53125
3
import { DepartmentModel } from "../models"; import axios from "axios"; export default class DepartmentsService { /** * Get all departments * @public */ public static getDepartments(): Promise<DepartmentModel[]> { return new Promise((resolve, reject) => { axios .get('http://www.advancedcareclinics.com/api/Specialties/get-all') .then((response) => { resolve(response.data.Data as DepartmentModel[]); }, (err) => { reject(err); }); }); } }
2d047aae9078d22e0a52e6679bd489d223bf3b79
TypeScript
Qlee-practice/good-practice-for-redux
/src/models/__test__/todo.spec.ts
2.5625
3
import { TasksModel } from "../todo"; import { storeService } from "../../services/store-service"; import { combineReducers, createStore, Store } from "redux"; describe('Model - TasksModel', () => { describe('#Create', () => { let store: Store; beforeEach(() => { store = createStore(combineReducers({ [TasksModel.name]: TasksModel.reducers })); storeService.setStore(store); }); it('should add the task to list when a task is created', () => { const task = { id: 666, name: 'Todo', done: false }; TasksModel.actions.create(task); expect(store.getState()[TasksModel.name].list).toEqual([666]); const tasks = storeService.select(TasksModel.selectors.allTasks); expect(tasks).toEqual([task]); }); it('should get the task by id when a ask is created', () => { const task = { id: 666, name: 'Todo', done: false }; TasksModel.actions.create(task); expect(store.getState()[TasksModel.name].data).toEqual({ 666: task }); const storeTask = storeService.select(TasksModel.selectors.getTask(666)); expect(storeTask).toEqual(task); }); }); });
cdef4cee2600932d4f6902d7112f4cf3206c0eb4
TypeScript
souldreamer/string-template-parser
/src/parser.ts
3.0625
3
export interface Pipe { name: string; parameters: string[]; } export interface Variable { name: string; pipes: Pipe[]; } export interface ParsedString { literals: string[]; variables: Variable[]; } const enum ParseState { Literal, Variable, Pipe, PipeParameter } export const DEFAULT_QUOTED_STRING_REGEX = /^('((?:[^'\\]|\\.)*)'|'((?:[^'\\]|\\.)*)$|"((?:[^"\\]|\\.)*)"|"((?:[^"\\]|\\.)*)$)/; export function parseStringTemplateGenerator({ ESCAPE = /^\\/, VARIABLE_START = /^\${\s*/, VARIABLE_END = /^\s*}/, PIPE_START = /^\s*\|\s*/, PIPE_PARAMETER_START = /^\s*:\s*/, QUOTED_STRING = DEFAULT_QUOTED_STRING_REGEX, QUOTED_STRING_TEST = null, QUOTED_STRING_GET_AND_ADVANCE = null, QUOTED_STRING_IN_PARAMETER_TEST = null, QUOTED_STRING_IN_PARAMETER_GET_AND_ADVANCE = null }: { ESCAPE?: RegExp, VARIABLE_START?: RegExp, VARIABLE_END?: RegExp, PIPE_START?: RegExp, PIPE_PARAMETER_START?: RegExp, QUOTED_STRING?: RegExp, QUOTED_STRING_TEST?: (remainingString: string) => boolean | null, QUOTED_STRING_GET_AND_ADVANCE?: (remainingString: string, advance: (length: number) => void) => string | null, QUOTED_STRING_IN_PARAMETER_TEST?: (remainingString: string) => boolean | null, QUOTED_STRING_IN_PARAMETER_GET_AND_ADVANCE?: (remainingString: string, advance: (length: number) => void) => string | null } = {}) { const quotedStringTest = QUOTED_STRING_TEST || ((remainingString: string) => QUOTED_STRING.test(remainingString)); const quotedStringGetAndAdvance = QUOTED_STRING_GET_AND_ADVANCE || getQuotedStringAndAdvanceForRegex(QUOTED_STRING); const quotedStringInParameterTest = QUOTED_STRING_IN_PARAMETER_TEST || ((remainingString: string) => QUOTED_STRING.test(remainingString)); const quotedStringInParameterGetAndAdvance = QUOTED_STRING_IN_PARAMETER_GET_AND_ADVANCE || getQuotedStringAndAdvanceForRegex(QUOTED_STRING); return function parseStringTemplate(input: string): ParsedString { let remainingString = input; let parsedString: ParsedString = {literals: [], variables: []}; let parseState = <ParseState>ParseState.Literal; let currentLiteral = ''; let currentVariable: Variable = {name: '', pipes: []}; let currentPipe: Pipe = {name: '', parameters: []}; let currentPipeParameter: string = ''; let existsCurrentVariable = false; let existsCurrentPipe = false; let existsCurrentPipeParameter = false; while (remainingString && remainingString.length > 0) { switch (parseState) { case ParseState.Literal: if (ESCAPE.test(remainingString)) { currentLiteral += getEscapedCharacter(); continue; } if (VARIABLE_START.test(remainingString)) { parseState = ParseState.Variable; newCurrentVariable(); parsedString.literals.push(currentLiteral); currentLiteral = ''; skipMatch(VARIABLE_START); continue; } currentLiteral += remainingString[0]; advance(); break; case ParseState.Variable: if (ESCAPE.test(remainingString)) { currentVariable.name += getEscapedCharacter(); continue; } if (testVariableEnd() || testPipeStart()) continue; if (quotedStringTest(remainingString)) { currentVariable.name += quotedStringGetAndAdvance(remainingString, advance); continue; } currentVariable.name += remainingString[0]; advance(); break; case ParseState.Pipe: if (ESCAPE.test(remainingString)) { currentPipe.name += getEscapedCharacter(); continue; } if (testVariableEnd() || testPipeParameterStart() || testPipeStart()) continue; if (quotedStringTest(remainingString)) { currentPipe.name += quotedStringGetAndAdvance(remainingString, advance); continue; } currentPipe.name += remainingString[0]; advance(); break; case ParseState.PipeParameter: if (ESCAPE.test(remainingString)) { currentPipeParameter += getEscapedCharacter(); continue; } if (testVariableEnd() || testPipeParameterStart() || testPipeStart()) continue; if (quotedStringInParameterTest(remainingString)) { currentPipeParameter += quotedStringInParameterGetAndAdvance(remainingString, advance); continue; } currentPipeParameter += remainingString[0]; advance(); break; } } if (existsCurrentPipeParameter) currentPipe.parameters.push(currentPipeParameter); if (existsCurrentPipe) currentVariable.pipes.push(currentPipe); if (existsCurrentVariable) parsedString.variables.push(currentVariable); parsedString.literals.push(currentLiteral); return parsedString; function advance(length: number = 1) { remainingString = remainingString.substr(length); } function skipMatch(regex: RegExp = /^/) { advance((<RegExpMatchArray>remainingString.match(regex))[0].length); } function getEscapedCharacter(): string { let escapedCharacter: string; skipMatch(ESCAPE); escapedCharacter = remainingString.length > 0 ? remainingString[0] : ''; advance(); return escapedCharacter; } function newCurrentVariable({isNull = false} = {}) { currentVariable = {name: '', pipes: []}; existsCurrentVariable = !isNull; } function deleteCurrentVariable() { parsedString.variables.push(currentVariable); newCurrentVariable({isNull: true}); } function newCurrentPipe({isNull = false} = {}) { currentPipe = {name: '', parameters: []}; existsCurrentPipe = !isNull; } function deleteCurrentPipe() { currentVariable.pipes.push(currentPipe); newCurrentPipe({isNull: true}); } function newCurrentPipeParameter({isNull = false} = {}) { currentPipeParameter = ''; existsCurrentPipeParameter = !isNull; } function deleteCurrentPipeParameter() { currentPipe.parameters.push(currentPipeParameter); newCurrentPipeParameter({isNull: true}); } function testVariableEnd(): boolean { if (!VARIABLE_END.test(remainingString)) return false; skipMatch(VARIABLE_END); if (parseState >= ParseState.PipeParameter) deleteCurrentPipeParameter(); if (parseState >= ParseState.Pipe) deleteCurrentPipe(); if (parseState >= ParseState.Variable) deleteCurrentVariable(); parseState = ParseState.Literal; return true; } function testPipeStart(): boolean { if (!PIPE_START.test(remainingString)) return false; skipMatch(PIPE_START); if (parseState >= ParseState.PipeParameter) deleteCurrentPipeParameter(); if (parseState >= ParseState.Pipe) deleteCurrentPipe(); if (parseState >= ParseState.Variable) newCurrentPipe(); parseState = ParseState.Pipe; return true; } function testPipeParameterStart(): boolean { if (!PIPE_PARAMETER_START.test(remainingString)) return false; skipMatch(PIPE_PARAMETER_START); if (parseState >= ParseState.PipeParameter) deleteCurrentPipeParameter(); if (parseState >= ParseState.Pipe) newCurrentPipeParameter(); parseState = ParseState.PipeParameter; return true; } }; } export const parseStringTemplate = parseStringTemplateGenerator(); export function getQuotedStringAndAdvanceForRegex(regex: RegExp) { return (remainingString: string, advance: (length: number) => void) => { const quotedStringMatch = <RegExpMatchArray>remainingString.match(regex); advance(quotedStringMatch[0].length); return quotedStringMatch.slice(2).join('').replace('\\\\', '\\'); }; }
8966f839350a996ccc9e13756d51c5be3e46071e
TypeScript
geoffdutton/amplitude
/test/errors.test.ts
2.65625
3
import { expect } from 'chai' import { AmplitudeErrorResponse, axiosErrorCatcher } from '../src/errors' interface MockAxiosError extends Error { response?: { status: number data: unknown } } describe('errors', () => { it('catches axios response errors', async () => { const err: MockAxiosError = new Error('some error with response') err.response = { status: 500, data: { errMsg: 'missing user_id' } } let caughtErr try { await axiosErrorCatcher(Promise.reject(err)) } catch (e) { caughtErr = e } expect(caughtErr.status).to.eq(500) expect(caughtErr.data).to.eql({ errMsg: 'missing user_id' }) expect(caughtErr).to.be.instanceof(AmplitudeErrorResponse) }) it('catches non axios errors', async () => { const err = new Error('some std error') let caughtErr try { await axiosErrorCatcher(Promise.reject(err)) } catch (e) { caughtErr = e } expect(caughtErr.status).to.be.undefined expect(caughtErr.message).to.eq('some std error') }) })
e02e3a49e11ea33bc78caf18fb6c5c93a09f35dd
TypeScript
green-fox-academy/jnsmtnr
/week-03/day-2/print-each-line.ts
3.078125
3
'use strict'; export { } declare function require(path: string): any; const fs = require('fs'); try { let fileContent = fs.readFileSync('my-file.txt', 'utf-8'); console.log(fileContent); } catch(err) { console.log('Unable to read file: my-file.txt'); } // Write a program that opens a file called 'my-file.txt', then prints // each of lines form the file. // If the program is unable to read the file (for example it does not exists), // then it should print an error message like: 'Unable to read file: my-file.txt'
5660a715c49237d82fd2572c4f77ee2746b3835e
TypeScript
Mayssa1000/mobius-viewer-dev-0-7
/src/assets/core/inline/_set.ts
3.3125
3
/** * Set functions for working with sets, using lists as a data structure. Does not modify input list. */ import * as Mathjs from 'mathjs'; /** * Generates a list of unique items. * @param list */ export function setMake(debug: boolean, list: any[]): any[] { return Array.from(new Set(list)); } /** * Generates a list of unique items from the union of the two input lists. * @param list1 * @param list2 */ export function setUni(debug: boolean, list1: any[], list2: any[]): any[] { return Mathjs.setUnion(list1, list2); } /** * Generates a list of unique items from the intersection of the two input lists. * @param list1 * @param list2 */ export function setInt(debug: boolean, list1: any[], list2: any[]): any[] { return Mathjs.setIntersect(list1, list2); } /** * Generates a list of unique items from the difference of the two input lists. * @param list1 * @param list2 */ export function setDif(debug: boolean, list1: any[], list2: any[]): any[] { return Mathjs.setDifference(list1, list2); }
2f149580ef05ec186cbf0271de8f4e93b346649b
TypeScript
echovijaypatel/epam-angular-task
/my-app/src/app/state/auth.reducer.ts
2.828125
3
import { User } from '../models/user'; import * as AuthActions from './auth.actions'; export const initialUserState: User = { id: null, name: null, login: null, password: null, fakeToken: null, token: null, }; export interface AuthState { isAuthenticated: boolean; user: User | null; errorMessage: string | null; } export const initialState: AuthState = { isAuthenticated: false, errorMessage: '', user: initialUserState, }; export function authReducer( state: AuthState = initialState, action: AuthActions.Actions ) { switch (action.type) { case AuthActions.AUTH_LOGIN_SUCCESS: state = action.payload; return state; case AuthActions.SET_AUTH_INFO: state = action.payload; return state; case AuthActions.AUTH_LOGIN_FAIL: state = initialState; return state; case AuthActions.REMOVE_AUTH_INFO: state = initialState; return state; default: { return state; } } }
847c0f68fd6685df9762e5c192c7d02bfac0f8f6
TypeScript
roberta-fiume/angular-directives
/src/app/unless.directive.ts
2.53125
3
import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core'; @Directive({ selector: '[appUnless]' }) export class UnlessDirective { // the setter is a method of the property and it gets executed whenever the property changes and it changes outside of this directive so // whenever the condition we pass changes or some parameters of this condition. @Input() set appUnless(condition: boolean) { if(!condition) { this.vcRef.createEmbeddedView(this.templateRef); } else { this.vcRef.clear(); } } constructor(private templateRef: TemplateRef<any>, private vcRef: ViewContainerRef) { } }
cb6eec20cb583c88c5a4fda2efa49c812e13d431
TypeScript
fluffynuts/zarro
/tests/gulp-tasks/modules/create-temp-file.spec.ts
2.578125
3
import "expect-even-more-jest"; import { folderExists, mkdir, readTextFile } from "yafs"; import { faker } from "@faker-js/faker"; import { Sandbox } from "filesystem-sandbox"; describe(`create-temp-file`, () => { const createTempFile = requireModule<CreateTempFile>("create-temp-file"), os = require("os"), isWindows = os.platform() === "win32", tempDir = isWindows ? resolveFirstEnvVarFolder("TEMP", "TMP") : "/tmp"; describe(`when no contents provided`, () => { it(`should create a temporary file with no contents`, async () => { // Arrange // Act const sut = await create(); // Assert expect(sut.path) .toBeFile(); const contents = await readTextFile(sut.path); expect(contents) .toBeEmptyString(); sut.destroy(); expect(sut.path) .not.toBeFile(); }); }); describe(`when contents provided`, () => { it(`should create the temp file with contents`, async () => { // Arrange // Act const expected = faker.word.words(), sut = await create(expected); // Assert expect(sut.path) .toBeFile(); const contents = await readTextFile(sut.path); expect(contents) .toEqual(expected); sut.destroy(); expect(sut.path) .not.toBeFile(); }); }); describe(`when target folder is provided`, () => { it(`should use it`, async () => { // Arrange const sandbox = await Sandbox.create(), expected = faker.word.words(), target = sandbox.fullPathFor(faker.word.sample()), sut = await create(expected, target); // Act expect(sut.path) .toBeFile(); expect(sut.path) .toEqual(target); const contents = await readTextFile(sut.path); expect(contents) .toEqual(expected); sut.destroy(); expect(sut.path) .not.toBeFile(); // Assert }); afterEach(async () => { await Sandbox.destroyAll(); }); }); async function create( contents?: string | Buffer, at?: string ): Promise<TempFile> { return createTempFile( contents, at ); } async function resolveFirstEnvVarFolder(...vars: string[]): Promise<string> { const firstDefined = vars.reduce((acc: Optional<string>, cur: string) => { if (acc) { return acc; } if (!!process.env[cur]) { return process.env[cur]; } return undefined; }, undefined); if (!firstDefined) { throw new Error(`Can't find defined env var amongst: '${ vars }'`); } if (!await folderExists(firstDefined)) { await mkdir(firstDefined); } return firstDefined; } });
f3fe1698bad1f2ea860e2b6fcda52c65e068adab
TypeScript
future4code/dumont-LAMA10
/lama-template/src/controller/ShowController.ts
2.78125
3
import { Request, Response } from "express"; import { ShowInputDTO } from "../business/entities/Show"; import { Authenticator } from "../business/services/Authenticator"; import { IdGenerator } from "../business/services/IdGenerator"; import { ShowBusiness } from "../business/ShowBusiness"; import { ShowDatabase } from "../data/ShowDatabase"; const showBusiness = new ShowBusiness( new IdGenerator(), new Authenticator(), new ShowDatabase() ) export class ShowController { public createShow = async (req: Request, res: Response): Promise<void> => { try { const token: string = req.headers.authorization as string const input: ShowInputDTO = { bandId: req.body.bandId, weekDay: req.body.weekDay, startTime: req.body.startTime, endTime: req.body.endTime, token: token } await showBusiness.createShow(input) res.status(201).send({ message: "Show created" }) } catch (error) { res .status(error.statusCode || 400) .send({ error: error.message }) } } public getShowByDay = async (req: Request, res: Response): Promise<void> => { try { const day = String(req.query.day).toUpperCase(); const result = await showBusiness.getShowByDay(day); res.status(200).send({ result }) } catch (error) { res .status(error.statusCode || 400) .send({ error: error.message }) } } }
5595543043d2c5ee5c3f2a7d005a2129fc0a4ee5
TypeScript
leon740727/eth-agent
/example/client.ts
2.703125
3
import { w3cwebsocket as W3CWebSocket } from 'websocket'; import { ActionRequest, EventsRequest, Result, Event, Json } from '../index'; import { EventListener } from '../m/utils'; import EventStream from '../m/event-stream'; function connect (url: string, subprotocol: string): Promise<W3CWebSocket> { var conn = new W3CWebSocket(url, subprotocol); conn.onerror = () => { throw new Error('w3cwebsocket error'); }; return new Promise((resolve, reject) => { conn.onopen = () => { resolve(conn); } }); } class EventConnection { private conn: W3CWebSocket; private handlerOf: {[event: string]: (event: Event) => void} = {}; private eventStream = new EventStream<Json>(e => 'm'); connect (url: string): Promise<void> { return connect(url, '') .then(conn => { this.conn = conn; this.conn.onmessage = e => this.eventStream.trigger(JSON.parse(e.data)); }); } close () { this.conn.close(); } async setListeners (listeners: {event: string, handler: EventListener<Event>}[]): Promise<Result.Type<string[]>> { listeners.forEach(l => this.handlerOf[l.event] = l.handler); const req: EventsRequest = { type: 'EventsRequest', events: listeners.map(l => l.event), lastEventId: null, } this.conn.send(JSON.stringify(req)); const res = await this.eventStream.waitFor('m') as Result.Type<string[]>; this.eventStream.on('m', e => this.handlerOf[(e as any as Event).event](e as any)) return res; } } function exec (command: string, args: Json[]): Promise<Result.Type<Json>> { return connect(agentUrl, '') .then(conn => { const req: ActionRequest = { type: 'ActionRequest', command, arguments: args, } conn.send(JSON.stringify(req)); return new Promise<Result.Type<Json>>((resolve, reject) => { conn.onmessage = e => { const result = JSON.parse(e.data) as Result.Type<Json>; conn.close(); resolve(result); } }); }); } const agentUrl = 'ws://localhost:8080/'; const ec = new EventConnection(); ec.connect(agentUrl) .then(_ => { ec.setListeners([{event: 'add', handler: e => console.log(`event: `, e)}]) .then(res => console.log(`setListeners: `, res)); }); exec('add', [27]).then(result => console.log(`exec: `, result));
687872abd50dc4100db105da826caf77c5e4af95
TypeScript
tntcomputers/cnds
/Plugins/Lpp.Dns.General.Metadata/Content/ViewModels/Terms/DateRange.ts
2.578125
3
/// <reference path="../../../../../Lpp.Mvc.Composition/Lpp.Mvc.Boilerplate/jsBootstrap.d.ts" /> /// <reference path="../../Models/Terms.ts" /> /// <reference path="../../ViewModels/Terms.ts" /> module RequestCriteriaViewModels { export class DateRangeTerm extends RequestCriteriaViewModels.Term { public Title: KnockoutObservable<string>; public StartDate: KnockoutObservable<Date>; public EndDate: KnockoutObservable<Date>; public DateRangeTermType: KnockoutObservable<RequestCriteriaModels.DateRangeTermTypes>; constructor(dateRangeData: RequestCriteriaModels.IDateRangeTermData) { super(RequestCriteriaModels.TermTypes.DateRangeTerm); var start = null; if (dateRangeData.StartDate && dateRangeData.StartDate != null) { start = moment.utc(dateRangeData.StartDate).local().toDate(); } var end = null; if (dateRangeData.EndDate && dateRangeData.EndDate != null) { end = moment.utc(dateRangeData.EndDate).local().toDate(); } this.Title = ko.observable(dateRangeData.Title); this.StartDate = ko.observable(start); this.EndDate = ko.observable(end); this.DateRangeTermType = ko.observable(dateRangeData.DateRangeTermType); super.subscribeObservables(); } public toData(): RequestCriteriaModels.ITermData { var superdata = super.toData(); var data: RequestCriteriaModels.IDateRangeTermData = { TermType: superdata.TermType, Title: this.Title(), StartDate: this.StartDate(), EndDate: this.EndDate(), DateRangeTermType: this.DateRangeTermType() }; return data; } public static ObservationPeriod(): DateRangeTerm { return new DateRangeTerm({ Title: "Observation Period", TermType: RequestCriteriaModels.TermTypes.DateRangeTerm, StartDate: null, EndDate: null, DateRangeTermType: RequestCriteriaModels.DateRangeTermTypes.ObservationPeriod }); } public static SubmitDateRange(): DateRangeTerm { return new DateRangeTerm({ Title: "Submit Date Range", TermType: RequestCriteriaModels.TermTypes.DateRangeTerm, StartDate: null, EndDate: null, DateRangeTermType: RequestCriteriaModels.DateRangeTermTypes.SubmitDateRange }); } } }
34452953592491d77a22a82028a08c4a9e7b3472
TypeScript
mastong/shapes-game
/app/app.component.ts
2.625
3
import { Component } from '@angular/core'; import { CircleModel } from './circle.model'; import { SquareModel } from './square.model'; import { ShapeModel } from './shape.model'; import { ShapeService } from './shape.service'; import { Utils } from './utils'; import { ToastsManager } from 'ng2-toastr/ng2-toastr'; @Component({ selector: 'my-app', template: ` <div class=".container-fluid"> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4"> <h1 class="title">Let's play with shapes!</h1> </div> <div class="col-md-4"></div> </div> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4"> <svg attr.width="{{canvasWidth}}" attr.height="{{canvasHeight}}" class="board"> <g *ngFor="let shape of shapes"> <g [ngSwitch]="shape.getType()"> <g *ngSwitchCase="'circle'" circleShape [circleData]="shape" (onDivide)="divide($event)"></g> <g *ngSwitchCase="'square'" squareShape [squareData]="shape" (onDivide)="divide($event)"></g> <g *ngSwitchDefault><!-- Shape type unknow --></g> </g> </g> </svg> </div> <div class="col-md-4"></div> </div> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4"> <!-- TODO Should use the canvasWidth variable, but angular won't let me do it :( --> <div class="gameData" style="width: 500;"> <span>Level : {{level}}</span> <span>Score : {{score}}</span> <span>Timer : {{timer}}</span> <button class="btn btn-success" type="button" (click)="launchNewGame();">Launch a new game!</button> </div> </div> <div class="col-md-4"></div> </div> </div> `, providers: [ShapeService] }) export class AppComponent { /** * The timer duration */ private timer: number; /** * The technical id used to stop a timer once it's started */ private timerThreadId: any; /** * all the shape types handled by the application */ private shapeTypes: Array<string> = ['circle', 'square']; /** * the current shape type that will be added on the add button click * Not sure if this property will be kept in the future, when the shapes will be added in a more automatic way */ private currentShapeType: string; /** * all the shapes currently on the board */ private shapes: ShapeModel[] = []; /** * Indicate if the game is currently on or not. */ private running: boolean = false; /** * The current score */ private score: number = 0; /* * The current level. * Each level increase the difficulty */ private level: number = 1; static parameters = [ToastsManager, 'canvasWidth', 'canvasHeight', ShapeService]; constructor(public toastr: ToastsManager, private canvasWidth: number, private canvasHeight: number, private shapeService: ShapeService){ } public ngOnInit() { //this.running = true; this.moveShapes(); } /** * Add a new shape to the board, based on the type selected in the select. * Only present during the dev, but will be removed/replaced later by some kind of automatic process */ public add(): void{ if(!this.currentShapeType){ console.warn("No shape type selected..") return; } this.shapes.push(this.shapeService.generateShape(this.currentShapeType)); } /** * Update the position of all the shapes on the board. * This method will be called at each navigator refresh */ public moveShapes(){ if(this.running){ this.shapes.forEach((shape: ShapeModel) =>{ shape.move(this.canvasWidth, this.canvasHeight); }); } requestAnimationFrame(()=> this.moveShapes()); } /** * Remove the given shape from the board, and replace it with the result of it's division, if any * @param shape The shape to remove from the board and divide */ public divide(shape: ShapeModel): void{ if(this.running){ let newShapes: ShapeModel[] = this.shapeService.divide(shape); let index: number = this.shapes.indexOf(shape); this.shapes.splice(index, 1); newShapes.forEach((shape: ShapeModel) =>{ this.shapes.push(shape); }); this.score += shape.getScoreValue(); if(this.shapes.length === 0){ this.level++; this.initNewRound(this.level); } } } /** * Start a game by : * - resetting the score to 0 * - resetting the timer * - clearing the board * - generating a new set of shapes */ public launchNewGame(){ this.score = 0; this.level = 1; this.initNewRound(this.level); } /** * Init a new round for a given level. * Reset the timer and generate a new set of shapes. * The higher the level, the more shapes are generated. */ private initNewRound(level: number){ this.shapes = []; for(let i: number = 0; i < level; i++){ this.shapes.push(this.shapeService.generateShape(this.getRandomShapeType())); } this.timer = 30+(level-1)*5; if(this.timerThreadId){ clearInterval(this.timerThreadId); } this.timerThreadId = setInterval(this.decreaseTimer, 1000, this); this.running = true; this.moveShapes(); } /** * Decrement the timer by one. Must be called every second. * When the timer reach 0, end the game * @param context The object representing the game */ private decreaseTimer(context: AppComponent): void{ console.log("decreaseTimer"); context.timer--; if(context.timer === 0){ context.running = false; clearInterval(context.timerThreadId); context.toastr.success("Your score : "+context.score, "Game Over"); } } /** * Return a shape type randomly chosen from all the currently available type * @returns the chosen shape type name */ private getRandomShapeType(): string{ return this.shapeTypes[Utils.randInt(0, this.shapeTypes.length-1)]; } //************** Debug functions, not used ***************************** private debugShapes(){ console.log("Shapes :"); this.shapes.forEach((shape: ShapeModel)=>{ console.log(shape); }); } public toggleRunning(){ this.running = !this.running; if(this.running){ requestAnimationFrame(()=> this.moveShapes()); } } //********************************************************************** }
6e1e91d5f39b769ee3a3ab46f996cdcfc65ac94f
TypeScript
vadistic/training-exercises
/ds/utils/random.ts
2.609375
3
export const randomInt = (min = -100, max = 100): number => { return Math.floor(Math.random() * (max - min)) + min }
c64ec53b2708f06230febfb6187866593b8fcfc1
TypeScript
gallofeliz/node-camera-recorder
/src/onvif-camera.ts
2.5625
3
import { Camera } from '.' import { EventEmitter } from 'events' import * as url from 'url' import { Cam as OnvifModuleCamera, CamOpts as OnvifModuleCameraOptions } from 'onvif' type OnvifCameraUriOptions = { uri: string, name?: string } type OnvifCameraOptsForOnvifModule = { name?: string } & OnvifModuleCameraOptions type OnvifCameraOptions = OnvifCameraOptsForOnvifModule | OnvifCameraUriOptions const isOnvifCameraUriOptions = (opts: OnvifCameraOptions): opts is OnvifCameraUriOptions => { return typeof (opts as OnvifCameraUriOptions).uri === 'string' } export default class OnvifCamera extends EventEmitter implements Camera { protected onvifCamOps: OnvifModuleCameraOptions protected name: string protected onvifCamPromise: Promise<OnvifModuleCamera> | undefined public constructor(uri: string) public constructor(opts: OnvifCameraOptions) public constructor(uriOrOpts: string | OnvifCameraOptions) { super() let opts = typeof uriOrOpts === 'string' ? { uri: uriOrOpts } : uriOrOpts if (isOnvifCameraUriOptions(opts)) { const {hostname, port, username, password} = new url.URL(`onvif://${opts.uri}`) opts = { ...opts, hostname, port: parseInt(port, 10), username, password } } this.name = opts.name || opts.hostname this.onvifCamOps = opts } protected async connect(): Promise<OnvifModuleCamera> { if (!this.onvifCamPromise) { this.onvifCamPromise = new Promise((resolve, reject) => { const onvifCam = new OnvifModuleCamera(this.onvifCamOps, (err) => { if(err) { onvifCam.removeAllListeners('rawRequest') onvifCam.removeAllListeners('rawResponse') const correctStackedError = new Error('Onvif Connection Error : ' + err.message) // Avoid Camera locking delete this.onvifCamPromise return reject(correctStackedError) } resolve(onvifCam) }) onvifCam.on('rawResponse', (response) => this.emit('onvifResponse', response) ) onvifCam.on('rawRequest', (request) => this.emit('onvifRequest', request.replace(/(<Password>|<Password .*>)([^<]+)(<\/Password>)/g, '$1***$3')) ) }) } return this.onvifCamPromise } public async getStreamUri(profileToken?: string | null): Promise<{uri: string}> { const onvifCam = await this.connect() return new Promise((resolve, reject) => { onvifCam.getStreamUri({profileToken}, (err, data) => { if (err) { const correctStackedError = new Error('Onvif getStreamUri Error : ' + err.message) return reject(correctStackedError) } resolve(data) }) }) } public async getSnapshotUri(profileToken?: string | null): Promise<{uri: string}> { const onvifCam = await this.connect() return new Promise((resolve, reject) => { onvifCam.getSnapshotUri({profileToken}, (err, data) => { if (err) { const correctStackedError = new Error('Onvif getSnapshotUri Error : ' + err.message) return reject(correctStackedError) } resolve(data) }) }) } public async getProfiles(): Promise<Array<{$: {token: string}}>> { const onvifCam = await this.connect() return onvifCam.profiles } public getName(): string { return this.name } }
ed21910522a2f35d3b2162d686199849ec6aac99
TypeScript
dcmox/moxyscript-conditions
/tests/moxy-conditions.test.ts
2.734375
3
import assert from 'assert' import sinon from 'sinon' import * as testSuite from '../moxy-conditions' import { demographics } from './test-data' describe('Moxy Conditions test suite', () => { it('Should not console.log (Sanitize Input)', () => { const conditions = [ { // Injection Example key: 'country', operator: 'eq', value: "US') && console.error('***unsanitized input***') && ('1' === '1", }, ] const spyMockLog = sinon.spy(console, 'error') const conditionsForOffer = testSuite.conditionsToString(conditions) testSuite.itemsMatchConditions(demographics.users, conditionsForOffer) sinon.assert.notCalled(spyMockLog) spyMockLog.restore() }) it('Conditions less than and equal to should match case.', () => { const conditions = [ { key: 'age', operator: 'lt', value: 20, }, { key: 'alcohol_use', operator: 'eq', value: true, }, ] const conditionsForOffer = testSuite.conditionsToString(conditions) const result = testSuite.itemsMatchConditions( demographics.users, conditionsForOffer, ) assert.equal(result.length, 1, 'Only one item should match') assert.equal(result[0].id, 1937125, 'ID does not match!') }) it('Should test conditions gt and between and match case while two should fail.', () => { const conditions = [ { key: 'registered', operator: 'gt', value: new Date('2019-10-05'), }, { key: 'registered', operator: 'between', value: new Date('2019-10-07'), valueB: new Date('2019-10-10'), }, ] const conditionsForOffer = testSuite.conditionsToString(conditions) let result = testSuite.itemsMatchConditions( demographics.users, conditionsForOffer, ) assert.equal(result.length, 1, 'Only one item should match') assert.equal(result[0].id, 1937126, 'ID does not match!') result = testSuite.itemsFailConditions( demographics.users, conditionsForOffer, ) assert.equal(result.length, 2, 'Two items should fail conditions') }) it('Should detect invalid key', () => { const conditions = [ { key: "`console.log('test') && (1 ", operator: 'eq', value: 1, }, ] const result = testSuite.conditionsValidate(conditions) if (typeof result !== 'boolean') { assert.equal(result[0].reason, 'Key contains unsafe character') } assert.notEqual( result, true, 'Passing invalid key should not evaluate to true', ) }) it('Should detect invalid value', () => { const conditions = [ { key: 'age', operator: 'eq', value: "`console.log('test')`", }, ] const result = testSuite.conditionsValidate(conditions) if (typeof result !== 'boolean') { assert.equal(result[0].reason, 'Value contains unsafe character') } assert.notEqual( result, true, 'Passing invalid value should not evaluate to true', ) }) it('Should detect invalid operators and invalid date comparisons', () => { const conditions = [ { key: 'registered', operator: 'blah', value: new Date('2019-10-05'), }, { key: 'registered', operator: 'between', value: new Date('2019-10-05'), valueB: 'blah', }, { key: 'registered', operator: 'between', value: 'blah', valueB: 'blah2', }, ] const result = testSuite.conditionsValidate(conditions) if (typeof result !== 'boolean') { assert.equal(result[0].reason, 'Operator is not valid.') assert.equal(result[1].reason, 'Both values must be of same type') assert.equal( result[2].reason, 'Between operator can only be used on Dates | numbers', ) } assert.notEqual( result, true, 'Passing invalid operator should not evaluate to true', ) }) it('Should detect invalid string and string comparisons', () => { const conditions = [ { key: 'age', operator: 'gt', value: true, }, { key: 'age', operator: 'lt', value: true, }, { key: 'age', operator: 'gt', value: 'blah', }, ] const result = testSuite.conditionsValidate(conditions) if (typeof result !== 'boolean') { assert.equal( result[0].reason, 'boolean comparisons must only be eq | neq', ) assert.equal( result[1].reason, 'boolean comparisons must only be eq | neq', ) assert.equal( result[2].reason, 'string comparisons must only be eq | neq', ) } assert.notEqual( result, true, 'Passing invalid operator should not evaluate to true', ) }) }) // { // key: 'age', // operator: 'lt', // value: 20, // }, // { // key: 'alcohol_use', // operator: 'eq', // value: true, // },
60111af9d2545e189ce07951958336740602ed39
TypeScript
markmehere/weather-app
/src/redux/actions/weather.ts
2.859375
3
import { GenericAction } from "../../types/GenericAction"; import { CityType } from "../../types/CityType"; import { WeatherDetails } from "../reducers/weather"; import { MetaWeatherResponse } from "../../types/MetaWeatherResponse"; import { GenericThunk } from "../../types/GenericThunk"; import { WeatherKind } from "../../types/WeatherKind"; import { fetchWeather } from "../fetch/weather"; export const GET_FORECAST = 'GET_FORECAST'; export const GET_FORECAST_SUCCESS = 'GET_FORECAST_SUCCESS'; export const GET_FORECAST_FAILURE = 'GET_FORECAST_FAILURE'; export const LOAD_MOCK_FORECAST = 'LOAD_MOCK_FORECAST'; export type GetForecastAction = GenericAction<CityType>; export type GetForecastSuccessAction = GenericAction<WeatherDetails>; export type GetForecastFailureAction = GenericAction<string>; export type LoadMockForecastAction = GenericAction<null>; export type GetForecastSuccessActionCreator = (data: MetaWeatherResponse, city: CityType) => GetForecastSuccessAction; export type GetForecastActionCreator = (city: CityType, callback?: () => void) => GenericThunk; export type LoadMockForcastGenerator = () => LoadMockForecastAction; const getForecastSuccess: GetForecastSuccessActionCreator = (data, city) => { return { type: GET_FORECAST_SUCCESS, payload: { city, forecast: data.consolidated_weather.map((day) => ({ max: day.max_temp, min: day.min_temp, kind: day.weather_state_abbr })) } }; } const getForecastFailure = (error: string) => { return { type: GET_FORECAST_FAILURE, payload: error }; } const hash = (str: string) => { let hash = 0; [...(str as any)].forEach((c, i) => hash = i * 300 + str.charCodeAt(i)); return hash; }; export const fakeGetForecast: GetForecastActionCreator = (city) => { const cityHash = hash(city.label); return (dispatch) => { dispatch({ type: GET_FORECAST, payload: city }); setTimeout(() => { dispatch({ type: GET_FORECAST_SUCCESS, payload: { city, forecast: [6, 3, -2, 4, 1, 8].map((day) => { const max = (cityHash + day) % 38; let choice = [ WeatherKind.Clear, WeatherKind.HeavyCloud, WeatherKind.LightCloud ]; if (max < 22) choice = [ WeatherKind.HeavyRain, WeatherKind.LightRain, WeatherKind.Showers ]; if (max < 10) choice = [ WeatherKind.Snow, WeatherKind.Sleet, WeatherKind.Hail ]; return { max: max, min: Math.min(max - 3, (cityHash - day) % 32), kind: choice[(cityHash + day) % 3] }; }) } }) }, 1000) } } export const getForecast: GetForecastActionCreator = (city, callback) => { return (dispatch) => { dispatch({ type: GET_FORECAST, payload: city }); return fetchWeather(city).then( (response: Response) => { if (response.ok) { const promise = response.json().then( (data: MetaWeatherResponse) => dispatch(getForecastSuccess(data, city)), (error: TypeError) => dispatch(getForecastFailure(error.message)) ); if (callback) promise.then(callback); } else { dispatch(getForecastFailure(`${response.status} - ${response.statusText}`)); } }, (error: TypeError) => dispatch(getForecastFailure(error.message)) ); } } export const loadMockForecast: LoadMockForcastGenerator = () => ({ type: LOAD_MOCK_FORECAST, payload: null });
57a7945a431c77ee32a40c50b68a231a06a610b8
TypeScript
omarandstuff/desplega-api
/src/Printer.ts
3.453125
3
import { RowElement } from './Printer.types' /** * Advanced terminal printer * */ export default class Printer { /** * Will draw a single terminal row adjusting text if necesary * * @param {Object} elements array of line seccions to draw * options are: * text: actual text to draw * style: chalk function to format text * fit: bool value to fit this element in the available space * blank: bool value to only draw a space between text elements * symbol: value to use instead of spaces when the element is clank * * @param {Bool} inline Keep drawing the line in the same terminal line * */ public drawRow(elements: RowElement[], inline?: boolean): void { const terminalWidth: number = process.stdout.columns const processedElements = this.fitElements(elements, terminalWidth) const fixedWidth = this.calculateFixedElementsWidth(processedElements) const availableWidth = Math.max(0, terminalWidth - fixedWidth) const rendered = this.buildAndFormat(processedElements, availableWidth) if (inline) { process.stdout.write(`${rendered}\r`) } else { process.stdout.write(`${' '.repeat(terminalWidth)}\r`) console.log(rendered) } } /** * Cleans the curren teminal line in case the teminal draw an inline raw ans * prints a string adding a tab at the begining. * * @param {String} string actual string to draw. * * @param {Number} tabSize How many spaces to draw before the string. * */ public draw(string: string, tabSize = 0): void { const terminalWidth = process.stdout.columns const finalString = string .replace(/(\r|[\n]$)/g, '') .split('\n') .map(line => { return `${' '.repeat(tabSize)}${line}` }) .join('\n') process.stdout.write(`${' '.repeat(terminalWidth)}\r`) console.log(finalString) } private applyFormat(element: RowElement, optionalText?: string, raw?: boolean): string { if (element.style && !raw) { return element.style(optionalText || element.text) } return optionalText || element.text } private buildAndFormat(elements: RowElement[], availableWidth: number, raw?: boolean): string { const dynamicCount = this.calculateDynamicCount(elements) const widthPerDynamicElement = Math.floor(availableWidth / dynamicCount) const specialDynamic = widthPerDynamicElement === 0 let availableDynamixSpace = availableWidth let uncalculateDynamicSpace = availableWidth - widthPerDynamicElement * dynamicCount return elements .map((element: RowElement): string => { let rendered: string if (element.blank) { if (specialDynamic) { if (availableDynamixSpace) { availableDynamixSpace-- rendered = this.applyFormat(element, ' ') } } else { const extraSpace = uncalculateDynamicSpace-- > 0 ? 1 : 0 const blank = (element.symbol || ' ').repeat(widthPerDynamicElement + extraSpace) rendered = this.applyFormat(element, blank, raw) } } else if (element.fit) { if (specialDynamic) { if (availableDynamixSpace) { availableDynamixSpace-- rendered = this.applyFormat(element, element.text[0], raw) } } else { const extraSpace = uncalculateDynamicSpace-- > 0 ? 1 : 0 const finalWith = widthPerDynamicElement + extraSpace if (element.text.length > finalWith) { const exceed = element.text.length - finalWith const cutPosition = element.text.length - exceed const addDots = cutPosition - 3 > 0 const extraCut = addDots ? 3 : 0 const extraDots = addDots ? '...' : '' const cuttedText = element.text.substring(0, cutPosition - extraCut) rendered = this.applyFormat(element, `${cuttedText}${extraDots}`, raw) } else { const lack = finalWith - element.text.length const amplifiedText = `${element.text}${' '.repeat(lack)}` rendered = this.applyFormat(element, amplifiedText, raw) } } } else { rendered = this.applyFormat(element) } return rendered }) .join('') } private calculateDynamicCount(elements: RowElement[], onlyBlanks?: boolean): number { return elements.reduce((currentCount, element) => { if ((element.fit && !onlyBlanks) || element.blank) { return currentCount + 1 } return currentCount }, 0) } private calculateFixedElementsWidth(elements: RowElement[]): number { return elements.reduce((currentWidth, element) => { if (!element.fit && !element.blank) { return currentWidth + element.text.length } return currentWidth }, 0) } private fitElements(elements: RowElement[], targetWidth: number): RowElement[] { const fixedWidth = this.calculateFixedElementsWidth(elements) const availableWidth = Math.max(0, targetWidth - fixedWidth) const dynamicCount = this.calculateDynamicCount(elements) const widthPerDynamicElement = Math.floor(availableWidth / dynamicCount) const removeDynamics = fixedWidth >= targetWidth let currentWidth = 0 return elements .map( (element: RowElement): RowElement => { if (currentWidth < targetWidth) { if (element.fit || element.blank) { if (!removeDynamics) { currentWidth += widthPerDynamicElement return element } } else { currentWidth += element.text.length if (currentWidth >= targetWidth) { const exceed = currentWidth - targetWidth const cutPosition = element.text.length - exceed return { ...element, text: element.text.substring(0, cutPosition) } } return element } } } ) .filter(element => element) } }
c1d3488b9e2aace119be0513de1cb5a474263256
TypeScript
zshannon/vite-plugin-bugsnag
/src/types.ts
2.640625
3
/** * Describes the build you are reporting to Bugsnag. */ export interface Build { /** * Your Bugsnag API key [required] */ apiKey: string /** * The version of the application you are building [required] */ appVersion: string /** * 'production', 'staging' etc. Leave blank if this build can be released to different releaseStages. */ releaseStage?: string /** * An object describing the source control of the build. * * If not specified, the module will attempt to detect source control information from .git, .hg and the nearest package.json */ sourceControl?: object /** * The application you are using to manage your source code repository */ provider?: 'github' | 'github-enterprise' | 'gitlab' | 'gitlab-onpremise' | 'bitbucket' | 'bitbucket-server' /** * A URL (git/ssh/https) pointing to the repository, or webpage representing the repository */ repository?: string /** * The unique identifier for the commit (e.g. git SHA) */ revision?: string /** * The name of the person/machine that created this build. * * Defaults to the result of the `whoami` command. */ builderName?: string /** * Automatically associate this build with any new error events and sessions * that are received for the releaseStage until a subsequent build notification is received. * * If this is set to true and no releaseStage is provided the build will be applied to 'production'. */ autoAssignRelease?: boolean } export interface ReportBuildOptions { /** * The minimum severity of log to output. * @default 'warn' */ logLevel?: 'debug' | 'info' | 'warn' | 'error' /** * Provide a different logger object `{ debug, info, warn, error }`. */ logger?: object /** * The path to search for source control info. * @default process.cwd() */ path?: string /** * Post the build payload to a URL other than the default. * @default 'https://build.bugsnag.com' */ endpoint?: string } export interface BuildReporterConfig extends Build, ReportBuildOptions { /** * Whether to send the build information to Bugsnag. * * @default `true` when building in `production` mode. * @default `false` when building in `development` mode. */ sendReport?: boolean } /** * Describes a sourcemap file for one of the built files. */ export interface Sourcemap { url: string source: string map: string } export interface SourceMapUploaderConfig { /** * Your Bugsnag API key [required] */ apiKey: string /** * The path to your bundled assets (as the browser will see them). * * This option must either be provided here, or as base in your Vite config. */ base?: string /** * The version of the application you are building. * * Defaults to the version set in your project's package.json file, if one is specified there. */ appVersion?: string /** * The codeBundleId (e.g. for NativeScript projects) */ codeBundleId?: string /** * Whether you want to overwrite previously uploaded sourcemaps */ overwrite?: boolean /** * Post the build payload to a URL other than the default. * @default 'https://upload.bugsnag.com' */ endpoint?: string /** * A list of bundle file extensions which shouldn't be uploaded. * * @default ['.css'] */ ignoredBundleExtensions?: string[] }
d284304d3140c258dc9f33f3c6117df9f204c46f
TypeScript
draity/exiftool-vendored.js
/src/WriteTask.ts
2.609375
3
import * as _path from "path" import { Tags, WriteTags } from "./ExifTool" import { ExifToolTask } from "./ExifToolTask" import { htmlEncode } from "./String" const successRE = /1 image files? updated/ // See https://sno.phy.queensu.ca/%7Ephil/exiftool/faq.html#Q10 // (`-charset utf8` is set by default) const utfCharsetArgs = [ "-charset", "filename=utf8", "-codedcharacterset=utf8", "-E" ] function enc(value: any): string { return typeof value == "number" ? value.toString() : htmlEncode(String(value)) } export class WriteTask extends ExifToolTask<void> { private constructor(readonly sourceFile: string, readonly args: string[]) { super(args) } static for( filename: string, tags: WriteTags, optionalArgs: string[] = [] ): WriteTask { const sourceFile = _path.resolve(filename) const args: string[] = [...utfCharsetArgs] Object.keys(tags) .filter(k => typeof k === "string" && tags.propertyIsEnumerable(k)) .forEach((key: keyof Tags) => { const value = tags[key] if (Array.isArray(value)) { ;(value as any[]).forEach(ea => args.push(`-${key}=${enc(ea)}`)) } else { args.push(`-${key}=${enc(value)}`) } }) optionalArgs.forEach(ea => args.push(ea)) args.push(sourceFile) return new WriteTask(sourceFile, args) } toString(): string { return "WriteTask(" + this.sourceFile + ")" } protected parse(data: string, err: Error): void { if (err) throw err if (this.errors.length > 0) throw new Error(this.errors.join(";")) data = data.trim() if (successRE.exec(data) != null) { return } else { throw new Error("No success message: " + data) } } }
5c3f49dde05727fcc4bdd154263233e22c499715
TypeScript
piesome/valta
/src/Common/Types/BuildingTypes.ts
2.71875
3
import {BuildingType, TypeManager} from "."; export class BuildingTypes extends TypeManager<BuildingType> { constructor() { super(); this.typeName = "building"; } public transformRaw(data: any): BuildingType { return new BuildingType( data.name, data.cost, ); } }
7df7129a401f2a9eaef5d1cdf38ea066f7641b7f
TypeScript
Choheeseok/citrus-market
/src/libs/user/signup.check.ts
2.515625
3
import UserWriteForm from "../../models/user/user.signup"; import UserModel from "../../models/user/user"; const checkOmission = (data: UserWriteForm): string => { let str: string = ``; if (!data.email) str += `'이메일'`; if (!data.password) str += `'비밀번호'`; if (!data.confirmPassword) str += `'비밀번호 확인'`; if (!data.nickname) str += `'닉네임'`; return str; }; const checkSameData = async (data: UserWriteForm): Promise<string> => { let str: string = ``; const sameEmailData = await UserModel.findOne({ email: data.email }); if (sameEmailData) str += `'${data.email}'`; const sameNicknameData = await UserModel.findOne({ email: data.email }); if (sameNicknameData) str += `'${data.nickname}'`; return str; }; const checkConfirmPassword = (data: UserWriteForm): string => { let str: string = ``; if (data.password !== data.confirmPassword) str += `'비밀번호'`; return str; }; export = { checkOmission, checkSameData, checkConfirmPassword };
4adebb426c70957d6101b2bae293fc7ad76efac6
TypeScript
vincentlaucsb/experiencer
/src/components/Helpers.test.ts
2.875
3
import { assignIds, process, arraysEqual } from "./Helpers"; import { BasicResumeNode } from "./utility/Types"; test('assignIDs Test', async () => { const node = { type: 'FlexibleRow', childNodes: [ { type: 'FlexibleColumn' }, { type: 'FlexibleColumn' } ] } as BasicResumeNode; // Assign unique IDs assignIds(node); // Test const topId = node['uuid']; expect(topId).toBeDefined(); // Test that IDs are unique expect(node.childNodes).toBeDefined(); if (node.childNodes) { node.childNodes.forEach( (child) => { expect(child['uuid']).not.toBe(topId); expect(child['uuid']).toBeDefined(); } ); expect(node.childNodes[0]['uuid']).not.toBe(node.childNodes[1]['uuid']); } }); test('Helpers Test', async () => { let left = [0, 1, 0]; let right = [0, 1, 1]; expect(arraysEqual(left, right)).toBeFalsy(); }); test('process Test', async () => { const textWithNdash = "January 2014 -- December 2016" expect(process(textWithNdash)).toBe("January 2014 \u2013 December 2016"); const textWithMdash = "January 2014 --- December 2016" expect(process(textWithMdash)).toBe("January 2014 \u2014 December 2016"); });
7c9ad6395623549c415d94a7899f3d1ad653344a
TypeScript
briebug/ngrx-auto-entity
/projects/ngrx-auto-entity/src/lib/selectors/selections.selectors.spec.ts
2.78125
3
import { mapToCurrentEntities, mapToCurrentEntitiesKeys, mapToCurrentEntity, mapToCurrentEntityKey } from './selections.selectors'; describe('mapToCurrentEntity', () => { it('should return undefined if no selections root', () => { const current = mapToCurrentEntity(undefined, undefined); expect(current).toBeUndefined(); }); it('should return undefined if no entities root', () => { const current = mapToCurrentEntity({}, undefined); expect(current).toBeUndefined(); }); it('should return undefined if empty root', () => { const current = mapToCurrentEntity({}, {}); expect(current).toBeUndefined(); }); it('should return undefined if no entity matching current entity key', () => { const current = mapToCurrentEntity({ currentEntityKey: 1 }, { 2: { id: 2 } }); expect(current).toBeUndefined(); }); it('should return entity matching current entity key', () => { const current = mapToCurrentEntity({ currentEntityKey: 2 }, { 2: { id: 2 } }); expect(current).toEqual({ id: 2 }); }); }); describe('mapToCurrentEntityKey', () => { it('should return undefined if no selections root', () => { const key = mapToCurrentEntityKey(undefined); expect(key).toBeUndefined(); }); it('should return undefined if enmpty selections root', () => { const key = mapToCurrentEntityKey({}); expect(key).toBeUndefined(); }); it('should return current entity key', () => { const key = mapToCurrentEntityKey({ currentEntityKey: 2 }); expect(key).toBe(2); }); }); describe('mapToCurrentEntities', () => { it('should return empty array if no selections root', () => { const current = mapToCurrentEntities(undefined, undefined); expect(current).toEqual([]); }); it('should return empty array if no entities root', () => { const current = mapToCurrentEntities({}, undefined); expect(current).toEqual([]); }); it('should return empty array if empty root', () => { const current = mapToCurrentEntities({}, {}); expect(current).toEqual([]); }); it('should return empty array if no entities matching current entity keys', () => { const current = mapToCurrentEntities( { currentEntitiesKeys: [1, 4, 6, 8, 9, 10] }, { 2: { id: 2 }, 3: { id: 3 }, 5: { id: 5 }, 7: { id: 7 }, 11: { id: 11 }, 13: { id: 13 } } ); expect(current).toEqual([]); }); it('should return entities matching current entity keys', () => { const current = mapToCurrentEntities( { currentEntitiesKeys: [2, 3, 5, 7, 11, 13] }, { 2: { id: 2 }, 3: { id: 3 }, 5: { id: 5 }, 7: { id: 7 }, 11: { id: 11 }, 13: { id: 13 } } ); expect(current).toEqual([{ id: 2 }, { id: 3 }, { id: 5 }, { id: 7 }, { id: 11 }, { id: 13 }]); }); }); describe('mapToCurrentEntitiesKeys', () => { it('should return empty array if no selections root', () => { const key = mapToCurrentEntitiesKeys(undefined); expect(key).toEqual([]); }); it('should return empty array if enmpty selections root', () => { const key = mapToCurrentEntitiesKeys({}); expect(key).toEqual([]); }); it('should return current entity keys', () => { const key = mapToCurrentEntitiesKeys({ currentEntitiesKeys: [2, 3, 5, 7, 11, 13] }); expect(key).toEqual([2, 3, 5, 7, 11, 13]); }); });
fef01602a4fa684caba8e5ff9113caee0f5bf506
TypeScript
SammyShehter/URL-shortener
/server/src/app.ts
2.546875
3
import * as dotenv from 'dotenv' import * as expressWinston from 'express-winston' import * as http from 'http' import * as winston from 'winston' import express from 'express' import cors from 'cors' import debug from 'debug' import { CommonRoutesConfig } from './routes/common/common.routes.config' import { UserRoutes } from './routes/users/users.routes.config' import { LinkRoutes } from './routes/links/links.routes.config' dotenv.config() const app: express.Application = express() const server: http.Server = http.createServer(app) const port: string = process.env.PORT const routes: Array<CommonRoutesConfig> = [] const debugLog: debug.IDebugger = debug('app') app.use(express.json()) app.use(cors()) // here we are preparing the expressWinston logging middleware configuration, // which will automatically log all HTTP requests handled by Express.js const loggerOptions: expressWinston.LoggerOptions = { transports: [new winston.transports.Console()], format: winston.format.combine( winston.format.json(), winston.format.prettyPrint(), winston.format.colorize({ all: true }) ), meta: true, msg: 'HTTP {{req.method}} {{req.url}}', expressFormat: true, colorize: false, ignoreRoute: function (req, res) { return false }, } const errorLoggerOptions: expressWinston.ErrorLoggerOptions = { transports: [new winston.transports.Console()], format: winston.format.combine( winston.format.prettyPrint(), winston.format.colorize({ all: true }), winston.format.json() ), } // initialize the logger with the above configuration app.use(expressWinston.logger(loggerOptions)) app.use(expressWinston.errorLogger(errorLoggerOptions)) // here we are crashing on unhandled errors and spitting out a stack trace, // but only when in debug mode if (process.env.DEBUG) { process.on('unhandledRejection', function (reason) { debugLog('Unhandled Rejection:', reason) process.exit(1) }) } else { loggerOptions.meta = false // when not debugging, make terse } // Creating instace of Routes routes.push(new UserRoutes(app)) routes.push(new LinkRoutes(app)) // Start server server.listen(port, () => { console.log(`Server started at port ${port}`) routes.forEach((route: CommonRoutesConfig) => { debugLog(`Routes configured for ${route.getName()}`) }) })
aae477b231ab69caa7e364ac5b414c792e5aebe5
TypeScript
jirkapok/GasPlanner
/projects/planner/src/app/shared/formatters.spec.ts
2.5625
3
import { DateFormats } from './formaters'; describe('Date formatters', () => { describe('Chart', () => { it('Shows only minutes for 3000 seconds', () => { const result = DateFormats.selectChartTimeFormat(300); expect(result).toEqual('%M:%S'); }); it('Shows also hours for 3600 seconds', () => { const result = DateFormats.selectChartTimeFormat(3600); expect(result).toEqual('%H:%M:%S'); }); }); describe('Table', () => { it('Shows only minutes as one number for 3000 seconds', () => { const result = DateFormats.selectTimeFormat(300); expect(result).toEqual('m:ss'); }); it('Shows also hours as one number for 3600 seconds', () => { const result = DateFormats.selectTimeFormat(3600); expect(result).toEqual('mm:ss'); }); }); });
bb1dfb038eddb48c4f04331569300e57914faf50
TypeScript
uStudioCompany/ts4ocds
/packages/ts4ocds/extensions/conversions/conversion.d.ts
3.046875
3
/** * @packageDocumentation * @module Conversions */ import type { Coefficient } from './coefficient'; /** * Conversion is used to describe conversions and its coefficients applicable * for specific value received for requirement or observation */ export interface Conversion { /** * An identifier for this conversion. */ id: string | number; /** * The free-text rationale of using of this conversion */ rationale?: string; /** * Free text description of this conversion could be shared here */ description?: string; /** * A list of applicable coefficients for this conversion */ coefficients: Coefficient[]; /** * The schema element that the conversion applies. * For example, the conversion may be defined against a requirement or against a metric. */ relatesTo?: 'requirement' | 'observation'; /** * Where 'relatesTo' is not empty this field must be populated with the id of the item in this tender section * which the conversion relates to. */ relatedItem?: string; } /** * Conversion is used to describe conversions and its coefficients applicable * for specific value received for requirement or observation */ export interface RelatedConversion extends Conversion { /** * The schema element that the conversion applies. * For example, the conversion may be defined against a requirement or against a metric. */ relatesTo: 'requirement' | 'observation'; /** * Where 'relatesTo' is not empty this field must be populated with the id of the item in this tender section * which the conversion relates to. */ relatedItem: string; } /** * Conversion is used to describe conversions and its coefficients applicable * for specific value received for requirement or observation */ export interface UnrelatedConversion extends Conversion { /** * The schema element that the conversion applies. * For example, the conversion may be defined against a requirement or against a metric. */ relatesTo?: never; /** * Where 'relatesTo' is not empty this field must be populated with the id of the item in this tender section * which the conversion relates to. */ relatedItem?: never; }
7ddfb2ab1a1e614857958938941ad997c108ce7b
TypeScript
rodrigojmartin/greek-heroes
/cypress/integration/greek-heroes.cy-spec.ts
2.6875
3
import { inputData } from '../../src/Utils'; describe('Greek heroes calculation', () => { beforeEach(() => { cy.visit('/'); }); it('rounds numbers with more than 2 decimals to 2 decimals', () => { inputData('2310000.159897'); cy.contains('Result is 2 310 000.16'); }); it('adds 2 fixed decimals even if the number is an integer', () => { inputData('1600'); cy.contains('Result is 1 600.00'); }); it('handles 0', () => { inputData('0'); cy.contains('Result is 0.00'); }); it('handles negative numbers', () => { inputData('-1000000'); cy.contains('Result is -1 000 000.00'); }); it('throws an error message when the user enters non numbers', () => { inputData('Camila'); cy.contains('Result is not a number'); }); it('transforms a scientific e notation correctly', () => { inputData('3.456e6'); cy.contains('Result is 3 456 000.00'); }); }); //export {}; //Little hack needed when isolatedModules was set to true in tsconf
bc3133a3d1cbb9130f7389e9b2b1760bc230175d
TypeScript
fossabot/discord-bot-1
/src/tests/sample-test.test.ts
2.96875
3
import { expect } from "chai"; function sample(bool: boolean) { if (bool) return true; return false; } describe("Sample test", () => { it("should return true", () => { const result = sample(true); expect(result).to.equal(true); }); it("should return false", () => { const result = sample(false); expect(result).to.equal(false); }); });
d3ba391127db5e0595f827b39e70aaa497b13753
TypeScript
ottoBitPd/colletta
/code/test/model/Firebase/FirebaseUserManagerTest.ts
2.703125
3
import {expect} from 'chai'; import 'mocha'; import {Student} from "../../../src/ts/model/Data/Student"; import {FirebaseUserManager} from "../../../src/ts/model/Firebase/FirebaseUserManager"; import {User} from "../../../src/ts/model/Data/User"; import {Teacher} from "../../../src/ts/model/Data/Teacher"; describe('FirebaseUserManager', function() { let student:User; let teacher:Teacher; let test=new FirebaseUserManager() ; before(function () { student = new Student("1", "gioperry15", "ciao", "giovanni", "Peron", "Castelfranco", "Unipd","giov.anni@gmail.com"); teacher=new Teacher("1","Bortolone", "ciao", "Michele", "Bortone", "Scorze", "Venezia", "A110", "borto.lone@gmail.com"); }); describe('FirebaseUserManager.insert()', function () { it('should return the insert student in database', async function() { expect(await test.insert(student)).to.equal(true); }); it('should return false beacause doesn\'t insert student in database', async function() { expect(await test.insert(student)).to.equal(false); }); it('should return the insert teacher in database', async function() { expect(await test.insert(teacher)).to.equal(true); }); }); describe('FirebaseUserManager.search()', function () { it('should return search student in database', async function() { student.setID(await test.search("gioperry15")); expect(student.getID()).to.be.not.equal("1"); }); it('should return search obj in database', async function() { teacher.setID(await test.search("Bortolone")); expect(teacher.getID()).to.be.not.equal("1"); }); }); describe('FirebaseUserManager.read()', function () { it('should return read obj in database', async function() { const data = await test.read(student.getID()); expect(data.getID()).to.equals(student.getID()) && expect(data.getCity()).to.equals(student.getCity()) && expect(data.getUsername()).to.equals(student.getUsername()) && expect(data.getEmail()).to.equals(student.getEmail()) && expect(data.getSchool()).to.equals(student.getSchool()) && expect(data.getPassword()).to.equals(student.getPassword()) && expect(data.getLastName()).to.equals(student.getLastName()); }); }); describe('FirebaseUserManager.update()', function () { it('should return update database', async function() { expect(await test.update("/data/users/"+student.getID()+"/city","Ibiza")).to.be.not.eql(student.getCity()) && expect(await test.update("/data/users/"+student.getID()+"/password","Ciaone")).to.be.not.eql(student.getPassword()) && expect(await test.update("/data/users/"+student.getID()+"/name","Alberto")).to.be.not.eql(student.getName()) && expect(await test.update("/data/users/"+student.getID()+"/lastname","Zennaro")).to.be.not.eql(student.getLastName()) && expect(await test.update("/data/users/"+student.getID()+"/school","Adria")).to.be.not.eql(student.getSchool()) && expect(await test.update("/data/users/"+student.getID()+"/username","gioperry155")).to.be.not.eql(student.getUsername()) && expect(await test.update("/data/users/"+teacher.getID()+"/INPScode","A001")).to.be.not.eql(teacher.getINPS()) && expect(await test.update("/data/users/"+student.getID()+"/email","alb.zenna@gmail.com")).to.be.not.eql(student.getEmail()) && expect(await test.update("/data/users/"+student.getID()+"/emailschool","albertozennaro@unipd.it")).to.be.undefined; }); }); describe('FirebaseUserManager.elements()', function () { it('should return elements database', async function() { let now=await test.elements(); expect(now.get(student.getID())).not.to.be.undefined; }); }); describe('FirebaseUserManager.remove()', function () { it('should return the remove student in database', async function() { expect(await test.remove(student.getID())).to.equal(true); }); it('should return the remove teacher in database', async function() { expect(await test.remove(teacher.getID())).to.equal(true); }); it('should return false because student doesn\'t exist', async function() { expect(await test.remove(student.getID())).to.equal(false); }); }); });