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
6a27945f8950d1e990b5abece4965663164aa45f
TypeScript
higa4/wikidata-mall-telegram-game
/source/lib/interface/notification.ts
2.59375
3
import {Notification} from '../types/notification' import {countdownHourMinute} from './formatted-time' import {emojis} from './emojis' export function notificationText(notification: Notification, fireDate: Date): string { const millisecondsUntil = notification.date.getTime() - fireDate.getTime() const secondsUntil = millisecondsUntil / 1000 let text = '' switch (notification.type) { case 'skillFinished': text += emojis.skillFinished text += emojis.skill break case 'storeProductsEmpty': text += emojis.shopProductsEmpty text += emojis.storage break case 'employeeRetired': text += emojis.retirement break default: throw new Error(`notification message not implemented for type: ${notification.type}`) } text += notification.text if (secondsUntil > 60) { text += '\n' text += countdownHourMinute(secondsUntil) } return text }
ad0a8b5eb01f2eda7bd3fec3121427bf5ee1fe98
TypeScript
alenaksu/tiny-lit
/packages/core/src/utils.ts
2.84375
3
import { TemplateInterface } from './types'; export function comment(data: string = ''): Comment { return document.createComment(data); } export function text(data: string = ''): Text { return document.createTextNode(data); } export function isNode(obj: any, type?: number): boolean { return ( !!obj && !!(<Node>obj).nodeType && (!type || (<Node>obj).nodeType === type) ); } export function isPrimitive(val: any) { return val !== Object(val); } export function replaceRange(newNode: Node, range: any) { const [startNode, endNode] = <any>[].concat(range); if (!startNode.parentNode) return; if (endNode && startNode.nextSibling !== endNode) { removeNodes(startNode.nextSibling!, endNode); } startNode.parentNode!.replaceChild(newNode, startNode); } export function removeNodes( startNode: Node, endNode: Node | null = null, parent: Node | null = startNode.parentNode! ): void { if (!parent) return; while (startNode !== endNode) { const nextNode = startNode.nextSibling!; parent.removeChild(startNode); startNode = nextNode; } } export function moveTemplate( template: TemplateInterface, after: Node, parent: Node = after.parentNode! ): void { const [startNode, endNode] = template.range!; const before = after.nextSibling!; let node = startNode; do { const nextNode = node!.nextSibling!; parent.insertBefore(node, before as Node); node = nextNode; } while (node !== endNode); parent.insertBefore(endNode, before as Node); } export function getNodeIndex(node: Node): number { let index = 0; while ((node = node.previousSibling!)) index++; return index; } export function getNodePath(node: Node): Array<number> { const path: number[] = []; while (node.parentNode) { path.unshift(getNodeIndex(node)); node = node.parentNode; } return path; } export function getNodeByPath(node: Node, path: Array<number>): Node { for (let i = 0, l = path.length; i < l; i++) node = node.childNodes[path[i]]; return node; } export const TemplateSymbol = Symbol(); export function isSameTemplate( t1: TemplateInterface, t2: TemplateInterface ): boolean { return isTemplate(t1) && isTemplate(t2) && t1.strings === t2.strings; } export function isTemplate(obj: any): boolean { return obj && obj[TemplateSymbol]; } export const MARKER_PREFIX = `__${Math.random().toString().slice(2)}_`; export const MARKER_RE = new RegExp( `<!--${MARKER_PREFIX}(\\d+)-->|${MARKER_PREFIX}(\\d+)` ); export const TEXT_ELEMENT = /^(?:style|textarea)$/i; export function markerNumber(value) { const m = MARKER_RE.exec(value); MARKER_RE.lastIndex = 0; return m ? Number(m[1] || m[2]) : -1; }
5c982e2fc7daefda2bc75b19a957d3fb0e189841
TypeScript
aportraitofjoyce/todolist
/src/store/reducers/tasks-reducer/tasks-reducer.test.ts
2.671875
3
import { createTask, deleteTask, fetchTasks, Tasks, tasksReducer, updateTaskStatus, updateTaskTitle } from './tasks-reducer' import {TaskResponse} from '../../../api/tasks-api' import {addTodolist, removeTodolist, setTodolists} from '../todolists-reducer/todolists-reducer' import {TaskStatuses} from '../../../types/server-response-types' let startState: Tasks beforeEach(() => { startState = { 'TD1': [ { id: '1', title: 'CSS', status: TaskStatuses.New, addedDate: '', order: 0, todoListId: 'TD1', }, { id: '2', title: 'JS', status: TaskStatuses.Completed, addedDate: '', order: 0, todoListId: 'TD1' }, { id: '3', title: 'React', status: TaskStatuses.New, addedDate: '', order: 0, todoListId: 'TD1' } ], 'TD2': [ { id: '1', title: 'bread', status: TaskStatuses.New, addedDate: '', order: 0, todoListId: 'TD2' }, { id: '2', title: 'milk', status: TaskStatuses.Completed, addedDate: '', order: 0, todoListId: 'TD2' }, { id: '3', title: 'tea', status: TaskStatuses.New, addedDate: '', order: 0, todoListId: 'TD2' } ] } }) test('correct task should be deleted from correct array', () => { const args = {taskID: '2', todolistID: 'TD2'} const endState = tasksReducer(startState, deleteTask.fulfilled(args, '', args)) expect(endState).toEqual({ 'TD1': [ { id: '1', title: 'CSS', status: TaskStatuses.New, addedDate: '', order: 0, todoListId: 'TD1', }, { id: '2', title: 'JS', status: TaskStatuses.Completed, addedDate: '', order: 0, todoListId: 'TD1' }, { id: '3', title: 'React', status: TaskStatuses.New, addedDate: '', order: 0, todoListId: 'TD1' } ], 'TD2': [ { id: '1', title: 'bread', status: TaskStatuses.New, addedDate: '', order: 0, todoListId: 'TD2' }, { id: '3', title: 'tea', status: TaskStatuses.New, addedDate: '', order: 0, todoListId: 'TD2' } ] }) }) test('correct task should be added to correct array', () => { const newTask: TaskResponse = { id: '100', title: 'juice', status: 0, addedDate: '', order: 0, todoListId: 'TD2', } const endState = tasksReducer(startState, createTask.fulfilled({task: newTask}, '', { todolistID: 'TD2', title: 'juice' })) expect(endState['TD1'].length).toBe(3) expect(endState['TD2'].length).toBe(4) expect(endState['TD2'][0].id).toBeDefined() expect(endState['TD2'][0].title).toBe('juice') }) test('status of specified task should be changed', () => { const args = {todolistID: 'TD2', taskID: '2', status: 2} const endState = tasksReducer(startState, updateTaskStatus.fulfilled(args, '', args)) expect(endState['TD2'].length).toBe(3) expect(endState['TD2'][1].status).toBe(2) }) test('title of specified task should be changed', () => { const args = {todolistID: 'TD2', taskID: '2', title: 'coffee'} const endState = tasksReducer(startState, updateTaskTitle.fulfilled(args, '', args)) expect(endState['TD2'].length).toBe(3) expect(endState['TD2'][1].title).toBe('coffee') }) test('new array should be added when new todolist is added', () => { const newTodo = { id: '100', title: 'juice', status: 0, addedDate: '', deadline: '', description: '', order: 0, startDate: '', priority: 0, todoListId: 'TD2' } const endState = tasksReducer(startState, addTodolist({todolist: newTodo})) const keys = Object.keys(endState) const newKey = keys.find(k => k !== 'TD1' && k !== 'TD2') if (!newKey) { throw Error('new key should be added') } expect(keys.length).toBe(3) expect(endState[newKey]).toEqual([]) }) test('property with todolistId should be deleted', () => { const action = removeTodolist({todolistID: 'TD2'}) const endState = tasksReducer(startState, action) const keys = Object.keys(endState) expect(keys.length).toBe(1) expect(endState['TD2']).not.toBeDefined() }) test('Empty arrays of tasks should be added after set todolists', () => { const action = setTodolists({ todolists: [ {id: '1', title: 'What to learn', order: 0, addedDate: ''}, {id: '2', title: 'What to buy', order: 0, addedDate: ''} ] }) const endState = tasksReducer({}, action) const keys = Object.keys(endState) expect(keys.length).toBe(2) expect(endState['1']).toStrictEqual([]) expect(endState['2']).toStrictEqual([]) }) test('Tasks should be added for selected todolist', () => { const action = fetchTasks.fulfilled({tasks: startState['TD1'], todolistID: 'TD1'}, '', {todolistID: 'TD1'}) const endState = tasksReducer({'TD1': [], 'TD2': []}, action) expect(endState['TD1'].length).toBe(3) expect(endState['TD2'].length).toBe(0) })
e1be54fd987c82fe9556dbf62d667a55cb114ddf
TypeScript
Fabrice-TIERCELIN/typescript-plugins-of-mine
/typescript-plugin-proactive-code-fixes/spec/tests/newExpr.ts
3.28125
3
// not an issue - just use getFullStart, getFullWidth, etc import Project, { TypeGuards, Identifier } from 'ts-morph'; const project1 = new Project({ useVirtualFileSystem: true }) const sourceFile = project1.createSourceFile('src/index.ts', ` class A{ } new A().foo() const oo = { bar: 1 } `) const id = sourceFile.getFirstDescendant(d=>TypeGuards.isIdentifier(d)&&d.getText()==='foo') as Identifier const decl = sourceFile.getClass('A') const constr1 = decl.addConstructor({ parameters: [{name: 'foo', type: 'number'}] }) const construcText = sourceFile.getText().substring(constr1.getFullStart(), constr1.getEnd()) console.log(construcText); console.log(constr1.getText()); const bar = sourceFile.getFirstDescendant(c=>c.getText()==='bar: 1') console.log(bar.getParent().getKindName()); // class A{ // constructor(foo: number) { // } // }
0fe4a6d34a6700edef3832829383164bae9a7347
TypeScript
k5trismegistus/mangashuraku
/api/src/utils/genThumbnail.ts
2.609375
3
import * as imagemagick from 'imagemagick' import { PathLike } from 'fs' import { basename, join } from 'path' export const genThumbnail = ( originalPath: string, dstDir: string, width: number ): Promise<any> => { return new Promise((resolve, reject) => { const filename = basename(originalPath) imagemagick.resize( { srcPath: originalPath, dstPath: join(dstDir, filename), width: width, }, (err: Error, result: any) => { if (err) return reject(err) resolve(result) } ) }) }
2b7aff17ccb92302783b200f64c7a58f37f2a777
TypeScript
validated-changeset/validated-changeset
/test/utils/object-without.test.ts
3
3
import objectWithout from '../../src/utils/object-without'; describe('Unit | Utility | object without', () => { it('it excludes the given keys from all merged objects', () => { const objA = { name: 'Ivan' }; const objB = { name: 'John' }; const objC = { age: 27 }; const objD = objectWithout(['age'], objA, objB, objC); expect(objD).toEqual({ name: 'John' }); expect(objA.name).toEqual('Ivan'); expect(objC.age).toEqual(27); }); });
9e6511fa53afa429ad8ee7428d4672ca957a36fe
TypeScript
warigaya-kenji/kitamura
/src/logic/web-storage.ts
3.265625
3
/** * ソートする * @param list 一覧 */ const _sort = (list: Array<{ index: number }>): Array<any> => { if (list && list.length > 0 && Object.prototype.hasOwnProperty.call(list[0], 'index')) { const sortList = list.sort((a, b) => { if (+a.index < +b.index) return -1; if (+a.index > +b.index) return 1; return 0; }); return sortList; } return list; }; const WebStorage = { /** * SessionStorageへの格納 * @param key キー名 * @param value 値 */ setSessionStorage(key: string, value: any) { const convertJson = JSON.stringify(value); sessionStorage.setItem(key, convertJson); }, /** * SessionStorageへの格納 * @param key キー名 * @param value 値 */ getSessionStorage(key: string): any { const jsonVal = sessionStorage.getItem(key); const val = jsonVal ? JSON.parse(jsonVal) : undefined; return Array.isArray(val) ? _sort(val) : val; } }; export default WebStorage;
53a51c53ba3ac5bd00fb0de296d5606457dd0036
TypeScript
piesome/valta
/src/Common/Types/TerrainTypes.ts
2.5625
3
import {TerrainType, TypeManager} from "."; export class TerrainTypes extends TypeManager<TerrainType> { constructor() { super(); this.typeName = "terrain"; } public transformRaw(data: any): TerrainType { return new TerrainType( data.name, data.movementCost, data.debugColor, ); } }
61b22c8af309a3185e47daad0f9b46f83dd68b0b
TypeScript
hzoo/babel
/packages/babel-helper-annotate-as-pure/src/index.ts
2.703125
3
import * as t from "@babel/types"; import type { Node } from "@babel/types"; const PURE_ANNOTATION = "#__PURE__"; const isPureAnnotated = ({ leadingComments }: Node): boolean => !!leadingComments && leadingComments.some(comment => /[@#]__PURE__/.test(comment.value)); export default function annotateAsPure( pathOrNode: Node | { node: Node }, ): void { const node = pathOrNode["node"] || pathOrNode; if (isPureAnnotated(node)) { return; } t.addComment(node, "leading", PURE_ANNOTATION); }
19fd1fa2c41d5999ed02181099698c74aeae9c1e
TypeScript
osedhelu/BackendTypeScript
/src/app/_function/bcryptjs.ts
2.625
3
import * as bcryp from 'bcryptjs' export class PassFn { comprar(password1: string, password2: string) { return bcryp.compareSync(password1, password2) } async generate(password1: string) { return bcryp.hashSync(password1, 10) } }
28451c21f0e10302e431fe76d09c116cd7269478
TypeScript
otawang/typescript-study-source
/src/chapter1/chapter1.ts
3.96875
4
let isDone : boolean = false; let decimal: number = 6; let hex: number = 0xf00d; let binary: number = 0b10; let octal: number = 0o71; let color: string = 'blue'; color = 'red'; let fullName: string = 'Dongwoo Seo'; let age: number= 38; let sentence : string = `Hello, my name is ${fullName}. I'll be ${age + 1} years old next year. `; //첫 번째 방법 let list1: number[] = [1,2,3,4,5]; //두 번째 방법 let list2: Array<number> = [1,2,3,4,5]; let x: [string, number]; x = ['hello', 10]; //x = [10, 'hello']; //Error tuple 설정이 달라서 //x = ['hello', 10, 1, 3, 'efwefwefwf']; //Error 2개만 설정했는데 2개 이상아리서 에러 console.log(x[0].substr(1)); //console.log(x[1].substr(1)); // Error 숫자에 없는 메소드 // 책과 다르게 전부 에러 // x[3] = "world"; // 좋아요, 'string'은 'string | number'에 할당될 수 있습니다. // console.log(x[5].toString()); // 좋아요, 'string' 및 'number'에 모두 'toString'이 있습니다. // x[6] = true; // 오류, 'boolean'은 'string | number' 타입이 아닙니다. enum Color {Red, Green, Blue}; let c: Color = Color.Red; let notSure: any = 4; notSure = 'sdqwwdqwdqwdwqd'; notSure = false; let notSure2:any = 4; notSure2.toFixed(); let notSure3:Object = 4; // notSure3.toFixed(); Error let nerverTest:never = (function():never {throw Error('') })(); let aaa:number = nerverTest; //가능 //nerverTest = 100; //불가능 declare function create(o: object | null): void; create({ prop: 0 }); // OK create(null); // OK // create(42); // Error // create("string"); // Error // create(false); // Error create(undefined); // OK, --strictNullChecks 킬 경우 에러 function foo() { // okay to capture 'a' return a; } // illegal call 'foo' before 'a' is declared // runtimes should throw an error here foo(); let a; const test1 ={a:10, b:20, c:30}; function testSpread(...test1) { console.log(test1); } function testSpread2(a) { console.log(...a); } testSpread2({a:1, b:2, c:3});
d7cfba8dd5457ffa3901c4f2ccacae30019db6dd
TypeScript
JHSeo-git/catch-a-nest
/packages/catch-a-nest-backend/src/entity/User.ts
2.8125
3
import { generateToken } from '@src/lib/token/jwt'; import { Entity, PrimaryGeneratedColumn, Column, Index, CreateDateColumn, UpdateDateColumn, getRepository, } from 'typeorm'; import { AuthToken } from './AuthToken'; @Entity({ name: 'users' }) export class User { @PrimaryGeneratedColumn() id!: number; @Column() email!: string; @Column() display_name!: string; @Column({ length: 255, nullable: true }) photo_url?: string; @Column({ default: false }) is_admin!: boolean; @Index() @CreateDateColumn({ type: 'timestamp' }) created_at!: Date; @UpdateDateColumn({ type: 'timestamp' }) updated_at!: Date; async generateUserToken() { const authToken = new AuthToken(); authToken.user = this; await getRepository(AuthToken).save(authToken); const accessToken = await generateToken( { userId: this.id, }, { subject: 'accessToken', expiresIn: '1h', } ); const refreshToken = await generateToken( { userId: this.id, tokenId: authToken.id, }, { subject: 'refreshToken', expiresIn: '30d', } ); return { accessToken, refreshToken, }; } async refreshUserToken( tokenId: string, refreshTokenExp: number, originRefreshToken: string ) { const diff = refreshTokenExp * 1000 - new Date().getTime(); let refreshToken = originRefreshToken; // half of 30d; if (diff < 1000 * 60 * 60 * 24 * 15) { refreshToken = await generateToken( { userId: this.id, tokenId: tokenId, }, { subject: 'refreshToken', expiresIn: '30d', } ); } const accessToken = await generateToken( { userId: this.id, }, { subject: 'accessToken', expiresIn: '1h', } ); return { refreshToken, accessToken, }; } }
764b40d1fc0e030b8fc8dde84984077790a0947a
TypeScript
okal/plottable
/test/components/xDragBoxLayerTests.ts
2.59375
3
///<reference path="../testReference.ts" /> describe("Interactive Components", () => { describe("XDragBoxLayer", () => { let SVG_WIDTH = 400; let SVG_HEIGHT = 400; it("bounds()", () => { let svg = TestMethods.generateSVG(SVG_WIDTH, SVG_HEIGHT); let dbl = new Plottable.Components.XDragBoxLayer(); dbl.boxVisible(true); dbl.renderTo(svg); let topLeft = { x: SVG_WIDTH / 4, y: SVG_HEIGHT / 4 }; let bottomRight = { x: SVG_WIDTH / 2, y: SVG_HEIGHT / 2 }; dbl.bounds({ topLeft: topLeft, bottomRight: bottomRight }); let actualBounds = dbl.bounds(); assert.strictEqual(actualBounds.topLeft.y, 0, "box starts at top"); assert.strictEqual(actualBounds.topLeft.x, topLeft.x, "left edge set correctly"); assert.strictEqual(actualBounds.bottomRight.y, dbl.height(), "box ends at bottom"); assert.strictEqual(actualBounds.bottomRight.x, bottomRight.x, "right edge set correctly"); svg.remove(); }); it("resizes only in x", () => { let svg = TestMethods.generateSVG(SVG_WIDTH, SVG_HEIGHT); let dbl = new Plottable.Components.XDragBoxLayer(); dbl.boxVisible(true); dbl.resizable(true); dbl.renderTo(svg); let topLeft = { x: SVG_WIDTH / 4, y: SVG_HEIGHT / 4 }; let bottomRight = { x: SVG_WIDTH / 2, y: SVG_HEIGHT / 2 }; dbl.bounds({ topLeft: topLeft, bottomRight: bottomRight }); let actualBounds = dbl.bounds(); let dragTo = { x: SVG_WIDTH * 3 / 4, y: SVG_HEIGHT / 2 }; TestMethods.triggerFakeDragSequence(dbl.background(), actualBounds.bottomRight, dragTo); actualBounds = dbl.bounds(); assert.strictEqual(actualBounds.bottomRight.x, dragTo.x, "resized in x"); assert.strictEqual(actualBounds.topLeft.y, 0, "box still starts at top"); assert.strictEqual(actualBounds.bottomRight.y, dbl.height(), "box still ends at bottom"); svg.remove(); }); it("stays full height after resizing", () => { let svg = TestMethods.generateSVG(SVG_WIDTH, SVG_HEIGHT); let dbl = new Plottable.Components.XDragBoxLayer(); dbl.boxVisible(true); dbl.resizable(true); dbl.renderTo(svg); let topLeft = { x: SVG_WIDTH / 4, y: SVG_HEIGHT / 4 }; let bottomRight = { x: SVG_WIDTH / 2, y: SVG_HEIGHT / 2 }; dbl.bounds({ topLeft: topLeft, bottomRight: bottomRight }); let heightBefore = dbl.height(); let boundsBefore = dbl.bounds(); svg.attr("height", 2 * SVG_HEIGHT); dbl.redraw(); assert.notStrictEqual(dbl.height(), heightBefore, "component changed size"); let boundsAfter = dbl.bounds(); assert.strictEqual(boundsAfter.topLeft.x, boundsBefore.topLeft.x, "box keeps same left edge"); assert.strictEqual(boundsAfter.topLeft.y, 0, "box still starts at top"); assert.strictEqual(boundsAfter.bottomRight.x, boundsBefore.bottomRight.x, "box keeps same right edge"); assert.strictEqual(boundsAfter.bottomRight.y, dbl.height(), "box still ends at bottom"); svg.remove(); }); it("throws error on getting y scale", () => { let dbl = new Plottable.Components.XDragBoxLayer(); assert.throws(() => dbl.yScale(), "no yScale"); }); it("throws error on setting y scale", () => { let dbl = new Plottable.Components.XDragBoxLayer(); assert.throws(() => dbl.yScale(new Plottable.Scales.Linear()), "yScales cannot be set"); }); it("throws error on getting y extent", () => { let dbl = new Plottable.Components.XDragBoxLayer(); assert.throws(() => dbl.yExtent(), "no yExtent"); }); it("moves only in x", () => { let svg = TestMethods.generateSVG(SVG_WIDTH, SVG_HEIGHT); let dbl = new Plottable.Components.XDragBoxLayer(); dbl.boxVisible(true); dbl.movable(true); dbl.renderTo(svg); let topLeft = { x: SVG_WIDTH / 4, y: SVG_HEIGHT / 4 }; let bottomRight = { x: SVG_WIDTH * 3 / 4, y: SVG_HEIGHT * 3 / 4 }; dbl.bounds({ topLeft: topLeft, bottomRight: bottomRight }); let boundsBefore = dbl.bounds(); let dragDistance = 10; TestMethods.triggerFakeDragSequence(dbl.background(), { x: SVG_WIDTH / 2, y: SVG_HEIGHT / 2 }, { x: SVG_WIDTH / 2 + dragDistance, y: SVG_HEIGHT / 2 + dragDistance } ); let boundsAfter = dbl.bounds(); assert.strictEqual(boundsAfter.topLeft.x, boundsBefore.topLeft.x + dragDistance, "left edge moved"); assert.strictEqual(boundsAfter.topLeft.y, 0, "box still starts at top"); assert.strictEqual(boundsAfter.bottomRight.x, boundsBefore.bottomRight.x + dragDistance, "right edge moved"); assert.strictEqual(boundsAfter.bottomRight.y, dbl.height(), "box still ends at bottom"); svg.remove(); }); it("destroy() does not error if scales are not inputted", () => { let svg = TestMethods.generateSVG(); let sbl = new Plottable.Components.XDragBoxLayer(); sbl.renderTo(svg); assert.doesNotThrow(() => sbl.destroy(), Error, "can destroy"); svg.remove(); }); }); });
79c7dfb2dc6b69b109029c030cd98401346c6318
TypeScript
green-fox-academy/OrgovanGeza
/week-03/day-03/Exercises/Pokémon/main.ts
3.65625
4
import { strictEqual } from 'assert'; import { Pokemon } from './Pokemon' let pokemonOfAsh: Pokemon[] = initializePokemon(); // Every pokemon has a name and a type. // Certain types are effective against others, e.g. water is effective against fire. // Ash has a few pokemon. // A wild pokemon appeared! let wildPokemon: Pokemon = new Pokemon('Oddish', 'grass', 'water'); // Which pokemon should Ash use? // Implement the following `chooseEffective` function which will choose the most effective pokemon for Ash console.log(`I choose you!, ${chooseEffective(pokemonOfAsh, wildPokemon)}`); function initializePokemon(): Pokemon[] { return [ new Pokemon('Bulbasaur', 'grass', 'water'), new Pokemon('Pikachu', 'electric', 'water'), new Pokemon('Charizard', 'fire', 'grass'), new Pokemon('Pidgeot', 'flying', 'fighting'), new Pokemon('Kingler', 'water', 'fire') ]; } function chooseEffective (poke1:Pokemon[], poke2:Pokemon) { for (let i=0; i<poke1.length; i++){ if (poke1[i].isEffectiveAgainst(poke2)) { return poke1[i].name; } } }
6312cfab38319941e4f45e5b6c0846ee1b62caaa
TypeScript
LoicMahieu/yup-locales
/src/locales/de.ts
3.0625
3
/*eslint-disable no-template-curly-in-string*/ /** * This work is derived from skress/yup-locale-de. * https://github.com/skress/yup-locale-de/ */ import printValue from '../util/printValue'; import { LocaleObject, FormatErrorParams } from 'yup'; // Based on https://github.com/jquense/yup/blob/2973d0a/src/locale.js export const mixed: LocaleObject['mixed'] = { default: '${path} ist ungültig', required: '${path} ist ein Pflichtfeld', oneOf: '${path} muss einem der folgenden Werte entsprechen: ${values}', notOneOf: '${path} darf keinem der folgenden Werte entsprechen: ${values}', notType: ({ path, type, value, originalValue }: FormatErrorParams) => { const isCast = originalValue != null && originalValue !== value; let msg = `${path} muss vom Typ \`${type}\` sein, ` + `aber der Wert war: \`${printValue(value, true)}\`` + (isCast ? ` (gecastet aus dem Wert \`${printValue(originalValue, true)}\`).` : '.'); if (value === null) { msg += `\n Wenn "null" als leerer Wert gedacht ist, müssen Sie das Schema als \`.nullable()\` markieren.`; } return msg; }, }; export const string: LocaleObject['string'] = { length: '${path} muss genau ${length} Zeichen lang sein', min: '${path} muss mindestens ${min} Zeichen lang sein', max: '${path} darf höchstens ${max} Zeichen lang sein', matches: '${path} muss wie folgt aussehen: "${regex}"', email: '${path} muss eine gültige E-Mail-Adresse enthalten', url: '${path} muss eine gültige URL sein', trim: '${path} darf keine Leerzeichen am Anfang oder Ende enthalten', lowercase: '${path} darf nur Kleinschreibung enthalten', uppercase: '${path} darf nur Großschreibung enthalten', }; export const number: LocaleObject['number'] = { min: '${path} muss größer oder gleich ${min} sein', max: '${path} muss kleiner oder gleich ${max} sein', lessThan: '${path} muss kleiner sein als ${less}', moreThan: '${path} muss größer sein als ${more}', positive: '${path} muss eine positive Zahl sein', negative: '${path} muss eine negative Zahl sein', integer: '${path} muss eine ganze Zahl sein', }; export const date: LocaleObject['date'] = { min: '${path} muss später sein als ${min}', max: '${path} muss früher sein als ${max}', }; export const boolean: LocaleObject['boolean'] = {}; export const object: LocaleObject['object'] = { noUnknown: '${path}-Feld darf keine Schlüssel verwenden, die nicht im "Objekt-Shape" definiert wurden', }; export const array: LocaleObject['array'] = { min: '${path}-Feld muss mindestens ${min} Einträge haben', max: '${path}-Feld darf höchstens ${max} Einträge haben', };
093c44baae82b03100ead672cd55deef7a0aff18
TypeScript
SirPepe/html-import
/src/html-import.ts
2.609375
3
import { define, attr, href, string, reactive, event, } from "@sirpepe/schleifchen"; type State = "loading" | "done" | "fail" | "ready"; type Handler<E extends Event> = ((evt: E) => void) | null; type PromiseResponse = { element: HTMLImportElement; title: string; }; type FulfillmentCallbacks = [ Resolve: (entries: PromiseResponse[]) => any, Reject: (reason: any) => any ]; class ImportStartEvent extends Event { constructor() { super("importstart", { bubbles: true }); } } class ImportDoneEvent extends Event { constructor() { super("importdone", { bubbles: true }); } } class ImportAbortEvent extends Event { constructor() { super("importabort", { bubbles: true }); } } class ImportFailEvent extends Event { #reason: any; constructor(reason: any) { super("importfail", { bubbles: true }); this.#reason = reason; } get reason(): any { return this.#reason; } } function insertAfter(target: Element, content: Node): void { if (target.parentNode) { if (target.nextElementSibling) { target.parentNode.insertBefore(content, target.nextElementSibling); } else { target.parentNode.append(content); } } } // Fixing scripts is required because Firefox (rightly) treats scripts that are // cloned or adopted from other documents as suspicious and won't run them. So // we have to _manually_ clone the scripts and copy the original's content and // attributes over to the clones, because that's not suspicious at all. This // must happen in all browsers for the sake of consistency. Importing scripts // turns them asynchronous function fixScripts(context: DocumentFragment): void { const scripts = context.querySelectorAll("script"); for (const script of scripts) { const clone = document.createElement("script"); clone.text = script.text; for (const attribute of script.attributes) { clone.attributes.setNamedItem(attribute.cloneNode() as Attr); } insertAfter(script, clone); script.remove(); } } async function awaitNested( imports: Iterable<HTMLImportElement> ): Promise<PromiseResponse[]> { const promises: Promise<PromiseResponse[]>[] = []; for (const importElement of imports) { promises.push(importElement.done()); } const responses = await Promise.all(promises); return responses.flat(); } // no selector, no hash = entire body contents // selector, no hash = all elements matching selector // no selector, hash = first element matching hash // selector and hash = first element matching hash that also matches selector function extractContent( html: string, selector: string, hash: string ): { content: DocumentFragment; title: string } { const content = window.document.createDocumentFragment(); const source = new DOMParser().parseFromString(html, "text/html"); if (!selector && !hash) { // Can't use for-of here because adoptNode() removes the adopted nodes from // the source child list, for which document.body.childNodes is a *live* // view. while (source.body.childNodes.length > 0) { content.append(window.document.adoptNode(source.body.childNodes[0])); } } else if (selector && !hash) { const matchingDescendants = source.querySelectorAll(selector); for (const descendant of matchingDescendants) { if (!descendant?.parentElement?.closest(selector)) { content.append(window.document.adoptNode(descendant)); } } } else { const hashMatch = source.querySelector(hash); // basically getELementById() if (hashMatch && (!selector || hashMatch.matches(selector))) { content.append(hashMatch); } } return { content, title: source.title }; } @define("html-import") class HTMLImportElement extends HTMLElement { // Aborts running downloads and also serves as the object symbolizing the // current loading operation - AbortController is single-use anyway and so has // to be replaced for each request. #controller = new AbortController(); // Promise fulfillment triggers, registered via done() #callbacks: FulfillmentCallbacks[] = []; // Internal state management. If a new request happens while the state is // "loading", the AbortController needs to be used to stop the previous // download. #state: State = "ready"; // Public attributes @attr(href()) accessor src = ""; @attr(string()) accessor selector = ""; @attr(event()) accessor onimportstart: Handler<ImportStartEvent> = null; @attr(event()) accessor onimportdone: Handler<ImportDoneEvent> = null; @attr(event()) accessor onimportabort: Handler<ImportAbortEvent> = null; @attr(event()) accessor onimportfail: Handler<ImportFailEvent> = null; constructor(src?: string, selector?: string) { super(); if (src) { this.src = src; } if (selector) { this.selector = selector; } } // Reset the current loading operation, if any. Abort the fetch request, fire // an abort error, but keep the current callbacks alive. #setBack(): void { if (this.#state === "loading") { this.#controller.abort(); this.#controller = new AbortController(); this.dispatchEvent(new ImportAbortEvent()); } this.#state = "ready"; } // End the current loading operation as a success. Fire a "done" event, then // trigger and re-set the success callbacks #setDone(entries: PromiseResponse[]): void { this.dispatchEvent(new ImportDoneEvent()); this.#callbacks.forEach(([resolve]) => resolve(entries)); this.#callbacks = []; this.#state = "done"; } // End the current loading operation as a failure #setFail(reason: any): void { this.dispatchEvent(new ImportFailEvent(reason)); this.#callbacks.forEach(([, reject]) => reject(reason)); this.#callbacks = []; this.#state = "fail"; } get [Symbol.toStringTag](): string { return "HTMLImportElement"; } // Manually triggers a reload without changing src or selector async reload(): Promise<PromiseResponse[]> { this.#setBack(); if (!this.src) { return []; } return (await this.#load()) ?? []; } @reactive({ keys: ["src", "selector"] }) #import(): void { this.#setBack(); if (!this.src) { return; } this.#load(); } // Subclasses, extensions and tests may want to mess with this method to // implement their own loading logic. async fetch(url: string, signal: AbortSignal): Promise<string> { const response = await window.fetch(url, { signal }); if (response.ok) { return await response.text(); } else { throw new Error(`Response status not ok: ${response.statusText}`); } } // Subclasses, extensions and tests may want to mess with this method to // manipulate the content that is about the get used. beforeReplaceContent(content: DocumentFragment): DocumentFragment { return content; } // Subclasses, extensions and tests may want to mess with this method to // change how content gets replaced by new content. replaceContent(newContent: DocumentFragment): void { this.innerHTML = ""; this.append(newContent); } async #load(): Promise<PromiseResponse[] | undefined> { const src = this.src; this.#state = "loading"; this.dispatchEvent(new ImportStartEvent()); // this.#abortController may be replaced while the load function is in the // middle of its job. We need this reference to keep access the relevant // promise triggers for when the operation completes. try { const imported = extractContent( await this.fetch(src, this.#controller.signal), this.selector, new URL(src, window.location.origin).hash ); fixScripts(imported.content); this.replaceContent(this.beforeReplaceContent(imported.content)); const nested = await awaitNested(this.querySelectorAll("html-import")); const result = [{ element: this, title: imported.title }, ...nested]; this.#setDone(result); return result; } catch (error) { // Ignore abort "errors" if (!String(error).startsWith("AbortError")) { this.#setFail(`${String(error)} (${src})`); } } } done(): Promise<PromiseResponse[]> { return new Promise((...callbacks) => this.#callbacks.push(callbacks)); } get state(): State { return this.#state; } } export default HTMLImportElement; declare global { interface HTMLElementTagNameMap { "html-import": HTMLImportElement; } }
e153fd199f6817f8a3029936d700b473e8e937f7
TypeScript
BPesik/Playground
/react-app/src/store/online-status/reducers.ts
2.796875
3
import { UPDATE_ONLINE, OnlineStatusActionTypes, OnlineStatusState } from './types' export const initialOnlineStatusState: OnlineStatusState = false; export function onlineStatusReducer( state = initialOnlineStatusState, action: OnlineStatusActionTypes ): OnlineStatusState { switch (action.type) { case UPDATE_ONLINE: return action.payload; default: return state; } }
1795336e4038669eeb1d0cb2a52608eaf1b39a2d
TypeScript
sajedsoliman/my-diary
/src/backends/Store.ts
2.5625
3
import { useState, SetStateAction, Dispatch } from "react"; // Router import { useHistory } from "react-router-dom"; // firebase import { db, firebase, auth, storage } from "./database"; // contexts import { AuthUser } from "contexts/UserContext"; import { useDiary } from "./../contexts/DiaryContext"; // types import { ThroughDayTaskProps, MainTaskProps, RegisterUserProps, AuthUserProps, DiaryProps, } from "typescripts/commonTypes"; const Store = () => { const loggedUser = AuthUser(); const diary: any = useDiary(); const diariesRef = loggedUser !== "no user" ? db.collection("users").doc(loggedUser.id).collection("user-diaries") : db.collection("diaries"); // State vars const [loading, setLoading] = useState(false); // Router const history = useHistory(); const getDiary: (diaryDay: Date, setDiary: Dispatch<SetStateAction<DiaryProps | null>>) => void = (diaryDay, setDiary) => { // Check if it really existed return diariesRef .where("created_date", "==", diaryDay.toISOString().split("T")[0]) .onSnapshot((snapshot) => { const isExisted: boolean = !snapshot.empty; if (isExisted) { const data = snapshot.docs[0].data() as { created_date: string; main_tasks: MainTaskProps[]; throughDay_tasks: ThroughDayTaskProps[]; }; const completed_tasks: MainTaskProps[] = data.main_tasks.filter( (task: MainTaskProps) => task.completed ); const incompleted_tasks: MainTaskProps[] = data.main_tasks.filter( (task: MainTaskProps) => !task.completed ); const percentage = ((completed_tasks.length / data.main_tasks.length) * 100).toFixed(); const progress = `${percentage}%`; const diaryData = { ...snapshot.docs[0].data(), completed_tasks, incompleted_tasks, id: snapshot.docs[0].id, progress, } as DiaryProps; setDiary(diaryData); } else { // New Diary Info const diaryData: any = { created_date: diaryDay.toISOString().split("T")[0], main_tasks: [], throughDay_tasks: [], completed_tasks: [], incompleted_tasks: [], }; // Add it to the db diariesRef.add(diaryData).then((diaryDoc) => { const id = diaryDoc.id; setDiary({ ...diaryData, id }); }); } }); }; // handle add a task const addTask = ( taskInfo: { title: string; body: string } | { body: string }, listType: "main_tasks" | "throughDay_tasks" ) => { const newTask: MainTaskProps | ThroughDayTaskProps = { ...taskInfo, completed: false, completionNote: "", id: (new Date().getTime() * Math.random()).toString(), }; diariesRef.doc(diary.id).update({ [listType]: firebase.firestore.FieldValue.arrayUnion(newTask), }); return newTask.id; }; const handleUpdateTask = ( taskList: MainTaskProps[] | ThroughDayTaskProps[], listType: "main_tasks" | "throughDay_tasks", newData: object, taskId: string ) => { diariesRef.doc(diary.id).update({ [listType]: taskList.map((task) => { if (task.id === taskId) { return { ...task, ...newData }; } else return task; }), }); }; const handleDeleteTask = ( listType: "main_tasks" | "throughDay_tasks", task: MainTaskProps | ThroughDayTaskProps ) => { diariesRef.doc(diary.id).update({ [listType]: firebase.firestore.FieldValue.arrayRemove(task), }); }; // update a taskList as whole (when dragEnd and other uses) const handleUpdateTaskList = ( taskListType: "main_tasks" | "throughDay_tasks", newTaskList: MainTaskProps[] | ThroughDayTaskProps[], diaryId: string ) => { // getting the diaryId from props because of the diary context // since it lives in the same file we call this function (Diary.tsx) so it will be null if (loggedUser !== "no user") diariesRef.doc(diaryId).update({ [taskListType]: newTaskList, }); }; // handle add the user to db const addUserToDb = (userInfo: AuthUserProps) => { db.collection("users").doc(userInfo.id).set(userInfo); }; // handle upload a user avatar const handleUploadUserAvatar: (avatar: File) => Promise<string> = async (avatar) => { // 1. upload the avatar await storage.ref(`users-avatar/${avatar.name}`).put(avatar); // return the download url return storage .ref("users-avatar") .child(avatar.name) .getDownloadURL() .then((url) => url); }; // Handle register a user const handleRegisterUser: (userInfo: RegisterUserProps) => void = async (userInfo) => { // destructuring the user let { avatar, fullName, email, password } = userInfo; // set loading setLoading(true); // Auth the user const newUser = auth.createUserWithEmailAndPassword(email, password); // Check for the avatar if (avatar != null || avatar != undefined) { // handle upload the avatar avatar = await handleUploadUserAvatar(avatar as File); } // Update the user's fullName and avatar newUser.then((authUser) => { const dbUser = { fullName, email, avatar: avatar, id: authUser?.user?.uid, } as AuthUserProps; addUserToDb(dbUser); // Stop the loading progress setLoading(false); return authUser.user?.updateProfile({ photoURL: avatar as string | null, displayName: fullName, }); // history.replace("/"); }); }; // Handle sign in a user const handleSignin = (email: string, password: string) => { // set loading auth .signInWithEmailAndPassword(email, password) .then((loggedUser) => { // Go to home - if there is from page => go to it history.replace("/"); }) .catch((error) => alert(error.message)); }; // handle sign out const handleSignOut = () => { auth.signOut().then(() => { // Go to login page history.replace("/login"); }); }; return { getDiary, handleUpdateTask, handleUpdateTaskList, handleDeleteTask, addTask, loading, handleSignin, handleRegisterUser, handleSignOut, }; }; export default Store;
261904f0067158836e8fb8c86a6cc9177a1a4368
TypeScript
Kushagra767/website-2
/src/app/utils/subscription.ts
2.640625
3
import { Subscription } from 'rxjs'; export type PossibleSubscription = Subscription | undefined | null; export const unsubscribe = (subscriptions: PossibleSubscription | PossibleSubscription[]) => Array.isArray(subscriptions) ? subscriptions.map(unsubscribe) : subscriptions ? subscriptions.unsubscribe() : void 0;
d1e83fba60f3f9d17d01e6fd83a7ce48dc9f0d75
TypeScript
taylor928908/miggmagg-backend
/src/services/rouletteService.ts
2.640625
3
import {IRoulette} from '../interfaces/roulette' import {Roulette} from '../models' import {PointService, UserService} from '../services' import {db} from '../loaders' async function calculateRoulette(userId: number): Promise<{id: number}> { const connection = await db.beginTransaction() try { const roulette = await Roulette.findAll() const random = Math.random() * 100 let cumulative = 0 for (let i = 0; i < roulette.length; i++) { const {percentage, id, type, point} = roulette[i] cumulative += percentage if (random <= cumulative) { if (type === 'point') { await PointService.create({userId, type: 'roulette', point}, connection) await UserService.updatePoint({userId, point}, connection) } await db.commit(connection) return {id} } } throw new Error('roulette_error') } catch (e) { if (connection) await db.rollback(connection) throw e } } async function findAll(): Promise<IRoulette[]> { try { return await Roulette.findAll() } catch (e) { throw e } } export {calculateRoulette, findAll}
b7d31b82f2bd0040e327f671edb00fa318af6664
TypeScript
islamailani/invoicer
/src/app/store/actions/app.actions.ts
2.75
3
import { Action } from '@ngrx/store'; export enum AppActionTypes { CheckUpdateAvailable = '[App] Check Update available', SetUpdateAvailable = '[App] Set Update available' } export class CheckUpdateAvailable implements Action { readonly type = AppActionTypes.CheckUpdateAvailable; } export class SetUpdateAvailable implements Action { readonly type = AppActionTypes.SetUpdateAvailable; constructor(public payload: boolean) {} } export type AppActionsUnion = CheckUpdateAvailable | SetUpdateAvailable;
9ac08cb3c83a45c35bf2c3bcb3cd0fca1c0c0ba5
TypeScript
ppara1/Production-Angular
/apps/movies/src/app/+state/movies.reducer.spec.ts
2.84375
3
import { MoviesEntity } from './movies.models'; import * as MoviesActions from './movies.actions'; import { State, initialState, reducer } from './movies.reducer'; describe('Movies Reducer', () => { const createMoviesEntity = (id: string, name = '') => ({ id, name: name || `name-${id}`, } as MoviesEntity); beforeEach(() => {}); describe('valid Movies actions', () => { it('loadMoviesSuccess should return set the list of known Movies', () => { const movies = [ createMoviesEntity('PRODUCT-AAA'), createMoviesEntity('PRODUCT-zzz'), ]; const action = MoviesActions.loadMoviesSuccess({ movies }); const result: State = reducer(initialState, action); expect(result.loaded).toBe(true); expect(result.ids.length).toBe(2); }); }); describe('unknown action', () => { it('should return the previous state', () => { const action = {} as any; const result = reducer(initialState, action); expect(result).toBe(initialState); }); }); });
ab1ef57653a971aa0fe45395f82d0f7dc7342010
TypeScript
lukou-frontend/react-weui-ts
/build/es/components/cell/cell_header.d.ts
2.578125
3
import * as React from 'react'; import PropTypes from 'prop-types'; /** * Header of `Cell` * */ interface CellHeaderProps { className?: any; primary?: boolean; children?: React.ReactNode; style?: React.CSSProperties; [key: string]: any; } declare const CellHeader: { (props: CellHeaderProps): JSX.Element; propTypes: { /** * if cell body is the primary block * */ primary: PropTypes.Requireable<boolean>; }; defaultProps: { primary: boolean | undefined; }; }; export default CellHeader;
a2929133f7adf60db5b2a18010348b59460c4edf
TypeScript
farukh110/Recipe-Angular-App
/src/app/shopping-list/shopping.model.ts
2.984375
3
export class Shopping { public productName: string; public productAmount: number; constructor(productName: string, productAmount: number) { this.productName = productName; this.productAmount = productAmount; } }
0ff5a11515e0ad382f8b75dff58547dc83ad55c8
TypeScript
laginha87/habit-tracker
/src/App/selectors.ts
2.71875
3
import { State } from "../reducer"; import { DayResult, DayData } from "../model/types"; import { DateTime } from "luxon"; import { createSelector } from "reselect"; import { List } from "immutable"; export const getDays = (state: State) => state.app.days; export const getDate = (state: State) => state.app.day; export const getSpent = (state: State) => state.app.spent; export const getResultForDay = createSelector(getDays, getDate, (days: List<DayData>, date: DateTime): DayResult => { const entry = days.find((e) => e.date.hasSame(date, 'day')); return entry ? entry.result : null; }); const calculateTotal = createSelector(getDays, (res: List<DayData>) => { return res.sortBy(({ date }: DayData) => date).reduce(({ previous, chain, total, level, levelChain }, el, key) => { const good = (previous === null || el.date.startOf('day').diff(previous.date.startOf('day'), 'days').days) && el.result == "good"; previous = el; chain++; levelChain++; if (!good) { chain = levelChain = 0 level= Math.max(level - 1, 0) } else { total += level; if(levelChain >= level) { level++; levelChain = 0; total += level } } return { previous, chain, total, level, levelChain } }, { total: 0, chain: 0, previous: null, level: 0, levelChain: 0 }); }) export const getTotal = createSelector(calculateTotal, getSpent, (totals, spent) => { return totals.total - spent.reduce((a, { value }) => a + value, 0); }) export const getChain = createSelector(calculateTotal, (totals) => { return totals.chain; }) export const getLevel = createSelector(calculateTotal, (totals) => { return totals.level; }) export const getLevelChain = createSelector(calculateTotal, (totals) => { return totals.levelChain; }) export const getDateFormatted = createSelector(getDate, (date: DateTime): string => { if (date.hasSame(DateTime.local(), 'day')) { return 'Today'; } if (date.startOf('day').diff(DateTime.local().startOf('day'), 'day').days === -1) { return 'Yesterday'; } if (date.hasSame(DateTime.local(), 'week')) { return date.toFormat('cccc') } return date.toFormat('dd/MM/yyyy'); }) export const convertToEuros = (credits: number) => parseFloat((credits * 0.1).toFixed(2)) export const convertToTime = (credits: number) => credits * 10 export const convertFromTime = (minutes: number) => minutes * 0.1 export const convertFromEuros = (euros: number) => euros * 10 export const getWalletExtended = createSelector(getTotal, (total) => ({ euros: convertToEuros(total), minutes: convertToTime(total), total }))
fa324aa4300e0576466628274f16dae2436e12ac
TypeScript
ustaxcourt/ef-cms
/shared/src/business/utilities/DateHandler.formats.test.ts
2.6875
3
import * as DateHandler from './DateHandler'; const { createISODateString, formatDateString, FORMATS, prepareDateFromEST } = DateHandler; import { JoiValidationConstants } from '../entities/JoiValidationConstants'; describe('DateHandler', () => { describe('Date Formats', () => { let realDateNow; const mockTimeValue = 1530518207007; // '2018-07-02T07:56:47.007Z' const FORMATS_EXPECTED_OUTPUT = { DATE_TIME: '07/02/18 03:56 am', DATE_TIME_TZ: '07/02/18 3:56 am ET', DAY_OF_WEEK: '1', FILENAME_DATE: 'July_2_2018', ISO: '2018-07-02T03:56:47.007-04:00', LOG_TIMESTAMP: '2018/07/02 03:56:47.007 ET', MDYY: '7/2/18', MDYYYY: '7/2/2018', MMDDYY: '07/02/18', MMDDYYYY: '07/02/2018', MMDDYYYY_DASHED: '07-02-2018', MONTH_DAY_YEAR: 'July 2, 2018', MONTH_DAY_YEAR_WITH_DAY_OF_WEEK: 'Monday, July 2, 2018', SHORT_MONTH_DAY_YEAR: 'Jul 2, 2018', SORTABLE_CALENDAR: '2018/07/02', TIME: '03:56 am', TIME_TZ: '3:56 am ET', TRIAL_SORT_TAG: '20180702035647', TRIAL_TIME: '2018-07-02 3:56', UNIX_TIMESTAMP_SECONDS: '1530518207', WEEK: '27', YEAR: '2018', YEAR_TWO_DIGIT: '18', YYYYMM: '2018-07', YYYYMMDD: '2018-07-02', YYYYMMDD_NUMERIC: '20180702', }; beforeAll(() => { realDateNow = Date.now.bind(global.Date); const dateNowStub = jest.fn().mockReturnValue(mockTimeValue); global.Date.now = dateNowStub; }); afterAll(() => { global.Date.now = realDateNow; }); Object.keys(FORMATS).forEach(format => { it(`correctly formats dates using ${format}`, () => { const dateString = createISODateString(); const result = formatDateString(dateString, FORMATS[format]); expect(result).toEqual(FORMATS_EXPECTED_OUTPUT[format]); }); }); it('formats a date using pm (lowercase)', () => { const dateStringFormat = '2011-09-08T18:00:00.000Z'; const result = formatDateString(dateStringFormat, 'DATE_TIME_TZ'); expect(result).toEqual('09/08/11 2:00 pm ET'); }); it('converts EST to GMT', () => { const dateString = '2011-09-08 14:00'; // 2pm on Sept 9th const result = prepareDateFromEST(dateString, FORMATS.TRIAL_TIME); expect(result).toEqual('2011-09-08T18:00:00.000Z'); }); }); describe('createISODateString', () => { it('creates a date anew', () => { const myDate = createISODateString(); expect(myDate).toBeDefined(); }); it('creates a known timestamp', () => { // mock the date implementation and returning original value upon test completion const mockTimeValue = 1530518207007; const expectedReturnValue = '2018-07-02T07:56:47.007Z'; const realDateNow = Date.now.bind(global.Date); const dateNowStub = jest.fn().mockReturnValue(mockTimeValue); global.Date.now = dateNowStub; const myDate = DateHandler.createISODateString(); expect(myDate).toBe(expectedReturnValue); expect(dateNowStub).toHaveBeenCalled(); global.Date.now = realDateNow; }); it('creates a date from a year', () => { const myDate = DateHandler.createISODateString('2000', FORMATS.YEAR); expect(myDate).toBe('2000-01-01T05:00:00.000Z'); }); it('creates a date from a two-digit year', () => { const myDate = DateHandler.createISODateString( '89', FORMATS.YEAR_TWO_DIGIT, ); expect(myDate).toBe('1989-01-01T05:00:00.000Z'); }); it('creates an EST-set UTC date from a YYYY-MM-DD string', () => { const myDate = DateHandler.createISODateString('2001-01-01'); // Jan 1, 2001 at the stroke of midnight, EST expect(myDate).toBe('2001-01-01T05:00:00.000Z'); }); it('should not alter a zulu time string', () => { const myDate = DateHandler.createISODateString( '2001-01-01T00:00:00.000Z', ); // Jan 1, 2001 at the stroke of midnight, GMT expect(myDate).toBe('2001-01-01T00:00:00.000Z'); }); it('creates timestamps that strictly adhere to Joi formatting rules', () => { const thisDate = DateHandler.createISODateString(); expect( JoiValidationConstants.ISO_DATE.validate(thisDate).error, ).toBeUndefined(); }); }); });
7aea52a149655baf436be9f31cc6cf3135c4171d
TypeScript
genesfa/meiern
/common-lib/lib/Player.d.ts
2.53125
3
export declare class Player { name: string; id: number | null; constructor(name: string, id?: number | null); } export declare class SetPlayerNameAction { readonly name: string; static readonly type: string; constructor(name: string); } /** * Socket response for SetPlayerName * Contains Player object for new Player */ export declare class SetActivePlayerAction { readonly player: Player; static readonly type: string; constructor(player: Player); } export declare class SetPlayerListAction { readonly players: Player[]; static readonly type: string; constructor(players: Player[]); } export declare class GetPlayerListAction { static readonly type: string; } //# sourceMappingURL=Player.d.ts.map
7cfd77b071d93babd31db6c2732a35e54ba9ed27
TypeScript
danielo515/ergodox-configurator
/src/modules/ui.ts
2.84375
3
type State = { readonly importDialogOpen: boolean; }; const initialState: State = { importDialogOpen: false }; const prefix = "[ui]"; export const OPEN_IMPORT_DIALOG = `${prefix} OPEN_IMPORT_DIALOG`; const openImport = () => ({ type: OPEN_IMPORT_DIALOG }); export const CLOSE_IMPORT_DIALOG = `${prefix} CLOSE_IMPORT_DIALOG`; const closeImport = () => ({ type: CLOSE_IMPORT_DIALOG }); export const actions = { openImport,closeImport }; export default (state: State = initialState, { type, payload }): State => { switch (type) { case OPEN_IMPORT_DIALOG: return { ...state, importDialogOpen: true }; case CLOSE_IMPORT_DIALOG: return { ...state, importDialogOpen: false }; default: return state; } };
0f924bde39d5caccfd86d24f3fe10585e47b4aee
TypeScript
Irokotia/angular-tour-des-heroes
/src/app/data/serializable.ts
2.515625
3
/** * Created by fbm on 10/02/17. */ export class Serializable { fromJSON(json) { for (const propName in json) { if (json.hasOwnProperty(propName)) { this[propName] = json[propName]; } } return this; } }
977d6a9e286cbab1cc1a8a8bae9482b38610cd4e
TypeScript
madmonkey/RetailSDK
/POS/Extensions/SequentialSignature/Handlers/PostSignatureRequestHandler.ts
2.703125
3
/** * SAMPLE CODE NOTICE * * THIS SAMPLE CODE IS MADE AVAILABLE AS IS. MICROSOFT MAKES NO WARRANTIES, WHETHER EXPRESS OR IMPLIED, * OF FITNESS FOR A PARTICULAR PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OR CONDITIONS OF MERCHANTABILITY. * THE ENTIRE RISK OF THE USE OR THE RESULTS FROM THE USE OF THIS SAMPLE CODE REMAINS WITH THE USER. * NO TECHNICAL SUPPORT IS PROVIDED. YOU MAY NOT DISTRIBUTE THIS CODE UNLESS YOU HAVE A LICENSE AGREEMENT WITH MICROSOFT THAT ALLOWS YOU TO DO SO. */ import { ExtensionRequestHandlerBase, ExtensionRequestType } from "PosApi/Create/RequestHandlers"; import { ClientEntities } from "PosApi/Entities"; import PostSignatureRequest from "../Messages/PostSignatureRequest"; import PostSignatureResponse from "../Messages/PostSignatureResponse"; import SequentialSignatureManager from "../Managers/SequentialSignatureManager"; /** * The request handler for PostSignatureRequest. */ export default class PostSignatureRequestHandler<TResponse extends PostSignatureResponse> extends ExtensionRequestHandlerBase<TResponse> { /** * Gets the supported request type. * @return {ExtensionRequestType<TResponse>} The supported abstract or concrete request type. */ public supportedRequestType(): ExtensionRequestType<TResponse> { return PostSignatureRequest; } /** * Executes the request handler asynchronously. * @param {PostSignatureRequest<TResponse>} request PostSignature request. * @return {Promise<ClientEntities.ICancelableDataResult<TResponse>>} The promise with a cancelable result containing the response. */ public executeAsync(request: PostSignatureRequest<TResponse>) : Promise<ClientEntities.ICancelableDataResult<PostSignatureResponse>> { let sequentialSignatureManager: SequentialSignatureManager = new SequentialSignatureManager(this.context); return sequentialSignatureManager.postSignature(request.isSigned, request.registerResponse, request.sequenceType) .then(() => { let returnResult: ClientEntities.ICancelableDataResult<PostSignatureResponse> = { canceled: false, data: new PostSignatureResponse() }; return Promise.resolve(returnResult); }); } }
64252df98e3a20b18877d5cea01d71aa14b21209
TypeScript
iamthismarvin/craftsmith
/src/store/modules/character.ts
2.828125
3
import { db } from '@/database'; import { CharacterState, Stats } from '@/utilities/interfaces'; export default { namespaced: true, state: { id: null, name: null, experience: null, stats: { dexterity: null, intelligence: null, stamina: null, strength: null, }, }, getters: { experience: (state: CharacterState) => state.experience, id: (state: CharacterState) => state.id, name: (state: CharacterState) => state.name, stats: (state: CharacterState) => state.stats, usedStatPoints: (state: CharacterState) => state.stats.dexterity + state.stats.intelligence + state.stats.stamina + state.stats.strength, }, mutations: { SET_EXPERIENCE_STATE(state: CharacterState, payload: number) { state.experience = payload; }, SET_ID_STATE(state: CharacterState, payload: number) { state.id = payload; }, SET_NAME_STATE(state: CharacterState, payload: string) { state.name = payload; }, SET_STATS_STATE(state: CharacterState, payload: Stats) { state.stats = payload; }, }, actions: { async SET_CHARACTER_FROM_DB({ commit }: { commit: Function }) { const id: number = Number(localStorage.getItem('id')); const character = await db.character.get(id); if (character) { commit('SET_EXPERIENCE_STATE', character.experience); commit('SET_ID_STATE', character.id); commit('SET_NAME_STATE', character.name); commit('SET_STATS_STATE', character.stats); } else { console.log(`Character (id: ${id}) does not exists.`); } }, }, };
412d22285d7976ec2e79cf95ef9f64ca56771cd7
TypeScript
dantehemerson/flash-cards-backend
/src/modules/card/card.network.ts
2.515625
3
import { Router } from 'express' import { response } from '../../response' import { createCard, findCards } from './card.controller' import { ConflictException } from '../../exceptions/conflict.exception' import { HttpException } from '../../exceptions/http.exception' export const cardRouter = Router() cardRouter.get('/', async (req, res) => { try { const cards = await findCards(req.body) response.success(req, res, cards, 200) } catch (error) { response.error(req, res, error, 500) } }) cardRouter.post('/', async (req, res, next) => { try { let createdMessage try { createdMessage = await createCard(req.body) } catch (err) { throw new ConflictException('Error creating....') } response.success(req, res, createdMessage, 201) } catch (error) { next(error) } })
233d0010533c8c7ebdbe9ef0de29cfad82ebc1fa
TypeScript
saldyy/graphql-practice
/be/src/resolver/author/AuthorResolver.ts
2.75
3
import { Author } from "entity/Author"; import { Book } from "entity/Book"; import { Arg, Mutation, Query, Resolver, InputType, Field, Authorized, } from "type-graphql"; import { Like } from "typeorm"; import { AuthorInput, AuthorQueryInput } from "./AuthorInput"; @Resolver(Author) export class AuthorResolver { @Authorized(["admin"]) @Mutation(() => Author) async createAuthor( @Arg("data", () => AuthorInput) data: AuthorInput ): Promise<Author> { console.log(data, "hihi"); const author = await Author.create(data).save(); const listNewBooks = []; for (const book of data.books) { const newBook = new Book(book.title, author); await newBook.save(); listNewBooks.push(newBook); } author.books = listNewBooks; console.log(author); return author; } @Query(() => [Author]) async authors( @Arg("params", () => AuthorQueryInput) params: AuthorQueryInput ): Promise<Author[]> { const { limit, page, key } = params; console.log(params, "params"); const listAuthor = await Author.find({ skip: (page - 1) * limit, take: limit, where: { name: Like(`%${key}%`) }, relations: ["books"], }); return listAuthor; } }
69a8ae82059186506893d3c6a266e94de48481c6
TypeScript
keindev/codecolor.js
/src/utils.ts
3.203125
3
import { IToken } from './types.js'; const isCross = (a: IToken, b: IToken): boolean => a.start >= b.start && a.start <= b.end && a.end >= b.end; const isIncludedIn = (a: IToken, b: IToken): boolean => a.start >= b.start && a.end <= b.end; export const half = (value: number): number => ~~(value / 2); export const compare = (left: number, right: number, token: IToken, tokens: IToken[]): number => { if (right <= tokens.length && left < right) { const middle = tokens[right - 1]; if (middle) { if (middle.end <= token.start) return compare(right, right + half(tokens.length - right + 1), token, tokens); if (middle.start >= token.end) return compare(left, left + half(right - left), token, tokens); if (isIncludedIn(token, middle)) return -Infinity; if (isIncludedIn(middle, token)) return right === 1 ? Infinity : -(right - 1); if (isCross(middle, token)) return Infinity; } } return right; };
9d6a237857dc31c9637bc981c3a3ef6fa9f51d8e
TypeScript
braintree/credit-card-type
/src/lib/is-valid-input-type.ts
2.96875
3
export function isValidInputType<T>(cardNumber: T): boolean { return typeof cardNumber === "string" || cardNumber instanceof String; }
71e5ae65a551731be3d1f343c4ca6603cb5ac640
TypeScript
Shunseii/express-mods-server
/src/seeds/create-mock-games.seed.ts
2.65625
3
import { Factory, Seeder } from "typeorm-seeding"; import { Game } from "../entities/Game"; import { Mod } from "../entities/Mod"; import { User } from "../entities/User"; import { GameFactoryContext } from "../factories/game.factory"; import { getRandomArrElement, getRandomNumBetween, } from "../utils/getRandomNum"; const AllGames: GameFactoryContext[] = [ { name: "The Elder Scrolls V: Skyrim", gameSlug: "skyrim", imageName: "skyrim", description: "The next chapter in the highly anticipated Elder Scrolls saga arrives from the makers of the 2006 and 2008 Games of the Year, Bethesda Game Studios. Skyrim reimagines and revolutionizes the open-world fantasy epic, bringing to life a complete virtual world open for you to explore any way you choose.", }, ]; export default class CreateMockGames implements Seeder { public async run(factory: Factory) { let count = 0; const createdGames = await factory<Game, GameFactoryContext>(Game)() .map(async (game) => { const { name, imageName, gameSlug, description } = AllGames[count++]; game.name = name; game.gameSlug = gameSlug; game.imageName = imageName; game.description = description; return game; }) .createMany(AllGames.length); const createdUsers = await factory(User)().createMany( getRandomNumBetween(1, 7) ); await factory(Mod)() .map(async (mod) => { const randomGame = getRandomArrElement(createdGames); const randomUser = getRandomArrElement(createdUsers); mod.author = randomUser; mod.game = randomGame; return mod; }) .createMany(20); } }
7c0cef287146b246f4f9565ff5858d9937697e09
TypeScript
ishabo/swapp
/src/store/swapi/reducers/index.ts
2.640625
3
import { Action } from 'redux'; import { actionTypes } from '../actions'; export interface ISwapiPerson { name: string; height: string; mass: string; hair_color: string; skin_color: string; eye_color: string; birth_year: string; gender: string; homeworld: string; films: string[]; species: string[]; vehicles: string[]; starships: string[]; created: string; edited: string; url: string; } export interface ISwapiStarship { name: string; model: string; manufacturer: string; cost_in_credits: string; length: string; max_atmosphering_speed: string; crew: string; passengers: string; cargo_capacity: string; consumables: string; hyperdrive_rating: string; MGLT: string; starship_class: string; pilots: string[]; films: string[]; created: string; edited: string; url: string; } export interface ISwapiState { data: { people: ISwapiPerson[]; starships: ISwapiStarship[]; }; meta: { isFetching: boolean; }; } const initialState: ISwapiState = { data: { people: [], starships: [] }, meta: { isFetching: false } }; interface ISwapiAction extends Action { payload: ISwapiPerson[] | ISwapiStarship[]; } export const swapiReducer = (state = initialState, action: ISwapiAction) => { switch (action.type) { case actionTypes.SAVE_PEOPLE: return { ...state, data: { ...state.data, people: action.payload as ISwapiPerson[] }, meta: { isFetching: false } }; case actionTypes.SAVE_STARSHIPS: return { ...state, data: { ...state.data, starships: action.payload as ISwapiStarship[] }, meta: { isFetching: false } }; case actionTypes.FETCH_PEOPLE: case actionTypes.FETCH_STARSHIPS: return { ...state, data: state.data, meta: { isFetching: true } }; default: return state; } };
00f8f17e065ac944278f0ccadc721b690df8619f
TypeScript
leorrose/HStyle
/app/client/src/app/team-members/team-members.component.ts
3.015625
3
import { TeamMemberService } from '../services/team-member.service'; import { TeamMember } from './../models/team-member'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-team-members', templateUrl: './team-members.component.html', styleUrls: ['./team-members.component.css'] }) export class TeamMembersComponent implements OnInit { teamMembers: Array<TeamMember[]>; constructor(private teamMemberService: TeamMemberService) { } ngOnInit(): void { // create chunks of team members - each chunk is a row in html this.teamMembers = this.chunkArray(this.teamMemberService.getTeamMembers(), 3); } /** * method split array into chunks * @param array array of team members * @param size number of element in each chunk * @returns array of chunks (arrays of team members) */ chunkArray(array: TeamMember[], size: number): Array<TeamMember[]> { // test array isn't empty if (array && array.length > 0){ const result = []; // create copy to not change original const arrayCopy = [...array]; // split array into chunks of same size while (arrayCopy.length > 0) { result.push(arrayCopy.splice(0, size)); } // if last chunk is not size we push empty objects if (result[result.length - 1].length !== size) { const toAdd = size - result[result.length - 1].length; for (let i = 0; i < toAdd; i++) { result[result.length - 1].push({}); } } return result; } return []; } }
0a34f8c40002c4fba8cd65e835978c5dee467457
TypeScript
therealmbittarelli/design-patterns-exploration
/observer/observer.ts
3.984375
4
// Observer pattern enables objects to 'subscribe' to be notified about state change events // (and unsubscribe) interface Subject { // Attach observer to the Subject attach(observer: Observer): void; // Detach observer to the Subject detach(observer: Observer): void; // Notify all attached observers notify(): void; } class ConcreteSubject implements Subject { public state: number; private observers: Observer[] = []; public attach(observer: Observer): void { const doesExist = this.observers.indexOf(observer) !== -1; if (doesExist) { return console.log("Observer has been attached already."); } console.log(`Attached an observer.`); this.observers.push(observer); } public detach(observer: Observer): void { const observerIndex = this.observers.indexOf(observer); if (observerIndex === -1) { return console.log("Nonexistent observer."); } this.observers.splice(observerIndex, 1); console.log("Detached an observer."); } public notify(): void { console.log("Notifying observers..."); for (let observer of this.observers) { observer.update(this); } } public someBusinessLogic(): void { console.log("Let's update state..."); this.state = Math.floor(Math.random() * (10 + 1)); console.log(`Updated state to ${this.state}`); this.notify(); } } interface Observer { update(subject: Subject): void; } class ConcreteObserverA implements Observer { public update(subject:Subject): void { if (subject instanceof ConcreteSubject && subject.state < 3) { console.log("ConcreteObserverA reacted to the event."); } } } class ConcreteObserverB implements Observer { public update(subject:Subject): void { if (subject instanceof ConcreteSubject && (subject.state === 0 || subject.state >= 3)) { console.log("ConcreteObserverB reacted to the event."); } } } let subject = new ConcreteSubject(); let observerOne = new ConcreteObserverA(); subject.attach(observerOne); let observerTwo = new ConcreteObserverB(); subject.attach(observerTwo); subject.someBusinessLogic(); subject.someBusinessLogic(); // subject.detach(observerTwo); subject.someBusinessLogic();
26ad97b507e6a224794b7022eddf39a0f80aaf30
TypeScript
michalczukm/mock-the-api-for-front-end-devs-presentation
/client/mock-api-client/src/app/notes/shared/note-type.pipe.ts
2.6875
3
import { Pipe, PipeTransform } from '@angular/core'; import { NoteType } from './note-type.model'; @Pipe({ name: 'noteType' }) export class NoteTypePipe implements PipeTransform { transform(value: NoteType): string { switch (value) { case NoteType.Meeting: return 'Meeting'; case NoteType.Personal: return 'Personal'; case NoteType.Urgent: return 'Urgent'; default: throw new Error(`NoteType "${value}" not supported!`); } } }
f8381dff1919806cea179a0f8eed3433c811a23e
TypeScript
victorvivenzio/angularexamples
/8. Formularios/src/app/components/data/data.component.ts
2.8125
3
import { Component } from '@angular/core'; import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms'; import {Observable} from 'rxjs/Observable'; @Component({ selector: 'app-data', templateUrl: './data.component.html', styles: [] }) export class DataComponent { public form: FormGroup; public user: Object = { fullname: { name: 'Victor', lastname: 'Vivenzio' }, email: 'victorvivenzio@gmail.com', hobbies: ['Correr', 'Comer', 'Tirar'] }; constructor() { this.form = new FormGroup({ 'fullname': new FormGroup({ 'name': new FormControl('', [ Validators.required, Validators.minLength(3) ]), 'lastname': new FormControl('', [Validators.required, this.noCaps]) } ), 'email': new FormControl('', [ Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\\.[a-z]{2,3}$') ] ), 'hobbies': new FormArray([ new FormControl('', Validators.required) ]), 'password1': new FormControl('', Validators.required ), 'password2': new FormControl(''), 'username': new FormControl('',Validators.required, this.checkUsername) }); this.form.controls['password2'].setValidators([ Validators.required, this.noPass.bind(this) ]); // this.form.patchValue(this.user); this.form.controls['username'].valueChanges.subscribe( (data) => { console.log(data) } ) this.form.controls['username'].statusChanges.subscribe( (data) => { console.log(data) } ) } private noCaps(control: FormControl): { [p: string]: boolean } { if (/[A-Z]/.test( control.value )) { return {nocaps: true}; } return null; } public noPass(control: FormControl ): {[s: string]: boolean} { let form: any = this.form.controls; if (control.value !== form['password1'].value) { return {nocaps: true}; } return null; }sdfs public checkUsername(control: FormControl): Promise<any>|Observable<any>{ let promise = new Promise( (resolve, reject) => { setTimeout(()=>{ if (control.value === "vivenzio"){ resolve({ exist:true }); } else { resolve( null ); } },3000) }); return promise; } public addHobbie(): void { (<FormArray>this.form.controls['hobbies']).push( new FormControl('', Validators.required) ); } public saveForm(): void { console.log(this.form); // this.form.reset({ // fullname : { // name: '', // lastname: '' // }, // email: '', // hobbies: [] // }); // // const hobbiesGroup = <FormArray> this.form.controls['hobbies']; // for (let index = hobbiesGroup.length - 1; index > 0; index--) { // hobbiesGroup.removeAt(index); // } } }
c35f1c8a5dded546eac8a1daf5026712fe77b744
TypeScript
Parez/mean-stack-ngrx-citations
/src/app/models/citation.ts
2.53125
3
import {User} from "./user"; /** * Created by baunov on 14/10/16. */ export class Citation { //public static curId = 0; public _id:String = ""; constructor(public text:String = "", public author:String = "Unknown", public user:User = new User("Anonymous"), public tags:Array<String> = [], public date_published:number = Date.now(), public rank = 0, public views = 0, public likes = 0, public dislikes = 0) { //this._id = String(Citation.curId); //Citation.curId++; } }
449acfafb7ef8f2bf6233e6548464f66e717e909
TypeScript
Sansossio/twisted
/src/models-dto/status/status-v4/lol-status-content.dto.ts
2.625
3
/** * Lol Status Content dto */ export class LolStatusContentDTO { /** * Incident or Maintance status language * (e.g. `en_GB`) */ locale: string /** * Incident or Maintance * (e.g. `Account Transfers Unavailable`) */ content: string }
de6a3cd9df493f94af9adcfae9eb3cf8d12faff4
TypeScript
ildaro/Fitness-App
/src/app/services/storage.service.ts
2.640625
3
import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; export interface Item { id: number, title: string, value: string, modified: number } export interface Exercise { id: number, name: string, description: string, sets: number, reps: number, modified: number, } const ITEMS_KEY = 'my-items'; const EXER_KEY = 'my-exercises'; @Injectable({ providedIn: 'root' }) export class StorageService { constructor(private storage: Storage) { } // CREATE item addItem(item: Item): Promise<any> { return this.storage.get(ITEMS_KEY).then((items: Item[]) => { if (items) { items.push(item); return this.storage.set(ITEMS_KEY, items); } else { return this.storage.set(ITEMS_KEY, [item]); } }); } //create exercise addExercise(exercise: Exercise): Promise<any>{ return this.storage.get(EXER_KEY).then((exercises: Exercise[]) =>{ if(exercises){ exercises.push(exercise); return this.storage.set(EXER_KEY, exercises); }else{ return this.storage.set(EXER_KEY, [exercise]); } }); } // READ items getItems(): Promise<Item[]> { return this.storage.get(ITEMS_KEY); } //read exercises getExercises(): Promise<Exercise[]>{ return this.storage.get(EXER_KEY); } // UPDATE item updateItem(item: Item): Promise<any> { return this.storage.get(ITEMS_KEY).then((items: Item[]) => { if (!items || items.length === 0) { return null; } let newItems: Item[] = []; for (let i of items) { if (i.id === item.id) { newItems.push(item); } else { newItems.push(i); } } return this.storage.set(ITEMS_KEY, newItems); }); } //update Exercise updateExercise(exercise: Exercise): Promise<any>{ return this.storage.get(EXER_KEY).then((exercises: Exercise[]) => { if (!exercises || exercises.length === 0){ return null; } let newExercises: Exercise[] = []; for(let e of exercises){ if(e.id === exercise.id){ newExercises.push(exercise); }else{ newExercises.push(e); } } return this.storage.set(EXER_KEY, newExercises); }); } // DELETE deleteItem(id: number): Promise<Item> { return this.storage.get(ITEMS_KEY).then((items: Item[]) => { if (!items || items.length === 0) { return null; } let toKeep: Item[] = []; for (let i of items) { if (i.id !== id) { toKeep.push(i); } } return this.storage.set(ITEMS_KEY, toKeep); }); } //DELETE EXERCISE deleteExercise(id: number): Promise<Exercise>{ return this.storage.get(EXER_KEY).then((exercises: Exercise[]) => { if(!exercises || exercises.length === 0){ return null; } let toKeep: Exercise[] = []; for(let e of exercises){ if(e.id !== id){ toKeep.push(e); } } return this.storage.set(EXER_KEY, toKeep); }); } }
165ed4919067c606826c1a0b559f6187c119457f
TypeScript
pulumi/pulumi-datadog
/sdk/nodejs/monitorConfigPolicy.ts
2.515625
3
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** import * as pulumi from "@pulumi/pulumi"; import * as inputs from "./types/input"; import * as outputs from "./types/output"; import * as utilities from "./utilities"; /** * Provides a Datadog monitor config policy resource. This can be used to create and manage Datadog monitor config policies. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as datadog from "@pulumi/datadog"; * * const test = new datadog.MonitorConfigPolicy("test", { * policyType: "tag", * tagPolicy: { * tagKey: "env", * tagKeyRequired: false, * validTagValues: [ * "staging", * "prod", * ], * }, * }); * ``` */ export class MonitorConfigPolicy extends pulumi.CustomResource { /** * Get an existing MonitorConfigPolicy resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: MonitorConfigPolicyState, opts?: pulumi.CustomResourceOptions): MonitorConfigPolicy { return new MonitorConfigPolicy(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'datadog:index/monitorConfigPolicy:MonitorConfigPolicy'; /** * Returns true if the given object is an instance of MonitorConfigPolicy. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is MonitorConfigPolicy { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === MonitorConfigPolicy.__pulumiType; } /** * The monitor config policy type Valid values are `tag`. */ public readonly policyType!: pulumi.Output<string>; /** * Config for a tag policy. Only set if `policyType` is `tag`. */ public readonly tagPolicy!: pulumi.Output<outputs.MonitorConfigPolicyTagPolicy | undefined>; /** * Create a MonitorConfigPolicy resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: MonitorConfigPolicyArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: MonitorConfigPolicyArgs | MonitorConfigPolicyState, opts?: pulumi.CustomResourceOptions) { let resourceInputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as MonitorConfigPolicyState | undefined; resourceInputs["policyType"] = state ? state.policyType : undefined; resourceInputs["tagPolicy"] = state ? state.tagPolicy : undefined; } else { const args = argsOrState as MonitorConfigPolicyArgs | undefined; if ((!args || args.policyType === undefined) && !opts.urn) { throw new Error("Missing required property 'policyType'"); } resourceInputs["policyType"] = args ? args.policyType : undefined; resourceInputs["tagPolicy"] = args ? args.tagPolicy : undefined; } opts = pulumi.mergeOptions(utilities.resourceOptsDefaults(), opts); super(MonitorConfigPolicy.__pulumiType, name, resourceInputs, opts); } } /** * Input properties used for looking up and filtering MonitorConfigPolicy resources. */ export interface MonitorConfigPolicyState { /** * The monitor config policy type Valid values are `tag`. */ policyType?: pulumi.Input<string>; /** * Config for a tag policy. Only set if `policyType` is `tag`. */ tagPolicy?: pulumi.Input<inputs.MonitorConfigPolicyTagPolicy>; } /** * The set of arguments for constructing a MonitorConfigPolicy resource. */ export interface MonitorConfigPolicyArgs { /** * The monitor config policy type Valid values are `tag`. */ policyType: pulumi.Input<string>; /** * Config for a tag policy. Only set if `policyType` is `tag`. */ tagPolicy?: pulumi.Input<inputs.MonitorConfigPolicyTagPolicy>; }
0e1ccbfe37267d796c4ece69224023e4574e592f
TypeScript
ccmikechen/typescript-design-pattern
/factory_method/weaponFactory.ts
3.8125
4
export abstract class Weapon { weaponType: string; length: number; constructor(weaponType: string, length: number) { this.weaponType = weaponType; this.length = length; } getInfo(): string { return `Type: ${this.weaponType} - ${this.length} cm`; } } class Sword extends Weapon { constructor(length: number) { super("Sword", length); } } class Knife extends Weapon { constructor(length: number) { super("Knife", length); } } export class WeaponFactory { createLongSword(): Sword { return new Sword(150); } createShortSword(): Sword { return new Sword(100); } createKnife(): Knife { return new Knife(50); } }
80357477ca7f566a2fbc6788877ff036e9e1ed99
TypeScript
Error-331/code_tests
/src/type_script/functions.ts
3.484375
3
'use strict'; export default async () => { interface Person { name: string; surname: string; age: number; docs: string[]; } interface Register { addBeforeRegisterListener(onBeforeRegister: (this: void, registerNumber: number) => void): void; } class Car { name: string; constructor(name: string) { this.name = name; } onBeforeRegister(this:void, registerNumber): void { console.log('register', registerNumber); } } let personObj1 = { name: 'Maksim', surname: 'Zaas', age: 26, docs: ['passport', 'foreign passport', 'driver licence'], log: function(this: Person) { console.log('Name:', this.name); console.log('Surname:', this.surname); console.log('Age:', this.age); console.log('Docs:', this.docs); } }; class VehicleRegister implements Register { vehicleBeforeRegisterHandlers: any[] = []; addBeforeRegisterListener(handler): void { this.vehicleBeforeRegisterHandlers.push(handler) } registerVehicles(): void { this.vehicleBeforeRegisterHandlers.forEach((beforeCallback, index) => { beforeCallback(index + 1); }); } } function exampleFunction1(param1: number, param2: number): number { return param1 + param2; } let exampleFunction2: (param1: number, param2: number) => number = function(param1: number, param2: number): number { return param1 + param2; }; // example function type function exampleFunction3(firstName: string, lastName?: string) { if (lastName) return firstName + " " + lastName; else return firstName; } function exampleFunction4(firstName: string, lastName: string = 'Smersh') { if (lastName) return firstName + " " + lastName; else return firstName; } function exampleFunction5(firstName: string = 'Misha', lastName: string) { if (lastName) return firstName + " " + lastName; else return firstName; } function exampleFunction6(firstName: string, ...restOfName: string[]) { return firstName + " " + restOfName.join("-"); } function personHavePassport(person:Person): boolean; function personHavePassport(docs: string[]): boolean; function personHavePassport(data): any { if (data instanceof Array) { return data.indexOf('passport') !== -1; } else { return data.docs.indexOf('passport') !== -1; } } console.log('TypeScript functions examples'); console.log('============================='); console.log(''); console.log('Simple example function that adds two numbers:', exampleFunction1(2, 3)); console.log('Same, but using function type:', exampleFunction2(4, 5)); console.log(''); console.log('Function that has optional parameters (one parameter):', exampleFunction3('Maksim')); console.log('Function that has optional parameters (two parameters):', exampleFunction3('Maksim', 'Zaas')); console.log(''); console.log('Function that has default value for second parameter:', exampleFunction4('Boris')); console.log('Function that has default value for first parameter:', exampleFunction5(undefined, 'Zhenkov')); console.log('Function that implements "rest" parameter:', exampleFunction6('Peter', 'Kitai', 'Gorodsky')); console.log(''); console.log('Testing object method while specifying "this":'); console.log(''); personObj1.log(); console.log(''); console.log('Example usage of "function as callback":'); console.log(''); let exampleCar1 = new Car('BMW'); let vehicleRegister1 = new VehicleRegister(); vehicleRegister1.addBeforeRegisterListener(exampleCar1.onBeforeRegister); vehicleRegister1.registerVehicles(); console.log(''); console.log('Function overload example:'); console.log(''); console.log(personHavePassport(personObj1)); console.log(personHavePassport(personObj1.docs)); console.log(''); console.log('--------------------------------------------------------'); console.log(''); }
e55c36e425d5d433d148980df6591ecf19b5d6bc
TypeScript
alyron/dc_laya_projects
/2DGame/src/framework/serialize/LocalValue.ts
2.75
3
module dc { /** * 本地数据 * @author hannibal * @time 2017-7-15 */ export class LocalValue { private static m_GlobalKey:string = ""; /** * 设置全局id,用于区分同一个设备的不同玩家 * @param key 唯一键,可以使用玩家id */ public static SetGlobalKey(key:string):void { this.m_GlobalKey = key; } public static Get(key: string):string { return Laya.LocalStorage.getItem(this.GetFullKey(key)); } public static Set(key: string, value: string):void { Laya.LocalStorage.setItem(this.GetFullKey(key), value); } public static Remove(key:string) { Laya.LocalStorage.removeItem(this.GetFullKey(key)); } public static Clear():void { Laya.LocalStorage.clear(); } private static GetFullKey(key:string):string { return this.m_GlobalKey+"_"+key; } } }
ba73f72cd6d2b7753a6537f823a3cfb79a236d7a
TypeScript
herculesinc/credo.io-emitter
/index.ts
2.78125
3
"use strict"; // IMPORTS // ================================================================================================ import * as redis from 'redis'; import * as msgpack from 'msgpack-js'; import * as uid2 from 'uid2'; // INTERFACES // ================================================================================================ // MODULE VARIABLES // ================================================================================================ var EVENT = 2; // from socket.io-parser var uid = 'em' + uid2(6); // EMITTER CLASS // ================================================================================================ export class Emitter { client: redis.RedisClient; prefix: string; namespaces: Map<string, Namespace>; constructor(client: redis.RedisClient, prefix?: string) { this.client = client; this.prefix = prefix || 'socket.io'; this.namespaces = new Map<string,Namespace>(); } of(nsp: string) { if (!this.namespaces.has(nsp)) { this.namespaces.set(nsp, new Namespace(nsp, this.client, this.prefix)); } return this.namespaces.get(nsp); } } // NAMESPACE CLASS // ================================================================================================ export class Namespace { name : string; rooms : string[]; client : redis.RedisClient; prefix : string; constructor(name: string, client: redis.RedisClient, prefix: string) { this.name = name; this.rooms = []; this.client = client; this.prefix = prefix; } in(room: string): Namespace { if (this.rooms.indexOf(room) < 0) { this.rooms.push(room); } return this; } emit(event: string, data: any) { var packet = { nsp: this.name, type: EVENT, data: [event, data] }; var channel = `${this.prefix}#${packet.nsp}#`; var message = msgpack.encode([uid, packet, { rooms: this.rooms }]); if (this.rooms.length > 0) { this.rooms.forEach((room) => { var roomChannel = channel + room + '#'; this.client.publish(roomChannel, message); }); } else { this.client.publish(channel, message); } this.rooms = []; } }
156354271e20dc3da27ace472b551e9f4b53cde0
TypeScript
copquesz/usjt-automato
/src/app/model/note.model.ts
3.046875
3
export class Note { id: number; x: number; y: number; w: number; h: number; value: number; image: HTMLImageElement; constructor(x: number, y: number, w: number, h: number, value: number, src: string) { this.x = x; this.y = y; this.w = w; this.h = h; this.value = value; this.image = new Image(); this.image.src = src; } load(context: CanvasRenderingContext2D) { this.image.onload = () => { context.drawImage(this.image, this.x, this.y, this.w, this.h); context.strokeRect(this.x, this.y, this.w, this.h); } } draw(context: CanvasRenderingContext2D) { context.drawImage(this.image, this.x, this.y, this.w, this.h); context.strokeRect(this.x, this.y, this.w, this.h); } }
4dcc6de219321930208b5067356a8a709251519d
TypeScript
yoursunny/NDNts
/packages/packet/test-fixture/sign-verify.ts
2.6875
3
import { Decoder, Encoder } from "@ndn/tlv"; import { expect } from "vitest"; import { Data, Interest, type SigInfo, type Signer, type Verifier } from ".."; type Packet = Interest | Data; type PacketCtor = typeof Interest | typeof Data; export const PacketTable: ReadonlyArray<{ PacketType: string; Packet: PacketCtor }> = [ { PacketType: "Interest", Packet: Interest }, { PacketType: "Data", Packet: Data }, ]; interface SignRecord { wire: Uint8Array; sigInfo: SigInfo; sigValue: Uint8Array; } interface VerifyRecord { verified: boolean; } export interface TestRecord { sA0: SignRecord; // sign with pvtA sA1: SignRecord; // sign with pvtA again sB0: SignRecord; // sign with pvtB sB1: SignRecord; // sign with pvtB again vAA: VerifyRecord; // verify pktA with pubA vAB: VerifyRecord; // verify pktA with pubB vBA: VerifyRecord; // verify pktB with pubA vBB: VerifyRecord; // verify pktB with pubB vMi: VerifyRecord; // verify mutated pktA (inserted byte) with pubA vMd: VerifyRecord; // verify mutated pktA (deleted byte) with pubA vMc: VerifyRecord; // verify mutated pktA (changed bit) with pubA } async function sign(cls: PacketCtor, pvt: Signer): Promise<[Packet, SignRecord]> { const src = new cls("/NAME"); await pvt.sign(src); const wire = Encoder.encode(src); const pkt = cls.decodeFrom(new Decoder(wire)); if (!pkt.sigInfo) { throw new Error("sigInfo is missing"); } if (!pkt.sigValue) { throw new Error("sigValue is missing"); } return [pkt, { wire, sigInfo: pkt.sigInfo, sigValue: pkt.sigValue, }]; } async function verify(pkt: Packet, pub: Verifier): Promise<VerifyRecord> { let verified: boolean; try { await pub.verify(pkt); verified = true; } catch { verified = false; } return { verified }; } export async function execute(cls: PacketCtor, pvtA: Signer, pubA: Verifier, pvtB: Signer, pubB: Verifier): Promise<TestRecord> { const [pktA, sA0] = await sign(cls, pvtA); const [pktB, sB0] = await sign(cls, pvtB); const pktMi = cls.decodeFrom(new Decoder(sA0.wire)); pktMi.sigValue = (() => { const sig = new Uint8Array(pktMi.sigValue.byteLength + 1); sig.set(pktMi.sigValue, 0); const offset = 1 + Math.trunc(Math.random() * sig.byteLength - 2); sig.copyWithin(offset + 1, offset); sig[offset] = 0xBB; return sig; })(); const pktMd = cls.decodeFrom(new Decoder(sA0.wire)); pktMd.sigValue = (() => { const sig = Uint8Array.from(pktMd.sigValue); const offset = Math.trunc(Math.random() * (sig.byteLength - 1)); sig.copyWithin(offset, offset + 1); return sig.subarray(0, -1); })(); const pktMc = cls.decodeFrom(new Decoder(sA0.wire)); pktMc.sigValue = (() => { const sig = Uint8Array.from(pktMc.sigValue); // Changing one bit is sometimes insufficient to break the signature, // so change five bits to reduce test failures. for (let i = 0; i < 5; ++i) { const offset = Math.trunc(Math.random() * sig.byteLength); sig[offset] ^= 0x01; } return sig; })(); return { sA0, sA1: (await sign(cls, pvtA))[1], sB0, sB1: (await sign(cls, pvtB))[1], vAA: await verify(pktA, pubA), vAB: await verify(pktA, pubB), vBA: await verify(pktB, pubA), vBB: await verify(pktB, pubB), vMi: await verify(pktMi, pubA), vMd: await verify(pktMd, pubA), vMc: await verify(pktMc, pubA), }; } export function check(record: TestRecord, { deterministic = false, sameAB = false, }: { deterministic?: boolean; sameAB?: boolean; } = {}) { // If signing algorithm is deterministic, both signatures should be the same. // Otherwise, they should be different. expect(!Buffer.compare(record.sA0.sigValue, record.sA1.sigValue)).toBe(deterministic); expect(!Buffer.compare(record.sB0.sigValue, record.sB1.sigValue)).toBe(deterministic); // If A and B are different keys, their signatures should be different. if (!sameAB) { expect(!Buffer.compare(record.sA0.sigValue, record.sB0.sigValue)).toBeFalsy(); } // Verification using counterpart of the signing key should succeed. expect(record.vAA.verified).toBeTruthy(); expect(record.vBB.verified).toBeTruthy(); // Verification using a different key should fail, unless A and B are the same (i.e. theDigestKey). expect(record.vAB.verified).toBe(sameAB); expect(record.vBA.verified).toBe(sameAB); // Verification on a mutated signature should fail. expect(record.vMi.verified).toBe(false); expect(record.vMd.verified).toBe(false); expect(record.vMc.verified).toBe(false); // Caller is responsible for checking SigInfo. }
bf5241558f255eeb42321ec674b97c3082df7627
TypeScript
rrsqrd/UciAngular2_hw5_RockysRides
/RockysRides/app/model/product.repository.ts
2.921875
3
 import { Injectable } from "@angular/core"; import { Product } from "./product.model"; import { RestDataSource } from "./rest.datasource"; @Injectable() export class ProductRepository { private products: Product[] = []; private categories: string[] = []; // ProductRepository service communicates with RestDataSource service constructor(private dataSource: RestDataSource) { //ProductRepository subscribes to the dataSource dataSource.getProducts().subscribe(data => { //11.26.2018 code change: added 'as Product' casting this.products = data as Product[]; //this.categories = data.map(p => p.category) // .filter((c, index, array) => array.indexOf(c) == index).sort(); // 11.26.2018 code change: using 'this.products' instead argument 'data' // resolved error TS2339: // Property 'map' does not exist on type 'Product | Order | Product[] | Order[]'. this.categories = this.products.map(p => p.category) .filter((c, index, array) => array.indexOf(c) == index).sort(); }); } getProducts(category: string = null): Product[] { return this.products .filter(p => category == null || category == p.category); } getProduct(id: number): Product { return this.products.find(p => p.id == id); } getCategories(): string[] { return this.categories; } saveProduct(product: Product) { if (product.id == null || product.id == 0) { this.dataSource.saveProduct(product) // 11.26.2018 code change: added 'as Product' casting .subscribe(p => this.products.push(p as Product)); } else { this.dataSource.updateProduct(product) .subscribe(p => { this.products.splice(this.products. findIndex(p => p.id == product.id), 1, product); }); } } deleteProduct(id: number) { this.dataSource.deleteProduct(id).subscribe(p => { this.products.splice(this.products. findIndex(p => p.id == id), 1); }) } }
e03037dd2afc60ca7cf0cc5c66dff25cd42daaf2
TypeScript
ilyajav/Counter---ReactTS
/src/bll/coutner-reducer.test.ts
3.0625
3
import { changeMaxValueAC, changeMinValueAC, counterReducer, increaseCounterValueAC, InitialState } from "./counter-reducer"; let state: InitialState beforeEach(() =>{ state = { minValue: 5, maxValue: 8, counter: 1 } }) test('max value must be changed', () =>{ const action = changeMaxValueAC(12) const endState = counterReducer(state,action) expect(endState.maxValue).toBe(12) }) test('min value must be changed', () =>{ const action = changeMinValueAC(2) const endState = counterReducer(state,action) expect(endState.minValue).toBe(2) expect(endState.counter).toBe(endState.minValue) }) test('increase min value', () =>{ const action = increaseCounterValueAC() const endState = counterReducer(state, action) expect(endState.counter).toBe(2) })
70d93c2c4f639cdfa431cc149745b32688514ae7
TypeScript
zenatureza/job-matching
/backend/src/modules/candidates/repositories/ICandidatesRepository.ts
2.515625
3
import RecruitingApiCandidateTechnologyDTO from '@modules/technologies/dtos/RecruitingApiCandidateTechnologyDTO'; import RecruitingApiCandidateDTO from '../dtos/RecruitingApiCandidateDTO'; import Candidate from '../infra/typeorm/entities/Candidate.entity'; export default interface ICandidatesRepository { /** Finds by recruiting api ids */ findByIds(ids: number[]): Promise<Candidate[] | undefined>; save(recruitingApiCandidates: Candidate[]): Promise<Candidate[]>; findByFilters( city: string, experience: string, technologies: RecruitingApiCandidateTechnologyDTO[], ): Promise<Candidate[] | undefined>; }
7d3026ab9170f61c19adcae7353f189bc35d6cc5
TypeScript
lawvs/Algorithm-Training
/leetcode/350.intersection-of-two-arrays-ii.ts
3.15625
3
function intersect(nums1: number[], nums2: number[]): number[] { const arr = [] const m: { [x: number]: number } = {} for (const num1 of nums1) { m[num1] = (m[num1] || 0) + 1 } for (const num2 of nums2) { if (m[num2]) { m[num2] -= 1 arr.push(num2) } } return arr }
0d72b9ee4c8659d42a61f4b1df1c0d2db23a8f21
TypeScript
LeonBaudouin/Portfolio
/src/js/Canvas/Shapes/Square/DarkThemeSquareRenderer.ts
2.734375
3
import { DarkThemeSquareState } from "./DarkThemeSquareState"; import { RendererInterface } from "../../Core/Abstract/RendererInterface"; import { Canvas } from "../../Canvas"; export class DarkThemeSquareRenderer implements RendererInterface { public Render(state: DarkThemeSquareState, ctx: CanvasRenderingContext2D): void { const { position, angle, strokeColor, strokeSize, size, image } = state; ctx.save(); ctx.translate( position.x, position.y ); ctx.rotate(angle); if (image != null) { this.RenderImage(state, ctx); } ctx.strokeStyle = strokeColor.toString(); ctx.lineWidth = strokeSize; ctx.strokeRect(- size / 2, - size / 2, size, size); ctx.restore(); } private RenderImage(state: DarkThemeSquareState, ctx: CanvasRenderingContext2D): void { const { angle, strokeSize, size, image, imageOpacity } = state; const { height } = Canvas.getSize() const { width: imageWidth, height: imageHeight } = image const width = height * imageWidth / imageHeight; ctx.beginPath(); const clipSize = size + strokeSize; ctx.rect(- clipSize / 2, - clipSize / 2, clipSize, clipSize); ctx.clip(); ctx.rotate(- angle); ctx.globalAlpha = imageOpacity; ctx.drawImage(image, - width / 2, - height / 2, width, height); ctx.globalAlpha = 1; ctx.rotate(angle); } }
420aee6cff3fcab6ea7f18c6d34cdf6e772196d6
TypeScript
katalogoc/printer
/src/types/structs.ts
2.53125
3
export interface HashMap<T> { [key: string]: T; } export interface StoredFile { id: string path: string }
1f76ee3c51be07e777597c16d30bf5d09b777afb
TypeScript
Gelio/loose-ts-check
/src/cli/io/get-program-input.ts
2.546875
3
import { createInterface } from 'readline'; export const getProgramInput = () => new Promise<string[]>((resolve) => { const programInput: string[] = []; const rl = createInterface(process.stdin); rl.on('line', (line) => { programInput.push(line); }); rl.once('close', () => { resolve(programInput); }); });
5535dbda3dc202afd3e1b405c4284f6940570a08
TypeScript
Kuchasz/photographers-panel
/packages/panel/src/sdk.ts
2.546875
3
import { GraphQLClient } from 'graphql-request'; import * as Dom from 'graphql-request/dist/types.dom'; import gql from 'graphql-tag'; export type Maybe<T> = T | null; export type InputMaybe<T> = Maybe<T>; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; }; export type Client = { __typename?: 'Client'; id: Scalars['Int']; name: Scalars['String']; }; export type DeleteResult = { __typename?: 'DeleteResult'; affectedRows: Scalars['Int']; }; export type Like = { __typename?: 'Like'; imageId: Scalars['String']; liked: Scalars['Boolean']; likes: Scalars['Int']; }; export type LikedPhoto = { __typename?: 'LikedPhoto'; directoryName: Scalars['String']; fileName: Scalars['String']; likes: Scalars['Float']; }; export type Mutation = { __typename?: 'Mutation'; connect: Client; likeImage: Like; unlikeImage: DeleteResult; }; export type MutationConnectArgs = { name: Scalars['String']; }; export type MutationLikeImageArgs = { clientId: Scalars['Int']; imageId: Scalars['String']; }; export type MutationUnlikeImageArgs = { clientId: Scalars['Int']; imageId: Scalars['String']; }; export type Query = { __typename?: 'Query'; likedPhotos: Array<LikedPhoto>; likes: Array<Like>; }; export type QueryLikedPhotosArgs = { galleryId: Scalars['Int']; }; export type QueryLikesArgs = { clientId: Scalars['Int']; }; export const LikesDocument = gql` query likes($clientId: Int!) { likes(clientId: $clientId) { imageId liked likes } } `; export const LikedPhotosDocument = gql` query likedPhotos($galleryId: Int!) { likedPhotos(galleryId: $galleryId) { likes fileName directoryName } } `; export const LikeImageDocument = gql` mutation likeImage($imageId: String!, $clientId: Int!) { likeImage(imageId: $imageId, clientId: $clientId) { imageId } } `; export const UnlikeImageDocument = gql` mutation unlikeImage($imageId: String!, $clientId: Int!) { unlikeImage(imageId: $imageId, clientId: $clientId) { affectedRows } } `; export const ConnectClientDocument = gql` mutation connectClient($name: String!) { connect(name: $name) { id } } `; export type SdkFunctionWrapper = <T>(action: (requestHeaders?:Record<string, string>) => Promise<T>, operationName: string, operationType?: string) => Promise<T>; const defaultWrapper: SdkFunctionWrapper = (action, _operationName, _operationType) => action(); export function getSdk(client: GraphQLClient, withWrapper: SdkFunctionWrapper = defaultWrapper) { return { likes(variables: LikesQueryVariables, requestHeaders?: Dom.RequestInit["headers"]): Promise<LikesQuery> { return withWrapper((wrappedRequestHeaders) => client.request<LikesQuery>(LikesDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'likes', 'query'); }, likedPhotos(variables: LikedPhotosQueryVariables, requestHeaders?: Dom.RequestInit["headers"]): Promise<LikedPhotosQuery> { return withWrapper((wrappedRequestHeaders) => client.request<LikedPhotosQuery>(LikedPhotosDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'likedPhotos', 'query'); }, likeImage(variables: LikeImageMutationVariables, requestHeaders?: Dom.RequestInit["headers"]): Promise<LikeImageMutation> { return withWrapper((wrappedRequestHeaders) => client.request<LikeImageMutation>(LikeImageDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'likeImage', 'mutation'); }, unlikeImage(variables: UnlikeImageMutationVariables, requestHeaders?: Dom.RequestInit["headers"]): Promise<UnlikeImageMutation> { return withWrapper((wrappedRequestHeaders) => client.request<UnlikeImageMutation>(UnlikeImageDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'unlikeImage', 'mutation'); }, connectClient(variables: ConnectClientMutationVariables, requestHeaders?: Dom.RequestInit["headers"]): Promise<ConnectClientMutation> { return withWrapper((wrappedRequestHeaders) => client.request<ConnectClientMutation>(ConnectClientDocument, variables, {...requestHeaders, ...wrappedRequestHeaders}), 'connectClient', 'mutation'); } }; } export type Sdk = ReturnType<typeof getSdk>; export type LikesQueryVariables = Exact<{ clientId: Scalars['Int']; }>; export type LikesQuery = { __typename?: 'Query', likes: Array<{ __typename?: 'Like', imageId: string, liked: boolean, likes: number }> }; export type LikedPhotosQueryVariables = Exact<{ galleryId: Scalars['Int']; }>; export type LikedPhotosQuery = { __typename?: 'Query', likedPhotos: Array<{ __typename?: 'LikedPhoto', likes: number, fileName: string, directoryName: string }> }; export type LikeImageMutationVariables = Exact<{ imageId: Scalars['String']; clientId: Scalars['Int']; }>; export type LikeImageMutation = { __typename?: 'Mutation', likeImage: { __typename?: 'Like', imageId: string } }; export type UnlikeImageMutationVariables = Exact<{ imageId: Scalars['String']; clientId: Scalars['Int']; }>; export type UnlikeImageMutation = { __typename?: 'Mutation', unlikeImage: { __typename?: 'DeleteResult', affectedRows: number } }; export type ConnectClientMutationVariables = Exact<{ name: Scalars['String']; }>; export type ConnectClientMutation = { __typename?: 'Mutation', connect: { __typename?: 'Client', id: number } };
2c097115e38e40b5ddf38bf4b7971b32de4aa2fe
TypeScript
ryusaka/react_fsa_thunk_example
/app/src/reducers/pure.ts
3.125
3
import axios, { AxiosResponse } from 'axios' import { Dispatch } from 'redux' const SYNC = 'user/SYNC_PURE' as const const ASYNC_START = 'user/ASYNC_START_PURE' as const const ASYNC_DONE = 'user/ASYNC_DONE_PURE' as const const ASYNC_FAILED = 'user/ASYNC_FAILED_PURE' as const class CustomError extends Error { } export interface State { syncText: string, waiting?: boolean, finished?: boolean, response?: string, error?: CustomError, } const syncActionCreator = (text: string) => ({ type: SYNC, text, }) const asyncActionStartCreator = () => { return { type: ASYNC_START, } } const asyncActionDoneCreator = ({response}: {response: string}) => { return { type: ASYNC_DONE, response, } } const asyncActionFailedCreator = (error: CustomError) => { return { type: ASYNC_FAILED, error, } } type Actions = ReturnType<typeof syncActionCreator> | ReturnType<typeof asyncActionStartCreator> | ReturnType<typeof asyncActionDoneCreator> | ReturnType<typeof asyncActionFailedCreator> export const asyncAction = (params) => { return async (dispatch: Dispatch) => { let res: AxiosResponse dispatch(asyncActionStartCreator()) try { res = await axios.get('/wait1000', {params}) // if (res.status !== 200) { // throw new CustomError(`Error ${res.status}: ${res.statusText}`) // } dispatch(syncActionCreator('sync action dispatched')) } catch (e) { return dispatch(asyncActionFailedCreator(e)) } return dispatch(asyncActionDoneCreator(res.data)) } } export const initial: State = { syncText: 'not dispatched', waiting: false, finished: false, response: '', } export const reducer = (state: State = initial, action: Actions): State => { switch (action.type) { case SYNC: { return { ...state, syncText: action.text, } } case ASYNC_START: { return { ...state, waiting: true, finished: false, error: undefined, response: '', } } case ASYNC_FAILED: { return { ...state, waiting: false, finished: false, response: '', error: action.error, } } case ASYNC_DONE: { return { ...state, waiting: false, finished: true, response: action.response, error: undefined, } } default: { return state } } }
7fc247e2d7d51c2264553b0a8aa62f45c5708fbe
TypeScript
jzj/LiveKit-Svelte-Exploration
/src/lib/utils/mediaConstraintsBuilder.ts
2.609375
3
export type MediaConstraintsInfos = { constraints: MediaStreamConstraints, needsUpdate: boolean } const buildDefault = (id) => ({deviceId: {exact: id}}) export function buildMediaConstraints(preferredDevices: Record<MediaDeviceKind, string>, existingStream?: MediaStream): MediaConstraintsInfos { const constraints: any = { video: { aspectRatio: { ideal: 16 / 9 }, }, audio: true, }; if(preferredDevices.audioinput) { constraints.audio = buildDefault(preferredDevices.audioinput) } if(preferredDevices.videoinput) { constraints.video = { ...constraints.video, ...buildDefault(preferredDevices.videoinput) } } return {constraints, needsUpdate: true}; }
6905c78b61fca3f12ffc9c684bedfa7c0fa9c169
TypeScript
SongFuZhen/easy_food
/modules/front/src/cuba/entities/easyfood_Shop.ts
2.640625
3
import { StandardEntity } from "./base/sys$StandardEntity"; import { User } from "./base/sec$User"; export class Shop extends StandardEntity { static NAME = "easyfood_Shop"; name?: string | null; phone?: string | null; address?: string | null; remark?: string | null; manager?: User | null; } export type ShopViewName = "_minimal" | "_local" | "_base"; export type ShopView<V extends ShopViewName> = V extends "_minimal" ? Pick<Shop, "id" | "name"> : V extends "_local" ? Pick<Shop, "id" | "name" | "phone" | "address" | "remark"> : V extends "_base" ? Pick<Shop, "id" | "name" | "phone" | "address" | "remark"> : never;
bf176ed5565d42dea98dbedc8e9d13b84f59acd9
TypeScript
johnnyb912/MigraineTracker
/src/app/store/Statements/statements.reducer.ts
2.921875
3
import {List} from 'immutable'; import * as _isUndefined from 'lodash/isUndefined'; import * as _add from 'lodash/add'; import * as _round from 'lodash/round'; import * as _toNumber from 'lodash/toNumber'; import {IPayloadAction} from '../index'; import {StatementsActions} from './statements.actions'; import {INITIAL_STATEMENTS_STATE} from './statements.initial-state'; import { StatementsState, BillingStatementSummaryState, IBillingStatementSummaryState, BillingStatementState, BillingStatementTotalsState, BillingStatementExpandedState } from './types'; /** * App Dashboard State Reducer * * @param state * @param action * @returns {any} * @constructor */ export const STATEMENTS_STATE_REDUCER = (state : StatementsState = INITIAL_STATEMENTS_STATE, action : IPayloadAction) : StatementsState => { switch (action.type) { case StatementsActions.STATEMENTS_REFRESH : { // NOTE: when this action triggers an initial load of statements data has occurred, and as such, // we need to make some assumptions about what the currently selected active statements are // specifically, any statements that have a status of 'Late' or 'Due' should be automatically selected // update statements collection state = state.merge({ statements : updateStatements(action.payload) }) as StatementsState; // update state totals state = state.merge({ stateTotals : calculateStateTotals(state) }) as StatementsState; break; } case StatementsActions.STATEMENTS_UPDATE_ACTIVE_STATEMENTS : { // update statements collection state = state.merge({ statements : updateSelectedStatements(state, action.payload) }) as StatementsState; // update state totals state = state.merge({ stateTotals : calculateStateTotals(state) }) as StatementsState; break; } case StatementsActions.STATEMENTS_EXPAND_BILL : // update active statements state = state.merge({ statements : updateExpandedState(state, action.payload) }) as StatementsState; break; case StatementsActions.STATEMENTS_PAY_ALL : { // we need to look at active statements here and make sure it's populated // with every available bill that is Late or Due, not just what the user selected state = state.merge({ statements : payAllStatements(state) }) as StatementsState; break; } default : return state; } return state; }; /** * updates the current list of statements, essentially combining model data returned from an api with any UI related state data * we need to capture as well * @param statements */ function updateStatements(statements : List<IBillingStatementSummaryState>) : List<BillingStatementSummaryState> { // create immutable version of our new model data return List<BillingStatementSummaryState>(statements.map(value => new BillingStatementSummaryState(value)).map((summary) => { // need to set any statements that are 'Late' or 'Due' to selected true by default return summary.set('statements', summary.get('statements').map(item => { if (item.get('status') === 'Due' || item.get('status') === 'Late') { return item.set('selected', true).set('expanded', true); } else { return item; } })); })); } /** * updates the current list of selected active statements. This func will either assign values to the activeStatements * collection based on * @param state * @param newStatement * @returns {List<BillingStatementState>} */ function updateSelectedStatements(state : StatementsState, newStatement : BillingStatementState) : List<BillingStatementSummaryState> { // is this a multiselect scenario i.e. are we dealing with a new statement that is 'Late' or 'Due' if (newStatement.get('status') === 'Late' || newStatement.get('status') === 'Due') { // we need to inspect any previously selected statements first. If any of the previously selected statements // were statements that have a status of either 'Paid' or 'Pending' then we need to unselect these // If any of the previously selected statements have a status of 'Late' or 'Due' we leave these selected // as the user is allowed to select multiple unpaid statements at the same time for payment return state.get('statements').map((summary) => summary.set('statements', summary.get('statements').map(item => { // look for exact match between the statement selected and the current item if (newStatement.equals(item)) { // if this item is already selected previously then we need to deselect it if (item.get('selected')) { return item.set('selected', false); } else { return item.set('selected', true); } } else { // the current item is not the statement that was selected but we should still examine this item // to see if it was previously selected or not // was this statement previously selected if (item.get('selected')) { // check this item's status, if it is not 'Late' or 'Due' we need to deselect it if (item.get('status') !== 'Late' && item.get('status') !== 'Due') { return item.set('selected', false); } else { // so it's possible that the user has already selected multiple statements for payment // and is now trying to unselect one of the previously selected ones so let's check for that here /*if (item.get('selected')) { return item.set('selected', false); } else {*/ return item; // } } } else { return item; } } }))); } else { // single select, wipe out all previously selected return state.get('statements').map((summary) => summary.set('statements', summary.get('statements').map(item => { // is the statement that was selected? if (newStatement.get('statementId') === item.get('statementId')) { return item.set('selected', true); } else { return item.set('selected', false); } }))); } } /** * examine statements and figure out totals and due date for selected statements * @param state * @returns {number} */ function calculateStateTotals(state : StatementsState) : BillingStatementTotalsState { let stateTotals : BillingStatementTotalsState = new BillingStatementTotalsState({ totalDue : 0, selectedTotal : 0, dueDate : undefined, numSelected : 0, displayPaymentButton : false }), numSelected : number = 0; state.get('statements').forEach((item) => { item.get('statements').forEach((stuff) => { // totalDue is based on late or due statements if (stuff.get('status') === 'Late' || stuff.get('status') === 'Due') { // update total amount due stateTotals = stateTotals.set('totalDue', stateTotals.get('totalDue') + _round(_add(_toNumber(stuff.get('amount'))), 2)) as BillingStatementTotalsState; } // selected total is based on selected statements if (stuff.get('selected')) { // update selected total stateTotals = stateTotals.set('selectedTotal', stateTotals.get('selectedTotal') + _round(_add(_toNumber(stuff.get('amount'))), 2)) as BillingStatementTotalsState; // does the selected item also have a status of 'Late' or 'Due' ?? if (stuff.get('status') === 'Late' || stuff.get('status') === 'Due') { // update payment button display state stateTotals = stateTotals.set('displayPaymentButton', true) as BillingStatementTotalsState; } // increment number of selected items numSelected++; } }); }); // due date depends on selected statements if (numSelected === 0) { stateTotals = stateTotals.set('dueDate', undefined) as BillingStatementTotalsState; } // if there's only one statement then that's the due date else if (numSelected === 1) { let result = undefined; // search for lone selected statement state.get('statements').find(year => { year.get('statements').find(value => { if (value.get('selected')) { result = value.get('dueDate'); } }); }); // did we find it? if (!_isUndefined(result)) { // store its due date stateTotals = stateTotals.set('dueDate', result) as BillingStatementTotalsState; } else { // no active statements stateTotals = stateTotals.set('dueDate', undefined) as BillingStatementTotalsState; } } // if there's more than one, whichever one is LATE is the due date else if (numSelected > 1) { state.get('statements').forEach((item) => { let result = item.get('statements').find(value => { return value.get('status') === 'Late'; }); // if we found a match and the dueDate is not already previously defined... if (!_isUndefined(result) && !stateTotals.dueDate) { // update due date with the date of the LATE bill stateTotals = stateTotals.set('dueDate', result.get('dueDate')) as BillingStatementTotalsState; } }); } // store # of currently selected bills stateTotals = stateTotals.set('numSelected', numSelected) as BillingStatementTotalsState; return stateTotals; } /** * updates the current list of statements, essentially combining model data returned from an api with any UI related state data * we need to capture as well * @param statements */ function payAllStatements(statements : StatementsState) : List<BillingStatementSummaryState> { // now let's update the statements property of our object with any UI related state properties we care about return statements.get('statements').map(summary => summary.set('statements', summary.get('statements').map(item => { if (item.get('status') === 'Due' || item.get('status') === 'Late') { return item.set('selected', true).set('expanded', true); } else { return item.set('selected', false).set('expanded', false); } }))); } /** * updates the expanded state property of a given bill in the activeStatements slice of the statements state * @param state * @param expandedState */ function updateExpandedState(state : StatementsState, expandedState : BillingStatementExpandedState) : List<BillingStatementSummaryState> { // we know the selected indices of this statement so drill down and use an update on it to flip the 'expanded' property return state.get('statements').updateIn([expandedState.yearIndex, 'statements', expandedState.itemIndex], element => element.set('expanded', !expandedState.statement.get('expanded')) ); }
895b804e8f106f40a032f22fcdcf7179bd31b7ff
TypeScript
pjcarly/ember-field-components
/addon/components/output-field-text/component.ts
2.5625
3
import OutputFieldComponent, { OutputFieldArguments, } from "../output-field/component"; import { FieldOptionsInterface } from "@getflights/ember-field-components/services/field-information"; export interface FieldOptionsMaskInterface extends FieldOptionsInterface { mask: string; regex: RegExp; } export default class OutputFieldTextComponent extends OutputFieldComponent< OutputFieldArguments > { get mask(): string | undefined { const fieldOptions = <FieldOptionsMaskInterface>this.fieldOptions; return this.widgetName === "mask" && fieldOptions && fieldOptions.hasOwnProperty("mask") ? fieldOptions.mask : undefined; } get regex(): RegExp | undefined { const fieldOptions = <FieldOptionsMaskInterface>this.fieldOptions; return this.widgetName === "mask" && fieldOptions && fieldOptions.hasOwnProperty("regex") ? fieldOptions.regex : undefined; } }
317b8c69a2ffc3dc196304e24f6796baf3de991f
TypeScript
arduano/matrix-operations
/matrix.ts
3.3125
3
import Fraction from "./fraction"; import RowOp from "./rowOp"; import { ind } from "./helper"; export default class Matrix { protected data: Fraction[][] get width() { return this.data[0].length; } get height() { return this.data.length; } constructor(array: (number | Fraction)[][] | Matrix) { if(array instanceof Matrix) array = array.data; let height = array.length; if (height === 0) throw new Error('Zero height matrix'); let width = array[0].length; if (width === 0) throw new Error('Zero width matrix'); this.data = []; array.forEach(row => { let r: Fraction[] = []; if (row.length !== width) throw new Error('Row width doesnt match'); row.forEach(e => { if (e instanceof Fraction) { r.push(e); } else { r.push(new Fraction(e)); } }) this.data.push(r); }); } clone() { return new Matrix(this.data); } static identity(width: number, height?: number) { height = height ? height : width; return new Matrix( ind(width).map(i => ind(height!).map(j => i === j ? 1 : 0) ) ) } protected assertDim(mat: Matrix) { if (mat.width !== this.width || mat.height !== this.height) { throw new Error(`Matrix dimentions dont match: (${this.width}, ${this.height}) and (${mat.width}, ${mat.height})`) } } print() { console.log(this.toString()); } toString() { let newData = [ ['', ...ind(this.width).map(i => `c${i + 1}`)], ...this.data.map((r, i) => [ `r${i + 1}`, ...r.map(v => v.toString()) ]) ] newData[0].forEach((_, i) => { let max = Math.max(...newData.map(r => r[i].length)); newData.forEach(r => { while (r[i].length < max) r[i] += ' '; }) }); return newData.map(r => r.join(' ')).join('\n'); } getVal(x: number, y: number) { return this.data[y - 1][x - 1]; } setVal(x: number, y: number, val: number | Fraction) { val = Fraction.checkFrac(val); this.data[y - 1][x - 1] = val; } getRow(row: number) { return new Matrix([this.data[row - 1]]); } getCol(col: number) { return new Matrix(this.data.map(r => [r[col - 1]])); } sumElem() { return this.data.reduce((s, r) => s.add(r.reduce((s2, e) => e.add(s2), new Fraction(0))), new Fraction(0)) } transpose() { return new Matrix( ind(this.width).map(i => ind(this.height).map(j => this.data[j][i]) ) ) } add(mat: Matrix) { this.assertDim(mat); return new Matrix(ind(this.height).map(i => ind(this.width).map(j => this.data[i][j].add(mat.data[i][j])) )) } multElwise(mat: Matrix | number | Fraction) { if(mat instanceof Matrix){ this.assertDim(mat); return new Matrix(ind(this.height).map(i => ind(this.width).map(j => this.data[i][j].mult((mat as Matrix).data[i][j])) )) } else{ return new Matrix(ind(this.height).map(i => ind(this.width).map(j => this.data[i][j].mult(mat)) )) } } multRow(row: number, fac: number | Fraction) { row -= 1; let copy = this.clone(); copy.data[row] = copy.data[row].map(v => v.mult(fac)); return copy; } swapRows(r1: number, r2: number) { r1 -= 1; r2 -= 1; let copy = this.clone(); let temp = copy.data[r1]; copy.data[r1] = copy.data[r2]; copy.data[r2] = temp; return copy; } addRows(r1: number, r2: number, fac: number | Fraction) { r1 -= 1; r2 -= 1; let copy = this.clone(); ind(copy.width).forEach(i => copy.data[r2][i] = copy.data[r2][i].add(copy.data[r1][i].mult(fac))) return copy; } gauss(): RowOp[] { let mat = this.clone(); let ops: RowOp[] = []; let width = Math.min(mat.width, mat.height); const useOp = (op: RowOp) => { mat = op.apply(mat); ops.push(op) } ind(width).forEach(i => { if (mat.data[i][i].isZero) { let nonzero = mat.data.reduce((p, r, val) => { if (p !== -1) return p; if (!r[i].isZero) { if (!mat.data[i][val].isZero || val > i) { return val; } } return -1; }, -1) if (nonzero === -1) { throw new Error(`Unsolvable`); } useOp(RowOp.swap(nonzero + 1, i + 1)); } }) ind(width).forEach(i => { if (mat.data[i][i].isZero) { let nonzero = mat.data.reduce((p, r, val) => { if (p !== -1 || val <= i) return p; if (!r[i].isZero) { return val; } return -1; }, -1) if (nonzero === -1) { throw new Error(`Unsolvable`); } useOp(RowOp.swap(nonzero + 1, i + 1)); } ind(i + 1, mat.height).forEach(j => { if (!mat.data[j][i].isZero) { let fac = mat.data[j][i].div(mat.data[i][i]); useOp(RowOp.add(i + 1, j + 1, fac.mult(-1))); } }) }) ind(width).forEach(i => { useOp(RowOp.mult(i + 1, mat.data[i][i].flip())); }) ind(width).forEach(_i => { let i = width - _i - 1; ind(i).forEach(j => { if (!mat.data[j][i].isZero) { let fac = mat.data[j][i].div(mat.data[i][i]); useOp(RowOp.add(i + 1, j + 1, fac.mult(-1))); } }) }) return ops; } isSimilarTo(mat: Matrix) { this.assertDim(mat); let similar = true; let val: Fraction | undefined; ind(this.height).forEach(i => { if (!similar) return; ind(this.width).forEach(j => { if (!similar) return; if (mat.data[i][j].isZero || this.data[i][j].isZero) return; let div = mat.data[i][j].div(this.data[i][j]); if (val) { if (div.eq(val)) { similar = false; return; } } val = div; }) }) return (similar); } lowerDecomp() { return this.angleDecomp(true); } upperDecomp() { return this.angleDecomp(false); } angleDecomp(lower: boolean): RowOp[] { let mat = this.clone(); let ops: RowOp[] = []; let width = Math.min(mat.width, mat.height); const useOp = (op: RowOp) => { mat = op.apply(mat); ops.push(op) } ind(width).forEach(i => { if (mat.data[i][i].isZero) { let list = lower ? ind(0, i) : ind(i + 1, mat.height); let nonzero = list.reduce((p, val) => { if (p !== -1) return p; if (!mat.data[val][i].isZero) { return val; } return -1; }, -1) if (nonzero === -1) { throw new Error(`Unsolvable`); } useOp(RowOp.add(nonzero + 1, i + 1, 1)); } }) let list = lower ? ind(width) : ind(width).reverse(); list.forEach(i => { if (mat.data[i][i].isZero) { throw new Error(`Unsolvable`); } let list2 = lower ? ind(i + 1, mat.height) : ind(i); list2.forEach(j => { if (!mat.data[j][i].isZero) { let fac = mat.data[j][i].div(mat.data[i][i]); useOp(RowOp.add(i + 1, j + 1, fac.mult(-1))); } }) }) return ops; } mult(mat: Matrix) { if (mat.height !== this.width) throw new Error('Invalid matrix multiplication size'); return new Matrix( ind(this.height).map(i => ind(mat.width).map(j => this.getRow(i + 1).transpose().multElwise(mat.getCol(j + 1)).sumElem() ) ) ) } applyOps(ops: RowOp[]) { let mat = this.clone(); ops.forEach(op => { mat = op.apply(mat); }); return mat; } applyOpsInverse(ops: RowOp[]) { let mat = this.clone(); [...ops].reverse().forEach(op => { mat = op.inverse().apply(mat); }); return mat; } inverse() { let ops = this.gauss(); return Matrix.identity(this.height).applyOps(ops); } solveFor(mat: Matrix){ if(mat.height !== this.height) throw new Error('Heights must match'); return mat.applyOps(this.gauss()); } getLU(){ try{ let lowerSteps = this.lowerDecomp(); return { lower: this.applyOps(lowerSteps), upper: Matrix.identity(this.height).applyOpsInverse(lowerSteps) } } catch{ let upperSteps = this.upperDecomp(); return { lower: this.applyOps(upperSteps), upper: Matrix.identity(this.height).applyOpsInverse(upperSteps) } } } }
13f8a7f1bd97e7958578e064bf94077fcbd6f9a5
TypeScript
rondomoon/rondo-framework
/packages/server/src/entities/BaseEntitySchemaPart.ts
2.609375
3
import { EntitySchemaColumnOptions } from 'typeorm' const transformer = { from: (value: Date) => !isNaN(value.getTime()) ? value.toISOString() : value, to: (value: undefined | null | string) => value ? new Date(value) : value, } export const BaseEntitySchemaPart: { id: EntitySchemaColumnOptions createDate: EntitySchemaColumnOptions updateDate: EntitySchemaColumnOptions } = { id: { type: Number, primary: true, generated: true, }, createDate: { type: Date, createDate: true, transformer, }, updateDate: { type: Date, updateDate: true, transformer, }, }
b8c8b05ad212f1023a25bc7c0bfbbedfc33e1a0b
TypeScript
KrisztianNagy/UntoldJSONEnhancer
/test/02.expression-combined-binary-operator.test.ts
2.921875
3
import { expect } from 'chai'; import JSONEnhancer from '../src'; describe('Expression Combined Binary Operators', () => { it('should be able to combine plus and mins', () => { const enhancer = new JSONEnhancer(); const expressionEvaluator = enhancer.evaluator; const result = expressionEvaluator.evaluate('5 + 6 - 7'); expect(result.error).to.eq(false); expect(result.value).to.eq(4); }); it('should be able to know + and * precendence', () => { const enhancer = new JSONEnhancer(); const expressionEvaluator = enhancer.evaluator; const result = expressionEvaluator.evaluate('5 + 3 * 2 + 1'); expect(result.error).to.eq(false); expect(result.value).to.eq(12); }); it('should be able to know + - () precendence', () => { const enhancer = new JSONEnhancer(); const expressionEvaluator = enhancer.evaluator; const result = expressionEvaluator.evaluate('6 - (2 + 3)'); expect(result.error).to.eq(false); expect(result.value).to.eq(1); }); });
14e6b58c509c31535d13d911c33707627283f7ff
TypeScript
jackovsky8/lb4-soft-delete
/src/__tests__/unit/repositories/soft-delete-crud.repository.ts
2.734375
3
import {expect} from '@loopback/testlab'; import { EntityNotFoundError, juggler, model, property, } from '@loopback/repository'; import {SoftDeleteCrudRepository} from '../../../repositories'; import {SoftDeleteEntity} from '../../../model'; describe('SoftDeleteCrudRepository', () => { let ds: juggler.DataSource; // Define a Item Model with Soft Deletion @model({name: 'Item'}) class Item extends SoftDeleteEntity { @property({ type: 'string', required: true, name: 'title', }) title?: string; @property({ type: 'string', name: 'description', }) description?: string; @property({ type: 'number', id: true, name: 'id', }) id: number; constructor(data: Partial<Item>) { super(data); } } beforeEach(() => { ds = new juggler.DataSource({ name: 'db', connector: 'memory', }); }); describe('save', () => { it('implements Repository.save()', async () => { const repo = new SoftDeleteCrudRepository<Item, typeof Item.prototype.id>( Item, ds, ); let item = new Item({ title: 't1', description: 'd1', }); item = await repo.save(item); expect(item.id).to.eql(1); }); it('implements Repository.save() - replace existing one', async () => { const repo = new SoftDeleteCrudRepository<Item, typeof Item.prototype.id>( Item, ds, ); let item = new Item({ title: 't1', description: 'd1', }); item = await repo.save(item); expect(item.id).to.eql(1); item.title = 't2'; await repo.save(item); item = await repo.findById(1); expect(item.title).to.eql('t2'); expect(item.description).to.eql('d1'); }); it('throws when try to replace deleted', async () => { const repo = new SoftDeleteCrudRepository<Item, typeof Item.prototype.id>( Item, ds, ); let item = new Item({ title: 't1', description: 'd1', }); item = await repo.save(item); expect(item.id).to.eql(1); item.title = 't2'; await repo.deleteById(1); await expect(repo.save(item)).to.be.rejected(); }); }); describe('create', () => { it('implements Repository.create()', async () => { const repo = new SoftDeleteCrudRepository<Item, typeof Item.prototype.id>( Item, ds, ); const item = await repo.create({title: 't3', description: 'c3'}); const result = await repo.findById(item.id); expect(result.toJSON()).to.eql(item.toJSON()); }); it('implements Repository.createAll()', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const items = await repo.createAll([ {title: 't3', description: 'c3'}, {title: 't4', description: 'c4'}, ]); expect(items.length).to.eql(2); const result = await repo.find(); expect(items.length).to.eql(2); const mapped = result.map(n => n.title + ':' + n.description); expect(mapped).to.deepEqual(['t3:c3', 't4:c4']); }); }); describe('find', () => { it('implements Repository.find()', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.createAll([ {title: 't1', description: 'c1'}, {title: 't2', description: 'c2'}, ]); const items = await repo.find({where: {title: 't1'}}); expect(items.length).to.eql(1); }); it('implements Repository.find() with deleted item', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.createAll([ {title: 't1', description: 'c1'}, {title: 't2', description: 'c2'}, ]); const count = await repo.deleteAll({title: 't1'}); expect(count.count).to.eql(1); let items = await repo.find({where: {title: 't1'}}); expect(items.length).to.eql(0); items = await repo.find(); expect(items.length).to.eql(1); }); it('implements Repository.find() with deleted item (only deleted)', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.createAll([ {title: 't1', description: 'c1'}, {title: 't2', description: 'c2'}, ]); const count = await repo.deleteAll({title: 't1'}); expect(count.count).to.eql(1); let items = await repo.find({where: {title: 't1'}, onlyDeleted: true}); expect(items.length).to.eql(1); items = await repo.find({where: {title: 't2'}, onlyDeleted: true}); expect(items.length).to.eql(0); items = await repo.find({onlyDeleted: true}); expect(items.length).to.eql(1); }); it('implements Repository.find() with deleted item (with deleted)', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.createAll([ {title: 't1', description: 'c1'}, {title: 't2', description: 'c2'}, ]); const count = await repo.deleteAll({title: 't1'}); expect(count.count).to.eql(1); let items = await repo.find({where: {title: 't1'}, withDeleted: true}); expect(items.length).to.eql(1); items = await repo.find({where: {title: 't2'}, withDeleted: true}); expect(items.length).to.eql(1); items = await repo.find({withDeleted: true}); expect(items.length).to.eql(2); }); }); describe('findOne', () => { it('implements Repository.findOne()', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.createAll([ {title: 't1', description: 'c1'}, {title: 't1', description: 'c2'}, ]); const item = await repo.findOne({ where: {title: 't1'}, order: ['description DESC'], }); expect(item).to.not.be.null(); expect(item && item.title).to.eql('t1'); expect(item && item.description).to.eql('c2'); }); it('implements Repository.findOne() with deleted item (only deleted)', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.createAll([ {title: 't1', description: 'c1'}, {title: 't1', description: 'c2'}, ]); let item = await repo.findOne({ where: {title: 't1'}, onlyDeleted: true, order: ['description DESC'], }); expect(item).to.be.null(); const count = await repo.deleteAll({description: 'c1'}); expect(count.count).to.eql(1); item = await repo.findOne({ where: {title: 't1'}, onlyDeleted: true, order: ['description DESC'], }); expect(item).to.not.be.null(); expect(item && item.title).to.eql('t1'); expect(item && item.description).to.eql('c1'); }); it('implements Repository.findOne() with deleted item (with deleted)', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.createAll([ {title: 't1', description: 'c1'}, {title: 't1', description: 'c2'}, ]); let item = await repo.findOne({ where: {title: 't1'}, withDeleted: true, order: ['description DESC'], }); expect(item).to.not.be.null(); expect(item && item.title).to.eql('t1'); expect(item && item.description).to.eql('c2'); const count = await repo.deleteAll({description: 'c2'}); expect(count.count).to.eql(1); item = await repo.findOne({ where: {title: 't1'}, withDeleted: true, order: ['description DESC'], }); expect(item).to.not.be.null(); expect(item && item.title).to.eql('t1'); expect(item && item.description).to.eql('c2'); }); it('returns null if Repository.findOne() does not return a value', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.createAll([ {title: 't1', description: 'c1'}, {title: 't1', description: 'c2'}, ]); const item = await repo.findOne({ where: {title: 't5'}, order: ['description DESC'], }); expect(item).to.be.null(); }); }); describe('findById', () => { it('returns the correct instance', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({ title: 'a-title', description: 'a-description', }); const result = await repo.findById(item.id); expect(result && result.toJSON()).to.eql(item.toJSON()); }); it('throws when soft deleted - no Filter', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({ title: 'A1', description: 'B1', }); await repo.delete(item); await expect(repo.findById(item.id)).to.be.rejectedWith({ code: 'ENTITY_NOT_FOUND', message: 'Entity not found: Item with id ' + item.id, }); }); it('throws not when soft deleted . Filter withDeleted', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({ title: 'A1', description: 'B1', }); await repo.delete(item); const result = await repo.findById(item.id, {withDeleted: true}); expect(result.title).to.eql('A1'); expect(result.description).to.eql('B1'); }); it('throws not when soft deleted - Filter onlyDeleted', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({ title: 'A1', description: 'B1', }); await repo.delete(item); const result = await repo.findById(item.id, {onlyDeleted: true}); expect(result.title).to.eql('A1'); expect(result.description).to.eql('B1'); }); it('throws when not soft deleted - Filter onlyDeleted', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({ title: 'A1', description: 'B1', }); await expect( repo.findById(item.id, {onlyDeleted: true}), ).to.be.rejectedWith({ code: 'ENTITY_NOT_FOUND', message: 'Entity not found: Item with id ' + item.id, }); }); it('throws not when not soft deleted - Filter withDeleted', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({ title: 'A1', description: 'B1', }); const result = await repo.findById(item.id, {withDeleted: true}); expect(result.title).to.eql('A1'); expect(result.description).to.eql('B1'); }); it('throws when the instance does not exist', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await expect(repo.findById(999999)).to.be.rejectedWith({ code: 'ENTITY_NOT_FOUND', message: 'Entity not found: Item with id 999999', }); }); }); describe('soft and hard deletes', () => { it('implements Repository.delete()', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({title: 't3', description: 'c3'}); await repo.delete(item); const found = await repo.find({where: {id: item.id}}); expect(found).to.be.empty(); }); it('implements Repository.deleteHard() - soft deleted first - gets deleted', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); let item: Item = await repo.create({title: 't3', description: 'c3'}); await repo.delete(item); item = ( await repo.find({ where: {id: item.id}, withDeleted: true, }) )[0]; await repo.deleteHard(item); let found = await repo.find({where: {id: item.id}}); expect(found).to.be.empty(); found = await repo.find({where: {id: item.id}, withDeleted: true}); expect(found).to.be.empty(); }); it('implements Repository.deleteHard() - not soft deleted first - throws Error', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({title: 't3', description: 'c3'}); await expect(repo.deleteHard(item)).to.be.rejectedWith( EntityNotFoundError, ); }); it('implements Repository.deleteById()', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({title: 't3', description: 'c3'}); await repo.deleteById(item.id); const found = await repo.find({where: {id: item.id}}); expect(found).to.be.empty(); }); it('implements Repository.deleteHardById() - soft deleted first - gets deleted', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({title: 't3', description: 'c3'}); await expect(repo.deleteHardById(item.id)).to.be.rejectedWith( EntityNotFoundError, ); }); it('implements Repository.deleteHardById() - not soft deleted first - throws Error', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({title: 't3', description: 'c3'}); await repo.deleteById(item.id); const found = await repo.find({where: {id: item.id}}); expect(found).to.be.empty(); }); it('throws EntityNotFoundError when deleting an unknown id', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await expect(repo.deleteById(99999)).to.be.rejectedWith( EntityNotFoundError, ); }); it('implements Repository.deleteAll()', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.create({title: 't3', description: 'c3'}); await repo.create({title: 't4', description: 'c4'}); const result = await repo.deleteAll({title: 't3'}); expect(result.count).to.eql(1); }); }); describe('restore', () => { it('implements Repository.restore()', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); let item = await repo.create({title: 't3', description: 'c3'}); await repo.delete(item); item = await repo.findById(item.id, {onlyDeleted: true}); await repo.restore(item); item = await repo.findById(item.id); expect(item.title).to.eql('t3'); expect(item.description).to.eql('c3'); }); it('throws when try to restore not deleted one', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({title: 't3', description: 'c3'}); await expect(repo.restore(item)).to.be.rejectedWith(EntityNotFoundError); }); it('implements Repository.restoreById()', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); let item = await repo.create({title: 't3', description: 'c3'}); await repo.deleteById(item.id); item = await repo.findById(item.id, {onlyDeleted: true}); await repo.restoreById(item.id); item = await repo.findById(item.id); expect(item.title).to.eql('t3'); expect(item.description).to.eql('c3'); }); it('throws when try to restore not deleted one by id', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({title: 't3', description: 'c3'}); await expect(repo.restoreById(item)).to.be.rejectedWith( EntityNotFoundError, ); }); }); describe('updates', () => { it('implements Repository.updateById()', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({title: 't3', description: 'c3'}); const id = item.id; const delta = {description: 'c4'}; await repo.updateById(id, delta); const updated = await repo.findById(id); expect(updated.toJSON()).to.eql(Object.assign(item.toJSON(), delta)); }); it('throws EntityNotFound error when updating an soft deleted id', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({title: 't3', description: 'c3'}); await repo.delete(item); await expect(repo.updateById(item.id, {title: 't4'})).to.be.rejectedWith( EntityNotFoundError, ); }); it('throws EntityNotFound error when updating an unknown id', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await expect(repo.updateById(9999, {title: 't4'})).to.be.rejectedWith( EntityNotFoundError, ); }); it('implements Repository.updateAll()', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.create({title: 't3', description: 'c3'}); await repo.create({title: 't4', description: 'c4'}); const result = await repo.updateAll({description: 'c5'}, {}); expect(result.count).to.eql(2); const items = await repo.find({where: {title: 't3'}}); expect(items[0].description).to.eql('c5'); }); it('implements Repository.updateAll() without a where object', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.create({title: 't3', description: 'c3'}); await repo.create({title: 't4', description: 'c4'}); const result = await repo.updateAll({description: 'c5'}); expect(result.count).to.eql(2); const items = await repo.find(); const titles = items.map(n => `${n.title}:${n.description}`); expect(titles).to.deepEqual(['t3:c5', 't4:c5']); }); it('implements Repository.updateAll() without a where object - only not soft deleted ones', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.create({title: 't3', description: 'c3'}); await repo.create({title: 't4', description: 'c4'}); await repo.deleteAll({title: 't4'}); const result = await repo.updateAll({description: 'c5'}); expect(result.count).to.eql(1); let items = await repo.find(); expect(items[0].title).to.eql('t3'); expect(items[0].description).to.eql('c5'); items = await repo.find({onlyDeleted: true}); expect(items[0].title).to.eql('t4'); expect(items[0].description).to.eql('c4'); }); }); describe('replace', () => { it('implements Repository.replaceById()', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({title: 't3', description: 'c3'}); await repo.replaceById(item.id, {title: 't4', description: undefined}); const result = await repo.findById(item.id); expect(result.toJSON()).to.eql({ id: item.id, title: 't4', description: undefined, deletedAt: undefined, }); }); it('throws EntityNotFound error when replacing an deleted id', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({title: 't3', description: 'c3'}); await repo.delete(item); await expect(repo.replaceById(item.id, {title: 't4'})).to.be.rejectedWith( EntityNotFoundError, ); }); it('throws EntityNotFound error when replacing an unknown id', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await expect(repo.replaceById(9999, {title: 't4'})).to.be.rejectedWith( EntityNotFoundError, ); }); }); describe('count', () => { it('implements Repository.count()', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.create({title: 't3', description: 'c3'}); await repo.create({title: 't4', description: 'c4'}); const result = await repo.count(); expect(result.count).to.eql(2); }); it('implements Repository.count() with a deleted one', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.create({title: 't3', description: 'c3'}); await repo.create({title: 't4', description: 'c4'}); await repo.deleteAll({title: 't4'}); const result = await repo.count(); expect(result.count).to.eql(1); }); it('implements Repository.countWithDeleted()', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.create({title: 't3', description: 'c3'}); await repo.create({title: 't4', description: 'c4'}); await repo.create({title: 't5', description: 'c5'}); await repo.deleteAll({title: 't4'}); const result = await repo.countWithDeleted(); expect(result.count).to.eql(3); }); it('implements Repository.countOnlyDeleted()', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); await repo.create({title: 't3', description: 'c3'}); await repo.create({title: 't4', description: 'c4'}); await repo.create({title: 't5', description: 'c5'}); await repo.deleteAll({title: 't4'}); const result = await repo.countOnlyDeleted(); expect(result.count).to.eql(1); }); }); describe('exist', () => { it('implements Repository.exists()', async () => { const repo = new SoftDeleteCrudRepository(Item, ds); const item = await repo.create({title: 't3', description: 'c3'}); const ok = await repo.exists(item.id); expect(ok).to.be.true(); }); }); });
92d17189f34e49dfcabcffec56dc1a875bec6bad
TypeScript
yijiaow/ticketing
/tickets/src/models/ticket.ts
2.875
3
import mongoose, { Schema } from 'mongoose'; import { updateIfCurrentPlugin } from 'mongoose-update-if-current'; // An interface that describes the properties required to create a new ticket interface TicketAttrs { title: string; price: number; userId: string; } // An interface that describes to properties a ticket document has interface TicketDoc extends mongoose.Document { title: string; price: number; userId: string; orderId?: string; } // An interface that describes the properties a ticket model has interface TicketModel extends mongoose.Model<TicketDoc> { build(attrs: TicketAttrs): TicketDoc; } const ticketSchema = new Schema( { title: { type: String, required: true }, price: { type: Number, required: true, min: 0 }, userId: { type: String, required: true }, orderId: { type: String }, }, { toJSON: { transform(doc, ret) { ret.id = ret._id; delete ret._id; }, }, } ); ticketSchema.plugin(updateIfCurrentPlugin); ticketSchema.statics.build = (attrs: TicketAttrs) => { return new Ticket(attrs); }; export const Ticket = mongoose.model<TicketDoc, TicketModel>( 'Ticket', ticketSchema );
87f7fe29165bb14a0c1a3119423a1ddfdd31be7e
TypeScript
EvgenyiFedotov/store-api
/approach-without-contract.t.ts
2.96875
3
import { context, attachStore, attachDepend } from "./src/context"; import { store } from "./src/store"; import { depend } from "./src/depend"; const stringApi = store({ init: "", api: ({ setState, reset }) => ({ set: (value: string) => setState(value), reset, }), }); const numberApi = store({ init: 0, api: ({ getState, setState, reset }) => ({ set: (value: number) => setState(value), inc: () => setState(getState() + 1), dec: () => setState(prev => prev - 1), reset, }), }); const initName = depend({ stores: { name: stringApi }, handler: ({ name }) => name.api.set("Bob"), }); const initAge = depend({ stores: { age: numberApi }, handler: ({ age }) => age.api.set(10), }); const initAlise = depend({ stores: { name: stringApi, age: numberApi }, handler: ({ name, age }) => ({ name: name.api.set("Alise"), age: age.api.set(5), }), }); const appDepends = () => ({ initName: attachDepend(initName), initAge: attachDepend(initAge), initAlise: attachDepend(initAlise), initBoth: { name: attachDepend(initName), age: attachDepend(initAge), }, }); const appStores = () => ({ name: attachStore("name", stringApi), age: attachStore("age", numberApi), }); const app = context(); app(appDepends); app(appStores);
4296e5702672d6a54dc2028ae0af91a72eac0b93
TypeScript
just214/logically
/firebase/db/db.api.ts
3.03125
3
import * as firebase from "firebase"; import "firebase/firestore"; import { auth } from "../../Auth/api"; const db = firebase.firestore(); /* * ***UTILITY FUNCTIONS*** * The following stamps are injected into every db create, update and delete methods. * getCreatedStamp - returns an object with timestamp and current user id. * getModifiedStamp - returns an object with timestamp and current user id. * getDocData - returns data retrieved from a DocumentQuery. * getListData - returns data retrieved from a QuerySnapshot * handleAsync - a wrapper for all db methods that handles error notifications. * deleteField - */ function getCreatedStamp() { if (!auth().currentUser) { return { created_at: new Date() }; } const userId = auth().currentUser.uid; return { created_at: firebase.firestore.FieldValue.serverTimestamp(), created_by: userId }; } function getModifiedStamp() { const userId = auth().currentUser.uid; return { last_modified_at: firebase.firestore.FieldValue.serverTimestamp(), last_modified_by: userId }; } function getDocData(result) { if (!result.exists) { return null; } return result.data(); } function getListData(result) { if (result.empty) { return []; } const data = []; result.forEach(doc => { // * doc.data() is never undefined for query doc snapshots data.push(doc.data()); }); return data; } function deleteField() { return firebase.firestore.FieldValue.delete(); } function handleAsync(callback) { return callback.catch(error => { // Notification.error({ // title: "Oops...something went wrong.", // message: error.message // }); }); } /* S ubscribe C reate R ead U pdate D elete */ /* * ***CREATE UPDATE DELETE*** * create - creates a new document or fail if that document already exists. * set - replaces ALL fields in the document or creates it if it doesn't exist. * setMerge - updates fields in a document or creates it if it doesn't exist. * update - updates fields in the document or fail if that document does not exist. * commitBatch * _delete */ function create(ref, values) { const callback = ref.set({ ...values, ...getCreatedStamp() }); return handleAsync(callback); } function set(ref, values) { const callback = ref.set({ ...values, ...getModifiedStamp() }); return handleAsync(callback); } function setMerge(ref, values) { const callback = ref.set( { ...values, ...getModifiedStamp() }, { merge: true } ); return handleAsync(callback); } function update(ref, values) { const callback = ref.set( { ...values, ...getModifiedStamp() }, { merge: true } ); return handleAsync(callback); } function commitBatch(batch) { return handleAsync(batch.commit()); } function _delete(ref) { return handleAsync(ref.delete()); } /* * ***READ*** * get - The get method will return either * 1. QuerySnapshot for lists * 2. DocumentSnapshot for documents * The QuerySnapshot has a 'docs' property (array), which is used to determine * if a document or list was retrieved. */ async function get(ref) { try { const result = await ref.get(); if (result.docs) { // * This is a list return getListData(result); } // * This is a document return getDocData(result); } catch (error) { // Notification.error({ // title: "Oops...", // message: error.message // }); } } /* * ***READ*** * subscribe - Creates a real-time connection to a document or list. * ARGUMENTS: * 1. ref - This is the db ref to the doc or list to be subscribed to. * 2. callback - The values are passed to the callback anytime the subscription * returns new values. * * This methods also returns a promise, which resolves with the data. * This is used in the handleInitialFetch method in App.vue * * The subscribe method will return either: * 1. QuerySnapshot for lists * 2. DocumentSnapshot for documents * The QuerySnapshot has a 'docs' property (array), which is used to determine * if a document or list was retrieved. */ function subscribe(ref, callback) { return new Promise(resolve => { return ref.onSnapshot(result => { let data; if (result.docs) { data = getListData(result); } else { data = getDocData(result); } resolve(data); return callback(data); }); }); } export { db, create, set, setMerge, update, commitBatch, _delete, get, subscribe, deleteField, getCreatedStamp };
43b1a05895d8fe8b43c40826cee3b91db1cf7e18
TypeScript
hupo256/vite-react-ts-antd
/src/utils/index.ts
2.890625
3
interface parmsObj { [name: string]: any } export function urlParamHash(url: string = location.href) { let params: parmsObj = {} let hash = url.slice(url.indexOf('?') + 1).split('&') for (let i = 0; i < hash.length; i++) { const h = hash[i].split('=') // params[h[0]] = h[1] } return params } // localStorage export function setStorage(key: string, value: any) { window.localStorage.setItem(key, JSON.stringify(value)) } export function getStorage(key: string) { let data = window.localStorage.getItem(key) return data && data !== 'undefined' ? JSON.parse(data) : '' } export default getStorage
acb23fc7ed2cebe7344fdcfd2dffcdbcaaee2eb8
TypeScript
pi-base/core
/src/Logic/Prover.ts
2.90625
3
import { And, Atom, Formula, Or, evaluate, negate, properties, } from '../Formula' import ImplicationIndex from './ImplicationIndex' import Queue from './Queue' import { Id, Implication } from './Types' import { Derivations, Proof } from './Derivations' export type { Proof } from './Derivations' // TODO: is it deduction, or derivation export type Contradiction<TheoremId = Id, PropertyId = Id> = Proof< TheoremId, PropertyId > export type Result<TheoremId = Id, PropertyId = Id> = | { kind: 'contradiction' contradiction: Contradiction<TheoremId, PropertyId> } | { kind: 'derivations'; derivations: Derivations<TheoremId, PropertyId> } export default class Prover< TheoremId = Id, PropertyId = Id, Theorem extends Implication<TheoremId, PropertyId> = Implication< TheoremId, PropertyId > > { private traits: Map<PropertyId, boolean> private derivations: Derivations<TheoremId, PropertyId> private queue: Queue<TheoremId, PropertyId, Theorem> constructor( implications: ImplicationIndex<TheoremId, PropertyId, Theorem>, traits: Map<PropertyId, boolean> = new Map() ) { this.traits = traits this.derivations = new Derivations([...traits.keys()]) this.queue = new Queue(implications) traits.forEach((_: boolean, id: PropertyId) => { this.queue.mark(id) }) } run(): Result<TheoremId, PropertyId> { let theorem while ((theorem = this.queue.shift())) { const contradiction = this.apply(theorem) if (contradiction) { return { kind: 'contradiction', contradiction } } } return { kind: 'derivations', derivations: this.derivations } } force( theorem: TheoremId, formula: Formula<PropertyId>, support: PropertyId[] = [] ): Contradiction<TheoremId, PropertyId> | undefined { switch (formula.kind) { case 'and': return this.forceAnd(theorem, formula, support) case 'atom': return this.forceAtom(theorem, formula, support) case 'or': return this.forceOr(theorem, formula, support) } } private apply( implication: Theorem ): Contradiction<TheoremId, PropertyId> | undefined { const a = implication.when const c = implication.then const av = evaluate(a, this.traits) const cv = evaluate(c, this.traits) if (av === true && cv === false) { return this.contradiction(implication.id, [ ...properties(a), ...properties(c), ]) } else if (av === true) { return this.force(implication.id, c, [...properties(a)]) } else if (cv === false) { return this.force(implication.id, negate(a), [...properties(c)]) } } private contradiction( theorem: TheoremId, properties: PropertyId[] ): Contradiction<TheoremId, PropertyId> { return this.derivations.expand([theorem, properties]) } private forceAtom( theorem: TheoremId, formula: Atom<PropertyId>, support: PropertyId[] ): Contradiction<TheoremId, PropertyId> | undefined { const property = formula.property if (this.traits.has(property)) { if (this.traits.get(property) !== formula.value) { return this.contradiction(theorem, [property]) } else { return } } this.traits.set(property, formula.value) this.derivations.addEvidence(property, formula.value, theorem, support) this.queue.mark(property) } private forceAnd( theorem: TheoremId, formula: And<PropertyId>, support: PropertyId[] ): Contradiction<TheoremId, PropertyId> | undefined { for (const sub of formula.subs) { const contradiction = this.force(theorem, sub, support) if (contradiction) { return contradiction } } } private forceOr( theorem: TheoremId, formula: Or<PropertyId>, support: PropertyId[] ): Contradiction<TheoremId, PropertyId> | undefined { const result = formula.subs.reduce( ( acc: | { falses: Formula<PropertyId>[] unknown: Formula<PropertyId> | undefined } | undefined, sf: Formula<PropertyId> ) => { if (!acc) { return undefined } const value = evaluate(sf, this.traits) if (value === true) { return undefined // Can't force anything } else if (value === false) { acc.falses.push(sf) } else if (acc.unknown) { return undefined // Can't determine which to force } else { acc.unknown = sf } return acc }, { falses: Array<Formula<PropertyId>>(), unknown: undefined } ) if (!result) return const falseProps = result.falses.reduce<PropertyId[]>( (acc, f) => acc.concat([...properties(f)]), [] ) if (result.falses.length === formula.subs.length) { return this.contradiction(theorem, falseProps) } else if (result.unknown) { return this.force(theorem, result.unknown, [...support, ...falseProps]) } } }
9a4b142688ca1df0749ca266ece9ed19a2776409
TypeScript
SkaceKamen/vscode-sqflint
/server/typings/modules/glob/index.d.ts
2.875
3
// Generated by typings // Source: https://raw.githubusercontent.com/typed-typings/npm-minimatch/74f47de8acb42d668491987fc6bc144e7d9aa891/minimatch.d.ts declare module '~glob~minimatch' { function minimatch (target: string, pattern: string, options?: minimatch.Options): boolean; namespace minimatch { export function match (list: string[], pattern: string, options?: Options): string[]; export function filter (pattern: string, options?: Options): (element: string, indexed: number, array: string[]) => boolean; export function makeRe (pattern: string, options?: Options): RegExp; /** * All options are `false` by default. */ export interface Options { /** * Dump a ton of stuff to stderr. */ debug?: boolean; /** * Do not expand `{a,b}` and `{1..3}` brace sets. */ nobrace?: boolean; /** * Disable `**` matching against multiple folder names. */ noglobstar?: boolean; /** * Allow patterns to match filenames starting with a period, even if the pattern does not explicitly have a period in that spot. * * Note that by default, `a\/**\/b` will not match `a/.d/b`, unless `dot` is set. */ dot?: boolean; /** * Disable "extglob" style patterns like `+(a|b)`. */ noext?: boolean; /** * Perform a case-insensitive match. */ nocase?: boolean; /** * When a match is not found by `minimatch.match`, return a list containing the pattern itself if this option is set. When not set, an empty list is returned if there are no matches. */ nonull?: boolean; /** * If set, then patterns without slashes will be matched against the basename of the path if it contains slashes. For example, `a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`. */ matchBase?: boolean; /** * Suppress the behavior of treating `#` at the start of a pattern as a comment. */ nocomment?: boolean; /** * Suppress the behavior of treating a leading `!` character as negation. */ nonegate?: boolean; /** * Returns from negate expressions the same as if they were not negated. (Ie, true on a hit, false on a miss.) */ flipNegate?: boolean; } export class Minimatch { constructor (pattern: string, options?: Options); /** * The original pattern the minimatch object represents. */ pattern: string; /** * The options supplied to the constructor. */ options: Options; /** * Created by the `makeRe` method. A single regular expression expressing the entire pattern. This is useful in cases where you wish to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled. */ regexp: RegExp; /** * True if the pattern is negated. */ negate: boolean; /** * True if the pattern is a comment. */ comment: boolean; /** * True if the pattern is `""`. */ empty: boolean; /** * Generate the regexp member if necessary, and return it. Will return false if the pattern is invalid. */ makeRe (): RegExp | boolean; /** * Return true if the filename matches the pattern, or false otherwise. */ match (fname: string): boolean; /** * Take a `/-`split filename, and match it against a single row in the `regExpSet`. This method is mainly for internal use, but is exposed so that it can be used by a glob-walker that needs to avoid excessive filesystem calls. */ matchOne (fileArray: string[], patternArray: string[], partial: boolean): boolean; } } export = minimatch; } // Generated by typings // Source: https://raw.githubusercontent.com/types/npm-glob/59ca0f5d4696a8d4da27858035316c1014133fcb/glob.d.ts declare module 'glob' { import events = require('events'); import fs = require('fs'); import minimatch = require('~glob~minimatch'); function glob (pattern: string, cb: (err: Error, matches: string[]) => void): void; function glob (pattern: string, options: glob.Options, cb: (err: Error, matches: string[]) => void): void; namespace glob { export function sync (pattern: string, options?: Options): string[]; export function hasMagic (pattern: string, options?: Options): boolean; export interface Cache { [path: string]: boolean | string | string[]; } export interface StatCache { [path: string]: fs.Stats; } export interface Symlinks { [path: string]: boolean; } export interface Options extends minimatch.Options { /** * The current working directory in which to search. Defaults to `process.cwd()`. */ cwd?: string; /** * The place where patterns starting with `/` will be mounted onto. Defaults to `path.resolve(options.cwd, "/")` (`/` on Unix systems, and `C:\` or some such on Windows.) */ root?: string; /** * Include `.dot` files in normal matches and `globstar` matches. Note that an explicit dot in a portion of the pattern will always match dot files. */ dot?: boolean; /** * By default, a pattern starting with a forward-slash will be "mounted" onto the root setting, so that a valid filesystem path is returned. Set this flag to disable that behavior. */ nomount?: boolean; /** * Add a `/` character to directory matches. Note that this requires additional stat calls. */ mark?: boolean; /** * Don't sort the results. */ nosort?: boolean; /** * Set to true to stat all results. This reduces performance somewhat, and is completely unnecessary, unless `readdir` is presumed to be an untrustworthy indicator of file existence. */ stat?: boolean; /** * When an unusual error is encountered when attempting to read a directory, a warning will be printed to stderr. Set the `silent` option to true to suppress these warnings. */ silent?: boolean; /** * When an unusual error is encountered when attempting to read a directory, the process will just continue on in search of other matches. Set the `strict` option to raise an error in these cases. */ strict?: boolean; /** * See `cache` property above. Pass in a previously generated cache object to save some fs calls. */ cache?: Cache; /** * A cache of results of filesystem information, to prevent unnecessary stat calls. While it should not normally be necessary to set this, you may pass the statCache from one glob() call to the options object of another, if you know that the filesystem will not change between calls. (See https://github.com/isaacs/node-glob#race-conditions) */ statCache?: StatCache; /** * A cache of known symbolic links. You may pass in a previously generated `symlinks` object to save lstat calls when resolving `**` matches. */ symlinks?: Symlinks; /** * DEPRECATED: use `glob.sync(pattern, opts)` instead. */ sync?: boolean; /** * In some cases, brace-expanded patterns can result in the same file showing up multiple times in the result set. By default, this implementation prevents duplicates in the result set. Set this flag to disable that behavior. */ nounique?: boolean; /** * Set to never return an empty set, instead returning a set containing the pattern itself. This is the default in glob(3). */ nonull?: boolean; /** * Set to enable debug logging in minimatch and glob. */ debug?: boolean; /** * Do not expand `{a,b}` and `{1..3}` brace sets. */ nobrace?: boolean; /** * Do not match `**` against multiple filenames. (Ie, treat it as a normal `*` instead.) */ noglobstar?: boolean; /** * Do not match `+(a|b)` "extglob" patterns. */ noext?: boolean; /** * Perform a case-insensitive match. Note: on case-insensitive filesystems, non-magic patterns will match by default, since `stat` and `readdir` will not raise errors. */ nocase?: boolean; /** * Perform a basename-only match if the pattern does not contain any slash characters. That is, `*.js` would be treated as equivalent to `**\/*.js`, matching all js files in all directories. */ matchBase?: any; /** * Do not match directories, only files. (Note: to match only directories, simply put a `/` at the end of the pattern.) */ nodir?: boolean; /** * Add a pattern or an array of glob patterns to exclude matches. Note: `ignore` patterns are always in `dot:true` mode, regardless of any other settings. */ ignore?: string | string[]; /** * Follow symlinked directories when expanding `**` patterns. Note that this can result in a lot of duplicate references in the presence of cyclic links. */ follow?: boolean; /** * Set to true to call `fs.realpath` on all of the results. In the case of a symlink that cannot be resolved, the full absolute path to the matched entry is returned (though it will usually be a broken symlink) */ realpath?: boolean; } export class Glob extends events.EventEmitter { constructor (pattern: string, cb?: (err: Error, matches: string[]) => void); constructor (pattern: string, options: Options, cb?: (err: Error, matches: string[]) => void); /** * The minimatch object that the glob uses. */ minimatch: minimatch.Minimatch; /** * The options object passed in. */ options: Options; /** * Boolean which is set to true when calling `abort()`. There is no way at this time to continue a glob search after aborting, but you can re-use the statCache to avoid having to duplicate syscalls. * @type {boolean} */ aborted: boolean; /** * Convenience object. */ cache: Cache; /** * Cache of `fs.stat` results, to prevent statting the same path multiple times. */ statCache: StatCache; /** * A record of which paths are symbolic links, which is relevant in resolving `**` patterns. */ symlinks: Symlinks; /** * An optional object which is passed to `fs.realpath` to minimize unnecessary syscalls. It is stored on the instantiated Glob object, and may be re-used. */ realpathCache: { [path: string]: string }; found: string[]; /** * Temporarily stop the search. */ pause(): void; /** * Resume the search. */ resume(): void; /** * Stop the search forever. */ abort(): void; } } export = glob; }
d24391a9ef91e1fc6fb5ba49ca60c903c677ca59
TypeScript
timdeschryver/ngrx-tslint-rules
/src/schematics/ng-add/index.ts
2.578125
3
import { chain, Rule, SchematicContext, SchematicsException, Tree, } from '@angular-devkit/schematics' import * as fs from 'fs' import * as path from 'path' import { Schema } from './schema' export default function(options: Schema): Rule { return (host: Tree, context: SchematicContext) => { return chain([ extendTSLintRules(options.path || './tslint.json', options.rules), ])(host, context) } } function extendTSLintRules(filePath: string, selectedRules: string[]) { return (tree: Tree) => { const tslint = tree.get(filePath) let asJson = JSON.parse(tslint.content.toString()) if (asJson === null || typeof asJson !== 'object') { throw new SchematicsException(`Error reading tslint file at ${filePath}`) } const recommendedOption = 'recommended' const recommended = selectedRules.includes(recommendedOption) const extendFrom = recommended ? 'ngrx-tslint-rules/recommended' : 'ngrx-tslint-rules' if (!asJson.extends) { asJson.extends = [extendFrom] } else if (typeof asJson.extends === 'string') { asJson.extends = [...new Set([asJson.extends, extendFrom])] } else if ('length' in asJson.extends) { asJson.extends = [...new Set([...asJson.extends, extendFrom])] } if (!recommended) { asJson.rules = asJson.rules || {} const configContent = fs.readFileSync( path.join(__dirname, 'rules-config.json'), 'utf-8', ) const rulesConfig = JSON.parse(configContent) const rulesToAdd = selectedRules .filter(p => p !== recommendedOption) .reduce((rules, name) => { const ruleInfo = rulesConfig[name] return { ...rules, [name]: { severity: `${ ruleInfo.type === 'functionality' ? 'error' : 'warning' }`, }, } }, {}) asJson.rules = { ...asJson.rules, ...rulesToAdd, } } tree.overwrite(filePath, JSON.stringify(asJson, null, 2)) return tree } }
1bb7a7228e0b97a46c2698fbc77b06abc8ea75b7
TypeScript
Tata-Images/Learning-TypeScript-I
/src/common/stringify.ts
3.515625
4
/** * Produce a string in JSON format for any standard json object * * Implemented as a data pre-prearator and wrapper for JSON.stringify() * * Note: (1) will handle a function by executing it and stringify the result * (2) will ignore Symbol, undefined, null and promises * * @since 0.0.1 * @category Object * * @refactor April 17, 2017 * * @export * @param {*} input * @returns {string} */ import { _stringifyReplacer } from '../base/_stringifyReplacer'; import { theTypeOf } from './theTypeOf'; export function stringify(input: any): string { let str: string; const type: string = theTypeOf(input); switch (type) { case 'function': str = stringify(input()); break; case 'symbol': case 'promise': case 'undefined': case 'null': str = ''; break; default: str = JSON.stringify(input, _stringifyReplacer); break; } // escape the output json string return str.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029'); }
4ac1df99abd3e42c27e2e365919deba8fa34a555
TypeScript
olayinkaadeleye/popularity-contest
/src/controller/candidateReadAction.ts
2.734375
3
import {Context} from "koa"; import {getManager} from "typeorm"; import {Candidate} from "../entity/Candidate"; /** * GET /candidates * * returns the top 30 links sorted by elo ranking as an array * * This is a simple GET, so no PoW is required. * * @param {Application.Context} context * @returns {Promise<void>} */ export async function candidateReadAction(context: Context) { const candidateRepo = getManager().getRepository(Candidate); context.body = await candidateRepo.createQueryBuilder('candidate') .select('candidate') .orderBy('candidate.elo', 'DESC') .limit(30) .getMany(); }
a65a81f174937985f04f1bfe8df7f020385f5c35
TypeScript
rivanildojr/curso-typeScript
/modulo-02/NumberAndBigInt/numberAndBigInt.ts
3.71875
4
// Example Number let number1: number = 23.0; let number2: number = 0x78CF; let number3: number = 0o577; let number4: number = 0b110001; console.log({number: number1, type: typeof number1}); console.log({hex: number2, type: typeof number2}); console.log({octal: number3, type: typeof number3}); console.log({binario: number4, type: typeof number4}); // Example BigInt let big1: bigint = 4545454587813189n; let big2: bigint = 0b0000000000000000000000001n; let big3: bigint = 0x200000000000003n; let big4: bigint = 0o40000000000000033n; console.log('BigInt - ', big1); console.log('BigInt - Binário', big2); console.log('BigInt - Hexadecimal', big3); console.log('BigInt - Octal', big4);
c48d960a1917a46cfa44dfc36ad6e629c5b744ce
TypeScript
circlecloud/ms
/packages/websocket/src/server/index.ts
2.53125
3
import { EventEmitter } from 'events' import { ServerOptions } from '../socket.io' import { WebSocketClient } from './client' import type { Request } from './request' export enum ServerEvent { detect = 'detect', request = 'request', upgrade = 'upgrade', connect = 'connect', connection = 'connection', message = 'message', error = 'error', disconnecting = 'disconnecting', disconnect = 'disconnect', } export interface JavaServerOptions extends ServerOptions { event?: EventEmitter root?: string httpRequestHandler?: (ctx, request) => void } export abstract class WebSocketServer extends EventEmitter { protected instance: any protected options: JavaServerOptions private clients: Map<string, WebSocketClient> constructor(instance: any, options: JavaServerOptions) { super() this.instance = instance this.options = options this.clients = new Map() this.initialize() } protected onconnect(handler: any) { let id = this.getId(handler) console.log('client', id, 'connect') let request = this.getRequest(handler) request.id = id let websocket = this.getSocket(handler) this.clients.set(this.getId(handler), websocket) this.emit(ServerEvent.connect, request, websocket) } protected onmessage(handler: any, message: string) { this.execute(handler, (websocket) => websocket.emit(ServerEvent.message, message)) } protected ondisconnect(handler: any, cause: string) { this.execute(handler, (websocket) => websocket.emit(ServerEvent.disconnect, cause)) } protected onerror(handler: any, error: Error) { this.execute(handler, (websocket) => websocket.emit(ServerEvent.error, error)) } protected execute(handler: any, callback: (websocket: WebSocketClient) => void) { let id = this.getId(handler) if (this.clients.has(id)) { this.clients.has(id) && callback(this.clients.get(id)) } else { console.trace('ignore execute', handler, 'callback', callback) } } public close() { this.clients.forEach(websocket => websocket.close()) this.doClose() } protected abstract initialize(): void protected abstract getId(handler: any): string protected abstract getRequest(handler: any): Request protected abstract getSocket(handler: any): WebSocketClient protected abstract doClose(): void } export const attach = (instance, options) => { if (!instance) { throw new Error('instance can\'t be undefiend!') } options = Object.assign({ event: new EventEmitter(), path: '/ws', root: root + Java.type("java.io.File").separatorChar + 'wwwroot', }, options) let WebSocketServerImpl = undefined if (instance.class.name.startsWith('io.netty.channel')) { WebSocketServerImpl = require("./netty").NettyWebSocketServer } else { WebSocketServerImpl = require("./tomcat").TomcatWebSocketServer } console.debug('create websocket server from ' + WebSocketServerImpl.name) return new WebSocketServerImpl(instance, options) }
6daab77ff85f5efa62b8e5eb76ee0e1d716f4230
TypeScript
DarioJiang/kone-api-examples
/src/examples/operational-apis-demo.ts
2.6875
3
import { fetchAccessToken, fetchResources, validateClientIdAndClientSecret } from '../common/koneapi' import { fetchEquipmentBasicInformation, fetchEquipmentStatus, fetchServiceOrdersList, fetchSingleServiceOrder } from '../common/operational-api-supporting-functions' /** * Update these two variables with your own credentials or set them up as environment variables. */ const CLIENT_ID: string = process.env.CLIENT_ID || 'YOUR_CLIENT_ID' // eg. 'dcf48ab0-a902-4b52-8c53-1a9aede716e5' const CLIENT_SECRET: string = process.env.CLIENT_SECRET || 'YOUR_CLIENT_SECRET' // eg. '31d1329f8344fc12b1a960c8b8e0fc6a22ea7c35774c807a4fcabec4ffc8ae5b' /** * Demo the Equipment Status API by fetching basic information of the equipment and its maintenance status */ const demoEquipmentStatusApi = async (accessToken: string, targetEquipmentId: string) => { // Acquire access token with needed scope to fetch equipment information const scopes = [`equipmentstatus/${targetEquipmentId}`] accessToken = await fetchAccessToken(CLIENT_ID, CLIENT_SECRET, scopes) console.log(`AccessToken with scope ${scopes} successfully fetched`) // Fetch basic information of equipment console.log(`Fetch basic information of the equipment ${targetEquipmentId}`) const equipmentInfo = await fetchEquipmentBasicInformation(accessToken, targetEquipmentId) console.log(equipmentInfo) // Fetch maintenance status of equipment console.log(`Fetch maintenance status of the equipment ${targetEquipmentId}`) const equipmentStatus = await fetchEquipmentStatus(accessToken, targetEquipmentId) console.log(equipmentStatus) } /** * Demo the Service Info API by fetching list of service orders and detail of a order for the equipment */ const demoServiceInfoApi = async (accessToken: string, targetEquipmentId: string) => { // Acquire access token with needed scope to fetch service order information const scopes = [`serviceinfo/${targetEquipmentId}`] accessToken = await fetchAccessToken(CLIENT_ID, CLIENT_SECRET, scopes) console.log(`AccessToken with scope ${scopes} successfully fetched`) // Fetch list of all service orders let serviceOrdersList console.log(`Fetch list of service orders for the equipment ${targetEquipmentId}`) serviceOrdersList = await fetchServiceOrdersList(accessToken, targetEquipmentId) console.log(serviceOrdersList) // Fetch detail of the first service order from the list if (!serviceOrdersList) { console.log('There is nothing in the service orders list, stop fetching details of a service order') return } const { serviceOrderId } = serviceOrdersList[0] console.log(`Fetch details of the service order id ${serviceOrderId} for the equipment ${targetEquipmentId}`) const singleServiceOrder = await fetchSingleServiceOrder(accessToken, targetEquipmentId, serviceOrderId) console.log(singleServiceOrder) } /** * Main function to start the script execution */ const start = async () => { validateClientIdAndClientSecret(CLIENT_ID, CLIENT_SECRET) // Fetch the first token which will by default contain application/inventory scope for our use in the next request let accessToken = await fetchAccessToken(CLIENT_ID, CLIENT_SECRET) console.log('AccessToken successfully fetched') // Fetch equipments to which the user has access to const equipments = await fetchResources(accessToken, 'ken') console.log('List of accessible equipments:', equipments) const targetEquipmentId = equipments[0] await demoEquipmentStatusApi(accessToken, targetEquipmentId) await demoServiceInfoApi(accessToken, targetEquipmentId) } start()
c365f1a6a350e3770d46334ccfc8cac89dd90cfa
TypeScript
just4programming/queue
/api/src/storage/storage.ts
3.03125
3
export interface Item { data: any type: string } export interface Storage<T extends Item> { push(item: T): T; pop(): T | null; getAll(): T[]; }
d6f8d6b895e382c2040de1ce75d20eab187a7054
TypeScript
sroman215/bootcamp
/api/Services/tictactoeService.ts
3.203125
3
import { Game } from "../Models/Game"; export class TicTacToeService { public defaultPosition: string = '-'; public boardSize: number = 3; public board: Array<Array<string>> = new Array(3); public currentPlayerTurn: number = 0; public lastPlayerTurn: number= 1; public personMap: Map<number, string> = new Map([ [0, 'X'], [1, 'O'] ]) private readonly verticalWinningCombos = [[0, 3, 6], [1, 4, 7], [2, 5, 8]]; private readonly horizontalWinningCombos = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]; private readonly diagonalWinningCombos = [[0, 4, 8], [2, 4, 6]]; private readonly winningCombos = [...this.verticalWinningCombos, ...this.horizontalWinningCombos, ...this.diagonalWinningCombos] constructor() { this.resetBoard(); } public get game(): Game { return { board: this.board, winner: this.checkForWinner(), playerLastMove: this.lastPlayerTurn, playerCurrentMove: this.currentPlayerTurn } } public startGame(): Game { this.resetBoard(); this.currentPlayerTurn = 0; return this.game } public placeMove(personId: number, xloc: number, yloc: number): Game { if (personId != this.currentPlayerTurn) { throw new Error (`Player ${personId} is trying to cheat `) } const personPiece = this.personMap.get(personId); if (!personPiece) { throw new Error(`Cannot find person with PersonId ${personId}`) } const boardEl = this.board[yloc][xloc]; if (boardEl != this.defaultPosition) { throw new Error(`Cannot place piece at position (${xloc}, ${yloc}) because piece already placed`) } if (!(this.isValidPosition(xloc) || this.isValidPosition(yloc))) { throw new Error (`Invalid board position provided`) } this.board[yloc][xloc] = personPiece this.currentPlayerTurn = 1 - personId; // Kind of hacky way to toggle this.lastPlayerTurn = personId return this.game } public checkForWinner(player: number = this.lastPlayerTurn): boolean { const flatBoard: Array<any> = [].concat.apply([], this.board); const playerPiece = this.personMap.get(player) const playerLocs = (flatBoard.map( (position, index) => position == playerPiece ? index : -1)).filter( (x: number) => x != -1) for (const combo of this.winningCombos) { const isWinner = combo.every(x => playerLocs.includes(x)) if (isWinner) { return true; } } return false; } private isValidPosition(position: number) { return true //__.inRange(position, 0, this.boardSize); } public displayBoard() { console.log(this.board[0]) console.log(this.board[1]) console.log(this.board[2]) } public resetBoard() { for (let i=0; i < this.boardSize; i++) { this.board[i] = new Array(this.boardSize) for (let j=0; j < this.boardSize; j++) { this.board[i][j]= this.defaultPosition; } } } }
5e300555939a45bf8e7ebbf1f3aa5ee35d8eff5b
TypeScript
VandyHacks/vaken
/src/common/util.d.ts
3.5625
4
import type { XOR } from 'ts-xor'; /** Utility type which makes an exclusive OR of all properties in T. */ type oneOf<T> = { [K in keyof T]: Pick<T, K> & FixTsUnion<T, K> }[keyof T]; type FixTsUnion<T, K extends keyof T> = { [Prop in keyof T]?: Prop extends K ? T[Prop] : never; }; /** Exclusive OR between T, U, and V, factoring in all properties of each type. */ type XOR3<T, U, V> = XOR<XOR<T, U>, V>;
dae5ae9d7e3287ab2ac0f184de5f387bec5e7eaf
TypeScript
creately/mockgen
/example/src/abstract.ts
3.109375
3
export abstract class TestAbstractClass { public a1: number; private a2: number; protected a3: number; public abstract aa1: number; protected abstract aa3: number; constructor( public b1: number, private b2: number, protected b3: number, ) {} public abstract get ac1(): number; protected abstract get ac3(): number; public abstract set ad1(v: number); protected abstract set ad3(v: number); public abstract ae1(): void; protected abstract ae3(): void; public get c1(): number { return 1 } private get c2(): number { return 1 } protected get c3(): number { return 1 } public set d1(v: number) {} private set d2(v: number) {} protected set d3(v: number) {} public e1(): void {} private e2(): void {} protected e3(): void {} }
5effffb2929b496b96e7a3855cfbff29afdf8fda
TypeScript
anjum121/MEAN
/src/models/Joke.ts
2.703125
3
/** * Created by anjum on 09/05/17. */ import * as mongoose from 'mongoose'; import * as uniqueValidator from 'mongoose-unique-validator'; import * as slug from 'slug'; let User = mongoose.model('User'); let Comment = mongoose.model('Comment'); let JokeSchema = new mongoose.Schema({ slug: {type: String, lowercase: true, unique: true}, title: String, description: String, body: String, favoritesCount: {type: Number, default: 0}, tagList: [{type: String}], author: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }] }, {timestamps: true}); JokeSchema.plugin(uniqueValidator, {message: 'is already taken sorry :('}); JokeSchema.methods.slugify = function () { this.slug = slug(this.title); }; JokeSchema.pre('validate', function (next) { this.slugify(); next(); }); JokeSchema.methods.toJSONFor = function (user) { return{ slug : this.slug, title : this.title, description : this.description, body : this.body, createdAt : this.createdAt, updatedAt : this.updatedAt, tagList : this.tagList, favorited: user ? user.isFavorite(this._id) : false, favoritesCount: this.favoritesCount, author: this.author.toProfileJSONFor(user) } }; JokeSchema.methods.updateFavoriteCount = function() { let joke = this; return User.count({favorites: {$in: [joke._id]}}).then(function(count){ joke.favoritesCount = count; return joke.save(); }); }; mongoose.model('Joke', JokeSchema);
fd5eb3ea4475fcf9646bc601473a021caf96ea21
TypeScript
Siwoo-Kim/proangular
/src/app/service/order-repository.service.ts
2.546875
3
import {Injectable} from "@angular/core"; import {Order} from "../model/Order.model"; import {Observable} from "rxjs/Observable"; import {RestDatasource} from "./rest-datasource.service"; /* * The service-api which provides Order Data from DataSource * to components. * The components does not contain orders data * unless any request is not received(proxy). */ @Injectable() export class OrderRepository{ orders: Order[] = []; private loaded: boolean = false; constructor(public dataSource: RestDatasource){ } //Including Proxy Feature loadOrders() { this.loaded = true; this.dataSource.getOrders().subscribe((orders: Order[]) => { this.orders = orders; console.log(this.orders) }) } getOrders(): Order[]{ if(!this.loaded){ this.loadOrders(); } return this.orders; } isEmpty(): boolean{ if(!this.loaded){ this.loadOrders(); } return this.orders.length == 0; } saveOrder(order: Order): Observable<Order> { return this.dataSource.saveOrder(order); } updateOrder(order: Order) { this.dataSource.updateOrder(order).subscribe((order: Order) => { this.orders.splice(this.orders.findIndex(_order => order.id == _order.id),1,order); }) } deleteOrder(id: number){ this.dataSource.deleteOrder(id).subscribe((order: Order) => { this.orders.splice(this.orders.findIndex(_order => _order.id == id),1); }); } }
5377c60ea55ba1bdf9f932b648eff22dc1fdb612
TypeScript
zengxp0605/ts-design-patterns
/src/6_proxy/a_common.ts
3.703125
4
// 抽象主题类 export interface Subject { /** * request */ request(); } // 真实主题类 export class RealSubject implements Subject { public request(): void { console.log('真实主题->request...'); } } export class Proxy implements Subject { private subject: Subject; // constructor(_subject: Subject) { this.subject = _subject; } public request(): void { this.before(); this.subject.request(); this.after(); } private before(): void { console.log('Proxy->before...'); } private after(): void { console.log('Proxy->before...'); } } class Client { public static main() { const sub = new RealSubject(); const proxy = new Proxy(sub); proxy.request(); } } // 执行代码 Client.main(); /** * Output: * Proxy->before... 真实主题->request... Proxy->before... */
992a23223cee177af3140ae8fe3b868bda287e69
TypeScript
colshacol/cratebox
/core/types/advanced.ts
4.21875
4
/** * This function checks if the function has received a parameter * @param {any} param */ function isUndefined(param: any) { return typeof param === "undefined"; } /** * This function checks if the type checker provider is indeed a function * @param {function} typeChecker */ function checkTypeChecker(type: any): boolean { return !isUndefined(type) && type.name && type.name !== "" && type.checker && typeof type.checker === "function"; } /** * This function checks if the provided value is a plain object * @param {object} value */ function isPlainObject(value: object) { if (value === null || typeof value !== "object") return false; const proto = Object.getPrototypeOf(value); return proto === Object.prototype || proto === null; } /** * Advanced Type System * Consists on objects that store will check against. */ export const advancedTypes = { /** * Array Type * The array type has the following properties: * name: name of the type for error feedback * checker: function to check types against * type: base type of the array * Behaviour: * Array type should be called as a function and the checker will check all of the * elements within the array to make sure that all of them are of the same type * as the declared array. */ array: function(type: any) { if (isUndefined(type)) { throw new TypeError(`Array type must be declared with a base type as it's argument`); } if (!checkTypeChecker(type)) { throw new TypeError(`The declared type of the array is not a valid base type`); } return { name: "array", type: type, checker(v: Array<any>): boolean { // Check if it's an array if (!Array.isArray(v)) return false; // Check if it has length 0 to prevent executing array type of elements if (v.length === 0) return true; // Set a flag for checking all of the elements let allOk = true; // Ietarte through the elements v.forEach((e: any) => { // Check if the type of this particular element matches the type of this array if (!this.type.checker(e)) allOk = false; }); return allOk; }, }; }, /** * Enum Type * The Enumeration type has the following properties: * name: name of the type for error feedback * checker: function to check types against * enums: array of literal strings * Behaviour: * Enum type should only contain one of the described literals */ enum: function(enumeration: Array<string>) { if (isUndefined(enumeration) || !Array.isArray(enumeration) || enumeration.length === 0) { throw new TypeError( `Enumeration type must be declared with an array of strings as it's argument with at least one value`, ); } enumeration.forEach(value => { if (typeof value !== "string") { throw new TypeError(`Enumeration type must be an array of string literals`); } }); return { name: "enum", enums: enumeration, checker(v: string): boolean { return this.enums.includes(v); }, }; }, /** * Literal Type * The Literal type has the following properties: * name: name of the type for error feedback * checker: function to check types against * literal: the literal to check against * Behaviour: * Literal type should only contain the described string literal */ literal: function(literal: string) { if (isUndefined(literal) || typeof literal !== "string") { throw new TypeError(`Literal type must be declared with a string literal to check against`); } return { name: "literal", literal: literal, checker(v: string): boolean { return v === literal; }, }; }, /** * Optional Type * The Optional type has the following properties: * name: name of the type for error feedback * checker: function to check types against * type: base type for this optional type * defaultValue: the default value in case a value is not provided */ optional: function(type: any, defaultValue: any) { if (isUndefined(type) || isUndefined(defaultValue)) { throw new TypeError(`Optional type must be declared with a type plus a default value for that type`); } return { name: "optional", type: type, defaultValue: defaultValue, checker(v: any): boolean { // TODO return this.type.checker(v); }, }; }, /** * Frozen Type * The Frozen type has the following properties * name: name of the type for error feedback * checker: function to check types against. */ frozen: function(obj: object) { if (isUndefined(obj) || !isPlainObject(obj)) { throw new TypeError(`Frozen type must be declared with and object literal`); } return { name: "frozen", checker(v: object): boolean { return isPlainObject(v); }, }; }, };
b9c006e974708b363f2bf95b044800c1724f0943
TypeScript
echo-mei/crciwms
/src/providers/date-util/date-util.ts
3.109375
3
import { Injectable } from '@angular/core'; @Injectable() export class DateUtilProvider { // 一天毫秒数 public DAY_MILLISECOND = 1 * 24 * 60 * 60 * 1000; format(date: Date, fmt: string): 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; } // 是否同一天 isSameDay(date1: Date, date2: Date) { return date1.getFullYear() == date2.getFullYear() && date1.getMonth() == date2.getMonth() && date1.getDate() == date2.getDate(); } // 是否闰年 isLeapYear(year) { return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0); } // 获取某年中某月的天数 getMonthDays(year, month) { return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month] || (this.isLeapYear(year) ? 29 : 28); } // 获取某年的第几周的开始和结束日期(周一为每周第一天,每年1号所在周为当年的第一周,从0开始表示第一周) getOneWeek(year, index) { let firstDate, lastDate; let date = new Date(year, 0, 1); if (date.getDay() > 1) { date = new Date(date.getTime() - (date.getDay() - 1) * this.DAY_MILLISECOND); } else if (date.getDay() == 0) { date = new Date(date.getTime() - 6 * this.DAY_MILLISECOND); } for (let i = 0; i <= index; i++) { firstDate = date; while (date.getDay()) { date = new Date(date.getTime() + 1 * this.DAY_MILLISECOND); } lastDate = date; date = new Date(date.getTime() + 1 * this.DAY_MILLISECOND); } return { firstDate: firstDate, lastDate: lastDate } } // 获取一年的所有周(周一为每周第一天,每年1号所在周为当年的第一周) getWeeksOfYear(year): { firstDate: Date, lastDate: Date }[] { let weeks = []; // 本年的第一周第一天的日期 let firstDate = new Date(year, 0, 1); if (firstDate.getDay() == 0) { firstDate = new Date(firstDate.getTime() - 6 * this.DAY_MILLISECOND); } else { firstDate = new Date(firstDate.getTime() - (firstDate.getDay() - 1) * this.DAY_MILLISECOND); } // 本年的最后周最后一天的日期 let lastDate = new Date(year, 11, 31); lastDate = new Date(lastDate.getTime() - firstDate.getDay() * this.DAY_MILLISECOND); while (firstDate.getTime() < lastDate.getTime()) { weeks.push({ firstDate: new Date(firstDate.getTime()), lastDate: new Date(firstDate.getTime() + 7 * this.DAY_MILLISECOND-1) }); firstDate = new Date(firstDate.getTime() + 7 * this.DAY_MILLISECOND); } return weeks; } // 获取日期所在周(周一为每周第一天,每年1号所在周为当年的第一周,从0开始表示第一周) getWeekOfDay(date: Date): { year: number, index: number, week: { firstDate: Date, lastDate: Date } } { let result; this.getWeeksOfYear(date.getFullYear()).find((week, i) => { let b = date >= week.firstDate && date <= week.lastDate; if (b) { result = { year: date.getFullYear(), index: i, week: week }; } return b; }); if (!result) { this.getWeeksOfYear(date.getFullYear() + 1).find((week, i) => { let b = date >= week.firstDate && date <= week.lastDate; if (b) { result = { year: date.getFullYear() + 1, index: i, week: week }; } return b; }); } return result; } // 获取日期所在季(从1开始表示第一季) getQuarterOfDay(date: Date): { year?: number, index?: number, quarter?: { firstDate: Date, lastDate: Date } } { let result; let year = date.getFullYear(); let month = date.getMonth(); if (month >= 0 && month <= 2) { result = { year: year, index: 1, quarter: { firstDate: new Date(year, 0, 1), lastDate: new Date(year, 2, 31) } }; } else if (month >= 3 && month <= 5) { result = { year: year, index: 2, quarter: { firstDate: new Date(year, 2, 1), lastDate: new Date(year, 5, 30) } }; } else if (month >= 6 && month <= 8) { result = { year: year, index: 3, quarter: { firstDate: new Date(year, 6, 1), lastDate: new Date(year, 8, 30) } }; } else if (month >= 9 && month <= 11) { result = { year: year, index: 4, quarter: { firstDate: new Date(year, 9, 1), lastDate: new Date(year, 11, 31) } }; } return result; } }
00f59abf37550963c2227d6b901feb92d84b21b2
TypeScript
vannobi/ti-2-express-proj
/src/util/BibTex.ts
2.515625
3
import Cite from 'citation-js'; export interface Bib { title: string; author: any[]; publisher: string; URL: string; edition: string; type: string; id: string; year: number; } export const extractBookFeatures = str => { const book = new Cite(str, { output: { style: 'bibtex', }, }); const newBib: Bib = { title: book.data[0].title, author: book.data[0].author, publisher: book.data[0].publisher, URL: book.data[0].URL, edition: book.data[0].edition, type: book.data[0].type, id: book.data[0].id, year: book.data[0].issued['date-parts'][0][0], }; return newBib; };
f703e11452874d54ec0cdcd935ad4edd5be9c753
TypeScript
khirayama/webnes
/src/NesDebugger.ts
2.65625
3
// tslint:disable:no-suspicious-comment import { logger } from 'logger'; import { dict } from 'nes/NES'; // tslint:disable-next-line:no-any declare var window: any; type debugInfoType = [string] | [string, number] | [string, number, number]; export class NesDebugger { private debugInfo: debugInfoType[]; constructor() { logger.call('nesDebugger.constructor'); window.__disassembled = (): void => { this.displayDisassembled(); }; } public setup(rom: Uint8Array): void { logger.call('nesDebugger.setup'); // tslint:disable-next-line:no-any const debugInfo: any[] = []; let pc: number = 0; let opcodeIndex: number = 0; // while (typeof rom[pc] !== 'undefined') { while (rom[pc] !== undefined) { // tslint:disable-next-line:no-any const op: any[] = []; const opcodeAddr: string = (pc + 0x8000).toString(16); const opcode: { fullName: string; mode: string } = dict[rom[pc].toString(16).toUpperCase()]; if (!opcode) { debugInfo[opcodeIndex] = [opcodeAddr]; pc += 1; opcodeIndex += 1; continue; } op.push(opcode.fullName); pc += 1; switch (opcode.mode) { case 'accumulator': case 'implied': { debugInfo[opcodeIndex] = [opcodeAddr, ...op]; opcodeIndex += 1; continue; } default: } op.push(rom[pc]); pc += 1; switch (opcode.mode) { case 'immediate': case 'relative': case 'zeroPage': case 'zeroPageX': case 'zeroPageY': case 'preIndexedIndirect': case 'postIndexedIndirect': { debugInfo[opcodeIndex] = [opcodeAddr, ...op]; opcodeIndex += 1; continue; } default: } op.push(rom[pc]); debugInfo[opcodeIndex] = [opcodeAddr, ...op]; opcodeIndex += 1; pc += 1; } this.debugInfo = debugInfo; } private displayDisassembled(): void { logger.call('nesDebugger.displayDisassembled'); this.debugInfo.forEach( (d: debugInfoType): void => { logger.call(d); }, ); } }
6669418701409b51876566dc64c4b5fda9e257f6
TypeScript
SiLeBAT/mibi-portal-server
/src/app/authentication/model/token.model.ts
2.546875
3
import { UserToken, User } from './user.model'; import { TokenType } from '../domain/enums'; export interface TokenPayload { sub: string; } export interface AdminTokenPayload extends TokenPayload { admin: boolean; } export interface TokenPort { generateToken(userId: string): string; verifyTokenWithUser(token: string, id: string): TokenPayload; verifyToken(token: string): TokenPayload; } export interface TokenService extends TokenPort { generateAdminToken(id: string): string; saveToken( token: string, type: TokenType, userId: string ): Promise<UserToken>; getUserTokenByJWT(token: string): Promise<UserToken>; deleteTokenForUser(user: User, type?: TokenType): Promise<boolean>; hasTokenForUser(user: User, type?: TokenType): Promise<boolean>; } export interface ParseTokenRepository { hasTokenForUser(user: User, type?: TokenType): Promise<boolean>; deleteTokenForUser(user: User, type?: TokenType): Promise<boolean>; saveToken(token: UserToken): Promise<UserToken>; getUserTokenByJWT(token: string): Promise<UserToken>; }
b95d85ece246e65b1baf61f940b3d67b83d263b8
TypeScript
HoltPicklesimer/Video-Game-Wishlist
/src/app/games/game-filter.pipe.ts
2.640625
3
import { Pipe, PipeTransform } from '@angular/core'; import { Game } from './game.model'; @Pipe({ name: 'gamesFilter', }) export class GamesFilterPipe implements PipeTransform { transform(games: Game[], term: string): any { let result: Game[] = []; if (term && term.length > 0) { result = games.filter((game: Game) => { return game.name.toLowerCase().includes(term.toLowerCase()); }); } return result.length < 1 ? games : result; } }
100414166996e00485909bf4238d2147eeb942c1
TypeScript
Wikia/jwplayer-fandom
/stand-alone/loaderHelper.ts
2.625
3
import { JwPlayerContainerId, RedVentureVideoDetails, RequireOnlyOne } from './types'; export interface RedVenturePlayerContext extends JwPlayerContainerId { /** * @description Describes the location where the video player is being embedded. Useful for adding context to video tracking events */ contextName: string; /** * @description One of two embed options. This option allows an html selector to be passed in, and the player finds the first matching Element on the page * @example * { * embedSelector: '.classNameSelector' * } */ embedSelector?: string; /** * @description One of two embed options. This option takes in a direct HtmlElement, such as a div span etc. This option is useful when there is already a reference to an element, and a search is not required. * @example * const element = document.createElement('div'); * { * embedHtmlElement: element * } * */ embedHtmlElement?: HTMLElement; /** * @description An 8 character JW Media Id that the JW Player can use to play a specific video tied to that id. * The best place to find those is - https://dashboard.jwplayer.com/p/cGlKNUnj/media * @example * { * mediaId: 'vC4EkkoA' * } * */ mediaId?: string; /** * @description An option that's passed into the JW Player component, which enables or disables the mini player that appears when the player is scrolled out of the user's viewport. * @default true * @example * { * showScrollPlayer: false * } * */ showScrollPlayer?: boolean; /** * @description An option that allows the JwPlayer Container Id to be auto incremented, by keeping track of how many times the window.loadPlayer function has been called. * When this option is enabled, it'll ignore the jwPlayerContainerEmbedId option, and use the default value of 'featured-video__player'. When the first player is instantiated, * the JWPlayer Container Id will be set to 'featured-video__player_1', to prevent clashes with the default id of 'featured-video__player'. If at any point, a player gets instantiated * on the same page with this option turned off, the player id number counter will not be incremented. * @example * { * autoIncrementJwPlayerContainerId: true * } * */ autoIncrementJwPlayerContainerId?: boolean; /** * @description An optional parameter that allows the JW Player URL to be passed in, and used by the JW Player library. The player URL will decide which player should be loaded. * The JW Players have different properties, and could be spread across different workspaces. The playerUrl can also take in a signed url, for workspaces * where the player is protected by signed urls. The signed player urls are non-jwt signed urls. * More information on this can be found at - https://docs.jwplayer.com/platform/reference/protect-your-content-with-signed-urls#types-of-signed-urls * @example - unsigned URL example * { * playerUrl: 'https://cdn.jwplayer.com/libraries/VXc5h4Tf.js' * }, * @example - signed URL example * { * playerUrl: 'https://cdn.jwplayer.com/libraries/5cvxbGL3.js?sig=abc123zzzaaa&exp=1674168554' * } * */ playerUrl?: string; /** * @description A JSON Web Token (JWT) for use with JW Player media ids that are Externally Hosted. * This token must be passed in whenever the JW Workspace that the mediaId is associated with is protected. * You can find out more details about content protection with signed urls by following this link - https://docs.jwplayer.com/platform/reference/protect-your-content-with-signed-urls * @example * { * jwtSignedContentAuth: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2NzQyNjIzODA2MDAsInJlc291cmNlIjoiL3YyL21lZGlhL2dic25YOW9KIiwiaWF0IjoxNjc0MjYyMzc2fQ.uZs5BYQe-_4IrDeMJCeEMcLF41RmpgrVyzt6PEKi1_I' * } * */ jwtSignedContentAuth?: string; /** * @description An optional parameter that determines whether the video should autoplay. * If left blank, the video will only autoplay based on certain cookies being set and the tab being visible. * @example * { * autoPlay: false * } * */ autoPlay?: boolean; } export type RedVenturePlayerContextProps = RequireOnlyOne< RedVenturePlayerContext, 'embedSelector' | 'embedHtmlElement' >; /* * If a JW Auth Token is passed in, then generate the correct query String. * If nothing is passed in, then just return a blank string. * */ const getJWMediaAuthToken = (context: RedVenturePlayerContextProps) => { if (context?.jwtSignedContentAuth) { return `?token=${context.jwtSignedContentAuth}`; } return ''; }; export async function getVideoDetails(context: RedVenturePlayerContextProps) { const mediaId = context?.mediaId; const mediaUrl = `https://cdn.jwplayer.com/v2/media/${mediaId}${getJWMediaAuthToken(context)}`; try { const response = await fetch(mediaUrl, { method: 'get', }); if (!response.ok) { console.error(`Could not find video details for mediaId: ${mediaId}`); return null; } return await response.json(); } catch (e) { console.error(`Could not fetch the video details for mediaId: ${mediaId}`, e); } } export const getVideoWrapperElement = ({ embedSelector, embedHtmlElement }: RedVenturePlayerContextProps): Element => { if (embedSelector) { return document.querySelector(embedSelector); } return embedHtmlElement; }; export const buildRedVentureVideoDetails = (jwDetails): RedVentureVideoDetails => { if (!jwDetails) { return null; } return { title: jwDetails?.title, description: jwDetails?.description, kind: jwDetails?.kind, playlist: jwDetails?.playlist, feed_instance_id: jwDetails?.feed_instance_id, videoTags: jwDetails?.playlist?.[0]?.tags, duration: jwDetails?.playlist?.[0]?.duration, mediaId: jwDetails?.playlist?.[0]?.mediaId, }; }; export const canPlayerRender = (context: RedVenturePlayerContextProps): boolean => { /* Start prop checking */ // Can't do anything if a context object isn't set. if (!context) { console.error('A context object was not provided for the RedVenture JW Player.'); return false; } // A contextName has to be provided so that the player understands where it is being placed. // This is important for tracking purposes. if (!context?.contextName) { console.error('A contextName has to be provided in the context object.'); return false; } // If neither is set, then we can't decide where to place the video player on the page if (!(context?.embedSelector || context?.embedHtmlElement)) { console.error( 'An embed element selector or embed HTML element must be provided in the context object, so that the video player can render on the page.', ); return false; } // A media id is required for the video player to play anything if (!context?.mediaId) { console.error('A mediaId has to be provided in the context object.'); return false; } /* End prop checking */ /* Start optional configuration prop checks */ if (!context?.showScrollPlayer) { console.debug('The scroll player feature will not be enabled.'); } /* End optional configuration prop checks */ return true; }; const newsAndRatingsNamesWithDefaultPlayer = [ 'gamespot', 'gamefaqs', 'comicvine', 'tvguide', 'metacritic' ]; export const assurePlayerUrl = (context: RedVenturePlayerContextProps): RedVenturePlayerContextProps => { const newContext = { ...context }; if (!context.playerUrl && newsAndRatingsNamesWithDefaultPlayer.includes(context.contextName)) { newContext.playerUrl = 'https://cdn.jwplayer.com/libraries/0YAHnB5r.js'; } return newContext };
6805979141086b6b24b5174c146ba29dc34de7b1
TypeScript
codeAligned/DolphinNewsNode
/src/controllers/mysql/queries/queries.ts
2.671875
3
import { PostObject } from "../../../types/post"; import connection from "../connection"; import UserObject from "../../../types/user"; const crypto = require("crypto"); const secret = "mingade85"; export function createPost(postObject: PostObject) { return new Promise((resolve, reject) => { if (!postObject) { return reject("Undefined Post Object") } switch (postObject.post_type) { case "story": { console.log("Creating post..."); connection.query( "INSERT INTO post (title, url, time, helge_id, fk_user) VALUES (?, ?, ?, ?, (SELECT id FROM user WHERE username = ?))", [ postObject.post_title, postObject.post_url, new Date(), postObject.hanesst_id, postObject.username ], (error, results, fields) => { resolve(results); } ); break; } case "comment": { console.log("Creating comment..."); connection.query( "INSERT INTO comment (content, time, helge_id, fk_user, fk_post) VALUES (?, ?, ?, (SELECT id FROM user WHERE username = ?), (SELECT id FROM post WHERE helge_id = ?))", [ postObject.post_text, new Date(), postObject.hanesst_id, postObject.username, postObject.post_parent ], (error, results, fields) => { resolve(results); } ); break; } default: { reject("Invalid post_type"); } } }); } export function createUser(userObject: UserObject) { const hash = crypto .createHmac("sha256", secret) .update(userObject.password) .digest("hex"); return new Promise((resolve, reject) => { connection.query( "INSERT INTO user (username, password, email, karma, role) VALUES (?, ?, ?, ?, ?)", [ userObject.username, hash, userObject.email, userObject.karma, "member" ], (error, results, fields) => { if (error != null) { reject(error); } resolve(results); } ); }); } export function getUser(username: string, password: string) { const hash = crypto .createHmac("sha256", secret) .update(password) .digest("hex"); return new Promise((resolve, reject) => { connection.query( "SELECT * FROM user where username=? AND password=?", [username, hash], (error, results, fields) => { if (error !== null) { reject(error); } const user = results[0]; if (user === undefined) { reject(user) } resolve(user); } ); }); } export function getPosts(index: number, amount: number) { return new Promise((resolve, reject) => { connection.query( "SELECT post.id, post.url, post.title, post.text, post.time, post.fk_user, user.username, post.helge_id as hanesst_id FROM post LEFT JOIN user ON post.fk_user=user.id LIMIT ?,?", [index, amount], (error, results, fields) => { if (error != null) { return reject(error); } const parsedPost = results.map((item: any) => { return parsePostObject(item); }); resolve(parsedPost); } ); }); } function parsePostObject(post: any) { const postObj: PostObject = { id: post.id, time: post.time, hanesst_id: post.helge_id, post_parent: -1, post_text: post.text, post_title: post.title, post_type: "post", post_url: post.url, pwd_hash: "", username: post.username }; return postObj; } export function getPostVotes(postId: number) { return new Promise((resolve, reject) => { connection.query( "select sum(amount) as votes from vote_post where fk_post = ?", [postId], (error, results, fields) => { if (error != null) { reject(error); } resolve(results[0]); } ); }); } export function countComment(postId: number) { return new Promise((resolve, reject) => { connection.query( "SELECT COUNT(*) as commentAmount FROM comment WHERE comment.fk_post = ?", [postId], (error, results, fields) => { if (error != null) { reject(error); } resolve(results[0]); } ); }); } //Retrieves the latest (successfully) digested data export async function latestDigestedPostNumber() { return new Promise((resolve, reject) => { connection.query( "SELECT (SELECT MAX(helge_id) FROM comment) AS lastCommentId, (SELECT MAX(helge_id) FROM post) AS lastPostId", [], (error, results, fields) => { if (error != null) { return reject(error); } if (results && results.length > 0) { resolve(results[0]); } else { reject(0); } } ); }); } export function closeConnection() { connection.end(); }
7f791244cbf55ca510d6bf407fa8d8b33e2e0c59
TypeScript
nogataka/gatsby
/api/libs/errorCode.ts
2.546875
3
import { Response } from 'express' import { ValidationError } from 'express-validator' export const codes: {[key: number]: {code: number; message: string}} = { 301: {code: 301, message: 'page moved'}, 400: {code: 400, message: 'bad request'}, 404: {code: 404, message: 'not found'}, 409: {code: 409, message: 'conflict'}, 410: {code: 410, message: 'page is gone'}, 500: {code: 500, message: 'server error'}, } export const responseError = function(res: Response, code: number, error?: Error | {message: ValidationError[]}): Response { const result: {code: number; message: string | ValidationError[]} = codes[code] || {code: 500, message: 'server error'} if (error) { result.message = error?.message } return res.status(code).json(result) }
cb1084f5ccf0c6492e4512d0e842c678f17bfcb0
TypeScript
Hawkie/WebLib
/examples/game-air-rider/src/ts/Components/Ship/WeaponComponent.ts
2.546875
3
import { MoveWithVelocity } from "../../../../../../src/ts/gamelib/Actors/Movers"; import { Coordinate } from "../../../../../../src/ts/gamelib/DataTypes/Coordinate"; import { Transforms } from "../../../../../../src/ts/gamelib/Physics/Transforms"; import { DrawContext } from "../../../../../../src/ts/gamelib/Views/DrawContext"; import { IParticle, DisplayField } from "../../../../../../src/ts/gamelib/Components/ParticleFieldComponent"; import { FilterParticles } from "../../../../../../src/ts/gamelib/Actors/FieldParticleRemover"; import { AccelerateWithForces } from "../../../../../../src/ts/gamelib/Actors/Accelerator"; import { IVector } from "../../../../../../src/ts/gamelib/DataTypes/Vector"; import { DrawGraphic } from "../../../../../../src/ts/gamelib/Views/GraphicView"; import { Game } from "../../../../../../src/ts/gamelib/1Common/Game"; import { Assets } from "../../Assets/assets"; export interface IWeapon { readonly bullets: ReadonlyArray<IParticle>; readonly lastFired: number; readonly fired: boolean; readonly bulletVelocity: number; readonly bulletLifetime: number; readonly reloadTimeSec: number; readonly remaining: number; } export function CreateWeapon(reloadTimeSec: number, bulletVelocity: number): IWeapon { return { bullets: [], lastFired: undefined, fired: false, bulletLifetime: 5, bulletVelocity: bulletVelocity, reloadTimeSec: reloadTimeSec, remaining: 8, }; } export function DisplayWeapon(ctx: DrawContext, weapon: IWeapon): void { weapon.bullets.forEach(p => DrawGraphic(ctx, p.x-15, p.y-15, Assets.assets.fallingMan)); } export function RemoveBullet(weapon: IWeapon, bulletIndex: number): IWeapon { let b: IParticle[] = weapon.bullets.map(b => b); b.splice(bulletIndex, 1); return {...weapon, bullets: b }; } export function StopBullet(weapon: IWeapon, bulletIndex: number): IWeapon { let bs: IParticle[] = weapon.bullets.map(b => b); let b: IParticle = bs[bulletIndex]; const b2: IParticle = { x: b.x, y: b.y, Vx: 0, Vy: 0, born: b.born, size: 1, }; bs.splice(bulletIndex, 1, b2); return {...weapon, bullets: bs }; } export function PullTrigger(timeModifier: number, weapon: IWeapon, fireWeaponIntent: boolean, x: number, y: number, Vx: number, Vy:number, angle: number, bulletVelocity: number): IWeapon { // local varibales let reloaded: boolean = false; let fired: boolean = false; let remaining: number = weapon.remaining; // read object properties let bullets: IParticle[] = weapon.bullets.map(b => b); let lastFired: number = weapon.lastFired; const now:number = Date.now(); if (fireWeaponIntent) { if (lastFired === undefined // todo move this to weapon || ((now - lastFired) / 1000) > weapon.reloadTimeSec) { if (remaining > 0) { reloaded = true; lastFired = now; remaining--; } } } if (reloaded) { fired = true; let velocity: Coordinate = Transforms.VectorToCartesian(angle, bulletVelocity); let bullet: IParticle = { x: x, y: y, Vx: Vx + velocity.x, Vy: Vy + velocity.y, born: now, size: 2, }; // add bullets bullets.push(bullet); } // remove old bullets // bullets = FilterParticles(bullets, now, weapon.bulletLifetime); let gravity: IVector = { angle: 180, length: 50 }; let bulletsDead: IParticle[] = bullets.filter(b => b.size === 1); let bulletsFalling: IParticle[] = bullets.filter(b=>b.size !== 1).map(b => AccelerateWithForces(b, timeModifier, [gravity], 1)); bulletsFalling = bulletsFalling.map((b)=> MoveWithVelocity(timeModifier, b, b.Vx, b.Vy)); bullets = bulletsDead.concat(bulletsFalling); // move bullets and set fired return {...weapon, bullets: bullets, fired: fired, lastFired: lastFired, remaining: remaining, }; }
d270af4162d85cba0a09ecf73ce7e96cceab03ab
TypeScript
aberba/fask
/ts/color.ts
2.6875
3
module fsc { interface IColor { r: number; g: number; b: number; a: number; } class Color { color: IColor; constructor(r: number, g: number, b: number, a: number) { this.color.r = r; this.color.g = g; this.color.b = b; this.color.a = a || 0; } } export var Colors = { Black: "#000000", Grey: "#eeeeee", Yellow: "yellow", Green: "green", Blue: "blue", White: "white" }; }
e16914181a721b4dcf375b3c0acaef317e18c438
TypeScript
oiagorodrigues/typescript_learn
/src/lessons/2_classes/4_abstract.ts
3.78125
4
// abstract abstract class Animal2 { constructor(private _name: string) { }; get name() { return this._name } set name(newName: string) { this._name = newName } abstract makeSound(): void; move(meters: number) { console.log(`${this.name} moves ${meters} meters;`); }; } class Dog2 extends Animal2 { constructor(name: string) { super(name) } makeSound() { console.log(`${this.name} barks.`); } } class Snake extends Animal2 { constructor(name: string) { super(name) } makeSound() { console.log(`${this.name} ssssss.`); } } const popo2 = new Dog2('Popó'); popo2.makeSound(); popo2.move(2); const sneak = new Snake('Sneak'); sneak.makeSound(); sneak.move(5);
2a896eb715f4b8587be928638a86bb964e4daf52
TypeScript
oguzgelal/intertext
/packages/intertext-engine/src/Runner.ts
2.828125
3
import { Timeout, OnLoad, Alert, State, Request, Navigate, } from './types/commands'; import { Renderable } from './types/renderable'; type RunnerArgs<T> = { props: T; }; type RunnerFn<T> = (args: RunnerArgs<T>) => unknown; class Runner { private timeoutRunner: RunnerFn<Timeout> = () => null; private onloadRunner: RunnerFn<OnLoad> = () => null; private alertRunner: RunnerFn<Alert> = () => null; private stateRunner: RunnerFn<State> = () => null; private requestRunner: RunnerFn<Request> = () => null; private navigateRunner: RunnerFn<Request> = () => null; /** * Register a command */ public registerTimeoutCommand = (fn: RunnerFn<Timeout>): void => { this.timeoutRunner = fn; }; public registerOnLoadCommand = (fn: RunnerFn<OnLoad>): void => { this.onloadRunner = fn; }; public registerAlertCommand = (fn: RunnerFn<Alert>): void => { this.alertRunner = fn; }; public registerStateCommand = (fn: RunnerFn<State>): void => { this.stateRunner = fn; }; public registerRequestCommand = (fn: RunnerFn<Request>): void => { this.requestRunner = fn; }; public registerNavigateCommand = (fn: RunnerFn<Navigate>): void => { this.navigateRunner = fn; }; /** * Run a command */ public run = (args: { branch: Renderable }): unknown => { // List of items if (Array.isArray(args.branch)) { return args.branch.map((branch) => { return this.run({ branch }); }); } // Literal values if (typeof args.branch === 'string' || typeof args.branch === 'number') { return null; } // Timeout if (args.branch && 'timeout' in args.branch) { return this.timeoutRunner({ props: args.branch, }); } // OnLoad if (args.branch && 'onload' in args.branch) { return this.onloadRunner({ props: args.branch, }); } // Alert if (args.branch && 'alert' in args.branch) { return this.alertRunner({ props: args.branch, }); } // State if (args.branch && 'state' in args.branch) { return this.stateRunner({ props: args.branch, }); } // Request if (args.branch && 'request' in args.branch) { return this.requestRunner({ props: args.branch, }); } // Navigate if (args.branch && 'navigate' in args.branch) { return this.navigateRunner({ props: args.branch, }); } return null; }; } export default Runner;