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
ce4717f101b0617acc156ad2514743ea83964842
TypeScript
HappyJayXin/linkedin-clone-yt
/src/pages/api/snapshot.ts
2.515625
3
import type { NextApiRequest, NextApiResponse } from 'next' const data = [ { id: 1, data: { name: 'Jay', description: 'Description', message: 'Message', photoUrl: 'photoUrl' } } ] export type Data = typeof data export default (req: NextApiRequest, res: NextApiResponse<Data>) => { res.status(200).json(data) }
cb90c17ba370ce91b18d4bbfb2fd46db6ed8a662
TypeScript
akropolisio/credit-pool-frontend
/src/services/i18n/types.ts
2.671875
3
import { tKeys } from './constants'; interface CustomTranslateFunction { (phrase: ITranslateKey): string; (phrase: string, options?: number | InterpolationOptions): string; } interface InterpolationOptions { smart_count?: number | { length: number }; _?: string; [interpolationKey: string]: undefined | string | number | { length: number }; } interface IPhraseWithOptions { key: string; params: Record<string, string | number>; } export type ITranslateFunction = CustomTranslateFunction; export type ITranslateKey = string | IPhraseWithOptions; export type Lang = 'en' | 'ru'; export interface ITranslateProps { locale: Lang; tKeys: typeof tKeys; t: ITranslateFunction; changeLanguage: null | ((locale: Lang) => void); }
9188cadaf255ceb1cdf4ee76933ea9ab29a699f9
TypeScript
yszk0123/dotfiles
/deno/api/APIUtils.ts
2.796875
3
import { fromUint8Array } from 'https://denopkg.com/chiefbiiko/base64/mod.ts'; export type APIConfig = { endpoint: string; apiKey: string; }; export async function fetchJSON<T>( path: string, query: { [key: string]: string }, config: APIConfig ): Promise<T> { const encodedQuery = encodeQuery(query); const url = `${config.endpoint}${path}${ encodedQuery ? '?' : '' }${encodedQuery}`; const headers = new Headers({ Authorization: getAuthorizationHeader(config), }); const data = await fetch(url, { headers }); if (data.status !== 200) { throw new Error(`Failed to fetch data: ${data.statusText}`); } return data.json(); } export async function postJSON<S, T>( path: string, query: { [key: string]: string }, body: S, config: APIConfig ): Promise<T> { const encodedQuery = encodeQuery(query); const url = `${config.endpoint}${path}${ encodedQuery ? '?' : '' }${encodedQuery}`; const headers = new Headers({ Authorization: getAuthorizationHeader(config), }); const data = await fetch(url, { headers, body: JSON.stringify(body) }); if (data.status !== 200) { throw new Error(`Failed to fetch data: ${data.statusText}`); } return data.json(); } function getAuthorizationHeader(config: APIConfig): string { const encoded = fromUint8Array( new TextEncoder().encode(`${config.apiKey}:api_token`) ); return `Basic ${encoded}`; } function snakeCase(input: string): string { return input.replace(/([A-Z]\w*)/g, ($0, $1, $2) => `_${$1.toLowerCase()}`); } function encodeQuery(query: { [key: string]: string }): string { return Object.entries(query) .reduce((acc, [k, v]) => { return [...acc, `${snakeCase(k)}=${encodeURIComponent(v)}`]; }, [] as string[]) .join('&'); }
ba6dad3d86dbf10b107aacddcde55c87c9a90147
TypeScript
HanadyMurshed/Book
/chapter 29/code/29.2.ts
3.265625
3
/** * this is async gunctions call it is far from * threading but since threading is not allawed * in js I took this approuch eventhough I'm not * Sgit staisfied with the code t all */ class FakeThread { tag: number; freq_space; data_space; word_count_space: {} = {}; freq = []; constructor() { this.data_space = require('fs').readFileSync('./input\\dummy.txt').toString().replace(/[\W_|]+/gi, " ").split(" "); this.freq_space = []; } process(words: string[]) { return new Promise(resolve => { let freq = {}; let word = ""; var k = setInterval(() => { if (words.length == 0) { let items = Object.keys(freq).map(function (key) { return [key, freq[key]]; }, this.tag); this.freq_space.push(items); resolve(); clearInterval(k); } else { word = words.pop(); if (word in freq) { freq[word] += 1 } else { freq[word] = 1 } } }) }) } aggregate() { let word = ""; return new Promise(resolve => { var k = setInterval(() => { if (this.freq_space.length == 0 && this.freq.length == 0) { resolve(); clearInterval(k); } else { if (this.freq.length == 0) this.freq = this.freq_space.pop(); word = this.freq.pop(); if (word[0] in this.word_count_space) { this.word_count_space[word[0]] += word[1] } else { this.word_count_space[word[0]] = word[1] } } }) }) } async run(threadNumber: number) { /** * I chunked the data accros the workers it is not needed and can be removed */ let chunkSize = Math.round(this.data_space.length / threadNumber) let worker = [] for (let i = 0, d = 0; i < threadNumber; i++ , d += chunkSize) { worker.push(this.process( this.data_space.slice(d, d + chunkSize) )) } await Promise.all(worker); worker = []; for (let i = 0, d = 0; i < threadNumber; i++ , d += chunkSize) { worker.push(this.aggregate()) } await Promise.all(worker); this.sort_print(); } sort_print() { console.log(this.word_count_space) let items = Object.keys(this.word_count_space).map((key) => { return [key, this.word_count_space[key]]; }); items = items.sort((b, a) => { return a[1] - b[1] }); console.log(items.slice(0, 25)) } } new FakeThread().run(5);
df25de2426318796c6801ff2e2862b23f0f0fea8
TypeScript
Mahmuod14M/Hyper-Techno
/src/app/see-more.pipe.ts
2.515625
3
import {Pipe, PipeTransform} from '@angular/core'; @Pipe({ name: 'seeMore' }) export class SeemorePipe implements PipeTransform { transform(txt: string, lngth: number): string { const x = txt.slice(0, lngth); let final = ''; for (let i = 0; i < 5; i++) { final += x[i] + ' '; } return x + '...'; } }
7e52ec525406453ef009e4cde2776795301aff73
TypeScript
favedit/MoCloud3d
/TypeScript/source/common/math/SVector4.ts
2.8125
3
module sk.common.math { //========================================================== // <T>四维向量。</T> // // @struct // @author maocy // @version 150119 //========================================================== export class SVector4 extends SValue4 { //========================================================== // <T>序列化数据到输出流里。</T> // // @method // @param p:input:FByteStream 数据流 //========================================================== public serialize3(p) { var o = this; p.writeFloat(o.x); p.writeFloat(o.y); p.writeFloat(o.z); } //========================================================== // <T>从输入流里反序列化数据。</T> // // @method // @param p:input:FByteStream 数据流 //========================================================== public unserialize3(p) { var o = this; o.x = p.readFloat(); o.y = p.readFloat(); o.z = p.readFloat(); } } }
4af7c326dfb4e4da6418f2b9545105753300375c
TypeScript
anupsaw/file-server
/src/controllers/util.ts
2.71875
3
import * as path from 'path'; import * as fs from 'fs'; import { config } from '../settings/index'; export class Util { public static create(): Util { return new Util(); } /** Create directory */ public mkdir(dir: string): string { const findAndCreate = (rootPath: string, folder: string) => { rootPath += folder + '/'; const resolvedPath = path.resolve(rootPath); if (!fs.existsSync(resolvedPath)) { fs.mkdirSync(resolvedPath); } return rootPath; }; return dir.split('/').reduce(findAndCreate); } /** get document path if not present create the document */ public getDocumentPath(entity: string, baseFolder?: string): string { let dir, fileName; // baseFolder = (baseFolder === undefined) ? config.appDataFolder : baseFolder; baseFolder = process.cwd() + `/${config.baseFolder}`; console.log(baseFolder); if (!fs.existsSync(baseFolder)) { this.mkdir(baseFolder); } try { dir = baseFolder + '/' + entity + 's'; fileName = path.resolve(dir + '/' + entity + '.json'); if (!fs.existsSync(fileName)) { this.mkdir('/' + dir); fs.writeFileSync(fileName, JSON.stringify({}), 'utf-8'); } return fileName; } catch (error) { throw error; } } /** Get Random Id for an record */ public rand(digits: number) { return Math.floor(Math.random() * parseInt('8' + '9'.repeat(digits - 1)) + parseInt('1' + '0'.repeat(digits - 1))); } /** reorder and push the data */ public processData(reqData: any, fileData: any[]): any { try { reqData = this.reorderData(reqData); if (!Array.isArray(fileData)) fileData = []; fileData.push(reqData); return { reqData: reqData, fileData: fileData }; } catch (error) { throw error; } } /** Reorder Data */ public reorderData(data: { [x: string]: any; }) { const createdData: { [x: string]: any; } = {}; createdData['__id'] = this.rand(10); for (const key in data) { if (key != '__id') { createdData[key] = data[key]; } } return createdData; } public matchData(data: any[], options: { [x: string]: any; }, isMatchMany: boolean) { let matchedData; let matchedOne: any[] = []; const matchedMany = []; try { for (let i = 0; i < data.length; i++) { let isMatched = false, j = 0; for (const key in options) { if (j > 0 && !isMatched) break; isMatched = false; // not using === sign as to avoid data type match if (options[key] == data[i][key]) { isMatched = true; } j++; } if (isMatched) { if (isMatchMany) { matchedMany.push({ index: i, data: data[i] }); } else { matchedOne = [{ index: i, data: data[i] }]; break; } } } matchedData = isMatchMany ? matchedMany : matchedOne; return matchedData; } catch (error) { throw error; } } public patchData(to: { [x: string]: any; }, from: { [x: string]: any; }, ...ignore: any[]) { try { for (const key in from) { if (!ignore.hasOwnProperty(key) && key != '__id') { to[key] = from[key]; } } return to; } catch (error) { throw error; } } }
40caf63b9f811107383fccbcf6ed8fc09d5210bc
TypeScript
Azure/azure-iot-library
/configuration/src/envConfiguration.spec.ts
3.140625
3
/* Copyright (c) Microsoft Corporation. All Rights Reserved. */ import {EnvConfiguration} from './envConfiguration'; /** * Test EnvConfiguration's getString and get<T> methods. * * Before each spec set the environment variables appropriately. * Specs test: * - returned value is correct value and type * - unset key returns null * - errors thrown for incorrect usage of getString vs get<T> */ describe('Environment configuration provider', () => { let envConfig: EnvConfiguration; let envKeys: { [key: string]: string }; let fruitsObject: { [key: string]: string[] }; let keysNotInEnv: string[]; // Reset environment variables beforeEach( () => { envConfig = new EnvConfiguration(); // Environment variables and expected outputs envKeys = { CONN_STR: 'iot-hub-conn-str-val', MONGO_URI: 'mongodb://localhost:27017/test', STRINGIFIED_FRUITS: `{"fruits":["apple","banana"]}`, NESTED_OBJECT: `{"fruits":{"apples":{"gala":41,"jonagold":42,"honeycrisp":"43"}}}`, EMPTY_STRING: '', FALSE: 'false', ZERO: '0', NULL: 'null' }; fruitsObject = { fruits: ['apple', 'banana'] }; keysNotInEnv = ['NOT_PRESENT_1', 'NOT_PRESENT_2']; // Add desired keys in for (let key in envKeys) { process.env[key] = envKeys[key]; } // Remove undesired keys for (let key in keysNotInEnv) { delete process.env[key]; } }); it('gets correctly set values', () => { expect(envConfig.getString('CONN_STR')).toEqual(envKeys['CONN_STR']); expect(envConfig.getString('MONGO_URI')).toEqual(envKeys['MONGO_URI']); expect(envConfig.get<{ [key: string]: string[] }>('STRINGIFIED_FRUITS')) .toEqual(fruitsObject); expect(envConfig.get(['NESTED_OBJECT', 'fruits', 'apples', 'gala'])).toEqual(41); expect(envConfig.get('EMPTY_STRING')).toEqual(''); expect(envConfig.get('ZERO')).toEqual(0); expect(envConfig.get('FALSE')).toEqual(false); expect(envConfig.get('NULL')).toEqual(null); expect(envConfig.getString(['NESTED_OBJECT', 'fruits', 'apples', 'honeycrisp'])) .toEqual('43'); }); it('returns null for unset keys', () => { expect(envConfig.getString(keysNotInEnv[0])).toEqual(null); expect(envConfig.get(keysNotInEnv[1])).toEqual(null); expect(envConfig.get(['NESTED_OBJECT', 'fruits', 'bananas'])).toEqual(null); }); it('throws an error when using get<T> for a string', () => { expect( () => envConfig.get('CONN_STR') ).not.toThrow(); expect( () => envConfig.get('MONGO_URI') ).not.toThrow(); expect( () => envConfig.get('STRINGIFIED_FRUITS') ).not.toThrow(); expect( () => envConfig.getString('NESTED_OBJECT') ).not.toThrow(); expect( () => envConfig.get(['NESTED_OBJECT', 'fruits']) ).not.toThrow(); expect( () => envConfig.getString(['NESTED_OBJECT', 'fruits']) ).toThrow(); }); });
464c6a547ff62abebba8833a67b7d25c09826304
TypeScript
tcarrio/polyglot-snapshot-ts
/src/snapshot/validator.ts
3.03125
3
import { ValidationError } from "../errors"; import { isPromise } from "../util/is-promise"; export class SnapshotValidator { public static validate(snapshot: unknown): void { switch (typeof snapshot) { case "function": throw new ValidationError("Function not serialized"); case "bigint": case "symbol": case "boolean": case "number": case "string": case "undefined": return; case "object": if (snapshot === null) { return; } if (Array.isArray(snapshot)) { return snapshot.forEach((entry) => this.validate(entry)); } if (isPromise(snapshot)) { throw new ValidationError("Promise cannot be serialized"); } return Object.keys(snapshot).forEach((key) => this.validate(snapshot[key as never]) ); } } }
f0d71bf9daa008a5e8367edea9fbb40cc696da73
TypeScript
brandon-pereira/betterdo-api
/src/controllers/lists.ts
2.515625
3
import { throwError } from '../helpers/errorHandler'; import { ObjectId } from 'mongodb'; import { RouterOptions } from '../helpers/routeHandler'; import { List, ListDocument } from '../schemas/lists'; import { isCustomList, getCustomListById, getAccountsCustomLists } from '../helpers/customLists'; import { parseObjectID } from '../helpers/objectIds'; interface GetListOptions { includeCompleted?: boolean; } export function getLists( listId: ObjectId | string, { includeCompleted }: GetListOptions, { db, user, notifier }: RouterOptions ): Promise<List>; export function getLists( listId: undefined, { includeCompleted }: GetListOptions, { db, user, notifier }: RouterOptions ): Promise<Array<List>>; export async function getLists( listId: ObjectId | string | undefined, { includeCompleted }: GetListOptions = { includeCompleted: false }, { db, user, notifier }: RouterOptions ): Promise<List | Array<List>> { // Get lists based on query data if (typeof listId === 'string' && isCustomList(listId)) { const customList = await getCustomListById(listId, includeCompleted, { db, user, notifier }); if (!customList) { throwError('Unknown error'); } return customList; } else if (listId) { const list = await db.Lists.getList(user._id, listId); if (!list) { throwError('Invalid List ID'); } if (includeCompleted) { await list.populate({ path: 'completedTasks', populate: { path: 'createdBy', model: 'User', select: ['_id', 'firstName', 'lastName', 'profilePicture'] } }); } return { type: list.type, owner: list.owner, additionalTasks: includeCompleted ? 0 : list.additionalTasks, completedTasks: includeCompleted ? list.completedTasks : [], color: list.color, _id: list._id, title: list.title, tasks: list.tasks, members: list.members }; } const inbox = db.Lists.getUserInbox(user._id); const userLists = db.Users.getLists(user._id); const customLists = getAccountsCustomLists({ db, user, notifier }); const [_inbox, _userLists, _customLists] = await Promise.all([inbox, customLists, userLists]); const lists: Array<ListDocument> = [_inbox, ..._userLists, ..._customLists]; return lists.map(list => ({ type: list.type, additionalTasks: list.additionalTasks, completedTasks: [], color: list.color, tasks: list.tasks, members: list.members, owner: list.owner, _id: list._id, title: list.title })); } export async function createList( listObj: Partial<List>, { db, user }: RouterOptions ): Promise<ListDocument> { // Remove potentially harmful properties delete listObj.owner; delete listObj.members; delete listObj.type; // Attempt to create the list const list = new db.Lists({ ...listObj, owner: user._id }); await list.save(); // Add list to users array await db.Users.addListToUser(list._id, user); // Populate await db.Lists.populateList(list); // Return new list to front-end return list; } export async function updateList( listId: ObjectId | string, updatedList: Partial<List>, { db, user }: RouterOptions ): Promise<List> { // Ensure list id is passed if (!listId) throwError('Invalid List ID'); // Convert ListId to object if not if (typeof listId === 'string') { listId = parseObjectID(listId); } // Get list const list = await db.Lists.getUserListById(user._id, listId); // If no results, throw error if (!list) throwError('Invalid List ID'); // If inbox, don't allow editing some fields if (list.type === 'inbox') { updatedList = { tasks: updatedList.tasks }; } // Ensure tasks length matches and no new tasks injected if ( updatedList.tasks && (!Array.isArray(updatedList.tasks) || updatedList.tasks.length !== list.tasks.length || updatedList.tasks.find( _id => !list.tasks.map(task => task._id.toString()).includes(_id) )) ) { throwError('Invalid modification of tasks'); } else if (updatedList.tasks) { // Valid tasks, update order list.tasks = updatedList.tasks; // Don't merge below delete updatedList.tasks; } // If members list changes if (updatedList.members && Array.isArray(updatedList.members)) { const currentMembers = list.members.map(member => member._id.toString()); updatedList.members = updatedList.members.map(member => member.toString()); const newMembers = updatedList.members.filter( (member: string) => !currentMembers.includes(member) ); const removedMembers = currentMembers.filter( member => updatedList.members && !updatedList.members.includes(member) ); const addMembersPromise = Promise.all( newMembers.map(async (member: string) => { const user = await db.Users.findById(member); if (!user) throwError('Invalid modification of tasks'); await db.Users.addListToUser(list._id, user); }) ); const removeMembersPromise = Promise.all( removedMembers.map(async member => { const user = await db.Users.findById(member); if (!user) throwError('Invalid modification of tasks'); await db.Users.removeListFromUser(list._id, user); }) ); await Promise.all([addMembersPromise, removeMembersPromise]); list.members = updatedList.members; delete updatedList.members; } // Merge the lists.. validation on the model will handle errors Object.assign(list, updatedList); // Save the model await list.save(); // Repopulate object await db.Lists.populateList(list); // Return list to front-end return list; } interface GenericStatus { success: boolean; } export async function deleteList( listId: ObjectId | string, { db, user }: RouterOptions ): Promise<GenericStatus> { // Ensure list id is passed if (!listId) throwError('Invalid List ID'); // Convert ListId to object if not if (typeof listId === 'string') { listId = new ObjectId(listId); } // Get list (and ensure valid) const list = await db.Lists.findOne({ _id: listId, members: user._id, type: 'default' }); if (!list) { throwError('Invalid List ID'); } // await list.populate('members').execPopulate(); const status = await db.Lists.deleteOne({ _id: list._id }); if (status && status.deletedCount && status.deletedCount > 0) { // Remove list to users array await Promise.all( list.members.map(async member => { const _user = await db.Users.findById(member); if (!_user) return; await db.Users.removeListFromUser(new ObjectId(listId), _user); }) ); // Return success message return { success: true }; } throwError('Invalid List ID'); }
e1f603be7cab51d972adcf7ca60a850af1e23191
TypeScript
microsoft/ts-parsec
/packages/tspc-test/src/TestParser.ts
2.765625
3
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. // tslint:disable:no-duplicate-imports // tslint:disable:trailing-comma import * as assert from 'assert'; import * as parsec from 'typescript-parsec'; import { buildLexer, Token } from 'typescript-parsec'; import { alt, alt_sc, apply, errd, kleft, kmid, kright, opt, opt_sc, rep, rep_n, rep_sc, repr, seq, str, tok } from 'typescript-parsec'; function notUndefined<T>(t: T | undefined): T { assert.notStrictEqual(t, undefined); return <T>t; } function succeeded<TKind, TResult>(r: parsec.ParserOutput<TKind, TResult>): parsec.ParseResult<TKind, TResult>[] { if (r.successful) { return r.candidates; } throw new Error(`The parsing does not succeed: ${r.error.message}`); } enum TokenKind { Number, Identifier, Comma, Space, } const lexer = buildLexer([ [true, /^\d+/g, TokenKind.Number], [true, /^[a-zA-Z]\w*/g, TokenKind.Identifier], [false, /^,/g, TokenKind.Comma], [false, /^\s+/g, TokenKind.Space] ]); test(`Parser: str`, () => { const firstToken = notUndefined(lexer.parse(`123,456`)); { const result = succeeded(str('123').parse(firstToken)); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].result.text, '123'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken.next); } { const result = str('456').parse(firstToken); assert.strictEqual(result.successful, false); } }); test(`Parser: tok`, () => { const firstToken = notUndefined(lexer.parse(`123,456`)); { const result = succeeded(tok(TokenKind.Number).parse(firstToken)); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].result.text, '123'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken.next); } { const result = str('456').parse(firstToken); assert.strictEqual(result.successful, false); } }); test(`Parser: alt`, () => { { const firstToken = notUndefined(lexer.parse(`123,456`)); const result = succeeded(alt(tok(TokenKind.Number), tok(TokenKind.Identifier)).parse(firstToken)); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].result.text, '123'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken.next); } { const firstToken = notUndefined(lexer.parse(`abc,def`)); const result = succeeded(alt(tok(TokenKind.Number), tok(TokenKind.Identifier)).parse(firstToken)); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].result.text, 'abc'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken.next); } { const firstToken = notUndefined(lexer.parse(`123,456`)); const alt1 = alt(tok(TokenKind.Number), tok(TokenKind.Identifier)); const alt2 = alt(tok(TokenKind.Identifier), tok(TokenKind.Number)); const result = succeeded(alt(alt1, alt2).parse(firstToken)); assert.strictEqual(result.length, 2); assert.strictEqual(result[0].result.text, '123'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken.next); assert.strictEqual(result[1].result.text, '123'); assert.strictEqual(result[1].firstToken, firstToken); assert.strictEqual(result[1].nextToken, firstToken.next); } { const firstToken = notUndefined(lexer.parse(`abc,def`)); const alt1 = alt(tok(TokenKind.Number), tok(TokenKind.Identifier)); const alt2 = alt(tok(TokenKind.Identifier), tok(TokenKind.Number)); const result = succeeded(alt(alt1, alt2).parse(firstToken)); assert.strictEqual(result.length, 2); assert.strictEqual(result[0].result.text, 'abc'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken.next); assert.strictEqual(result[1].result.text, 'abc'); assert.strictEqual(result[1].firstToken, firstToken); assert.strictEqual(result[1].nextToken, firstToken.next); } }); test(`Parser: alt_sc`, () => { { const firstToken = notUndefined(lexer.parse(`123,456`)); const result = succeeded(alt_sc(tok(TokenKind.Number), tok(TokenKind.Identifier)).parse(firstToken)); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].result.text, '123'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken.next); } { const firstToken = notUndefined(lexer.parse(`abc,def`)); const result = succeeded(alt_sc(tok(TokenKind.Number), tok(TokenKind.Identifier)).parse(firstToken)); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].result.text, 'abc'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken.next); } { const firstToken = notUndefined(lexer.parse(`123,456`)); { const alt1 = apply(alt(tok(TokenKind.Number), tok(TokenKind.Identifier)), (value: Token<TokenKind>) => `alt1: ${value.text}`); const alt2 = apply(alt(tok(TokenKind.Identifier), tok(TokenKind.Number)), (value: Token<TokenKind>) => `alt2: ${value.text}`); const result = succeeded(alt_sc(alt1, alt2).parse(firstToken)); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].result, 'alt1: 123'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken.next); } { const alt1 = apply(tok(TokenKind.Identifier), (value: Token<TokenKind>) => `alt1: ${value.text}`); const alt2 = apply(alt(tok(TokenKind.Identifier), tok(TokenKind.Number)), (value: Token<TokenKind>) => `alt2: ${value.text}`); const result = succeeded(alt_sc(alt1, alt2).parse(firstToken)); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].result, 'alt2: 123'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken.next); } } { const firstToken = notUndefined(lexer.parse(`abc,def`)); { const alt1 = apply(alt(tok(TokenKind.Number), tok(TokenKind.Identifier)), (value: Token<TokenKind>) => `alt1: ${value.text}`); const alt2 = apply(alt(tok(TokenKind.Identifier), tok(TokenKind.Number)), (value: Token<TokenKind>) => `alt2: ${value.text}`); const result = succeeded(alt_sc(alt1, alt2).parse(firstToken)); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].result, 'alt1: abc'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken.next); } { const alt1 = apply(tok(TokenKind.Number), (value: Token<TokenKind>) => `alt1: ${value.text}`); const alt2 = apply(alt(tok(TokenKind.Identifier), tok(TokenKind.Number)), (value: Token<TokenKind>) => `alt2: ${value.text}`); const result = succeeded(alt_sc(alt1, alt2).parse(firstToken)); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].result, 'alt2: abc'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken.next); } } }); test(`Parser: seq`, () => { const firstToken = notUndefined(lexer.parse(`123,456`)); { const result = seq(tok(TokenKind.Number), tok(TokenKind.Identifier)).parse(firstToken); assert.strictEqual(result.successful, false); } { const result = succeeded(seq(tok(TokenKind.Number), tok(TokenKind.Number)).parse(firstToken)); assert.strictEqual(result.length, 1); assert.deepStrictEqual(result[0].result.map((value: Token<TokenKind>) => value.text), ['123', '456']); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, undefined); } }); test(`Parser: kleft, kmid, kright`, () => { const firstToken = notUndefined(lexer.parse(`123,456,789`)); { const result = succeeded(kleft(tok(TokenKind.Number), seq(tok(TokenKind.Number), tok(TokenKind.Number))).parse(firstToken)); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].result.text, '123'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, undefined); } { const result = succeeded(kmid(tok(TokenKind.Number), tok(TokenKind.Number), tok(TokenKind.Number)).parse(firstToken)); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].result.text, '456'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, undefined); } { const result = succeeded(kright(tok(TokenKind.Number), seq(tok(TokenKind.Number), tok(TokenKind.Number))).parse(firstToken)); assert.strictEqual(result.length, 1); assert.deepStrictEqual(result[0].result.map((value: Token<TokenKind>) => value.text), ['456', '789']); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, undefined); } }); test(`Parser: opt`, () => { const firstToken = notUndefined(lexer.parse(`123,456`)); { const result = succeeded(opt(tok(TokenKind.Number)).parse(firstToken)); assert.strictEqual(result.length, 2); assert.strictEqual((<Token<TokenKind>>result[0].result).text, '123'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken.next); assert.strictEqual(result[1].result, undefined); assert.strictEqual(result[1].firstToken, firstToken); assert.strictEqual(result[1].nextToken, firstToken); } }); test(`Parser: opt_sc`, () => { const firstToken = notUndefined(lexer.parse(`123,456`)); { const result = succeeded(opt_sc(tok(TokenKind.Number)).parse(firstToken)); assert.strictEqual(result.length, 1); assert.strictEqual((<Token<TokenKind>>result[0].result).text, '123'); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken.next); } { const result = succeeded(opt_sc(tok(TokenKind.Identifier)).parse(firstToken)); assert.strictEqual(result.length, 1); assert.strictEqual(result[0].result, undefined); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken); } }); test(`Parser: rep_sc`, () => { const firstToken = notUndefined(lexer.parse(`123,456`)); { const result = succeeded(rep_sc(tok(TokenKind.Number)).parse(firstToken)); assert.strictEqual(result.length, 1); assert.deepStrictEqual(result[0].result.map((value: Token<TokenKind>) => value.text), ['123', '456']); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, undefined); } { const result = succeeded(rep_sc(tok(TokenKind.Identifier)).parse(firstToken)); assert.strictEqual(result.length, 1); assert.deepStrictEqual(result[0].result.map((value: Token<TokenKind>) => value.text), []); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken); } }); test(`Parser: repr`, () => { const firstToken = notUndefined(lexer.parse(`123,456`)); { const result = succeeded(repr(tok(TokenKind.Number)).parse(firstToken)); assert.strictEqual(result.length, 3); assert.deepStrictEqual(result[0].result, []); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken); assert.deepStrictEqual(result[1].result.map((value: Token<TokenKind>) => value.text), ['123']); assert.strictEqual(result[1].firstToken, firstToken); assert.strictEqual(result[1].nextToken, firstToken.next); assert.deepStrictEqual(result[2].result.map((value: Token<TokenKind>) => value.text), ['123', '456']); assert.strictEqual(result[2].firstToken, firstToken); assert.strictEqual(result[2].nextToken, undefined); } }); test(`Parser: rep`, () => { const firstToken = notUndefined(lexer.parse(`123,456`)); { const result = succeeded(rep(tok(TokenKind.Number)).parse(firstToken)); assert.strictEqual(result.length, 3); assert.deepStrictEqual(result[0].result.map((value: Token<TokenKind>) => value.text), ['123', '456']); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, undefined); assert.deepStrictEqual(result[1].result.map((value: Token<TokenKind>) => value.text), ['123']); assert.strictEqual(result[1].firstToken, firstToken); assert.strictEqual(result[1].nextToken, firstToken.next); assert.deepStrictEqual(result[2].result, []); assert.strictEqual(result[2].firstToken, firstToken); assert.strictEqual(result[2].nextToken, firstToken); } }); test(`Parser: rep_n`, () => { const firstToken = notUndefined(lexer.parse(`123,456,789`)); { const result = succeeded(rep_n(tok(TokenKind.Number), 0).parse(firstToken)); assert.strictEqual(result.length, 1); assert.deepStrictEqual(result[0].result.length, 0); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken); } { const result = succeeded(rep_n(tok(TokenKind.Number), 1).parse(firstToken)); assert.strictEqual(result.length, 1); assert.deepStrictEqual(result[0].result.map((value: Token<TokenKind>) => value.text), ['123']); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken?.text, '456'); } { const result = succeeded(rep_n(tok(TokenKind.Number), 2).parse(firstToken)); assert.strictEqual(result.length, 1); assert.deepStrictEqual(result[0].result.map((value: Token<TokenKind>) => value.text), ['123', '456']); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken?.text, '789'); } { const result = succeeded(rep_n(tok(TokenKind.Number), 3).parse(firstToken)); assert.strictEqual(result.length, 1); assert.deepStrictEqual(result[0].result.map((value: Token<TokenKind>) => value.text), ['123', '456', '789']); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, undefined); } { const output = rep_n(tok(TokenKind.Number), 4).parse(firstToken); assert.strictEqual(output.successful, false); } }); test(`Parser: apply`, () => { const firstToken = notUndefined(lexer.parse(`123,456`)); { const result = succeeded( apply( repr(tok(TokenKind.Number)), (values: Token<TokenKind>[]) => { return values.map((value: Token<TokenKind>) => { return value.text; }).join(';'); } ).parse(firstToken) ); assert.strictEqual(result.length, 3); assert.strictEqual(result[0].result, ''); assert.strictEqual(result[0].firstToken, firstToken); assert.strictEqual(result[0].nextToken, firstToken); assert.strictEqual(result[1].result, '123'); assert.strictEqual(result[1].firstToken, firstToken); assert.strictEqual(result[1].nextToken, firstToken.next); assert.strictEqual(result[2].result, '123;456'); assert.strictEqual(result[2].firstToken, firstToken); assert.strictEqual(result[2].nextToken, undefined); } }); test(`Parser: errd`, () => { const firstToken = notUndefined(lexer.parse(`a`)); { const result = errd( apply( tok(TokenKind.Number), (value: Token<TokenKind>) => +value.text ), 'This is not a number!', 1024 ).parse(firstToken); assert.strictEqual(result.successful, true); if (result.successful) { assert.strictEqual(result.candidates.length, 1); assert.strictEqual(result.candidates[0].result, 1024); assert.strictEqual(result.candidates[0].firstToken, firstToken); assert.strictEqual(result.candidates[0].nextToken, firstToken); assert.deepStrictEqual(result.error, { kind: 'Error', pos: firstToken.pos, message: 'This is not a number!' }); } } });
749d2f1c34d4cc3e05e8e975ed3d3d85536e0dc1
TypeScript
graphprotocol/dharma-subgraph
/types/schema.ts
2.640625
3
import { TypedMap, Entity, Value, ValueKind, store, Address, Bytes, BigInt } from "@graphprotocol/graph-ts"; export class DebtOrder extends Entity { constructor(id: string) { this.set("id", Value.fromString(id)); return this; } save(): void { let id = this.get("id"); assert(id !== null, "Cannot save DebtOrder entity without an ID"); assert( id.kind == ValueKind.STRING, "Cannot save DebtOrder entity with non-string ID. " + 'Considering using .toHex() to convert the "id" to a string.' ); store.set("DebtOrder", id.toString(), this); } static load(id: string): DebtOrder | null { return store.get("DebtOrder", id) as DebtOrder | null; } get id(): string { let value = this.get("id"); if (value === null) { return null; } else { return value.toString() as string; } } set id(value: string) { if (value === null) { this.unset("id"); } else { this.set("id", Value.fromString(value as string)); } } get principle(): BigInt { let value = this.get("principle"); if (value === null) { return null; } else { return value.toBigInt() as BigInt; } } set principle(value: BigInt) { if (value === null) { this.unset("principle"); } else { this.set("principle", Value.fromBigInt(value as BigInt)); } } get principleToken(): Bytes { let value = this.get("principleToken"); if (value === null) { return null; } else { return value.toBytes() as Bytes; } } set principleToken(value: Bytes) { if (value === null) { this.unset("principleToken"); } else { this.set("principleToken", Value.fromBytes(value as Bytes)); } } get underwriter(): Bytes { let value = this.get("underwriter"); if (value === null) { return null; } else { return value.toBytes() as Bytes; } } set underwriter(value: Bytes) { if (value === null) { this.unset("underwriter"); } else { this.set("underwriter", Value.fromBytes(value as Bytes)); } } get underwriterFee(): BigInt { let value = this.get("underwriterFee"); if (value === null) { return null; } else { return value.toBigInt() as BigInt; } } set underwriterFee(value: BigInt) { if (value === null) { this.unset("underwriterFee"); } else { this.set("underwriterFee", Value.fromBigInt(value as BigInt)); } } get relayer(): Bytes { let value = this.get("relayer"); if (value === null) { return null; } else { return value.toBytes() as Bytes; } } set relayer(value: Bytes) { if (value === null) { this.unset("relayer"); } else { this.set("relayer", Value.fromBytes(value as Bytes)); } } get relayerFee(): BigInt { let value = this.get("relayerFee"); if (value === null) { return null; } else { return value.toBigInt() as BigInt; } } set relayerFee(value: BigInt) { if (value === null) { this.unset("relayerFee"); } else { this.set("relayerFee", Value.fromBigInt(value as BigInt)); } } get issuanceCancelledBy(): Bytes | null { let value = this.get("issuanceCancelledBy"); if (value === null) { return null; } else { return value.toBytes() as Bytes | null; } } set issuanceCancelledBy(value: Bytes | null) { if (value === null) { this.unset("issuanceCancelledBy"); } else { this.set("issuanceCancelledBy", Value.fromBytes(value as Bytes)); } } get beneficiary(): Bytes { let value = this.get("beneficiary"); if (value === null) { return null; } else { return value.toBytes() as Bytes; } } set beneficiary(value: Bytes) { if (value === null) { this.unset("beneficiary"); } else { this.set("beneficiary", Value.fromBytes(value as Bytes)); } } get underwriterRiskRating(): BigInt { let value = this.get("underwriterRiskRating"); if (value === null) { return null; } else { return value.toBigInt() as BigInt; } } set underwriterRiskRating(value: BigInt) { if (value === null) { this.unset("underwriterRiskRating"); } else { this.set("underwriterRiskRating", Value.fromBigInt(value as BigInt)); } } get termsContract(): Bytes { let value = this.get("termsContract"); if (value === null) { return null; } else { return value.toBytes() as Bytes; } } set termsContract(value: Bytes) { if (value === null) { this.unset("termsContract"); } else { this.set("termsContract", Value.fromBytes(value as Bytes)); } } get termsContractParameters(): Bytes { let value = this.get("termsContractParameters"); if (value === null) { return null; } else { return value.toBytes() as Bytes; } } set termsContractParameters(value: Bytes) { if (value === null) { this.unset("termsContractParameters"); } else { this.set("termsContractParameters", Value.fromBytes(value as Bytes)); } } get collaterals(): Array<string> | null { let value = this.get("collaterals"); if (value === null) { return null; } else { return value.toStringArray() as Array<string> | null; } } set collaterals(value: Array<string> | null) { if (value === null) { this.unset("collaterals"); } else { this.set("collaterals", Value.fromStringArray(value as Array<string>)); } } get repayments(): Array<string> | null { let value = this.get("repayments"); if (value === null) { return null; } else { return value.toStringArray() as Array<string> | null; } } set repayments(value: Array<string> | null) { if (value === null) { this.unset("repayments"); } else { this.set("repayments", Value.fromStringArray(value as Array<string>)); } } } export class Collateral extends Entity { constructor(id: string) { this.set("id", Value.fromString(id)); return this; } save(): void { let id = this.get("id"); assert(id !== null, "Cannot save Collateral entity without an ID"); assert( id.kind == ValueKind.STRING, "Cannot save Collateral entity with non-string ID. " + 'Considering using .toHex() to convert the "id" to a string.' ); store.set("Collateral", id.toString(), this); } static load(id: string): Collateral | null { return store.get("Collateral", id) as Collateral | null; } get id(): string { let value = this.get("id"); if (value === null) { return null; } else { return value.toString() as string; } } set id(value: string) { if (value === null) { this.unset("id"); } else { this.set("id", Value.fromString(value as string)); } } get tokenAddress(): Bytes { let value = this.get("tokenAddress"); if (value === null) { return null; } else { return value.toBytes() as Bytes; } } set tokenAddress(value: Bytes) { if (value === null) { this.unset("tokenAddress"); } else { this.set("tokenAddress", Value.fromBytes(value as Bytes)); } } get amount(): BigInt { let value = this.get("amount"); if (value === null) { return null; } else { return value.toBigInt() as BigInt; } } set amount(value: BigInt) { if (value === null) { this.unset("amount"); } else { this.set("amount", Value.fromBigInt(value as BigInt)); } } get status(): string { let value = this.get("status"); if (value === null) { return null; } else { return value.toString() as string; } } set status(value: string) { if (value === null) { this.unset("status"); } else { this.set("status", Value.fromString(value as string)); } } get collateralReturnedTo(): Bytes | null { let value = this.get("collateralReturnedTo"); if (value === null) { return null; } else { return value.toBytes() as Bytes | null; } } set collateralReturnedTo(value: Bytes | null) { if (value === null) { this.unset("collateralReturnedTo"); } else { this.set("collateralReturnedTo", Value.fromBytes(value as Bytes)); } } get debtOrder(): string { let value = this.get("debtOrder"); if (value === null) { return null; } else { return value.toString() as string; } } set debtOrder(value: string) { if (value === null) { this.unset("debtOrder"); } else { this.set("debtOrder", Value.fromString(value as string)); } } } export class CancelledDebtOrder extends Entity { constructor(id: string) { this.set("id", Value.fromString(id)); return this; } save(): void { let id = this.get("id"); assert(id !== null, "Cannot save CancelledDebtOrder entity without an ID"); assert( id.kind == ValueKind.STRING, "Cannot save CancelledDebtOrder entity with non-string ID. " + 'Considering using .toHex() to convert the "id" to a string.' ); store.set("CancelledDebtOrder", id.toString(), this); } static load(id: string): CancelledDebtOrder | null { return store.get("CancelledDebtOrder", id) as CancelledDebtOrder | null; } get id(): string { let value = this.get("id"); if (value === null) { return null; } else { return value.toString() as string; } } set id(value: string) { if (value === null) { this.unset("id"); } else { this.set("id", Value.fromString(value as string)); } } get cancelledBy(): Bytes { let value = this.get("cancelledBy"); if (value === null) { return null; } else { return value.toBytes() as Bytes; } } set cancelledBy(value: Bytes) { if (value === null) { this.unset("cancelledBy"); } else { this.set("cancelledBy", Value.fromBytes(value as Bytes)); } } } export class Repayment extends Entity { constructor(id: string) { this.set("id", Value.fromString(id)); return this; } save(): void { let id = this.get("id"); assert(id !== null, "Cannot save Repayment entity without an ID"); assert( id.kind == ValueKind.STRING, "Cannot save Repayment entity with non-string ID. " + 'Considering using .toHex() to convert the "id" to a string.' ); store.set("Repayment", id.toString(), this); } static load(id: string): Repayment | null { return store.get("Repayment", id) as Repayment | null; } get id(): string { let value = this.get("id"); if (value === null) { return null; } else { return value.toString() as string; } } set id(value: string) { if (value === null) { this.unset("id"); } else { this.set("id", Value.fromString(value as string)); } } get payers(): Array<Bytes> | null { let value = this.get("payers"); if (value === null) { return null; } else { return value.toBytesArray() as Array<Bytes> | null; } } set payers(value: Array<Bytes> | null) { if (value === null) { this.unset("payers"); } else { this.set("payers", Value.fromBytesArray(value as Array<Bytes>)); } } get beneficiaries(): Array<Bytes> | null { let value = this.get("beneficiaries"); if (value === null) { return null; } else { return value.toBytesArray() as Array<Bytes> | null; } } set beneficiaries(value: Array<Bytes> | null) { if (value === null) { this.unset("beneficiaries"); } else { this.set("beneficiaries", Value.fromBytesArray(value as Array<Bytes>)); } } get amounts(): Array<BigInt> | null { let value = this.get("amounts"); if (value === null) { return null; } else { return value.toBigIntArray() as Array<BigInt> | null; } } set amounts(value: Array<BigInt> | null) { if (value === null) { this.unset("amounts"); } else { this.set("amounts", Value.fromBigIntArray(value as Array<BigInt>)); } } get debtOrder(): string { let value = this.get("debtOrder"); if (value === null) { return null; } else { return value.toString() as string; } } set debtOrder(value: string) { if (value === null) { this.unset("debtOrder"); } else { this.set("debtOrder", Value.fromString(value as string)); } } }
213cea839ad30163adf12a38a5dda1149687a4d7
TypeScript
JonStargaryen/ts-stream
/src/map.ts
3.234375
3
import {createStream, Stream} from "./stream"; class MapIterator<S, T> implements Iterator<T> { constructor(private readonly map: (item: S) => T, private readonly iterator: Iterator<S>) { } next(value?: any): IteratorResult<T> { const item = this.iterator.next(); return item.done ? { done: true, value: undefined as any }: { done: false, value: this.map(item.value) }; } } export class Map { map<S, T>(this: Stream<T>, map: (item: T) => S): Stream<S> { return createStream(new MapIterator(map, this.iterator)); } }
518d1df48cad8df07325af02a9d69da31ab75108
TypeScript
Raindrips/cocos_creator_example
/happybird/assets/script/model/EffectInfo.ts
2.546875
3
import {ANITIME } from './typeModel' /** * * @param {开始播放的时间} playTime * @param {*cell位置} pos * @param {*第几次消除,用于播放音效} step * @param {*消除次数}step? */ export default interface EffectInfo{ playTime:ANITIME, pos:cc.Vec2, action: string step?:number }
eeed8ec0616fe50693fe03ad557c1baefb0da4a4
TypeScript
BlueGhostAlt/Codify
/src/modules/commands/admin/setpinchannel.ts
2.796875
3
import { Command } from "@enitoni/gears-discordjs"; import { ParseArgumentsState } from "../../../common/parsing/middleware/parseArguments"; import { matchPrefixesStrict } from "../../../common/matching/matchPrefixesStrict"; import { createMetadata } from "../help/createMetadata"; import knex from "../../../../db/knex"; import { Cooldown, setCooldown } from "../../../common/cooldown/middleware/comandCooldown"; const setPinsChannel = async ( serverid: string | undefined, pinschannel: string ): Promise<boolean> => { try { const serverRow = await knex("servers").where({ serverid }); if (serverRow.length === 0) { await knex("servers").insert({ serverid, pinschannel }); } else { await knex("servers") .where({ serverid }) .update({ serverid, pinschannel }); } return true; } catch (error) { return false; } }; export default new Command() .match(matchPrefixesStrict("setpinschannel")) .setMetadata( createMetadata({ name: "Set the pins channel for your server.", usage: "cc!setpinschannel [channelid]", description: "It sets the channel for were the cc!pin messages will go" }) ) .use<Cooldown>(setCooldown(15000)) .use<ParseArgumentsState>(async context => { const { message } = context; const { args } = context.state; if (message.guild !== null) message.delete(); if (!message.member!.hasPermission("ADMINISTRATOR")) { return message.channel.send( ":x: **Oops,** you aren't allowed to do that. Make sure you have the `Administrator` permission." ); } if (!args.length) { return message.channel.send(`:x:**ERROR:** No argument provided.`); } if (await setPinsChannel(message.guild?.id, args[0])) return message.channel.send( ":white_check_mark:**Successfully set the pins channel.**" ); else return message.channel.send(":x:**Oops,** something went wrong."); });
51b2198dea0c01af80826b5993a82b8e125fdb2f
TypeScript
zuned/Typescript
/CustomerV3.ts
3.5625
4
class Customer { //private _fName :string; //private _lName :string; private x :string;private y :string; constructor(fName :string , lName :string ) { // this._fName = fName;this._lName = lName; this.x = fName;this.y = lName; } get fName() :string { return this.x;//this._fName; } set fName(fName:string){ this.x = fName; //this._fName = fName; } get lName() :string { return this.y;//this._lName; } set lName(lName:string){ // this._lName = lName; this.y = lName; } } let cust = new Customer("Zuned" , "Ahmed"); console.log(cust.fName + " " + cust.lName);
053023fc1f52231cfc49b7c4de9cf5780da809e9
TypeScript
Netchive-old/Netchive
/src/common/plugins/data.ts
2.59375
3
import PluginPrototype from "../plugins/interface"; import { StreamSessionInterface } from "../record/streamSession/interface"; import { findPluginById } from "."; /** * 플러그인의 세션 정보를 가져옵니다. * @param plugin 플러그인 오브젝트 * @param streamSession 스트림 세션 */ export function getPluginSessionData(plugin: PluginPrototype, streamSession: StreamSessionInterface): any { return getPluginSessionDataById(plugin.id, streamSession); } /** * 플러그인의 세션 정보를 아이디를 통해 가져옵니다. * @param pluginId 플러그인의 고유 아이디 * @param streamSession 스트림 세션 */ export function getPluginSessionDataById(pluginId: string, streamSession: StreamSessionInterface): any { if (!findPluginById(pluginId)) { return undefined; } if (streamSession.plugins === undefined) { streamSession.plugins = {}; } if (streamSession.plugins[pluginId] === undefined) { streamSession.plugins[pluginId] = {}; } return streamSession.plugins[pluginId]; }
993fe5411fd3b85d19557db311d8d0a2e66f4f36
TypeScript
arturcarvalho/chatter
/chatter-fe/src/utils/applyTheme.ts
3.3125
3
type themeT = "light" | "dark"; /** * Sets attribute data-theme with theme * to ensure the css variables are applied. * @param {string} theme - The theme name ("light" | "dark") */ const applyTheme = (theme: themeT) => { // Going directly to the DOM. document.documentElement.setAttribute("data-theme", theme); }; export default applyTheme;
c178085908de0dbfbb7d85c733929fb369a8505b
TypeScript
taylorpreston/re-reselect
/typescript_test/cache.ts
3.109375
3
import createCachedSelector,{ FlatCacheObject, FifoCacheObject, LruCacheObject } from '../src/index'; type State = {foo: string}; const fooSelector = (state: State) => state.foo; const combinerSelector = (foo: string) => foo; function testFlatCacheObject () { // Accepts this cache object as an option createCachedSelector( fooSelector, combinerSelector, )( fooSelector, { cacheObject: new FlatCacheObject() } ); // Exposes the interface const cacheObject = new FlatCacheObject(); cacheObject.set('foo', () => {}); cacheObject.set(1, () => {}); const result1: any = cacheObject.get('foo'); const result2: any = cacheObject.get(2); cacheObject.remove('foo'); cacheObject.remove(1); cacheObject.clear(); } function testFifoCacheObject () { // Accepts this cache object as an option createCachedSelector( fooSelector, combinerSelector, )( fooSelector, { cacheObject: new FifoCacheObject({ cacheSize: 10 }) } ); // typings:expect-error new FifoCacheObject(); // Exposes the interface const cacheObject = new FifoCacheObject({ cacheSize: 10 }); cacheObject.set('foo', () => {}); cacheObject.set(1, () => {}); const result1: any = cacheObject.get('foo'); const result2: any = cacheObject.get(2); cacheObject.remove('foo'); cacheObject.remove(1); cacheObject.clear(); } function testLruCacheObject () { // Accepts this cache object as an option createCachedSelector( fooSelector, combinerSelector, )( fooSelector, { cacheObject: new LruCacheObject({ cacheSize: 10 }) } ); // typings:expect-error new LruCacheObject(); // Exposes the interface const cacheObject = new LruCacheObject({ cacheSize: 10 }); cacheObject.set('foo', () => {}); cacheObject.set(1, () => {}); const result1: any = cacheObject.get('foo'); const result2: any = cacheObject.get(2); cacheObject.remove('foo'); cacheObject.remove(1); cacheObject.clear(); }
78039c86b653362876d1c26cf385a1e70a94b421
TypeScript
devkeyboard/devkeyboard.github.io
/src/state/text-to-type-language.enum.ts
2.796875
3
import { SelectOption } from '../components/_core/select/select.component'; import { TextToTypeCategory } from './text-to-type-category.enum'; export enum TextToTypeLanguage { ENGLISH = 'english', FRENCH = 'french', JAVA = 'java', PYTHON = 'python', HTML = 'html', } export function getTextToTypeLanguage(category: TextToTypeCategory): SelectOption<TextToTypeLanguage>[] { switch (category) { case TextToTypeCategory.CODE: { return [ { label: 'Java', value: TextToTypeLanguage.JAVA, }, { label: 'Python', value: TextToTypeLanguage.PYTHON, }, { label: 'HTML', value: TextToTypeLanguage.HTML, }, ]; } case TextToTypeCategory.CUSTOM_TEXT: { return []; } default: { return [ { label: 'English', value: TextToTypeLanguage.ENGLISH, }, { label: 'French', value: TextToTypeLanguage.FRENCH, }, ]; } } }
af5fa205d06bae8fc48a653ddebb174fb3fc0935
TypeScript
FarheenIqbal/assignment
/src/renameKeys.ts
3.5625
4
// replaces names of multiple object keys with values provided type T = number | string | boolean type A = { [key: string]: T } type C = { [key: string]: string } export function renameKeys(keysObject: C, object: A): A { if (!keysObject || !object) { return {} } const newObj: A = {} const k1: string[] = Object.keys(object) const k2: string[] = Object.keys(keysObject) for (let i: number = 0; i < k1.length; i++) { const key: string = k1[i] if (k2.includes(key)) { const newName: string = keysObject[key] newObj[newName] = object[key] } else { newObj[key] = object[key] } } return newObj }
4413ce16d0e7b4084efa46e733b0593bdd062cd0
TypeScript
stjordanis/snyk
/test/jest/acceptance/snyk-monitor/project-attributes.spec.ts
2.84375
3
import { generateProjectAttributes } from '../../../../src/cli/commands/monitor'; import { PROJECT_CRITICALITY, PROJECT_ENVIRONMENT, PROJECT_LIFECYCLE, } from '../../../../src/lib/types'; describe('project attributes (--lifecycle, --environment, --business-criticality)', () => { it('returns undefined when they are all missing, for each option', () => { expect(generateProjectAttributes({})).toStrictEqual({ criticality: undefined, lifecycle: undefined, environment: undefined, }); }); it('parses the options correctly when they are valid', () => { expect( generateProjectAttributes({ 'business-criticality': 'critical,high', lifecycle: 'development,sandbox', environment: 'backend,frontend', }), ).toStrictEqual({ criticality: [PROJECT_CRITICALITY.CRITICAL, PROJECT_CRITICALITY.HIGH], lifecycle: [PROJECT_LIFECYCLE.DEVELOPMENT, PROJECT_LIFECYCLE.SANDBOX], environment: [PROJECT_ENVIRONMENT.BACKEND, PROJECT_ENVIRONMENT.FRONTEND], }); }); it('raises the correct error with an invalid business criticality', () => { expect(() => generateProjectAttributes({ 'business-criticality': 'invalid' }), ).toThrow( '1 invalid business-criticality: invalid. Possible values are: critical, high, medium, low', ); }); it('raises the correct error with an invalid lifecycle', () => { expect(() => generateProjectAttributes({ lifecycle: 'invalid' })).toThrow( '1 invalid lifecycle: invalid. Possible values are: production, development, sandbox', ); }); it('raises the correct error with an invalid environment', () => { expect(() => generateProjectAttributes({ environment: 'invalid' })).toThrow( '1 invalid environment: invalid. Possible values are: frontend, backend, internal, external, mobile, saas, onprem, hosted, distributed', ); }); it('raises the correct error with multiple invalid attributes', () => { expect(() => generateProjectAttributes({ lifecycle: 'invalid1,invalid2' }), ).toThrow(/2 invalid lifecycle: invalid1, invalid2/); }); });
5da6f3028019de3bfca6fb52a1602f10670f8992
TypeScript
ahayter-tombras/sfcc-types
/dw.util.d.ts
2.96875
3
declare namespace dw.util { declare class Collection<T> extends Object { // constants // - // properties get empty(): boolean get length(): number // constructors // - // methods add(...values: Object): boolean add1(object: Object): boolean addAll(objs: Collection): boolean clear(): void contains(obj: Object): boolean containsAll(objs: Collection): boolean getLength(): number isEmpty(): boolean iterator(): Iterator<T> remove(obj: Object): boolean removeAll(objs: Collection): boolean retainAll(objs: Collection): boolean size(): number toArray(): Array<T> toArray(start: number, size: number): Array<T> } declare class List<T> extends Collection<T> { // constants // - // properties static EMPTY_LIST: List<T> // constructors // - // methods addAt(index: number, value: Object): void concat(...values: Object): List<any> fill(obj: Object): void get(index: number): Object indexOf(value: Object): number join(): string join(separator: string): string lastIndexOf(value: Object): number pop(): Object push(...values: Object): number removeAt(index: number): Object replaceAll(oldValue: Object, newValue: Object): boolean reverse(): void rotate(distance: number): void set(index: number, value: Object): Object shift(): Object shuffle(): void size(): number slice(from: number): List<T> slice(from: number, to: number): List<T> sort(): void sort(comparator: Object): void subList(from: number, to: number): List<T> swap(i: number, j: number): void unshift(...values: Object): number } declare class ArrayList { // constants // - // properties // - // constructors ArrayList() ArrayList(collection: Collection) ArrayList(iterator: Iterator) ArrayList(...values: Object) // methods clone(): ArrayList } declare class Decimal extends Object { // constants // - // properties // - // constructors constructor(value: number) constructor(value: string) constructor() // methods abs(): Decimal add(value: number): Decimal add(value: Decimal): Decimal addPercent(value: number): Decimal addPercent(value: Decimal): Decimal divide(value: number): Decimal divide(value: Decimal): Decimal equals(other: Object): boolean get(): number hashCode(): number multiply(value: number): Decimal multiply(value: Decimal): Decimal negate(): Decimal round(decimals: number): Decimal subtract(value: number): Decimal subtract(value: Decimal): Decimal subtractPercent(value: number): Decimal subtractPercent(value: Decimal): Decimal toString(): string valueOf(): Object } declare class Iterator<T> extends Object { // constants // - // properties // - // constructors // - // methods asList(start: number, size: number): List<T> asList(): List<T> hasNext(): boolean next(): T // was Object } declare class SeekableIterator { // constants // - // properties get count(): number // constructors // - // methods asList(start: number, size: number): List close(): void first(): Object forward(n: number): void forward(n: number, size: number): void getCount(): number hasNext(): boolean next(): Object } declare class StringUtils extends Object { // constants const ENCODE_TYPE_HTML: number const ENCODE_TYPE_WML: number const ENCODE_TYPE_XML: number const TRUNCATE_CHAR: string const TRUNCATE_SENTENCE: string const TRUNCATE_WORD: string // properties // - // constructors // - // methods static decodeBase64(base64: string): string static decodeBase64(base64: string, characterEncoding: string): string static decodeString(str: string, type: number): string static encodeBase64(str: string): string static encodeBase64(str: string, characterEncoding: string): string static encodeString(str: string, type: number): string static format(format: string, ...args: Object): string static formatCalendar(calendar: Calendar): string static formatCalendar(calendar: Calendar, format: string): string static formatCalendar(calendar: Calendar, locale: string, pattern: number): string static formatDate(date: Date): string static formatDate(date: Date, format: string): string static formatDate(date: Date, format: string, locale: string): string static formatInteger(number: number): string static formatMoney(money: Money): string static formatNumber(number: number): string static formatNumber(number: number, format: string): string static formatNumber(number: number, format: string, locale: string): string static garble(str: string, replaceChar: string, suffixLength: number): string static ltrim(str: string): string static pad(str: string, width: number): string static rtrim(str: string): string static stringToHtml(str: string): string static stringToWml(str: string): string static stringToXml(str: string): string static trim(str: string): string static truncate(str: string, maxLength: number, mode: string, suffix: string): string } declare class Set<T> extends Collection<T> { // constants // - // properties static EMPTY_SET: Set<T> // constructors // - // methods // - } }
daf6a47c688975bb7da5ffe0141e25a424286d7f
TypeScript
zhao-bin-zero/vue3-ssr-nestjs
/server/modules/cats/interfaces/cat.interface.ts
3.375
3
/** * Interface cat * 该文件导出一个cat的接口,用于实现不同文件之间的数据交互。在实际项目中,接口文件不仅仅用于项目中不同模块之间的数据交互,也为实现前后端的统一开发提供了条件。 * * @export * @interface ICat */ export interface ICat { /** * name field * * @type {string} * @memberof ICat */ readonly name: string; /** * age field * * @type {number} * @memberof ICat */ readonly age: number; /** * breed field * * @type {string} * @memberof ICat */ readonly breed: string; }
ccf4d282fcae67e1586780adf246b7f3370bd0ee
TypeScript
VVladislaVLL/course_work_final
/src/game/models/plants/PotatoMine.ts
2.75
3
import Engine from '../../../engine'; import Cell from '../Cell'; import { PlantConfig } from '../../../types'; import Plant from '../Plant'; import Zombie from '../Zombie'; import Level from '../Level'; const READY_TIME = 15000; const POSITION_ADJUST_Y = 10; export class PotatoMine extends Plant { private isAttack: boolean; private isReady: boolean; private occupiedCells: Map<Cell, Plant>; private level: Level; constructor(config: PlantConfig, engine: Engine, level: Level, occupiedCells: Map<Cell, Plant>) { super(config, engine); this.occupiedCells = occupiedCells; this.level = level; } draw(cell: Cell) { super.draw(cell); this.switchState('notReady'); const levelTimer = this.engine.getTimer('levelTimer'); const growTimeout = this.engine.timeout(() => { growTimeout.destroy(); this.grow(); }, READY_TIME); levelTimer?.add(growTimeout); } grow() { this.switchState('grow'); this.node.then(() => { this.switchState('basic'); this.isReady = true; }); this.engine.audioPlayer.playSound('potato-mine_grow'); } isZombieInAttackArea(zombie: Zombie) { if (zombie.row !== this.cell.position.y || !zombie.position) return false; if (zombie.row === this.cell.position.y && zombie.column === this.cell.position.x) return true; return false; } attack(zombie: Zombie) { if (this.isDestroyedFlag) return; if (this.isAttack || !this.isReady) return; this.isAttack = true; this.engine.audioPlayer.playSound('potato-mine'); this.node.then(() => { this.health = 0; this.destroy(); this.occupiedCells.delete(this.cell); }); this.level.zombiesArr.forEach((targetZombie) => { if (this.isZombieInAttackArea(targetZombie) && targetZombie.health > 0) { targetZombie.reduceHealth(this.damage); if (targetZombie.health <= 0) { targetZombie.burn(); } } }); } public switchState(state: string, zombie?: Zombie) { if (state === 'attack' && (this.isAttack || !this.isReady)) return; this.node.position.plus(this.engine.vector(0, POSITION_ADJUST_Y)); super.switchState(state, zombie); } }
91e7a7abc4c3402ed077789a2d26641bba0c22b6
TypeScript
Timothy-Tolley/pc-slate-tools
/src/cart/get.ts
2.65625
3
import * as $ from 'jquery'; import { jsonFromjQuery } from './../jquery/'; import { ON_CART_FETCHED } from './events'; import { addTask, removeTask, nextTask, addFinishTrigger, errorQueue } from './queue'; //Internally tracked variable for knowing the current cart data. let currentCart = null; //Internal method only, do not use unless you know what you're doing!! export const setCurrentCart = (cart:any) => { window[`Cart`].data = cart; currentCart = cart; return cart; } /*** Current Cart ***/ export const getCurrentCart = () => { if(currentCart) return currentCart; //Using JavaScript if(window[`Cart`] && window[`Cart`].data) return currentCart = window [`Cart`].data; //Using JSON+jQuery let cartElement = $('[data-cart-json]'); if(cartElement.length) return currentCart = jsonFromjQuery(cartElement); //using Ajax... console.warn('No default cart was loaded, app will get cart via ajax and be blocking!! Dump the cart json into window.Cart before requesting it.'); getCartCB(null, null, { async: false }); return currentCart; }; //Promise Flavour export const getCart = () => { return new Promise((resolve,reject) => getCartCB(resolve, reject)); }; //Callback Flavour export const getCartCB = (callback?:any, errorCallback?:any, params?:object) => { let o:any = { callback, errorCallback, url: '/cart.js', method: 'GET', dataType: 'json', data: {}, action: 'get' }; if(params) o = {...o, params}; o.success = function(data:any) { setCurrentCart(data); if(this.callback) this.callback(data); addFinishTrigger({ event: ON_CART_FETCHED, data }); removeTask(this); nextTask(); }.bind(o); o.error = function(e,i) { if(typeof this.errorCallback === "function") { this.errorCallback(e ? e.responseJSON || e : 'Unknown Error'); } removeTask(this); errorQueue(); }.bind(o); o.task = function() { $.ajax(this); }.bind(o); addTask(o); };
acaca0e4d91fd93a59ba83d99cb820e6ba6bc738
TypeScript
drumonii/LeagueTrollBuild
/frontend/projects/troll-build/src/app/model/champion-spell.ts
2.625
3
/** * Champion spell. */ export interface ChampionSpell { key: string; name: string; description: string; tooltip: string; }
4dd70f566a5d7d041e52c221a6079874c51dc5d2
TypeScript
fahrisyany/AiChat-webapp
/src/tools/localStorage.ts
2.65625
3
export const setLocalStorage = (payload: { item: string, title: string }) => { localStorage.setItem(payload.title, payload.item); } export const getLocalStorage = (title: string) => { return localStorage.getItem(title); } export const removeLocalStorage = (title: string) => { localStorage.removeItem(title); }
2c35168c2509f1c345ef15096029b22e94a45aa2
TypeScript
Kava-Labs/javascript-sdk
/src/msg/hard/index.ts
2.53125
3
import { Coin } from '../../types/Coin'; function newMsgDeposit(depositor: string, amount: Coin[]) { return { type: 'hard/MsgDeposit', value: { depositor: depositor, amount: amount, }, }; } function newMsgWithdraw(depositor: string, amount: Coin[]) { return { type: 'hard/MsgWithdraw', value: { depositor: depositor, amount: amount, }, }; } function newMsgBorrow(borrower: string, amount: Coin[]) { return { type: 'hard/MsgBorrow', value: { borrower: borrower, amount: amount, }, }; } function newMsgRepay(sender: string, owner: string, amount: Coin[]) { return { type: 'hard/MsgRepay', value: { sender: sender, owner: owner, amount: amount, }, }; } function newMsgLiquidate(keeper: string, borrower: string) { return { type: 'hard/MsgLiquidate', value: { keeper: keeper, borrower: borrower, }, }; } export const hard = { newMsgDeposit, newMsgWithdraw, newMsgBorrow, newMsgRepay, newMsgLiquidate, };
853bac90b21d6eed4cf28fbe3632712b21e81436
TypeScript
kleintody/snips-action-directions
/src/handlers/utils.ts
2.578125
3
import { config } from 'snips-toolkit' import { WORK_SYNONYMS, HOME_SYNONYMS, TRAVEL_MODE_VARIABLES } from '../constants' export const getCurrentLocation = function() { if (config.get().currentLocation) { switch (config.get().currentLocation) { case 'work': return getWorkLocation() case 'home': return getHomeLocation() default: throw new Error('badCurrentAddress') } } else { throw new Error('noCurrentAddress') } } export const getWorkLocation = function() { if (!config.get().workAddress || !config.get().workCity) { throw new Error('noWorkAddress') } return config.get().workAddress + ' ' + config.get().workCity } export const getHomeLocation = function() { if (!config.get().homeAddress || !config.get().homeCity) { throw new Error('noHomeAddress') } return config.get().homeAddress + ' ' + config.get().homeCity } export const getCompleteAddress = function(location) { const workSynonyms = WORK_SYNONYMS[config.get().locale] if (workSynonyms && workSynonyms.includes(location)) { return getWorkLocation() } const homeSynonyms = HOME_SYNONYMS[config.get().locale] if (homeSynonyms && homeSynonyms.includes(location)) { return getHomeLocation() } // Increasing precision if current city in provided /* if (config.currentLocation) { switch (config.currentLocation) { case 'work': if (!location.includes(config.workCity)) { location += ' ' + config.workCity } break case 'home': if (!location.includes(config.homeCity)) { location += ' ' + config.homeCity } break default: break } } */ return location } export const checkCurrentCoordinates = function() { if (!config.get().currentCoordinates) { throw new Error('noCurrentCoordinates') } } export function containsFlag(flag: string, travelMode: string): boolean { const flags = TRAVEL_MODE_VARIABLES[config.get().locale] return flags && flags[flag] && travelMode === flags[flag] }
ef4f72c87b88ed78f516eccf37036a5b2530bcf7
TypeScript
beszczur/TIwPR
/src/app/dataproviders/dataprovider.service.ts
2.515625
3
import {Injectable} from '@angular/core'; import {Http} from '@angular/http'; import {Day} from '../models/day'; import {Task} from '../models/task'; import {Event} from '../models/event'; @Injectable() export class DataproviderService { private address = ''; public plan: any[] = [ new Day( 'MONDAY', '2017-04-24', [ new Event (1, 'ZSK', 0, '2017-04-24', false, [ new Task(1, 1, 'Zadanie 1 z konstruktora', 0, 0), new Task(2, 1, 'Zadanie 2 z konstruktora', 0, 1), ]), new Event (2, 'Angielski', 0, '2017-04-24', false, [ new Task(3, 2, 'Zadanie 1A z konstruktora', 0, 0), new Task(4, 2, 'Zadanie 2A z konstruktora', 0, 1), ]), ] ), new Day( 'TUESDAY', '2017-04-25', [ new Event(3, 'Praca', 0, '2017-04-25', false, [ new Task(5, 3, 'TASK 1C', 0, 0), new Task(6, 3, 'TASK 2C', 1, 1), ] ), new Event(4, 'NT4G', 0, '2017-04-25', false, [ new Task(7, 4, 'Task 1A', 1, 0), new Task(8, 4, 'Task 2A', 0, 1), ] ), ] ), new Day( 'WEDNESDAY', '2017-04-26', [ new Event(17, 'BSI', 0, '2017-04-26', false, []), ] ), new Day('TUESDAY', '2017-04-27', []), new Day('FRIDAY', '2017-04-28', []), new Day('WEEKEND', '2017-04-29/2017-04-30', [ new Event(5, 'Trip preparation', 0, '2017-04-29', false, [ new Task(9, 5, 'packing', 0, 0), new Task(10, 5, 'bike cleaning', 0, 0), ] ), ] ), ]; constructor() { } // private _http: Http) getWeekPlan(){ return this.plan; } public addEvent(event : Event){ for(var i=0; i<this.plan.length; i++) { if(this.plan[i].date == event.date) { this.plan[i].events.push(event); console.log(this.plan[i].events); return true; } } return false; } public addTask(task: Task) { for(var i=0; i<this.plan.length; i++) { var events= this.plan[i].events; for(var j=0; j<events.length; j++) { if(events[j].id === task.eventId) { this.plan[i].events[j].tasks.push(task); console.log(this.plan[i].events[j].tasks); return true; } } } return false; } public editTask(task: Task) { for(var i=0; i<this.plan.length; i++) { var events= this.plan[i].events; for(var j=0; j<events.length; j++) { if(events[j].id === task.eventId) { for(var k=0; k<events[j].tasks.length; k++) { if(events[j].tasks[k].id === task.id) { this.plan[i].events[j].tasks[k]=task; console.log(this.plan[i].events[j].tasks); return true; } } } } } return false; } //getWeekPlan() { //return // let author = new Author(firstName, surname); // var headers = new Headers(); // headers.append('Content-Type', 'application/json'); // var requestoptions = new RequestOptions({ // method: RequestMethod.Post, // url: this.address + 'searchNew/', // headers: headers, // body: JSON.stringify(author) // }) //} }
637c2885e165649392c65a1de7f83d06e1ed657b
TypeScript
tdude92/GalaxyGarden
/app/common/component/RigidBody.ts
2.96875
3
import * as THREE from 'three'; import { Orbit } from './Orbit' export abstract class RigidBody { /** * Base class for any object that will be in motion */ position: THREE.Vector3; solar_x_skew: THREE.Matrix4; solar_y_skew: THREE.Matrix4; // Rotation about axis axialTilt: number; angularSpeed: number; phi: number; // angle of rotation // Orbit orbit: Orbit; constructor(orbit_a:number, orbit_e:number, x_skew:number, y_skew:number) { this.solar_x_skew = new THREE.Matrix4().makeRotationX(x_skew); this.solar_y_skew = new THREE.Matrix4().makeRotationY(y_skew); this.orbit = new Orbit(orbit_a, orbit_e); } step(new_time:number): void { this.position = this.orbit.get_2d_coords(new_time) .applyMatrix4(this.solar_x_skew) .applyMatrix4(this.solar_y_skew); } }
7e40aec9f0a6879575852b1b58e18b1f9a5183af
TypeScript
airbnb/visx
/packages/visx-zoom/src/util/matrix.ts
3.15625
3
import { TransformMatrix, Point } from '../types'; export function identityMatrix(): TransformMatrix { return { scaleX: 1, scaleY: 1, translateX: 0, translateY: 0, skewX: 0, skewY: 0, }; } export function createMatrix({ scaleX = 1, scaleY = 1, translateX = 0, translateY = 0, skewX = 0, skewY = 0, }: Partial<TransformMatrix>): TransformMatrix { return { scaleX, scaleY, translateX, translateY, skewX, skewY, }; } export function inverseMatrix({ scaleX, scaleY, translateX, translateY, skewX, skewY, }: TransformMatrix) { const denominator = scaleX * scaleY - skewY * skewX; return { scaleX: scaleY / denominator, scaleY: scaleX / denominator, translateX: (scaleY * translateX - skewX * translateY) / -denominator, translateY: (skewY * translateX - scaleX * translateY) / denominator, skewX: skewX / -denominator, skewY: skewY / -denominator, }; } export function applyMatrixToPoint(matrix: TransformMatrix, { x, y }: Point) { return { x: matrix.scaleX * x + matrix.skewX * y + matrix.translateX, y: matrix.skewY * x + matrix.scaleY * y + matrix.translateY, }; } export function applyInverseMatrixToPoint(matrix: TransformMatrix, { x, y }: Point) { return applyMatrixToPoint(inverseMatrix(matrix), { x, y }); } export function scaleMatrix( scaleX: TransformMatrix['scaleX'], maybeScaleY: TransformMatrix['scaleY'] | undefined = undefined, ) { const scaleY = maybeScaleY || scaleX; return createMatrix({ scaleX, scaleY }); } export function translateMatrix( translateX: TransformMatrix['translateX'], translateY: TransformMatrix['translateY'], ) { return createMatrix({ translateX, translateY }); } export function multiplyMatrices(matrix1: TransformMatrix, matrix2: TransformMatrix) { return { scaleX: matrix1.scaleX * matrix2.scaleX + matrix1.skewX * matrix2.skewY, scaleY: matrix1.skewY * matrix2.skewX + matrix1.scaleY * matrix2.scaleY, translateX: matrix1.scaleX * matrix2.translateX + matrix1.skewX * matrix2.translateY + matrix1.translateX, translateY: matrix1.skewY * matrix2.translateX + matrix1.scaleY * matrix2.translateY + matrix1.translateY, skewX: matrix1.scaleX * matrix2.skewX + matrix1.skewX * matrix2.scaleY, skewY: matrix1.skewY * matrix2.scaleX + matrix1.scaleY * matrix2.skewY, }; } export function composeMatrices(...matrices: TransformMatrix[]): TransformMatrix { switch (matrices.length) { case 0: throw new Error('composeMatrices() requires arguments: was called with no args'); case 1: return matrices[0]; case 2: return multiplyMatrices(matrices[0], matrices[1]); default: { const [matrix1, matrix2, ...restMatrices] = matrices; const matrix = multiplyMatrices(matrix1, matrix2); return composeMatrices(matrix, ...restMatrices); } } }
bcb89452f0ff9fb6cb397d5592ceac321cb703bb
TypeScript
yueecui/screeps-world
/src/creep/role/Carrier.ts
2.53125
3
import { ENERGY_NEED, ENERGY_ENOUGH, WORK_IDLE, WORK_TRANSPORTER_SPAWN, WORK_TRANSPORTER_TOWER, WORK_TRANSPORTER_STORAGE_ENERGY, WORK_TRANSPORTER_CONTROLLER, MODE_SPAWN, MODE_CONTROLLER, WORK_TRANSPORTER_STORAGE_MINERAL, WORK_TRANSPORTER_TOMBSTONE, TRUE } from '@/common/constant'; const IDLE_POS = { x: 28, y: 27 } // 如果目标无视野,则先走到下面的位置 const MAP_POS: Record<string, [number,number]> = { 'W34N57': [7, 21] } export default function (creep: Creep) { if (Game.rooms.sim){ creep.doTask(); return; } if (creep.memory.room != undefined){ otherRoom(creep); }else{ updateStatus(creep); execute(creep); } } // 判断工作模式 const updateStatus = function(creep: Creep){ // 优先级最高任务 // 判断是否需要补充孵化能量 // 会中断其他工作优先进行本工作 if (creep.mode == MODE_CONTROLLER){ if (creep.checkWorkTransporterStorage_Mineral()) return; if (creep.checkWorkTransporterController()) return; // 空闲下才会执行的任务 if (creep.work == WORK_IDLE){ // if (creep.checkWorkTransporterController()) return; if (creep.checkWorkTransporterSpawn()) return; if (creep.checkWorkTransporterStorage_Energy()) return; if (creep.checkWorkTransporterTombstone()) return; if (creep.checkWorkTransporterTower()) return; // if (creep.checkWorkTransporterStorage_Mineral()) return; } }else { // if (creep.checkWorkTransporterTombstone()) return; if (creep.checkWorkTransporterSpawn()) return; // 空闲下才会执行的任务 if (creep.work == WORK_IDLE){ if (creep.checkWorkTransporterTower()) return; if (creep.checkWorkTransporterStorage_Energy()) return; if (creep.checkWorkTransporterController()) return; // if (creep.checkWorkTransporterStorage_Mineral()) return; } } } // 根据工作模式执行 const execute = function(creep: Creep){ if (creep.work != WORK_TRANSPORTER_STORAGE_MINERAL){ creep.recycleNearby(); // 回收周围的能量 } switch(creep.work){ case WORK_TRANSPORTER_SPAWN: creep.doWorkTransporterSpawn(); break; case WORK_TRANSPORTER_TOWER: creep.doWorkTransporterTower(); break; case WORK_TRANSPORTER_CONTROLLER: creep.doWorkTransporterController(); break; case WORK_TRANSPORTER_STORAGE_ENERGY: creep.doWorkTransporterStorage_Energy(); break; case WORK_TRANSPORTER_STORAGE_MINERAL: creep.doWorkTransporterStorage_Mineral(); break; case WORK_TRANSPORTER_TOMBSTONE: creep.doWorkTransporterTombstone(); break; case WORK_IDLE: if (creep.store[RESOURCE_ENERGY] > 0){ creep.energy = ENERGY_ENOUGH; creep.work = WORK_TRANSPORTER_STORAGE_ENERGY; }else{ creep.goToStay(); } break; default: creep.work = WORK_IDLE; } } // ROOM外采集测试 const otherRoom = function(creep: Creep){ creep.updateEnergyStatus(); if (creep.energy == ENERGY_ENOUGH){ if (creep.room.name != creep.bornRoom){ const room = Game.rooms[creep.bornRoom]; if (!room || !room.storage) { creep.say('⁉️');return; } creep.moveTo(room.storage); return; } const stores: Array<StructureStorage|StructureLink> = [creep.room.storage!] if (creep.room.name == 'W35N57'){ stores.push(Game.getObjectById('60b383415912304d8a2f1a7e' as Id<StructureLink>)!) } const target = creep.pos.findClosestByRange(stores)!; if (creep.transfer(target, RESOURCE_ENERGY) == ERR_NOT_IN_RANGE){ creep.moveTo(target); } if (creep.store.getUsedCapacity() == 0){ creep.energy = ENERGY_NEED; } }else{ creep.recycleNearby(); // 回收周围的能量 const pos = MAP_POS[creep.memory.room]; const move_target = new RoomPosition(pos[0], pos[1], creep.memory.room); if (creep.room.name != creep.memory.room){ creep.moveTo(move_target); return; } const containers: StructureContainer[] = [] for (const info of creep.room.containers){ const container = Game.getObjectById(info.id)!; if (container){ if (container.store.getFreeCapacity() < 1200){ containers.push(container); } }else{ creep.room.memory.flagPurge = TRUE; } } containers.sort((a, b) => { return b.store[RESOURCE_ENERGY] - a.store[RESOURCE_ENERGY]; }) if (containers[0]){ if (creep.withdraw(containers[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE){ creep.moveTo(containers[0]); } return; } if (creep.bornRoom == 'W35N57'){ if (creep.store[RESOURCE_ENERGY] > 800){ creep.energy = ENERGY_ENOUGH; } creep.moveTo(move_target); }else if (creep.store.getFreeCapacity() == 0){ creep.energy = ENERGY_ENOUGH; } } }
65772b4ed9f1a61007b967b9675b7b4ec9766d24
TypeScript
MagdaSzade/fintech-challenge
/src/helpers/returnRateOFBasicInvest.ts
2.921875
3
import {BasicInvestition, BasicInvestitionReturnRate, PAYMENT_PERIODS} from './types'; export const returnRate = ({ initialCapital, depositFrequency, additionalContribution, returnRate, duration, }: BasicInvestition): BasicInvestitionReturnRate => { let depositValue = initialCapital; let profitValue = 0; let totalReturn = initialCapital; const deposits = [{month: 0, depositValue: initialCapital, totalProfit: initialCapital}]; const sysPayPerNumber = depositFrequencyInMonths(depositFrequency); for (let i = 1; i <= duration; i++) { profitValue = (totalReturn * returnRate) / 1200; if (sysPayPerNumber !== 0 && i % sysPayPerNumber === 0) { depositValue += additionalContribution; totalReturn += additionalContribution; } totalReturn += profitValue; deposits.push({month: i, depositValue, totalProfit: totalReturn}); } const riskFactor = riskFactoryValue(returnRate); return {capital: depositValue, riskFactor, total: totalReturn, data: deposits}; }; const depositFrequencyInMonths = (months: PAYMENT_PERIODS): number => { switch (months) { case PAYMENT_PERIODS.NULL: return 0; case PAYMENT_PERIODS.MONTH: return 1; case PAYMENT_PERIODS.QUARTER: return 3; case PAYMENT_PERIODS.HALF_YEAR: return 6; case PAYMENT_PERIODS.YEAR: return 12; } }; const riskFactoryValue = (n: number): number => { return n < 2 ? 1 : n > 8 ? 7 : Math.round(n - 1); };
ddd94783a7fcbc7e897c2fcd7dd5ada2024ca822
TypeScript
tblong2105/CRUD-React-Redux-Typescripts
/FrontEnd/src/actions/Products.ts
2.703125
3
import { CREATE_PRODUCT, RETRIEVE_PRODUCTS, UPDATE_PRODUCT, DELETE_PRODUCT, IS_SUCCESS, IS_FAIL, } from "./Types"; import ProductDataService from '../services/ProductService'; import { Dispatch } from 'react' import { IBrand } from "../@types/Ibrand"; import { Iproduct } from "../@types/IProduct"; import { handleError } from '../helpers/HandleError' import { CREATE_SUCCESS, DELETE_SUCCESS, UPDATE_SUCCESS } from "../helpers/Constant"; import { ActionEntity } from "../@types/EntityActionType"; import { StatusActionEntity } from "../@types/StatusActionType"; /** * Products * * Version 1.0 * * Date: 08-06-2021 * * Copyright * * Modification Logs: * DATE AUTHOR DESCRIPTION * ----------------------------------------------------------------------- * 08-06-2021 LONGTB4 Create */ /** * Create product action * * @param productName * @param description * @param price * @param brand * @returns Promise */ export const createProduct = (productName: string, description: string, price: number, brand: IBrand) => async (dispatch: Dispatch<ActionEntity | StatusActionEntity>) => { try { // Create product function const res = await ProductDataService.create({ productName, description, price, brand }); dispatch({ type: CREATE_PRODUCT, payload: res.data, }); // Set message create product success dispatch({ type: IS_SUCCESS, payload: CREATE_SUCCESS }) return Promise.resolve(res.data); // If create product fail } catch (error) { // Set message create product fail dispatch({ type: IS_FAIL, payload: handleError(error) }); return Promise.reject(error); } }; /** * retrieve products action */ export const retrieveProducts = () => async (dispatch: Dispatch<ActionEntity | StatusActionEntity>) => { try { // Retrieve products function const res = await ProductDataService.getAll(); dispatch({ type: RETRIEVE_PRODUCTS, payload: res.data, }); // If retrieve products fail } catch (error) { // Set message retrieve products fail dispatch({ type: IS_FAIL, payload: handleError(error) }); } }; /** * update product action * * @param id * @param data * @returns Promise */ export const updateProduct = (id: number, data: Iproduct) => async (dispatch: Dispatch<ActionEntity | StatusActionEntity>) => { try { // Update products function const res = await ProductDataService.update(id, data); dispatch({ type: UPDATE_PRODUCT, payload: data, }); // Set message update product success dispatch({ type: IS_SUCCESS, payload: UPDATE_SUCCESS }) return Promise.resolve(res.data); // If update product fail } catch (error) { // Set message update product fail dispatch({ type: IS_FAIL, payload: handleError(error) }); return Promise.reject(error); } }; /** * Delete product action * * @param id */ export const deleteProduct = (id: number) => async (dispatch: Dispatch<ActionEntity | StatusActionEntity>) => { try { // Delete products function await ProductDataService.remove(id); dispatch({ type: DELETE_PRODUCT, payload: id, }); // Set message delete product success dispatch({ type: IS_SUCCESS, payload: DELETE_SUCCESS }) // If delete products fail } catch (error) { // Set message delete product fail dispatch({ type: IS_FAIL, payload: handleError(error) }); } }; /** * Find products by product name action * * @param productName */ export const findProductsByProductName = (productName: string) => async (dispatch: Dispatch<ActionEntity | StatusActionEntity>) => { try { // Find products by product name function const res = await ProductDataService.findByProductName(productName); dispatch({ type: RETRIEVE_PRODUCTS, payload: res.data, }); } catch (error) { } };
a814284c422e6d9bb0b100631821440899a63c31
TypeScript
fransflippo/sfdx-ci-plugin
/src/helpers/certificateGenerator.ts
2.796875
3
import * as forge from 'node-forge'; export class CertificateAndPrivateKey { public certificatePem: string; public privateKeyPem?: string; constructor(certificatePem: string, privateKeyPem?: string) { this.certificatePem = certificatePem; this.privateKeyPem = privateKeyPem; } } export interface GenerateCertificateCallback { beforeGeneratePrivateKey?: () => Promise<void>; onGeneratePrivateKey?: (privateKeyPem: string) => Promise<void>; beforeGenerateCertificate?: () => Promise<void>; onGenerateCertificate?: (certificatePem: string) => Promise<void>; } class CertificateGenerator { /** * Generates a private key and a certificate signed with that key and writes both * to files in PEM format. * @returns {string} */ public async generateCertificateAndPrivateKey(callback?: GenerateCertificateCallback): Promise<CertificateAndPrivateKey> { const pki = forge.pki; // Create key pair if (callback && callback.beforeGeneratePrivateKey) { await callback.beforeGeneratePrivateKey(); } const keys = pki.rsa.generateKeyPair(2048); // Convert private key to PEM format const privateKeyPem = pki.privateKeyToPem(keys.privateKey); if (callback && callback.onGeneratePrivateKey) { await callback.onGeneratePrivateKey(privateKeyPem); } // Create certificate if (callback && callback.beforeGenerateCertificate) { await callback.beforeGenerateCertificate(); } const cert = pki.createCertificate(); cert.publicKey = keys.publicKey; const attrs = [{ name: 'commonName', value: 'example.org' }, { name: 'countryName', value: '000' }, { shortName: 'ST', value: 'None' }, { name: 'localityName', value: 'None' }, { name: 'organizationName', value: 'Certificate generated by sfdx-ci-plugin using Forge' }, { shortName: 'OU', value: 'https://github.com/fransflippo/sfdx-ci-plugin' }]; cert.setSubject(attrs); cert.setIssuer(attrs); cert.version = 0; // Sign certificate cert.sign(keys.privateKey, forge.md.sha256.create()); // Convert certificate to PEM format const certificatePem = pki.certificateToPem(cert); if (callback && callback.onGenerateCertificate) { await callback.onGenerateCertificate(certificatePem); } return new CertificateAndPrivateKey(certificatePem, privateKeyPem); } } export default new CertificateGenerator();
feb3f039f5b49fce11575d2700f6a848cfbbe137
TypeScript
menucha-de/shared
/ui/projects/mica-shared/src/lib/mica-transport/models/store-action.model.ts
2.546875
3
export type Action = 'LOAD_ALL' | 'LOAD' | 'ADD' | 'EDIT' | 'REMOVE'; export const LOAD_ALL: Action = 'LOAD_ALL'; export const LOAD: Action = 'LOAD'; export const ADD: Action = 'ADD'; export const EDIT: Action = 'EDIT'; export const REMOVE: Action = 'REMOVE'; export interface StoreAction { type: Action; data: any; }
81bba69381807f539c61938750eb631a90106edf
TypeScript
kirpalmakanga/microtube
/@types/alltypes.d.ts
2.515625
3
export const SIZE_DEFAULT = 'default'; export const SIZE_MEDIUM = 'medium'; export const SIZE_HIGH = 'high'; declare global { interface Window { gapi: any; } } interface DeviceData { deviceId: string; deviceName: string; isMaster: boolean; } export interface File { url: string; } export interface ThumbnailsData { [key: string]: File; [SIZE_DEFAULT]: File; [SIZE_MEDIUM]: File; [SIZE_HIGH]: File; } export type GenericObject = { [key: string]: any }; interface PlaylistData { id: string; title: string; thumbnails: ThumbnailsData; itemCount: number; privacyStatus: string; } interface VideoData { id: string; title: string; description: string; thumbnails: ThumbnailsData; duration: number; publishedAt: string; channelId: string; channelTitle: string; privacyStatus: string; } interface PlaylistItemData extends VideoData { playlistId: string; playlistItemId: string; } export interface ChannelData { id: string; title: string; thumbnails: ThumbnailsData; } interface PlayerSyncPayload { action: string; data: GenericObject; } interface PlayerSyncHandlers { [key: string]: Function; } interface ShareConfig { title: string; url: string; } type HTMLElementWheelEvent = Event & { deltaY: number; }; type KeyboardEventName = 'keypress' | 'keydown' | 'keyup';
82ae19d555840a9bf72cce0ed63abd68fcd5813f
TypeScript
superpig/interpreter
/src/part7/__tests__/interpreter.test.ts
3.265625
3
import Lexer from '../spi/lexer' import { TokenType } from '../spi/token' import Interpreter from '../spi/interpreter' import Parser from '../spi/parser' describe('lexer', () => { function makeLexer(text: string) { const lexer = new Lexer(text) return lexer } test('test_lexer_integer', () => { const lexer = makeLexer('234') const token = lexer.getNextToken() expect(token.type).toBe(TokenType.INTEGER) expect(token.value).toBe(234) }) test('test_lexer_mul', () => { const lexer = makeLexer('*') const token = lexer.getNextToken() expect(token.type).toBe(TokenType.MUL) expect(token.value).toBe('*') }) test('test_lexer_div', () => { const lexer = makeLexer(' / ') const token = lexer.getNextToken() expect(token.type).toBe(TokenType.DIV) expect(token.value).toBe('/') }) test('test_lexer_plus', () => { const lexer = makeLexer(' + ') const token = lexer.getNextToken() expect(token.type).toBe(TokenType.PLUS) expect(token.value).toBe('+') }) test('test_lexer_minus', () => { const lexer = makeLexer(' - ') const token = lexer.getNextToken() expect(token.type).toBe(TokenType.MINUS) expect(token.value).toBe('-') }) }) describe('interpreter', () => { function makeInterpreter(text: string) { const lexer = new Lexer(text) const parser = new Parser(lexer) const interpreter = new Interpreter(parser) return interpreter } test('test_expression1', () => { const interpreter = makeInterpreter('2') const result = interpreter.interpret() expect(result).toBe(2) }) test('test_expression2', () => { const interpreter = makeInterpreter('2 + 7 * 4') const result = interpreter.interpret() expect(result).toBe(30) }) test('test_expression3', () => { const interpreter = makeInterpreter('7 - 8 / 4') const result = interpreter.interpret() expect(result).toBe(5) }) test('test_expression4', () => { const interpreter = makeInterpreter('14 + 2 * 3 - 6 / 2') const result = interpreter.interpret() expect(result).toBe(17) }) test('test_expression5', () => { const interpreter = makeInterpreter('7 + 3 * (10 / (12 / (3 + 1) - 1))') const result = interpreter.interpret() expect(result).toBe(22) }) test('test_expression6', () => { const interpreter = makeInterpreter('7 + 3 * (10 / (12 / (3 + 1) - 1)) / (2 + 3) - 5 - 3 + (8)') const result = interpreter.interpret() expect(result).toBe(10) }) test('test_expression7', () => { const interpreter = makeInterpreter('7 + (((3 + 2)))') const result = interpreter.interpret() expect(result).toBe(12) }) test('test_expression_invalid_syntax', () => { expect(() => { const interpreter = makeInterpreter('10 *') interpreter.interpret() }).toThrow() }) })
3ea95c3691ccb41ad9a8f06e356c52dc4a5fe4e8
TypeScript
perfectyang/ts-react
/todo-list/src/typing/index.ts
2.6875
3
import React, {Dispatch, SetStateAction, useState} from "react"; export interface ITodo { id: string; content: string; complete: boolean } export interface IDataList { dataList: ITodo[], deleteTodo: (id: string | number) => void } export interface IInputs { value?: string, addTodo: (todo:ITodo) => void } export interface IState { todoList: ITodo[] } export interface IAction { type: string; paylod: ITodo | string } type Fn<T> = (value: T) => void export const PlayMusicDispatchContext = React.createContext<Fn<IAction>>(() => {}) interface IContext { n: number; setN: Dispatch<SetStateAction<number>> } export const Ctext = React.createContext<IContext>({} as IContext)
29b6b40937306295320e64c3b30e7746a30b91a7
TypeScript
NepipenkoIgor/ts29022020
/old/functions-this.ts
3.265625
3
function getFullName(this: { name: string, surname: string }) { return `${this.name} ${this.surname}` } getFullName(); let account = { name: 'Ihor', surname: 'Nepipenko', age: 33, getFullName } account.getFullName(); type HandlerCb = (this: void, e: Event) => void class UIElement { addClickHandler(_onclick: Handler): void { } } class Handler { info!: string; onClickBad(this: this, _e: Event) { this.info = 'message' } } let h = new Handler(); let uiElement = new UIElement(); uiElement.addClickHandler(h.onClickBad)
f7d5ce3150f12d331b91912687356fcb5084ec29
TypeScript
hourliert/redux-crud-observable
/src/errors/__tests__/ApiError-test.ts
2.5625
3
import ApiError from '../ApiError'; describe('ApiError', () => { it('create an ApiError', () => { const error = new ApiError(); error.data = 'Error'; error.status = 500; expect(error).toBeInstanceOf(Error); expect(error.data).toEqual('Error'); expect(error.status).toEqual(500); }); });
7f9650e7f777ded7220e54db4a480031bdba2318
TypeScript
SAP/ui5-webcomponents
/packages/main/src/types/CarouselPageIndicatorStyle.ts
3.03125
3
/** * Different Carousel page indicator styles. * * @readonly * @enum {string} * @public * @author SAP SE * @alias sap.ui.webc.main.types.CarouselPageIndicatorStyle */ enum CarouselPageIndicatorStyle { /** * The page indicator will be visualized as dots if there are fewer than 9 pages. * If there are more pages, the page indicator will switch to displaying the current page and the total number of pages. (e.g. X of Y) * @public * @type {Default} */ Default = "Default", /** * The page indicator will display the current page and the total number of pages. (e.g. X of Y) * @public * @type {Numeric} */ Numeric = "Numeric", } export default CarouselPageIndicatorStyle;
961611eeb70b336dee4895e38ba4f719c5aa26e4
TypeScript
raziems/skinet
/client/src/app/basket/basket.service.ts
2.546875
3
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs'; import { map } from 'rxjs/operators'; import { environment } from 'src/environments/environment'; import { Basket, IBasket, IBasketItem, IBasketTotals } from '../shared/models/basket'; import { IDeliveryMethod } from '../shared/models/deliveryMethod'; import { IProduct } from '../shared/models/product'; import { BasketRoutingModule } from './basket-routing.module'; @Injectable({ providedIn: 'root' }) export class BasketService { baseUrl=environment.apiUrl; private basketSource = new BehaviorSubject<IBasket>(null); basket$ = this.basketSource.asObservable(); private basketTotalSource = new BehaviorSubject<IBasketTotals>(null); basketTotal$ = this.basketTotalSource.asObservable(); shipping=0; constructor(private http: HttpClient) { } setShippingPrice(deliveryMethod: IDeliveryMethod){ this.shipping=deliveryMethod.price; this.calculateTotals(); } getBasket(id:string){ return this.http.get(this.baseUrl +'basket?id='+id) .pipe( map((basket: IBasket)=> { this.basketSource.next(basket); //console.log(this.getCurrentBasketValue()); this.calculateTotals(); }) ); } setBasket(basket:IBasket){ return this.http.post(this.baseUrl +'basket', basket).subscribe((response: IBasket)=> { this.basketSource.next(response); //console.log(response); this.calculateTotals(); }, error=> { console.log(error); }); } getCurrentBasketValue(){ return this.basketSource.value; } addItemToBasket(item:IProduct, quantity=1){ const itemToAdd: IBasketItem=this.mapProductItemToBasketItem(item, quantity); //need to map between IProduct and IBasketItem bcoz the property is diff const basket = this.getCurrentBasketValue() ?? this.CreateBasket(); basket.items = this.addOrUpdateItem(basket.items, itemToAdd,quantity); this.setBasket(basket); } incrementItemQuantity(item:IBasketItem){ const basket=this.getCurrentBasketValue(); const foundItemIndex=basket.items.findIndex(x=> x.id===item.id); basket.items[foundItemIndex].quantity++; this.setBasket(basket); } decrementItemQuantity(item:IBasketItem){ const basket=this.getCurrentBasketValue(); const foundItemIndex=basket.items.findIndex(x=> x.id===item.id); if(basket.items[foundItemIndex].quantity>1){ basket.items[foundItemIndex].quantity--; this.setBasket(basket); }else { this.removeItemFromBasket(item); } } removeItemFromBasket(item: IBasketItem) { const basket=this.getCurrentBasketValue(); if (basket.items.some(x=>x.id===item.id)){//return bool basket.items=basket.items.filter(i=> i.id!==item.id); //return array if (basket.items.length>0){ this.setBasket(basket); }else{ this.deleteBasket(basket); } } } deleteLocalBasket(id:string) { this.basketSource.next(null); this.basketTotalSource.next(null); localStorage.removeItem('basket_id'); } //delete basket using API deleteBasket(basket: IBasket) { return this.http.delete(this.baseUrl+'basked?id='+ basket.id).subscribe(()=>{ this.basketSource.next(null); this.basketTotalSource.next(null); localStorage.removeItem('basket_id'); },error=>{ console.log(error); }) } private calculateTotals(){ const basket = this.getCurrentBasketValue(); const shipping = this.shipping; const subtotal=basket.items.reduce((a,b)=> (b.price*b.quantity)+a,0); //a = number, b=item, 0 = initial value for 'a', loop for each item in 'b' const total=subtotal+shipping; this.basketTotalSource.next({shipping,total, subtotal}) } private addOrUpdateItem(items: IBasketItem[], itemToAdd: IBasketItem, quantity: number): IBasketItem[] { console.log(items); const index =items.findIndex(i=> i.id===itemToAdd.id); //find the index in the basket, if exist, this is existing item if (index=== -1){ //to add existing item in basket itemToAdd.quantity=quantity; items.push(itemToAdd); }else { items[index].quantity+=quantity; } return items; } private CreateBasket(): IBasket { const basket = new Basket(); //create new basket with new id console.log("baskerId"+ basket.id) localStorage.setItem('basket_id', basket.id); //store basket.id in localstorage. Localstorage specific to the browser. return basket; } private mapProductItemToBasketItem(item: IProduct, quantity: number): IBasketItem { return { id:item.id, productName: item.name, price:item.price, pictureUrl: item.pictureUrl, quantity, brand: item.productBrand, type : item.productType } } }
888c45f9f8816d758855015073529e58eb38df83
TypeScript
greghart/climbing-app
/src/typescript/models/User.ts
2.75
3
import { Column, Entity, PrimaryGeneratedColumn, ManyToOne, OneToMany, } from 'typeorm'; import { cascadeOneToMany } from '../db/cascadeOptions'; import Comment from './Comment'; import Photo from './Photo'; /** * Users * * Users of the system. */ @Entity() export default class User { @PrimaryGeneratedColumn() id: number; @Column() email: string; @Column() name: string; @OneToMany(type => Comment, comment => comment.user, cascadeOneToMany) comments?: Comment[]; @OneToMany(type => Photo, photo => photo.user, cascadeOneToMany) photos?: Photo[]; }
1ec2522b4c75c2a5689de3216aa7288bc23e6d3d
TypeScript
luotaoyeah/learning-nodejs
/projects/12/src/book/learning-node-2e/03/03-01/03-01-01/03-01-01-D/03-01-01-D.ts
2.96875
3
/* * 如果 module identifier 是一个 folder, * 则 node 会寻找该 folder 下面的 package.json 的 main 属性指向的 module; */ console.log("\n-------------------------------------------------- 01"); /* { name: 'foo' } */ console.log(require("./folder-01")); /* * 如果 folder 下面没有 package.json,则寻找 index.js; */ console.log("\n-------------------------------------------------- 02"); /* { name: 'bar' } */ console.log(require("./folder-02")); export {};
17cdde153b9b87a8d305b3a8e2e63c89d4e3a316
TypeScript
cflFullstackDocente/CFL2021
/3.POO/tp-casino/Tragamonedas.ts
2.625
3
import * as rl from "readline-sync"; import GestorArchivos from "./GestorArchivos"; export default class Tragamonedas { protected probabilidad: number; protected gestorArchivos: GestorArchivos; public constructor(txtConfiguracion: string, txtResultados: string) { this.gestorArchivos = new GestorArchivos(txtConfiguracion, txtResultados); let config = this.gestorArchivos.leerTxt(); this.probabilidad = parseInt(config[0]) / 100; } public jugar(): void { this.procesarJugada(); } protected procesarJugada(): void { let apuesta = rl.questionInt("Ingrese el monto a apostar: "); let numerAzar = Math.random(); let resultado = apuesta; if (numerAzar <= this.probabilidad) { resultado = (1 / this.probabilidad) * apuesta; console.log(`Jugador gana: $${resultado}`); this.gestorArchivos.guardarResultado(resultado * -1 + ","); } else { console.log(`La casa gana: $${resultado}`); this.gestorArchivos.guardarResultado(resultado + ","); } } }
01b0e9589d7699de67ff6842ce7f4e9b80e891f4
TypeScript
travelgateX/core-businessrules
/src/test_rules/rule_xgty.ts
3.1875
3
import { Rule } from "../main"; export class TestRuleXgtY implements Rule { public status: boolean; public msg: string; public code: string; private x: Number; private y: Number; constructor(code: string, x: Number, y: Number) { this.code = code; this.x = x; this.y = y; this.status = true; } public process(): boolean { console.log("Processing " + this.code); if (this.x >= this.y) { this.status = true; console.log(this.code + " PASS"); return this.status; } console.log(this.code + " FAILS"); this.msg = "Error, X is less than y (X: " + this.x + ", Y: " + this.y + ")"; return this.status; } }
255441646644fc8a784a017bf079aaa697b4c664
TypeScript
zhifuliu/generator-gulp-ts-requirejs
/src/app/startup-fail-backup.ts
3
3
/// <reference path="../references.d.ts" /> /*var $ = require('jquery');*/ /*import $ = require('jquery');*/ /*import $ = require("jquery"); class App { public clickList = value => { console.log(value); }; private clickNum: number = 0; public clickBtn = () => { $('#msg').val((this.clickNum++).toString()); console.log(this.clickNum++) }; } var app = new App(); export = app; app.clickBtn();*/ /* 上面这种形式,能够运行,也会修改 dom */ /*import $ = require("jquery"); var clickList = value => { console.log(value); }; var clickNum: number = 0; var clickBtn = () => { $('#msg').val((clickNum++).toString()); //console.log(clickNum++) }; //clickBtn();*/ /* 上面这段代码一直运行不了,触发事件的时候,报错: 未定义函数,为什么? 看看 ts 编译后的 js 文件,编译成的时一个模板 define, 看 requirejs 文档,程序入口不是模板,模板是给别的程序代码引用的, 程序入口不应该是一个模板 require 只定义了两个函数: requirejs() 和 define() 一个用来定义模板,一个是真正的程序入口, 可以做一个实验,我不写ts,直接写js 用 requirejs 函数来写事件处理函数,这样index.html 可以绑定到 startup.js 中得事件处理程序上面 */ import $ = require("jquery"); var clickList = value => { console.log(value); }; var clickNum: number = 0; var clickBtn = () => { $('#msg').val((clickNum++).toString()); //console.log(clickNum++) }; //clickBtn();
e6a169f98351a923afb5fecc58138e213115882a
TypeScript
xuandai-py/NG-xdBook-seller
/src/app/services/authentication.service.ts
2.625
3
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { environment } from 'src/environments/environment'; import { User } from '../models/user.models'; import {map} from 'rxjs/operators'; const API_URL = `${environment.BASE_URL}/api/authentication/` @Injectable({ providedIn: 'root' }) export class AuthenticationService { // login > store user credentials > notify > Observers > Observable > RXJS public currentUser: Observable<User>; // get credential // behaviorSubject(host the value to share) > notify > Observers > Subcribe private currentUserSubjet: BehaviorSubject<User>; constructor(private http: HttpClient) { let storageUser; const storageUserAsStr = localStorage.getItem('currentUser'); if (storageUserAsStr) { storageUser = JSON.parse(storageUserAsStr); } this.currentUserSubjet = new BehaviorSubject<User>(storageUser); this.currentUser = this.currentUserSubjet.asObservable(); } public get currentUserValue(): User{ return this.currentUserSubjet.value; } login(user: User): Observable<any>{ return this.http.post<any>(API_URL + 'sign-in', user).pipe( // set current user observable object to intercept map(response => { if(response){ localStorage.setItem('currentUser', JSON.stringify(response)); this.currentUserSubjet.next(response); // next() send manual notification } }) ); } register(user: User): Observable<any>{ return this.http.post(API_URL + 'sign-up', user); } logout(){ localStorage.removeItem('currentUser'); this.currentUserSubjet.next(new User); } }
b3345cc63fb2b1659db32bf92de1afee6564d747
TypeScript
haandol/starhq
/src/decorator.ts
2.625
3
import * as _ from 'lodash'; import { IEvent } from './interface/event'; import { Metadata } from './interface/metadata'; function findEndpoint(endpoints: Array<any>, funcName: string): Metadata.Rest | null { return _.find(endpoints, (endpoint) => endpoint.funcName === funcName); } export namespace Decorator { export namespace Event { export function worker(eventClass: { new(...args): IEvent<any> } | string) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { const endpoints: Metadata.Event[] = Reflect.getOwnMetadata( Metadata.Key.WorkerEvent, target.constructor ) || []; let eventKey: string; if (!_.isString(eventClass)) { const event = new eventClass(); eventKey = event.key; } else { eventKey = eventClass; } const endpoint: Metadata.Event = { key: eventKey, funcName: propertyKey }; endpoints.push(endpoint); Reflect.defineMetadata(Metadata.Key.WorkerEvent, endpoints, target.constructor); } } export function fanout(eventClass: { new(...args): IEvent<any> } | string) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { const endpoints: Metadata.Event[] = Reflect.getOwnMetadata( Metadata.Key.FanoutEvent, target.constructor ) || []; let eventKey: string; if (!_.isString(eventClass)) { const event = new eventClass(); eventKey = event.key; } else { eventKey = eventClass; } const endpoint: Metadata.Event = { key: eventKey, funcName: propertyKey }; endpoints.push(endpoint); Reflect.defineMetadata(Metadata.Key.FanoutEvent, endpoints, target.constructor); } } } export namespace Endpoint { export function rpc(context?: any) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { const endpoints: Metadata.Rpc[] = Reflect.getOwnMetadata( Metadata.Key.Rpc, target.constructor ) || []; const endpoint: Metadata.Rpc = { funcName: propertyKey, context: context || {} }; endpoints.push(endpoint); Reflect.defineMetadata(Metadata.Key.Rpc, endpoints, target.constructor); } } export function graph(context?: any) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { const endpoints: Metadata.Graph[] = Reflect.getOwnMetadata( Metadata.Key.Graph, target.constructor ) || []; const endpoint: Metadata.Graph = { funcName: propertyKey, context: context || {} }; endpoints.push(endpoint); Reflect.defineMetadata(Metadata.Key.Graph, endpoints, target.constructor); } } export function rest(route, context?: any) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { const endpoints: Metadata.Rest[] = Reflect.getOwnMetadata( Metadata.Key.Rest, target.constructor ) || []; const [method, uri] = route.split(' '); const endpoint = findEndpoint(endpoints, propertyKey); if (endpoint) { endpoint.method = method; endpoint.uri = uri; } else { const endpoint: Metadata.Rest = { method: method, uri: uri, funcName: propertyKey, context: context || {} }; endpoints.push(endpoint); } Reflect.defineMetadata(Metadata.Key.Rest, endpoints, target.constructor); } } } export function requireLevel(level: number) { return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) { const endpoints: Metadata.Rest[] = Reflect.getOwnMetadata( Metadata.Key.Rest, target.constructor ) || []; const endpoint = findEndpoint(endpoints, propertyKey); if (endpoint) { const context: any = endpoint.context || {}; context.level = level; endpoint.context = context; } else { const endpoint: Metadata.Rest = { method: '', uri: '', funcName: propertyKey, context: { level } }; endpoints.push(endpoint); } Reflect.defineMetadata(Metadata.Key.Rest, endpoints, target.constructor); }; } }
e634d6769bd9070f0501cbd9ad593c552bd09ee4
TypeScript
tofsjonas/tenancies
/src/lib/firebase/firebase_storage.ts
2.5625
3
import { Tenancy, TenancyMetaData, DB_ID } from 'types/global' import db, { firestore } from 'lib/firebase/firebase.config' import { User } from 'contexts/AuthContext' type updateTenancyInStorageParams = { id: DB_ID data: TenancyMetaData } export const updateTenancyInStorage = async ({ id, data }: updateTenancyInStorageParams) => { const new_obj = { ...data, updated: firestore.FieldValue.serverTimestamp(), } await db.collection('tenancies').doc(id).update(new_obj) return new_obj } export const deleteTenancyFromStorage = async (id: string, user: User) => { console.log(user) await db.collection('tenancies').doc(id).delete() } export const getTenanciesFromStorage = async (user: User) => { const result: Tenancy[] = [] const docRef = db.collection('tenancies').where('owner', '==', user.is_anonymous ? null : user.uid) const data = await docRef.get() data.docs.forEach((item) => { const tenancy = { ...item.data(), db_id: item.id, } as Tenancy result.push(tenancy) }) return result } export const addTenancyToStorage = async (obj: Tenancy, user: User) => { const temp = { ...obj, owner: user.is_anonymous ? null : user.uid, created: firestore.FieldValue.serverTimestamp(), updated: firestore.FieldValue.serverTimestamp(), location: new firestore.GeoPoint(obj.x, obj.y), } const res = await db.collection('tenancies').add(temp) temp.db_id = res.id return temp }
9a8132df96fcada7716365fcbefc12e3f3357ef7
TypeScript
svrucina/frontend
/src/app/pipes/custom-date.pipe.ts
2.625
3
import { Pipe, PipeTransform } from '@angular/core'; import {DatePipe} from '@angular/common'; @Pipe({ name: 'customDate' }) export class CustomDatePipe implements PipeTransform { transform(date: Date | string, format: string = 'dd.MM.yyyy. HH:mm'): string { date = new Date(date); // if original type was a string return new DatePipe('en-US').transform(date, format); } }
c4ef898746f5eafa06e5220c8501fb2273851573
TypeScript
minhtran1995/Pirates-of-the-Caribbean
/Scripts/objects/player.ts
2.53125
3
/* *************************************************************************************** * Source file name : player.ts * * Author's name : Duc Minh Tran (300771859) * * Last Modified by : Duc Minh Tran (300771859) * * Last Modified date : March 27 2016 * * Program description : This is a webgame that use a Side Scroller background * * * * Revision History : 1 - Update Internal Documentation * * * *************************************************************************************** */ module objects { export class Player extends createjs.Bitmap { public width: number; public height: number; private _topBounds: number; private _bottomBounds: number; private _leftBounds: number; private _rightBounds: number; private _deadSoundPlayed: boolean; public hitMoney: boolean; public hitEnemy: boolean; public hitGunTreasure: boolean; public isShooting: boolean; public isDead: boolean; //Static Variables++++++ private static flag: boolean; private static up: boolean; private static down: boolean; private static left: boolean; private static right: boolean; public static counter: number; public static bulletCounter: number; public static moneyCounter: number; public static deadCounter: number; public static delay: number = 1; public static moneyAnimationDelay: number; private static didTheStuff: boolean; constructor() { super(assets.getResult("player")); this.y = 200; this.x = 0; this.width = this.getBounds().width; this.height = this.getBounds().height; this.regX = this.width * 0.5; this.regY = this.height * 0.5; this._topBounds = 350; this._bottomBounds = config.Screen.HEIGHT - this.height * 0.5; this._leftBounds = this.width * 0.5; this._rightBounds = config.Screen.WIDTH - this.width * 0.5; this.x = this.regX; Player.flag = false; Player.up = false; Player.down = false; Player.left = false; Player.right = false; Player.counter = 0; Player.moneyCounter = 2; Player.deadCounter = 19; Player.moneyAnimationDelay = 1; this.hitMoney = false; this.hitEnemy = false; this.hitGunTreasure = false; this.isShooting = false; this.isDead = false; Player.bulletCounter = 8; Player.didTheStuff = false; this._deadSoundPlayed = false; } //check if player is in the allowed range private _checkBounds(): void { if (this.y < this._topBounds) { this.y = this._topBounds; } if (this.y > this._bottomBounds) { this.y = this._bottomBounds; } if (this.x < this._leftBounds) { this.x = this._leftBounds; } if (this.x > this._rightBounds) { this.x = this._rightBounds; } } //update game objects in my scene public update(): void { //control document.onkeyup = function(e) { if (e.which == 87) { Player.up = false; } if (e.which == 83) { Player.down = false; } if (e.which == 65) { Player.left = false; } if (e.which == 68) { Player.right = false; } } document.onkeydown = function(e) { if (e.which == 87) { Player.up = true; } if (e.which == 83) { Player.down = true; } if (e.which == 65) { Player.left = true; } if (e.which == 68) { Player.right = true; } if (e.which == 32) { if (!Player.didTheStuff) { createjs.Sound.play("reloadSound"); Player.didTheStuff = true; } Cannon.isloaded = true; objects.Player.bulletCounter = 8; } else { Player.didTheStuff = false; } } //player can control this only when they are alive if (!this.isDead) { if (Player.up) { this.y -= 1.5; } if (Player.down) { this.y += 1.5; } if (Player.left) { this.x -= 3; } if (Player.right) { this.x += 3; } } //make sure bullet dont appear when player is idle window.onmouseup = function() { Player.flag = false; Player.counter = 0; } if (this.isDead) { this.y = this._bottomBounds - this.height * 0.5; if (Player.delay <= 120) { if (Player.delay % 10 === 0) { this.image = this.shuffleImages("dead"); } Player.delay++; } if (!this._deadSoundPlayed) { createjs.Sound.play("abandon_ship", 0, 0, 0, 2); createjs.Sound.play("sink"); this._deadSoundPlayed = true; }; window.onmousedown = function() { console.log("Mouse disabled"); }; } else { Player.delay = 1; window.onmousedown = function() { if (Cannon.isloaded) { console.log("Shoot"); Player.flag = true; createjs.Sound.play("leftClick"); if (Player.bulletCounter < 2) { Cannon.isloaded = false; } Player.bulletCounter--; } else { createjs.Sound.play("outOfBullets"); console.log("Reload"); } }; if (this.hitEnemy) { this.image = this.shuffleImages("hit"); //I Want to play only 1 animation at a time //reset everything that associate with money animation this.hitMoney = false; Player.moneyCounter = 2; Player.moneyAnimationDelay = 1; managers.Collision._moneyHit = 1; } if (this.hitMoney) { if (Player.moneyAnimationDelay <= 120) { if (Player.moneyAnimationDelay % 10 === 0) { if (Player.moneyAnimationDelay === 120) { this.image = this.shuffleImages("money"); Player.moneyAnimationDelay = 0; Player.moneyCounter = 2; } else { this.image = this.shuffleImages("money"); } } Player.moneyAnimationDelay++; } } //////// DO NOT TOUCH THIS if (Player.flag) { if (Player.counter <= 2) { this.isShooting = true; Cannon.shootCannon = true; } else { this.isShooting = false; } Player.counter++; } else { this.isShooting = false; Cannon.shootCannon = false; } //////////////////////// } this._checkBounds(); } //change player images - Animation public shuffleImages(val: string): Object { var obj = new Array<Object>(); //normal player obj[0] = assets.getResult("player"); //player shoot obj[1] = assets.getResult("cannonShoot"); //money animation obj[2] = assets.getResult("money1"); obj[3] = assets.getResult("money2"); obj[4] = assets.getResult("money3"); obj[5] = assets.getResult("money4"); obj[6] = assets.getResult("money5"); obj[7] = assets.getResult("money6"); obj[8] = assets.getResult("money7"); obj[9] = assets.getResult("money8"); obj[10] = assets.getResult("money9"); obj[11] = assets.getResult("money10"); obj[12] = assets.getResult("money11"); obj[13] = assets.getResult("money12"); //hitEnemy animation obj[14] = assets.getResult("hitEnemy"); obj[15] = assets.getResult("hitEnemy1"); obj[16] = assets.getResult("hitEnemy2"); obj[17] = assets.getResult("hitEnemy3"); obj[18] = assets.getResult("hitEnemy4"); //die obj[19] = assets.getResult("sinking"); obj[20] = assets.getResult("sinking1"); obj[21] = assets.getResult("sinking2"); obj[22] = assets.getResult("sinking3"); obj[23] = assets.getResult("sinking4"); obj[24] = assets.getResult("sinking5"); obj[25] = assets.getResult("sinking6"); obj[26] = assets.getResult("sinking7"); obj[27] = assets.getResult("sinking8"); obj[28] = assets.getResult("sinking9"); obj[29] = assets.getResult("sinking10"); obj[30] = assets.getResult("sinking11"); obj[31] = assets.getResult("sinking12"); var number; if (val === "") { number = 0; return obj[number]; } else if (val === "shoot") { return obj[1]; } else if (val === "money") { if (Player.moneyCounter > 13) { Player.moneyCounter = 2; } else { Player.moneyCounter++; } return obj[Player.moneyCounter]; } else if (val === "hit") { number = Math.round(Math.random() * 4) + 14; return obj[number]; } else if (val === "dead") { if (Player.deadCounter > 31) { Player.deadCounter = 19; } else { Player.deadCounter++; } return obj[Player.deadCounter]; } } } }
ec31e350ee03803c71f80a0ebc3eeebdf080448f
TypeScript
buildmotion/better-business-logic-with-typescript
/DesignPatterns/composite/src/app/modules/pattern/rule-component.ts
2.84375
3
import {IRuleComponent} from './../rule/rule-component.interface'; import {RuleResult} from './../rule/rule-result'; import {RenderType} from './../../rules/render-type.enum'; import {Severity} from './../../rules/severity.enum'; /** * This is the base class for all rules. All rules will extend from this class. New rules * should extend [RuleLeaf] or [CompositeRule] - these rule abstractions extend [RulePolicy]. */ export class RuleComponent { isValid: boolean = true; message: string; name: string; priority: number; result: RuleResult; isDisplayable: boolean; renderType: RenderType = RenderType.EvaluateAllRules; severity: Severity = Severity.Exception; source: string; constructor(name: string, message: string, isDisplayable: boolean); constructor(name: string, message: string, isDisplayable: boolean = false, severity: Severity = Severity.Exception, priority: number = 0) { this.name = name; this.message = message; this.isDisplayable = isDisplayable; this.priority = priority; this.severity = severity; } execute(): RuleResult { console.log('Begin execution of RulePolicy: ' + this.name); return this.render(); } /** * Each rule must implement this function and return a valid [RuleResult]. */ render(): RuleResult { throw new Error('Each concrete rule must implement this function and return a valid Result.'); } }
e73506755f2a456e35bf3a7afbb2c0a8621f1479
TypeScript
joetinoco/superslotmachine
/Scripts/scenes/menu.ts
2.5625
3
// MENU SCENE module scenes { export class Menu extends objects.Scene { // MENU SCENE ++++++++++++++++++++++++++++ // // Initial game screen with a "play" button // //PRIVATE INSTANCE VARIABLES ++++++++++++ private _playButton: objects.Button; private _titleScreen: createjs.Bitmap; private _startupSound: objects.Sound; // CONSTRUCTOR ++++++++++++++++++++++ constructor() { super(); } // PUBLIC METHODS +++++++++++++++++++++ // Start Method public start(): void { // add the title screen this._titleScreen = new createjs.Bitmap(assets.getResult('TitleScreen')); this.addChild(this._titleScreen); // add the PLAY button to the MENU scene this._playButton = new objects.Button( "PlayButton", config.Screen.CENTER_X, config.Screen.CENTER_Y + 20, true); this.addChild(this._playButton); // PLAY Button event listener this._playButton.on("click", this._startButtonClick, this); // add this scene to the global stage container stage.addChild(this); // Play the startup sound this._startupSound = new objects.Sound('StartSound'); this._startupSound.play(); } // INTRO Scene updates here public update(event: createjs.Event): void { } //EVENT HANDLERS ++++++++++++++++++++ // PLAY Button click event handler private _startButtonClick(event: createjs.MouseEvent) { // Switch to the game scene scene = config.Scene.SLOT_MACHINE; changeScene(); } } }
2ca2f5980a48d4b435e7e6768799f9476912333e
TypeScript
svenny96/webtech2
/example08-presentation/src/main/angular/src/app/angular/create-news/create-news.component.ts
2.625
3
import { Component, EventEmitter, Output } from '@angular/core'; import { NewsService } from '../news.service'; @Component({ selector: 'create-news', templateUrl: './create-news.component.html', styleUrls: ['./create-news.component.sass'] }) export class CreateNewsComponent { @Output() public created = new EventEmitter(); public headline: string = ""; public content: string = ""; public errorMessage: string; constructor(private newsService: NewsService) { } public createNews(e: Event): void { e.preventDefault(); this.errorMessage = null; if (this.headline.trim() != null && this.content.trim() != null) { this.newsService.create(this.headline, this.content).subscribe( () => { this.created.emit(); this.headline = ""; this.content = ""; }, () => this.errorMessage = 'Could not create news' ); } } getCharsLeft(): number { return 255 - this.content.length; } }
e99e102ab67ed3665650df4e62adfef6597221c1
TypeScript
j10wy/sandbox
/src/app/enum-select/enum-select.component.ts
2.609375
3
import { Component, OnInit } from '@angular/core'; type API = 'TEST' | 'ANOTHER_TEST'; type MODE = { [key in API]: string; }; @Component({ selector: 'app-enum-select', templateUrl: './enum-select.component.html', styleUrls: ['./enum-select.component.scss'], }) export class EnumSelectComponent implements OnInit { obj: MODE = { TEST: 'test', ANOTHER_TEST: 'test 2', }; constructor() { console.log(this.obj); } ngOnInit() {} }
8a290277d1a62ada7e20eec905c162fabe2bba2c
TypeScript
anthrio/shared
/src/middleware/current-user.ts
2.5625
3
import { Context, Next } from "koa"; import jwt from "jsonwebtoken"; interface UserPayload { id: string; email: string; } export const currentUser = (ctx: Context, next: Next) => { if (!ctx.session?.jwt) { return next(); } try { const payload = jwt.verify( ctx.session.jwt, process.env.JWT_KEY! ) as UserPayload; ctx.currentUser = payload; } catch (err) {} next(); };
0e30432644d4dfa2745b67c3806775a132742cbe
TypeScript
OfficeDev/Office-Addin-Scripts
/packages/eslint-plugin-office-addins/src/rules/call-sync-before-read.ts
2.546875
3
import { TSESTree } from "@typescript-eslint/utils"; import { Variable } from "@typescript-eslint/utils/dist/ts-eslint-scope"; import { findTopMemberExpression } from "../utils/utils"; import { findOfficeApiReferences, OfficeApiReference } from "../utils/utils"; export = { name: "call-sync-before-read", meta: { type: <"problem" | "suggestion" | "layout">"problem", messages: { callSync: "Call context.sync() before trying to read '{{name}}'.", }, docs: { description: "Always call load on the object's properties followed by a context.sync() before reading them.", category: < "Best Practices" | "Stylistic Issues" | "Variables" | "Possible Errors" >"Possible Errors", recommended: <false | "error" | "warn">false, url: "https://docs.microsoft.com/office/dev/add-ins/develop/application-specific-api-model#sync", }, schema: [], }, create: function (context: any) { let apiReferences: OfficeApiReference[] = []; function checkPropertyIsRead(node: TSESTree.MemberExpression): boolean { const topExpression: TSESTree.MemberExpression = findTopMemberExpression(node); switch (topExpression.parent?.type) { case TSESTree.AST_NODE_TYPES.AssignmentExpression: return topExpression.parent.right === topExpression; default: return true; } } function findReadBeforeSync(): void { const needSync: Set<Variable> = new Set<Variable>(); apiReferences.forEach((apiReference) => { const operation = apiReference.operation; const reference = apiReference.reference; const variable = reference.resolved; if (operation === "Get" && variable) { needSync.add(variable); } if (operation === "Sync") { needSync.clear(); } if (operation === "Read" && variable && needSync.has(variable)) { const node: TSESTree.Node = reference.identifier; if ( node.parent?.type === TSESTree.AST_NODE_TYPES.MemberExpression && checkPropertyIsRead(node.parent) ) { context.report({ node: node, messageId: "callSync", data: { name: node.name }, }); } } }); } return { Program() { apiReferences = findOfficeApiReferences(context.getScope()); apiReferences.sort((left, right) => { return ( left.reference.identifier.range[1] - right.reference.identifier.range[1] ); }); findReadBeforeSync(); }, }; }, };
9735f8ab6ef96706efd49409d70fdc475066220a
TypeScript
bgoonz/UsefulResourceRepo2.0
/GIT-USERS/lydia/DefinitelyTyped/types/feedparser/feedparser-tests.ts
2.640625
3
import request = require('request'); import * as FeedParser from "feedparser"; const req = request('https://news.google.com/news?cf=all&hl=en&pz=1&ned=us&output=rss'); const feedparser = new FeedParser({}); req.on("error", error => { // handle any request errors }); req.on("response", res => { if (res.statusCode !== 200) { req.emit('error', new Error('Bad status code')); } else { req.pipe(feedparser); } }); feedparser.on('error', (error: Error) => { // always handle errors }); feedparser.on('readable', () => { // This is where the action is! const stream = feedparser; const meta = feedparser.meta; // **NOTE** the "meta" is always available in the context of the feedparser instance let item: FeedParser.Item; while (item = stream.read()) { console.log(item); } });
8174c4f4eaa2dbc2deda848547965b8b4bc5d63e
TypeScript
h3poteto/megalodon
/megalodon/src/misskey/web_socket.ts
2.5625
3
import WS from 'ws' import dayjs, { Dayjs } from 'dayjs' import { v4 as uuid } from 'uuid' import { EventEmitter } from 'events' import { WebSocketInterface } from '../megalodon' import proxyAgent, { ProxyConfig } from '../proxy_config' import MisskeyAPI from './api_client' import { UnknownNotificationTypeError } from '../notification' /** * WebSocket * Misskey is not support http streaming. It supports websocket instead of streaming. * So this class connect to Misskey server with WebSocket. */ export default class WebSocket extends EventEmitter implements WebSocketInterface { public url: string public channel: 'user' | 'localTimeline' | 'hybridTimeline' | 'globalTimeline' | 'conversation' | 'list' public parser: Parser public headers: { [key: string]: string } public proxyConfig: ProxyConfig | false = false public listId: string | null = null private _accessToken: string private _reconnectInterval: number private _reconnectMaxAttempts: number private _reconnectCurrentAttempts: number private _connectionClosed: boolean private _client: WS | null = null private _channelID: string private _pongReceivedTimestamp: Dayjs private _heartbeatInterval: number = 60000 private _pongWaiting: boolean = false /** * @param url Full url of websocket: e.g. wss://misskey.io/streaming * @param channel Channel name is user, localTimeline, hybridTimeline, globalTimeline, conversation or list. * @param accessToken The access token. * @param listId This parameter is required when you specify list as channel. */ constructor( url: string, channel: 'user' | 'localTimeline' | 'hybridTimeline' | 'globalTimeline' | 'conversation' | 'list', accessToken: string, listId: string | undefined, userAgent: string, proxyConfig: ProxyConfig | false = false ) { super() this.url = url this.parser = new Parser() this.channel = channel this.headers = { 'User-Agent': userAgent } if (listId === undefined) { this.listId = null } else { this.listId = listId } this.proxyConfig = proxyConfig this._accessToken = accessToken this._reconnectInterval = 10000 this._reconnectMaxAttempts = Infinity this._reconnectCurrentAttempts = 0 this._connectionClosed = false this._channelID = uuid() this._pongReceivedTimestamp = dayjs() } /** * Start websocket connection. */ public start() { this._connectionClosed = false this._resetRetryParams() this._startWebSocketConnection() } /** * Reset connection and start new websocket connection. */ private _startWebSocketConnection() { this._resetConnection() this._setupParser() this._client = this._connect() this._bindSocket(this._client) } /** * Stop current connection. */ public stop() { this._connectionClosed = true this._resetConnection() this._resetRetryParams() } /** * Clean up current connection, and listeners. */ private _resetConnection() { if (this._client) { this._client.close(1000) this._client.removeAllListeners() this._client = null } if (this.parser) { this.parser.removeAllListeners() } } /** * Resets the parameters used in reconnect. */ private _resetRetryParams() { this._reconnectCurrentAttempts = 0 } /** * Connect to the endpoint. */ private _connect(): WS { let options: WS.ClientOptions = { headers: this.headers } if (this.proxyConfig) { options = Object.assign(options, { agent: proxyAgent(this.proxyConfig) }) } const cli: WS = new WS(`${this.url}?i=${this._accessToken}`, options) return cli } /** * Connect specified channels in websocket. */ private _channel() { if (!this._client) { return } switch (this.channel) { case 'conversation': this._client.send( JSON.stringify({ type: 'connect', body: { channel: 'main', id: this._channelID } }) ) break case 'user': this._client.send( JSON.stringify({ type: 'connect', body: { channel: 'main', id: this._channelID } }) ) this._client.send( JSON.stringify({ type: 'connect', body: { channel: 'homeTimeline', id: this._channelID } }) ) break case 'list': this._client.send( JSON.stringify({ type: 'connect', body: { channel: 'userList', id: this._channelID, params: { listId: this.listId } } }) ) break default: this._client.send( JSON.stringify({ type: 'connect', body: { channel: this.channel, id: this._channelID } }) ) break } } /** * Reconnects to the same endpoint. */ private _reconnect() { setTimeout(() => { // Skip reconnect when client is connecting. // https://github.com/websockets/ws/blob/7.2.1/lib/websocket.js#L365 if (this._client && this._client.readyState === WS.CONNECTING) { return } if (this._reconnectCurrentAttempts < this._reconnectMaxAttempts) { this._reconnectCurrentAttempts++ this._clearBinding() if (this._client) { // In reconnect, we want to close the connection immediately, // because recoonect is necessary when some problems occur. this._client.terminate() } // Call connect methods console.log('Reconnecting') this._client = this._connect() this._bindSocket(this._client) } }, this._reconnectInterval) } /** * Clear binding event for websocket client. */ private _clearBinding() { if (this._client) { this._client.removeAllListeners('close') this._client.removeAllListeners('pong') this._client.removeAllListeners('open') this._client.removeAllListeners('message') this._client.removeAllListeners('error') } } /** * Bind event for web socket client. * @param client A WebSocket instance. */ private _bindSocket(client: WS) { client.on('close', (code: number, _reason: Buffer) => { if (code === 1000) { this.emit('close', {}) } else { console.log(`Closed connection with ${code}`) if (!this._connectionClosed) { this._reconnect() } } }) client.on('pong', () => { this._pongWaiting = false this.emit('pong', {}) this._pongReceivedTimestamp = dayjs() // It is required to anonymous function since get this scope in checkAlive. setTimeout(() => this._checkAlive(this._pongReceivedTimestamp), this._heartbeatInterval) }) client.on('open', () => { this.emit('connect', {}) this._channel() // Call first ping event. setTimeout(() => { client.ping('') }, 10000) }) client.on('message', (data: WS.Data, isBinary: boolean) => { this.parser.parse(data, isBinary, this._channelID) }) client.on('error', (err: Error) => { this.emit('error', err) }) } /** * Set up parser when receive message. */ private _setupParser() { this.parser.on('update', (note: MisskeyAPI.Entity.Note) => { this.emit('update', MisskeyAPI.Converter.note(note)) }) this.parser.on('notification', (notification: MisskeyAPI.Entity.Notification) => { const n = MisskeyAPI.Converter.notification(notification) if (n instanceof UnknownNotificationTypeError) { console.warn(`Unknown notification event has received: ${notification}`) } else { this.emit('notification', n) } }) this.parser.on('conversation', (note: MisskeyAPI.Entity.Note) => { this.emit('conversation', MisskeyAPI.Converter.noteToConversation(note)) }) this.parser.on('error', (err: Error) => { this.emit('parser-error', err) }) } /** * Call ping and wait to pong. */ private _checkAlive(timestamp: Dayjs) { const now: Dayjs = dayjs() // Block multiple calling, if multiple pong event occur. // It the duration is less than interval, through ping. if (now.diff(timestamp) > this._heartbeatInterval - 1000 && !this._connectionClosed) { // Skip ping when client is connecting. // https://github.com/websockets/ws/blob/7.2.1/lib/websocket.js#L289 if (this._client && this._client.readyState !== WS.CONNECTING) { this._pongWaiting = true this._client.ping('') setTimeout(() => { if (this._pongWaiting) { this._pongWaiting = false this._reconnect() } }, 10000) } } } } /** * Parser * This class provides parser for websocket message. */ export class Parser extends EventEmitter { /** * @param message Message body of websocket. * @param channelID Parse only messages which has same channelID. */ public parse(data: WS.Data, isBinary: boolean, channelID: string) { const message = isBinary ? data : data.toString() if (typeof message !== 'string') { this.emit('heartbeat', {}) return } if (message === '') { this.emit('heartbeat', {}) return } let obj: { type: string body: { id: string type: string body: any } } let body: { id: string type: string body: any } try { obj = JSON.parse(message) if (obj.type !== 'channel') { return } if (!obj.body) { return } body = obj.body if (body.id !== channelID) { return } } catch (err) { this.emit('error', new Error(`Error parsing websocket reply: ${message}, error message: ${err}`)) return } switch (body.type) { case 'note': this.emit('update', body.body as MisskeyAPI.Entity.Note) break case 'notification': this.emit('notification', body.body as MisskeyAPI.Entity.Notification) break case 'mention': { const note = body.body as MisskeyAPI.Entity.Note if (note.visibility === 'specified') { this.emit('conversation', note) } break } // When renote and followed event, the same notification will be received. case 'renote': case 'followed': case 'follow': case 'unfollow': case 'receiveFollowRequest': case 'meUpdated': case 'readAllNotifications': case 'readAllUnreadSpecifiedNotes': case 'readAllAntennas': case 'readAllUnreadMentions': case 'unreadNotification': // Ignore these events break default: this.emit('error', new Error(`Unknown event has received: ${JSON.stringify(body)}`)) break } } }
de193691bac0ed6c58586be7e8496b4baaa0fbe7
TypeScript
JamesDunne/webmixer
/webmixer/src/compressor.ts
2.578125
3
import { dB_to_gain, gain_to_dB } from './util'; import { Parameter } from './parameter'; export class Compressor { opts: any; _threshold: Parameter; _ratio: Parameter; _knee: Parameter; _attack: Parameter; _release: Parameter; _makeupGain: Parameter; private compNode: DynamicsCompressorNode; private makeupGainNode: GainNode; constructor(opts) { this.opts = opts; this._threshold = new Parameter( opts.threshold || 0, (value) => { if (!this.compNode) return; this.compNode.threshold.value = value; } ); this._ratio = new Parameter( opts.ratio || 0, (value) => { if (!this.compNode) return; this.compNode.ratio.value = value; } ); this._knee = new Parameter( opts.knee || 0, (value) => { if (!this.compNode) return; this.compNode.knee.value = value; } ); this._attack = new Parameter( opts.attack || 0, (value) => { if (!this.compNode) return; this.compNode.attack.value = value; } ); this._release = new Parameter( opts.release || 0, (value) => { if (!this.compNode) return; this.compNode.release.value = value; } ); this._makeupGain = new Parameter( opts.makeupGain || 0, (value) => { if (!this.makeupGainNode) return; this.makeupGainNode.gain.value = dB_to_gain(value); } ); } applyOpts(opts) { this.opts = Object.assign(this.opts, opts); this.threshold.value = opts.threshold || this.threshold.value; this.ratio.value = opts.ratio || this.ratio.value; this.knee.value = opts.knee || this.knee.value; this.attack.value = opts.attack || this.attack.value; this.release.value = opts.release || this.release.value; this.makeupGain.value = opts.makeupGain || this.makeupGain.value; } createNodes(ac) { this.compNode = ac.createDynamicsCompressor(); this.makeupGainNode = ac.createGain(); this.compNode.connect(this.makeupGainNode); this.threshold.applyValue(); this.ratio.applyValue(); this.knee.applyValue(); this.attack.applyValue(); this.release.applyValue(); this.makeupGain.applyValue(); } get inputNode() { return this.compNode; } get outputNode() { return this.makeupGainNode; } get threshold() { return this._threshold; } get ratio() { return this._ratio; } get knee() { return this._knee; } get attack() { return this._attack; } get release() { return this._release; } get makeupGain() { return this._makeupGain; } get gainReduction() { if (!this.compNode) return 0; return this.compNode.reduction; } }
6d6a6f356a1e026255b5760f8f0c9915f03048f5
TypeScript
anyone-oslo/pages
/app/javascript/controllers/LoginController.ts
2.625
3
import { Controller } from "@hotwired/stimulus"; export default class LoginController extends Controller { declare readonly tabTargets: HTMLDivElement[]; static get targets() { return ["tab"]; } connect() { if (this.tabTargets.length > 0) { this.showTab(this.tabTargets[0].dataset.tab); } } changeTab(evt: Event) { evt.preventDefault(); if ("dataset" in evt.target && "tab" in evt.target.dataset) { this.showTab(evt.target.dataset.tab); } } showTab(tab: string) { this.tabTargets.forEach((t) => { if (t.dataset.tab == tab) { t.classList.remove("hidden"); } else { t.classList.add("hidden"); } }); } }
866b84edaef61a55cc9f3ed5417e7391272f6a71
TypeScript
pconeglian/b2b-cnae
/node/utils/companyInformation.ts
2.6875
3
import {CnaeOutput} from './cnae' export function FormatInformation(response:any) { var mainCnae: CnaeOutput = {code: response.cnae_principal.codigo, description: response.cnae_principal.descricao} var legalNature: LegalNature = {code: response.natureza_juridica.codigo, description: response.natureza_juridica.descricao} var address: Address = { street: response.endereco.logradouro, number: response.endereco.numero, complement: response.endereco.complemento, cep: response.endereco.cep, district: response.endereco.bairro, city: response.endereco.municipio, state: response.endereco.uf } var cadastralSituation: CadastralSituation = { code: response.situacao_cadastral.codigo, date: response.situacao_cadastral.data, motive: response.situacao_cadastral.motivo } var phoneNumbers: PhoneNumber[] = [{ddd: response.telefones[0].ddd, number: response.telefones[0].numero}] var secondarieCnaes: CnaeOutput[] = [] response.cnae_secundarias.forEach((secondarieCnae:any) => { let currentCnae: CnaeOutput = {code: secondarieCnae.codigo, description: secondarieCnae.descricao} secondarieCnaes.push(currentCnae) }); var information: CompanyInformation = { ni: response.ni, oppeningDate: response.data_abertura, companyName: response.nome_empresarial, tradeName: response.nome_fantasia, mainCnae, legalNature, address, specialSituation: response.situacao_especial, cadastralSituation, agency: response.orgao, establishmentType: response.tipo_estabelecimento, email: response.correio_eletronico, socialCapital: response.capital_social, size: response.porte, phoneNumbers, agencyName: response.nome_orgao, federativeEntity: response.ente_federativo, secondarieCnaes } return information } export interface CompanyInformation{ ni: string oppeningDate: string companyName: string tradeName: string mainCnae: CnaeOutput legalNature: LegalNature address: Address specialSituation: string cadastralSituation: CadastralSituation agency: string establishmentType: string email: string socialCapital: string size: string phoneNumbers: PhoneNumber[] secondarieCnaes: CnaeOutput[] agencyName: String federativeEntity: String } interface LegalNature { code: string, description: string } interface Address{ street: string number: string complement: string cep: string district: string city: string state: string } interface CadastralSituation { code: string date: string motive: string } interface PhoneNumber { ddd: string number: string }
517940d1d6c7ab0c5ca5e22bc8c11874ce13e0f3
TypeScript
a-bachelet/SeriousBambouApi
/src/fixtures/quizz-fixture.ts
2.578125
3
/** * Models Imports */ import { Quizz, QuizzModel } from '../models/quizz'; /** * Abstract Classes Imports */ import { AbstractFixture } from '../abstract/abstract-fixture'; /** * Fixtures Imports */ import { ThemeFixture } from './theme-fixture'; /** * QuizzFixture Class Definition */ export class QuizzFixture extends AbstractFixture { public dependencies: string[] = [ ThemeFixture.name ]; /** * Creates quizzs in the database * Sets their documents as global fixture references */ public execute(): Promise<null> { return new Promise<null>(async (resolve: any) => { const quizzArtFirst: QuizzModel = await Quizz.create({ label: 'Quizz Art First', theme: this.getReference('theme-art') }); const quizzArtSecond: QuizzModel = await Quizz.create({ label: 'Quizz Art Second', theme: this.getReference('theme-art') }); this.setReference('quizz-art-first', quizzArtFirst); this.setReference('quizz-art-second', quizzArtSecond); resolve(null); }); } }
2e0071f2292206af5e2089d84de6f9f16287afb1
TypeScript
nannany/shooting-game
/src/controller/MyAircraftView.ts
2.859375
3
import { MyAircraft } from "../domain/aircraft/MyAircraft"; export class MyAircraftView { myAircraft: MyAircraft =MyAircraft.getInstance() ; sprite: PIXI.Sprite; // 弾の発射間隔 launchInterval: number; // フレーム数がインクリメントされていく counter: number=0; // 移動速度 speed: number; constructor( sprite: PIXI.Sprite, launchInterval: number, speed: number) { this.sprite = sprite; this.launchInterval = launchInterval; this.speed = speed; } // todo ビルダー作る。このコンストラクタだけだとどの属性が何番目の引数に当たるか迷う。 moveLeft(): void { this.myAircraft.$vx = -1 * this.speed; } stopLeft(): void { this.myAircraft.$vx = 0; } moveUp(): void { this.myAircraft.$vy = -1 * this.speed; } stopUp(): void { this.myAircraft.$vy = 0; } moveRight(): void { this.myAircraft.$vx = this.speed; } stopRight(): void { this.myAircraft.$vx = 0; } moveDown(): void { this.myAircraft.$vy = this.speed; } stopDown(): void { this.myAircraft.$vy = 0; } play(): void { this.myAircraft.adjustPosition(); this.sprite.x = this.myAircraft.$x; this.sprite.y = this.myAircraft.$y; this.counter++; } }
3aca3d175f671dab87e6fb9230d71071858b0bdf
TypeScript
Amourspirit/node-string-breaker
/src/index.ts
3.75
4
import { codePointFullWidth } from 'utf16-char-codes'; // #region enums /** * Split string kind */ export enum splitByOpt { /** Split by Width */ width, /** * Split by word * Defult */ word, /** Split by line */ line } /** * Line ending options */ export enum lnEndOpt { /** Take no action */ none, /** * Remove Line Break * Default * */ noLnBr, /** Encode line breaks as \\n */ encode } /** * Flags for Width output options * @example ```typescript let wFlags = widthFlags.fullwidth | widthFlags.surrogatePair; ``` * @see {@link IStringBreakOpt} */ export enum widthFlags { /** * No options will be applied */ none = 0, /** * Fullwidth chars will count for two positions * @see {@link https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms} */ fullwidth = 1 << 0, /** * Surrogae Pairs will count for two positions * @see {@link https://en.wikipedia.org/wiki/UTF-16} */ surrogatePair = 1 << 1, /** * When split using [width]{@link IStringBreakOpt.width} and this flag is set then the elements in the array * will split where there is a whitespace and not before. If the whitespace is * a printing char as in the case of \u1680 then it will be include at the end of the element: * Otherwise the whitespace is removed from the end of the element; * <div>&nbsp;</div> * Elemnets will not start with a whitespace unless that whitespace happens to be a printalbe whitespace * such as \u1680. For practical purposes all lines will not start with a whitespace. * @example ```typescript var str = 'On this\u1680day.\u1680For this morning, when Gregor\u3000Samsa woke from troubled dreams; he found himself transformed.'; const result: string[] = stringBreaker(str, { width: 10, lenOpt: widthFlags.nearestWord }); const strResult = result.join('\n'); console.log(strResult); ``` * <div>On this day.&#5760;</div> * <div>For this morning,</div> * <div>when Gregor</div> * <div>Samsa woke</div> * <div>from troubled</div> * <div>dreams; he</div> * <div>found himself</div> * <div>transformed.</div> */ nearestWord = 1 << 2 } // #endregion // #region interfaces /** * Options for {@link stringBreaker} * * Example to split string contains elemets of 10 ```typescript const opt: IStringBreakOpt = { width: 10 } ``` * * Example to split string contains elemets of 40 * and encode line endings into \n ```typescript * const opt: IStringBreakOpt = { * width: 40, * lnEnd: lnEndOpt.encode * } ``` * * Example to split string contains elemets of 40 * and keep Byte order mark if it exist ```typescript * const opt: IStringBreakOpt = { * width: 40, * noBOM: false * } ``` * * Example to split string contains one element per line ```typescript const opt: IStringBreakOpt = { splitOpt: splitByOpt.line } ``` * * Example to split string contains one element per word ```typescript const opt: IStringBreakOpt = { splitOpt: splitByOpt.word } ``` * * Example to split string contains elemets base up if the * character is fullwidth or halfwidth. * * Fullwidth chars would take up two positions in the element. * * Halfwidth chars would take up one postion in the element. ```typescript * const opt: IStringBreakOpt = { * width: 40, * lenOpt: widthFlags.fullwidth * } ``` * * Example to split string contains elemets base up if the * character is a surrogate pair. * * Surrogate pair chars would take up two positions in the element. ```typescript * const opt: IStringBreakOpt = { * width: 40, * lenOpt: widthFlags.surrogatePair * } ``` * * Example to split string contains elemets base up if the * character is fullwidth, halfwidth or surrogate pair. * * Fullwidth chars would take up two positions in the element. * * Halfwidth chars would take up one postion in the element. * * Surrogate pair chars would take up two positions in the element. ```typescript * const opt: IStringBreakOpt = { * width: 100, * lenOpt: widthFlags.fullwidth | widthFlags.surrogatePair * } ``` */ export interface IStringBreakOpt { /** * Width to break string at. * Default 80 */ width?: number; /** * Options for line endings */ lnEnd?: lnEndOpt; /** * If true extra spaces will be removed from the output. * Default false */ noExSp?: boolean; /** * If false and input string has BOM then the BOM will be added as the first byte of output. * BOM will not be counted in the width of the first line. * If false the return value will not have BOM included. * Default true */ noBOM?: boolean; /** * Flags for Width output options */ lenOpt?: widthFlags; /** * Option to break string. * Width, word, eol */ splitOpt?: splitByOpt; } // #endregion // #region export methods /** * Breaks a string into a string array * @param str The string to break into string array * @param opt parameters to affect the output. * Can be number or {@link IStringBreakOpt} * If a number is passed in it becomes the width for the output. * If no parameter is passed then output will be broken into string array * with 80 characters per element. * ```typescript let x: string[]; x = stringBreaker('some long text'); // is the same as x = stringBreaker('some long text', 80), // is the same as x = stringBreaker('some long text' {width: 80}); ``` * * Example: ```typescript * * import { stringBreaker } from 'string-breaker'; * * let x = stringBreaker('The quick brown fox jumped over the lazy dog', 5); * // x => ['The q','uick ','brown',' fox ','jumpe','d ove','r the',' lazy',' dog'] * * x = stringBreaker('Hello World\nNice 😇\nhmm... ', 5); * // x => ['Hello', ' Worl', 'dNice', ' 😇hmm', '... '] * * x = stringBreaker('\uD83D\uDE07Hello World\nNice 😇\nhmm...', 6); * // x => ['😇Hello', ' World', 'Nice 😇', 'hmm...'] * * x = stringBreaker('\uD83D\uDE07Hello World\nNice 😇\r\nhmm...', { * width: 6, * lnEnd: lnEndOpt.encode * }); * // x => ['😇Hello', ' World', '\\nNice', ' 😇\\nhm', 'm...'] ``` * * Split by End of Line * stringBreaker can split by eol by setting option lnEnd: lnEndOpt.splitByEol * * Example Splitting by End of Line: ```typescript import { stringBreaker } from 'string-breaker'; // mixing \n and \r will result in the same output let strSrc = 'Happy cat.'; strSrc += '\nThe quick brown fox jumped over the lazy dog.'; strSrc += '\r\nThe moon is full tonight.\rI like full moons!'; const x = stringBreaker(strSrc, { splitOpt: splitByOpt.line }); // x => [ // 'Happy cat.', // 'The quick brown fox jumped over the lazy dog.', // 'The moon is full tonight.', // 'I like full moons!' ] ``` * * Example splitting by Word: ```typescript import { stringBreaker } from 'string-breaker'; // mixing \n and \r will result in the same output let strSrc = 'Happy cat.'; strSrc += '\nThe quick brown\t\t fox jumped over the lazy dog.'; strSrc += '\r\nThe moon is full tonight.\rI like full moons!'; const x = stringBreaker(strSrc, { splitOpt: splitByOpt.word }); // x => [ 'Happy','cat.','The','quick','brown','fox','jumped', // 'over','the','lazy','dog.','The','moon','is','full', // 'tonight.','I','like','full','moons!' ] ``` * * Example split by width and preserve words * <div>&nbsp;</div> * When split using [width]{@link IStringBreakOpt.width} and flag {@link widthFlags.nearestWord} the elements in the array * will split where there is a whitespace and not before. If the whitespace is * a printing char as in the case of \u1680 then it will be include at the end of the element: * Otherwise the whitespace is removed from the end of the element; * <div>&nbsp;</div> * Elemnets will not start with a whitespace unless that whitespace happens to be a printalbe whitespace * such as \u1680. For practical purposes all lines will not start with a whitespace. * ```typescript import { stringBreaker } from 'string-breaker'; var str = 'On this\u1680day.\u1680For this morning, when Gregor\u3000Samsa woke from troubled dreams; he found himself transformed.'; const result: string[] = stringBreaker(str, { width: 10, lenOpt: widthFlags.nearestWord }); const strResult = result.join('\n'); console.log(strResult); ``` * <div>On this day.&#5760;</div> * <div>For this morning,</div> * <div>when Gregor</div> * <div>Samsa woke</div> * <div>from troubled</div> * <div>dreams; he</div> * <div>found himself</div> * <div>transformed.</div> */ export const stringBreaker = (str: string, opt?: IStringBreakOpt | number): string[] => { if (typeof str !== 'string') { throw new TypeError('stringBreaker: str parmeter must be of type string'); } const options: IStringBreakOpt = getOptions({ width: 80, lnEnd: lnEndOpt.noLnBr, noExSp: false, noBOM: true, lenOpt: widthFlags.none, splitOpt: splitByOpt.width }, opt); // only remove or encode line beaks when splitting by width if (options.splitOpt === splitByOpt.width) { switch (options.lnEnd) { case lnEndOpt.encode: str = encodeLnBr(str); break; case lnEndOpt.noLnBr: str = removeLnBr(str); break default: break; } } let result: string[]; if (options.noExSp === true) { str = removeExSp(str); } switch (options.splitOpt) { case splitByOpt.word: result = breakStrByEolWord(str, options); break; case splitByOpt.line: result = breakStrByEolWord(str, options); break; default: result = breakStrByCodePoint(str, options); break; } return result; } // #endregion // #region internal methods /** * @hidden * Gets the options for the string break * @param defaultOptions options to return if options is undefined * @param options options to apply */ const getOptions = (defaultOptions: IStringBreakOpt, options?: IStringBreakOpt | number): IStringBreakOpt => { if (options === null || options === undefined || typeof options === 'function') { return defaultOptions; } if (typeof options === 'number') { defaultOptions = { ...defaultOptions }; defaultOptions.width = options; options = defaultOptions; } if (options.width === undefined) { options.width = 80; } if (options.lnEnd === undefined) { options.lnEnd = lnEndOpt.noLnBr; } if (options.noExSp === undefined) { options.noExSp = false; } if (options.noBOM === undefined) { options.noBOM = true; } if (options.lenOpt === undefined) { options.lenOpt = widthFlags.none; } if (options.splitOpt === undefined) { options.splitOpt = splitByOpt.width; } return options; } /** * @hidden * Breaks string by word or by line * @param str String to break * @param opt Options to apply */ const breakStrByEolWord = (str: string, opt: IStringBreakOpt): string[] => { // eol has allready been cleaned at this point // all eol are \n let results: string[] = [] if (str.length === 0) { // results.push(''); return results; } let noBom: boolean = false; if (opt.noBOM === true) { noBom = true; } if (noBom === true) { const cp: number = Number(str.codePointAt(0)); if (isBom(cp) === true) { str = str.substr(1); if (str.length === 0) { // results.push(''); return results; } } } str = cleanLnBr(str); // clean the line breaks just in case irregular if (opt.splitOpt === splitByOpt.word) { // important to call clean white space after removing BOM // otherwise BOM would be converted to space. str = whiteSpToSp(str); // all whites sapce (tab, \n multi space) to single space str = str.trim(); if (str.length === 0) { return results; // return empty array if empty string } // all extra spaces have been replace by // a single space at this point results = str.split(' '); } else { if (str.length === 0) { return results; // return empty array if empty string } results = str.split(/\n/); } return results; } /** * @hidden */ const breakStrByCodePoint = (str: string, opt: IStringBreakOpt): string[] => { const maxWidth: number = Math.round(Number(opt.width)); // make sure it int if (maxWidth < 1) { throw new RangeError('stringBreaker: Width must be greater than zero'); } const lines: string[] = []; let ln: string[] = []; let noBom: boolean = false; let respectWidth: boolean = false; let respectSurrogagePair = false; let respectNearstWord = false; if (opt.lenOpt !== undefined) { // enums can be assigned any arbitrary number const fullMask = 7; // widthFlags.fullwidth | widthFlags.surrogatePair | widthFlags.nearestWord if (opt.lenOpt < widthFlags.none || opt.lenOpt > fullMask) { throw new RangeError(`stringBreaker: widthflags enum out of range. Expected value to be from ${widthFlags.none} to ${fullMask}`); } if ((opt.lenOpt & widthFlags.fullwidth) === widthFlags.fullwidth) { respectWidth = true; } if ((opt.lenOpt & widthFlags.surrogatePair) === widthFlags.surrogatePair) { respectSurrogagePair = true; } if ((opt.lenOpt & widthFlags.nearestWord) === widthFlags.nearestWord) { respectNearstWord = true; } } if (opt.noBOM === true) { noBom = true; } let width: number = 0; for (let i = 0; i < str.length; i++) { const code = str.codePointAt(i); if (code === undefined) { // in typescript this should never happen throw new Error(`stringBreaker Error: No code point exist in first parameter str at postion ${i}`); } const cp = Number(code); const char = String.fromCodePoint(cp); if (i === 0) { if (noBom === true) { if (isBom(cp) === true) { continue; } } else { if (isBom(cp) === true) { ln.push(char); continue; } } } // surrogate pair if (isSurrogatePair(cp) === true) { i++; } if (respectNearstWord === true && ln.length === 0) { // when breaking using nearest word whitespace should be ignored // if it is a the beinning of a line. if (isWhiteSpace(cp) === true && isPrintableWhiteSpace(cp) === false) { // don't worry about non-breaking spaces.they don't be long at the start of a line continue; } } width++; if (respectWidth === true && codePointFullWidth(cp) === true) { width++; } if (respectSurrogagePair === true && isSurrogatePair(cp) === true) { width++; } if (respectNearstWord === true) { // keep adding to ln until we reach the end or a word or line if (isWhiteSpace(cp) === false) { ln.push(char); continue; } else { // if it is a non breaking whitespace add it and continue if (isNonBreakSpace(cp) === true) { ln.push(char); continue; } // if it is a printable whites space then add it and continue if (isPrintableWhiteSpace(cp) === true) { ln.push(char); // do no continue let the width be tested } else if (width < maxWidth) { // other this is a non printing whitespace include it if we are not at maxWidth yet ln.push(char); } } } else { ln.push(char); } if (width >= maxWidth) { lines.push(ln.join('')); ln = []; width = 0; } } // pickup the remainder of the chars if (ln.length > 0) { lines.push(ln.join('')); ln = []; } return lines; } /** * @hidden * Test it see if a number is in the range of unicode z space * @param num a number representing a unicode character * @see [Unicode-Zs]{@link https://www.fileformat.info/info/unicode/category/Zs/list.htm} */ const isZSpace = (num: number): boolean => { const z: number[] = [ 0x0020, 0x00A0, 0x1680, 0x202F, 0x205F, 0x3000 ]; if(z.indexOf(num) !== -1) { return true; } if (num >= 0x2000 && num <= 0x200A) { return true; } return false; } /** * @hidden * Test it see if a number is in the range of unicode whitespace * @param num a number representing a unicode character * @see [wekipedia]{@link https://en.wikipedia.org/wiki/Whitespace_character} */ const isWhiteSpace = (num: number): boolean => { const w: number[] = [ 0x0085, 0x2029 ]; if (w.indexOf(num) !== -1) { return true; } if (num >= 0x0009 && num <= 0x000D) { return true; } if (isZSpace(num) === true) { return true; } return false } /** * @hidden * Test to see if a unicode number is a non-breaking space * @param num a number representing a unicode character */ const isNonBreakSpace = (num: number): boolean => { if (num === 0x00A0 || num === 0x202F) { return true; } return false; } /** * @hidden * Test to see of a unicode number is a printable Whitespace * @param num a number representing a unicode character * @description * This is the only whitespace char that I a aware of that shows * up as a visible character on the screen. I printed a text file with \u1680 at the end * of a line and it did indeed print. * Visual studio code removes this char in the editor if it is at the end of a line. */ const isPrintableWhiteSpace = (num: number): boolean => { if (num === 0x1680) { return true; } return false; } /** * @hidden * This replaces all instance of the \r\n then replaces all \n then finally * replaces all \r. It goes through and removes all types of line breaks * @param str String to replace line breaks in */ const removeLnBr = (str: string): string => { if (str.length === 0) { return ''; } return str.replace(/(\r\n|\n|\r)/gm, ''); } /** * @hidden * This replaces all instance of whitespace with a single space * @param str String to replace witespaces with space * * BOM qualifys as whitespace. If the str has a BOM it will be * replaced by a single space */ const whiteSpToSp = (str: string): string => { if (str.length === 0) { return ''; } // This replaces all instance of whitespace with a single space return str.replace(/\s+/gm, ' '); } /** * @hidden * This replaces all instance of the \r\n then replaces all \r. * It goes through and replaces all line breaks that are not strictly \n * @param str String to clean line breaks */ const cleanLnBr = (str: string): string => { if (str.length === 0) { return ''; } return str.replace(/(\r\n|\r)/gm, '\n'); } /** * @hidden * Replces two or spaces with a single space * @param str The string to repace in */ const removeExSp = (str: string): string => { if (str.length === 0) { return ''; } // matches 2 or more spaces return str.replace(/\x20\x20+/g, ' '); } /** * @hidden * Encodes linebreaks as \n * Any mix of \r \n becomes \n * @param str The string to repace in */ const encodeLnBr = (str: string): string => { return str.replace(/(\r\n|\n|\r)/gm, '\\n'); } /** * @hidden * Checkes to see if a number represents a surrogate pair * @param cp the number to test representing a unicode code point * @returns true if cp is unicode surrogate pair; Otherwise, false */ const isSurrogatePair = (cp: number): boolean => { if (cp >= 0x10000) { return true; } return false; } // https://unicodebook.readthedocs.io/unicode_encodings.html // // UTF-8 including a BOM is not needed and discouraged /** * @hidden * Checks to see if a number represents a byte order mark * @param cp the number to test * @returns true if cp matches BOM; Otherwise, false. * * Supports UTF-8, UTF-16, UTF-7 */ const isBom = (cp: number): boolean => { if ( cp === 0xFEFF // UTF-16-BE || cp === 0xFFFE // UTF-16-LE || cp === 0xEFBBBF // UTF-8 endianless || cp === 0x2B2F76382D // UTF-7 endianless +/v8- || cp === 0x2B2F7638 // UTF-7 +/v8 || cp === 0x2B2F7639 // UTF-7 +/v9 || cp === 0x2B2F7626 // UTF-7 +/v+ ) { return true; } return false; } // #endregion
abc1c2005c800d608679e4cec8e1a139a4244d04
TypeScript
panozhan/quickpicks-admin
/src/app/services/common.service.ts
2.59375
3
import { Injectable } from '@angular/core'; import { GameWithID, Contest, Game } from '../models/interfaces'; @Injectable({ providedIn: 'root' }) export class CommonService { constructor() { } dateWithMonth(date : string) : string{ let _month : string = date.slice(0,2); let day : string = date.slice(3,5); let month : string; switch(_month){ case '01': month = 'January'; break; case '02': month = 'February'; break; case '03': month = 'March'; break; case '04': month = 'April'; break; case '05': month = 'May'; break; case '06': month = 'June'; break; case '07': month = 'July'; break; case '08': month = 'August'; break; case '09': month = 'September'; break; case '10': month = 'October'; break; case '11': month = 'November'; break; case '12': month = 'December'; break; } return `${month} ${day}`; } timeWithTwelve(time : string) : string{ let _hour : string = time.slice(0,2); let min : string = time.slice(3,5); let hour : string; let deliminator : string; //'AM' or 'PM' switch(_hour){ case '00': hour = '12'; deliminator = 'AM'; break; case '01': hour = '1'; deliminator = 'AM'; break; case '02': hour = '2'; deliminator = 'AM'; break; case '03': hour = '3'; deliminator = 'AM'; break; case '04': hour = '4'; deliminator = 'AM'; break; case '05': hour = '5'; deliminator = 'AM'; break; case '06': hour = '6'; deliminator = 'AM'; break; case '07': hour = '7'; deliminator = 'AM'; break; case '08': hour = '8'; deliminator = 'AM'; break; case '09': hour = '9'; deliminator = 'AM'; break; case '10': hour = '10'; deliminator = 'AM'; break; case '11': hour = '11'; deliminator = 'AM'; break; case '12': hour = '12'; deliminator = 'PM'; break; case '13': hour = '1'; deliminator = 'PM'; break; case '14': hour = '2'; deliminator = 'PM'; break; case '15': hour = '3'; deliminator = 'PM'; break; case '16': hour = '4'; deliminator = 'PM'; break; case '17': hour = '5'; deliminator = 'PM'; break; case '18': hour = '6'; deliminator = 'PM'; break; case '19': hour = '7'; deliminator = 'PM'; break; case '20': hour = '8'; deliminator = 'PM'; break; case '21': hour = '9'; deliminator = 'PM'; break; case '22': hour = '10'; deliminator = 'PM'; break; case '23': hour = '11'; deliminator = 'PM'; break; } return `${hour}:${min} ${deliminator}`; } getString_GameDateAndTimeString(gameWithID : GameWithID) : string{ let _date = gameWithID.data.gameStartDate; let _time = gameWithID.data.gameStartTime; return `${this.dateWithMonth(_date)} ${this.timeWithTwelve(_time)}`; } comparator_gamesWithID_by_date(g1 : GameWithID,g2 : GameWithID) : number{ if(g1.data.gameStartDate < g2.data.gameStartDate){ return -1; } else if(g1.data.gameStartDate > g2.data.gameStartDate){ return 1; } else if(g1.data.gameStartTime < g2.data.gameStartTime){ return -1; } else if(g1.data.gameStartDate > g2.data.gameStartDate){ return 1; } else{ return 0; } } comparator_games_by_date(g1: Game, g2 : Game){ console.log('called'); if(g1.gameStartDate < g2.gameStartDate){ return -1; } else if(g1.gameStartDate > g2.gameStartDate){ return 1; } else if(g1.gameStartTime < g2.gameStartTime){ return -1; } else if(g1.gameStartDate > g2.gameStartDate){ return 1; } else{ return 0; } } comparator_contests_by_date(c1 : Contest, c2 : Contest){ if(c1.date < c2.date){ return -1; } else if(c1.date > c2.date){ return 1; } else{ return 0; } } }
4cf7241dd8de4613b18ec3c935495d659426599b
TypeScript
DanielWilches/-Anotaciones-RxJs
/src/Operadores-Time/01-debounceTime.ts
2.96875
3
/**Video #58: operador debounceTime */ import { Observer, fromEvent, Observable, observable } from 'rxjs'; import { debounceTime, map, pluck, distinctUntilChanged } from 'rxjs/operators'; const observer: Observer<any> = { next: value => console.log('next: ', value), error: error => console.error('error: ', error), complete: () => console.info('completado'), }; const click$: Observable<MouseEvent> = fromEvent<MouseEvent>(document, 'click'); // Ejemplo numero 1 click$.pipe( debounceTime(3000) // tap(console.log) );//.subscribe(observer); // Ejemplo numero 2 const input = document.createElement('input'); document.querySelector('body').append(input); const input$: Observable<KeyboardEvent> = fromEvent<KeyboardEvent>(input, 'keyup'); input$.pipe( debounceTime(1000), // map( val => val.target[`value`]), pluck('target','value'), distinctUntilChanged() ).subscribe(observer); /** * para mas informacion sobre este operador/ Operadores consulte 'APUNTES DEL CURSO RxJs' * que esta alojado dentro de este repositorio. */
5dc313db800837ce9478f54c63b6c47458082e26
TypeScript
michaelcoxon/collections
/src/Enumerators/SelectEnumerator.ts
3.140625
3
import { IEnumerator } from "../Interfaces/IEnumerator"; import { Undefinable, Selector } from "@michaelcoxon/utilities/lib/Types"; import EnumeratorBase from "./EnumeratorBase"; import Exception from '@michaelcoxon/utilities/lib/Exceptions/Exception'; export default class SelectEnumerator<T, TReturn> extends EnumeratorBase<TReturn> implements IEnumerator<TReturn> { private readonly _enumerator: IEnumerator<T>; private readonly _selector: Selector<T, TReturn>; private _currentItem?: TReturn; constructor(enumerator: IEnumerator<T>, selector: Selector<T, TReturn>) { super(); this._enumerator = enumerator; this._selector = selector; } public get current(): TReturn { if (this._currentItem === undefined) { throw new Exception("Current is undefined"); } return this._currentItem; } public moveNext(): boolean { this._currentItem = this.peek(); if (this._currentItem === undefined) { return false; } return this._enumerator.moveNext(); } public peek(): Undefinable<TReturn> { let item = this._enumerator.peek(); if (item === undefined) { return; } return this._selector(item); } public reset(): void { this._enumerator.reset(); } }
e54324e6cf5c6edb0ce1f233fe1048effeac1961
TypeScript
richardpark-msft/azure-sdk-for-js
/sdk/keyvault/keyvault-common/src/challengeBasedAuthenticationPolicy.ts
2.8125
3
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. /* eslint-disable @azure/azure-sdk/ts-use-interface-parameters */ import { TokenCredential } from "@azure/core-http"; import { BaseRequestPolicy, RequestPolicy, RequestPolicyOptions, RequestPolicyFactory } from "@azure/core-http"; import { Constants } from "@azure/core-http"; import { HttpOperationResponse } from "@azure/core-http"; import { WebResource } from "@azure/core-http"; import { AccessTokenCache, ExpiringAccessTokenCache } from "@azure/core-http"; type ValidParsedWWWAuthenticateProperties = // "authorization_uri" was used in the track 1 version of KeyVault. // This is not a relevant property anymore, since the service is consistently answering with "authorization". // | "authorization_uri" | "authorization" // Even though the service is moving to "scope", both "resource" and "scope" should be supported. | "resource" | "scope"; type ParsedWWWAuthenticate = { [Key in ValidParsedWWWAuthenticateProperties]?: string; }; /** * Representation of the Authentication Challenge */ export class AuthenticationChallenge { constructor(public authorization: string, public scope: string) {} /** * Checks that this AuthenticationChallenge is equal to another one given. * Only compares the scope. * This is exactly what C# is doing, as we can see here: * https://github.com/Azure/azure-sdk-for-net/blob/70e54b878ff1d01a45266fb3674a396b4ab9c1d2/sdk/keyvault/Azure.Security.KeyVault.Shared/src/ChallengeBasedAuthenticationPolicy.cs#L143-L147 * @param other - The other AuthenticationChallenge */ public equalTo(other: AuthenticationChallenge | undefined): boolean { return other ? this.scope.toLowerCase() === other.scope.toLowerCase() && this.authorization.toLowerCase() === other.authorization.toLowerCase() : false; } } /** * Helps keep a copy of any previous authentication challenges, * so that we can compare on any further request. */ export class AuthenticationChallengeCache { public challenge?: AuthenticationChallenge; public setCachedChallenge(challenge: AuthenticationChallenge): void { this.challenge = challenge; } } /** * Creates a new ChallengeBasedAuthenticationPolicy factory. * * @param credential - The TokenCredential implementation that can supply the challenge token. */ export function challengeBasedAuthenticationPolicy( credential: TokenCredential ): RequestPolicyFactory { const tokenCache: AccessTokenCache = new ExpiringAccessTokenCache(); const challengeCache = new AuthenticationChallengeCache(); return { create: (nextPolicy: RequestPolicy, options: RequestPolicyOptions) => { return new ChallengeBasedAuthenticationPolicy( nextPolicy, options, credential, tokenCache, challengeCache ); } }; } /** * Parses an WWW-Authenticate response. * This transforms a string value like: * `Bearer authorization="some_authorization", resource="https://some.url"` * into an object like: * `{ authorization: "some_authorization", resource: "https://some.url" }` * @param wwwAuthenticate - String value in the WWW-Authenticate header */ export function parseWWWAuthenticate(wwwAuthenticate: string): ParsedWWWAuthenticate { // First we split the string by either `, ` or ` `. const parts = wwwAuthenticate.split(/,* +/); // Then we only keep the strings with an equal sign after a word and before a quote. // also splitting these sections by their equal sign const keyValues = parts.reduce<string[][]>( (acc, str) => (str.match(/\w="/) ? [...acc, str.split("=")] : acc), [] ); // Then we transform these key-value pairs back into an object. const parsed = keyValues.reduce<ParsedWWWAuthenticate>( (result, [key, value]: string[]) => ({ ...result, [key]: value.slice(1, -1) }), {} ); return parsed; } /** * * Provides a RequestPolicy that can request a token from a TokenCredential * implementation and then apply it to the Authorization header of a request * as a Bearer token. * */ export class ChallengeBasedAuthenticationPolicy extends BaseRequestPolicy { private parseWWWAuthenticate: ( wwwAuthenticate: string ) => ParsedWWWAuthenticate = parseWWWAuthenticate; /** * Creates a new ChallengeBasedAuthenticationPolicy object. * * @param nextPolicy - The next RequestPolicy in the request pipeline. * @param options - Options for this RequestPolicy. * @param credential - The TokenCredential implementation that can supply the bearer token. * @param tokenCache - The cache for the most recent AccessToken returned by the TokenCredential. */ constructor( nextPolicy: RequestPolicy, options: RequestPolicyOptions, private credential: TokenCredential, private tokenCache: AccessTokenCache, private challengeCache: AuthenticationChallengeCache ) { super(nextPolicy, options); } /** * Gets or updates the token from the token cache into the headers of the received web resource. */ private async loadToken(webResource: WebResource): Promise<void> { let accessToken = this.tokenCache.getCachedToken(); // If there's no cached token in the cache, we try to get a new one. if (accessToken === undefined) { const receivedToken = await this.credential.getToken(this.challengeCache.challenge!.scope); accessToken = receivedToken || undefined; this.tokenCache.setCachedToken(accessToken); } if (accessToken) { webResource.headers.set( Constants.HeaderConstants.AUTHORIZATION, `Bearer ${accessToken.token}` ); } } /** * Parses the given WWW-Authenticate header, generates a new AuthenticationChallenge, * then if the challenge is different from the one cached, resets the token and forces * a re-authentication, otherwise continues with the existing challenge and token. * @param wwwAuthenticate - Value of the incoming WWW-Authenticate header. * @param webResource - Ongoing HTTP request. */ private async regenerateChallenge( wwwAuthenticate: string, webResource: WebResource ): Promise<HttpOperationResponse> { // The challenge based authentication will contain both: // - An authorization URI with a token, // - The resource to which that token is valid against (also called the scope). const parsedWWWAuth = this.parseWWWAuthenticate(wwwAuthenticate); const authorization = parsedWWWAuth.authorization!; const resource = parsedWWWAuth.resource! || parsedWWWAuth.scope!; if (!(authorization && resource)) { return this._nextPolicy.sendRequest(webResource); } const challenge = new AuthenticationChallenge(authorization, resource + "/.default"); // Either if there's no cached challenge at this point (could have happen in parallel), // or if the cached challenge has a different scope, // we store the just received challenge and reset the cached token, to force a re-authentication. if (!this.challengeCache.challenge?.equalTo(challenge)) { this.challengeCache.setCachedChallenge(challenge); this.tokenCache.setCachedToken(undefined); } await this.loadToken(webResource); return this._nextPolicy.sendRequest(webResource); } /** * Applies the Bearer token to the request through the Authorization header. * @param webResource - Ongoing HTTP request. */ public async sendRequest(webResource: WebResource): Promise<HttpOperationResponse> { // Ensure that we're about to use a secure connection. if (!webResource.url.startsWith("https:")) { throw new Error("The resource address for authorization must use the 'https' protocol."); } // The next request will happen differently whether we have a challenge or not. let response: HttpOperationResponse; if ( this.challengeCache.challenge === undefined || this.challengeCache.challenge === undefined ) { // If there's no challenge in cache, a blank body will start the challenge. const originalBody = webResource.body; webResource.body = ""; try { response = await this._nextPolicy.sendRequest(webResource); } finally { webResource.body = originalBody; } } else { // If we did have a challenge in memory, // we attempt to load the token from the cache into the request before we try to send the request. await this.loadToken(webResource); response = await this._nextPolicy.sendRequest(webResource); } // If we don't receive a response with a 401 status code, // then we can assume this response has nothing to do with the challenge authentication process. if (response.status !== 401) { return response; } // If the response status is 401, we only re-authenticate if the WWW-Authenticate header is present. const wwwAuthenticate = response.headers.get("WWW-Authenticate"); if (!wwwAuthenticate) { return response; } // We re-generate the challenge and see if we have to re-authenticate. return this.regenerateChallenge(wwwAuthenticate, webResource); } }
f3608484581d18a872c6de2e788322d8fdbb02d8
TypeScript
cportillosv/ts-book-vs
/ts-book-vs/asynchronous.ts
4.25
4
//Callbacks and higher-order functions var foo = function () // callback { console.log('foo'); } function bar(cb: () => void) { // higher order function console.log('bar'); cb(); } bar(foo); //prints 'bar' then prints 'foo' //Arrow functions class Person { name: string; constructor(name: string) { this.name = name; } greet() { alert(`Hi! My name is ${this.name}`); } greetDelay(time: number) { setTimeout(() => { alert(`Hi! My name is delay ${this.name}`); }, time); } } var charles = new Person("Charles"); charles.greet(); charles.greetDelay(1000); var sum = (num1: number, num2: number = 0) => { return num1 + num2; } console.log(sum(5));
7d12a2f4f637c6e59d8610e5eaff6b2aa25b5eb0
TypeScript
mmiszy/ddd-typescript
/src/modules/users/3-controllers-and-interface-adapters/createUserController.ts
2.609375
3
import { CreateUserUseCase } from '@modules/users/2-use-cases/createUser/createUserUseCase'; import { CreateUserRequestDTO } from '@modules/users/2-use-cases/createUser/createUserDTOs'; import * as BaseController from '@shared/3-controllers-and-interface-adapters/BaseController'; import { EmailAlreadyExistsError } from '@modules/users/2-use-cases/createUser/createUserErrors'; import * as Either from '@shared/types/either'; export const CreateUserController = ( createUserUseCase: ReturnType<typeof CreateUserUseCase>, ): BaseController.BaseController<null, CreateUserRequestDTO> => async req => { const dto = req.body; const result = await createUserUseCase({ email: dto.email, }); if (Either.isLeft(result)) { if (result.value instanceof EmailAlreadyExistsError) { return BaseController.conflict(result.value.message); } else { return BaseController.internal(); } } return BaseController.ok(result.value); };
e785be8379eaed9e2ede12b31270368b7b3a16e8
TypeScript
github/vscode-codeql
/extensions/ql-vscode/src/model-editor/extensions-workspace-folder.ts
2.71875
3
import { FileType, Uri, window, workspace, WorkspaceFolder } from "vscode"; import { getOnDiskWorkspaceFoldersObjects } from "../common/vscode/workspace-folders"; import { extLogger } from "../common/logging/vscode"; import { tmpdir } from "../common/files"; /** * Returns the ancestors of this path in order from furthest to closest (i.e. root of filesystem to parent directory) */ function getAncestors(uri: Uri): Uri[] { const ancestors: Uri[] = []; let current = uri; while (current.fsPath !== Uri.joinPath(current, "..").fsPath) { ancestors.push(current); current = Uri.joinPath(current, ".."); } // The ancestors are now in order from closest to furthest, so reverse them ancestors.reverse(); return ancestors; } async function getRootWorkspaceDirectory(): Promise<Uri | undefined> { // If there is a valid workspace file, just use its directory as the directory for the extensions const workspaceFile = workspace.workspaceFile; if (workspaceFile?.scheme === "file") { return Uri.joinPath(workspaceFile, ".."); } const allWorkspaceFolders = getOnDiskWorkspaceFoldersObjects(); // Get the system temp directory and convert it to a URI so it's normalized const systemTmpdir = Uri.file(tmpdir()); const workspaceFolders = allWorkspaceFolders.filter((folder) => { // Never use a workspace folder that is in the system temp directory return !folder.uri.fsPath.startsWith(systemTmpdir.fsPath); }); // Find the common root directory of all workspace folders by finding the longest common prefix const commonRoot = workspaceFolders.reduce((commonRoot, folder) => { const folderUri = folder.uri; const ancestors = getAncestors(folderUri); const minLength = Math.min(commonRoot.length, ancestors.length); let commonLength = 0; for (let i = 0; i < minLength; i++) { if (commonRoot[i].fsPath === ancestors[i].fsPath) { commonLength++; } else { break; } } return commonRoot.slice(0, commonLength); }, getAncestors(workspaceFolders[0].uri)); if (commonRoot.length === 0) { return await findGitFolder(workspaceFolders); } // The path closest to the workspace folders is the last element of the common root const commonRootUri = commonRoot[commonRoot.length - 1]; // If we are at the root of the filesystem, we can't go up any further and there's something // wrong, so just return undefined if (commonRootUri.fsPath === Uri.joinPath(commonRootUri, "..").fsPath) { return await findGitFolder(workspaceFolders); } return commonRootUri; } async function findGitFolder( workspaceFolders: WorkspaceFolder[], ): Promise<Uri | undefined> { // Go through all workspace folders one-by-one and try to find the closest .git folder for each one const folders = await Promise.all( workspaceFolders.map(async (folder) => { const ancestors = getAncestors(folder.uri); // Reverse the ancestors so we're going from closest to furthest ancestors.reverse(); const gitFoldersExists = await Promise.all( ancestors.map(async (uri) => { const gitFolder = Uri.joinPath(uri, ".git"); try { const stat = await workspace.fs.stat(gitFolder); // Check whether it's a directory return (stat.type & FileType.Directory) !== 0; } catch (e) { return false; } }), ); // Find the first ancestor that has a .git folder const ancestorIndex = gitFoldersExists.findIndex((exists) => exists); if (ancestorIndex === -1) { return undefined; } return [ancestorIndex, ancestors[ancestorIndex]]; }), ); const validFolders = folders.filter( (folder): folder is [number, Uri] => folder !== undefined, ); if (validFolders.length === 0) { return undefined; } // Find the .git folder which is closest to a workspace folder const closestFolder = validFolders.reduce((closestFolder, folder) => { if (folder[0] < closestFolder[0]) { return folder; } return closestFolder; }, validFolders[0]); return closestFolder?.[1]; } /** * Finds a suitable directory for extension packs to be created in. This will * always be a path ending in `.github/codeql/extensions`. The parent directory * will be determined heuristically based on the on-disk workspace folders. * * The heuristic is as follows (`.github/codeql/extensions` is added automatically unless * otherwise specified): * 1. If there is only 1 workspace folder, use that folder * 2. If there is a workspace folder for which the path ends in `.github/codeql/extensions`, use that folder * - If there are multiple such folders, use the first one * - Does not append `.github/codeql/extensions` to the path * 3. If there is a workspace file (`<basename>.code-workspace`), use the directory containing that file * 4. If there is a common root directory for all workspace folders, use that directory * - Workspace folders in the system temp directory are ignored * - If the common root directory is the root of the filesystem, then it's not used * 5. If there is a .git directory in any workspace folder, use the directory containing that .git directory * for which the .git directory is closest to a workspace folder * 6. If none of the above apply, return `undefined` */ export async function autoPickExtensionsDirectory(): Promise<Uri | undefined> { const workspaceFolders = getOnDiskWorkspaceFoldersObjects(); // If there's only 1 workspace folder, use the `.github/codeql/extensions` directory in that folder if (workspaceFolders.length === 1) { return Uri.joinPath( workspaceFolders[0].uri, ".github", "codeql", "extensions", ); } // Now try to find a workspace folder for which the path ends in `.github/codeql/extensions` const workspaceFolderForExtensions = workspaceFolders.find((folder) => // Using path instead of fsPath because path always uses forward slashes folder.uri.path.endsWith(".github/codeql/extensions"), ); if (workspaceFolderForExtensions) { return workspaceFolderForExtensions.uri; } // Get the root workspace directory, i.e. the common root directory of all workspace folders const rootDirectory = await getRootWorkspaceDirectory(); if (!rootDirectory) { void extLogger.log("Unable to determine root workspace directory"); return undefined; } // We'll create a new workspace folder for the extensions in the root workspace directory // at `.github/codeql/extensions` const extensionsUri = Uri.joinPath( rootDirectory, ".github", "codeql", "extensions", ); if ( !workspace.updateWorkspaceFolders( workspace.workspaceFolders?.length ?? 0, 0, { name: "CodeQL Extension Packs", uri: extensionsUri, }, ) ) { void extLogger.log( `Failed to add workspace folder for extensions at ${extensionsUri.fsPath}`, ); return undefined; } return extensionsUri; } export async function askForWorkspaceFolder(): Promise< WorkspaceFolder | undefined > { const workspaceFolders = getOnDiskWorkspaceFoldersObjects(); const workspaceFolderOptions = workspaceFolders.map((folder) => ({ label: folder.name, detail: folder.uri.fsPath, folder, })); // We're not using window.showWorkspaceFolderPick because that also includes the database source folders while // we only want to include on-disk workspace folders. const workspaceFolder = await window.showQuickPick(workspaceFolderOptions, { title: "Select workspace folder to create extension pack in", }); if (!workspaceFolder) { return undefined; } return workspaceFolder.folder; }
acd7410e325c9af02e52566cb08be783977c5c25
TypeScript
fbiayna/BoardPub
/client/src/reducers/userReducer.ts
2.703125
3
import actionTypes from '../actions/actionTypes' import { ActionUser } from '../utils/interfaces' const initialState = {} export default function userReducer (state: any = initialState, action: ActionUser) { let newState = null switch (action.type) { case actionTypes.LOAD_USER: newState = { ...state, user: action.user } break case actionTypes.LOAD_USER_ERROR: newState = { ...state, error: action.error } break case actionTypes.ADD_AND_LOAD_USER: newState = { ...state, user: action.user } break case actionTypes.ADD_AND_LOAD_USER_ERROR: newState = { ...state, error: action.error } break case actionTypes.ADD_FAVORITE: newState = { ...state, user: action.user } break case actionTypes.ADD_FAVORITE_ERROR: newState = { ...state, error: action.error } break case actionTypes.DELETE_FAVORITE: newState = { ...state, user: action.user } break case actionTypes.DELETE_FAVORITE_ERROR: newState = { ...state, error: action.error } break default: newState = state break } return newState }
6555c69f0d2afbe168b38d1ac936e538eb243684
TypeScript
azat-io/scroogie
/src/utils/random-int.ts
2.859375
3
const randomInt = (min: number, max: number): number => { const minNum = Math.ceil(min) const maxNum = Math.floor(max) return Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum } export default randomInt
45e89256b8f64ad310249ef8fa3502d9d64d73bc
TypeScript
EasonApolo/forvera
/app/src/utils/common.ts
2.859375
3
export const formatDate = (ISODateStr: string): string => { const date = new Date(ISODateStr) return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}` } const pad = (val: string | number): string => { return val < 10 ? `0${val}` : `${val}` } export const readFile = (file: File): Promise<SelectedImage> => { return new Promise((resolve) => { const reader = new FileReader() reader.onload = e => resolve({ blob: e.target!.result as string, file }) reader.readAsDataURL(file) }) } export const throttle = (func: Function) => { let timeout: any = null return (...args: any) => { if (!timeout) { func(...args) timeout = setTimeout(() => { timeout = null }, 1000) } } }
b1a71030d80078e461a7b80697f65dde9da86466
TypeScript
JohnSteck9/weather-data-processing
/scripts/prefill.ts
2.5625
3
import mysql from 'mysql'; import Redis from 'ioredis'; import zlib from 'zlib'; import _ from 'lodash'; import { data } from '../src/hourly.json'; Promise.resolve() .then(() => prefillMySql()) .then(() => prefillRedis()) .catch(error => console.error(error)) .finally(() => console.log('Finished')); function prefillMySql() { var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'example', multipleStatements: true }); const connect = new Promise((resolve, reject) => { connection.connect(error => { if (error) { reject(error); } else { console.log('Connected to MySql'); resolve(); } }) }); const createDb = new Promise((resolve, reject) => { connection.query(` DROP DATABASE IF EXISTS weather; CREATE DATABASE weather; `, error => { if (error) { reject(error); } else { console.log('weather Db is created'); resolve(); } }); }); const createTable = new Promise((resolve, reject) => { connection.query(` USE weather; CREATE TABLE hourly_statistics ( city_id VARCHAR(50) NOT NULL, time DATETIME NOT NULL, temperature FLOAT NOT NULL ); CREATE INDEX city_index ON hourly_statistics(city_id); CREATE TABLE hourly_statistics_no_index ( city_id VARCHAR(50) NOT NULL, time DATETIME NOT NULL, temperature FLOAT NOT NULL ); `, error => { if (error) { reject(error); } else { console.log('hourly_statistics and hourly_statistics_no_index Tables are created'); resolve(); } }); }); const insert = (values: string) => new Promise((resolve, reject) => { connection.query(` USE weather; INSERT INTO hourly_statistics (city_id, time, temperature) VALUES ${values}; INSERT INTO hourly_statistics_no_index (city_id, time, temperature) VALUES ${values}; `, error => { if (error) { reject(error); } else { resolve(); } }); }); const fill = new Promise(async (resolve, reject) => { try { for (let i = 0; i < 1000; i++) { const values = data.map(({ time, temperature }) => `('city-${i}', '${time}', ${temperature + _.random(-5, 5)})`) .join(', '); await insert(values); if ((i + 1) % 50 === 0) { console.log(`${(i + 1) * data.length} items added`); } } resolve(); } catch (error) { reject(error); } }); return connect .then(() => createDb) .then(() => createTable) .then(() => fill) .finally(() => connection.end(error => { if (error) { console.error(error); } })); } function prefillRedis() { const client = new Redis(); console.log('Connected to Redis'); client.on('error', (error: Error) => { console.error(error); }); const gzip = (value: string) => new Promise<Buffer>((resolve, reject) => { zlib.gzip(value, (error, buffer) => { if (error) { reject(error); } else { resolve(buffer); } }); }); const set = (key: string, buffer: Buffer) => new Promise((resolve, reject) => { client.set(key, buffer, (error: Error, reply: any) => { if (error) { reject(error); } else { resolve(reply) } }); }); return new Promise(async (resolve, reject) => { try { for (let i = 0; i < 1000; i++) { const value = await gzip( JSON.stringify( data.map(({ time, temperature }) => ({ time, temperature: temperature + _.random(-5, 5) })) ) ); await set(`city-${i}`, value); if ((i + 1) % 50 === 0) { console.log(`${(i + 1) * data.length} items added`); } } resolve(); } catch (error) { reject(error); } }) .then(() => client.quit()); }
1324b76533507e554d274cd679da74fa40bcc154
TypeScript
JanusBifrons/EquinoxNode
/src/game/world/sector.ts
2.703125
3
namespace FireHare.Equinox { export class District { static DISTRICT_MIN: Vector = new Vector(0, 0); static DISTRICT_MAX: Vector = new Vector(500, 500); static LimitPositionToDistrict(cVector: Vector): Vector { let nX: number = cVector.X; let nY: number = cVector.Y; if(cVector.X < District.DISTRICT_MIN.X) nX = District.DISTRICT_MAX.X; if(cVector.Y < District.DISTRICT_MIN.Y) nY = District.DISTRICT_MAX.Y; if(cVector.X > District.DISTRICT_MAX.X) nX = District.DISTRICT_MIN.X; if(cVector.Y > District.DISTRICT_MAX.Y) nY = District.DISTRICT_MIN.Y; return new Vector(nX, nY); } static RandomSpawn(): Vector { let cPosition: Vector = new Vector(Random.Next(0, District.DISTRICT_MAX.X), Random.Next(0, District.DISTRICT_MAX.Y)); return cPosition; } static draw(cCanvas: Canvas) { } static drawGrid(cCanvas: Canvas, cOffset: Vector) { let nSize: number = 5000; let nGridSize: number = 10; let nSmallGridSize: number = 10; let nThick: number = 2; let nThin: number = 1; let nX: number = (Math.round(cOffset.X / nSize) * nSize) - (nSize * (nGridSize / 2)); let nY: number = (Math.round(cOffset.Y / nSize) * nSize) - (nSize * (nGridSize / 2)); let nSmallX: number = 0; let nSmallY: number = 0; let m_kContext: CanvasRenderingContext2D = cCanvas.context; m_kContext.strokeStyle = 'darkgray'; // Draw first two lines cCanvas.moveToWorldSpace(); m_kContext.beginPath(); m_kContext.lineWidth = nThick; m_kContext.moveTo(nX, nY); m_kContext.lineTo(nX + (nSize * nGridSize), nY); m_kContext.moveTo(nX, nY); m_kContext.lineTo(nX, nY + (nSize * nGridSize)); m_kContext.stroke(); cCanvas.moveToScreenSpace(); for(var i = 0; i < nGridSize; i++) { nSmallX = nX; nSmallY = nY; cCanvas.moveToWorldSpace(); for(var j = 0; j < nSmallGridSize; j++) { m_kContext.beginPath(); m_kContext.lineWidth = nThin; m_kContext.moveTo(nSmallX, nSmallY); m_kContext.lineTo(nSmallX + (nSize * nGridSize), nSmallY); m_kContext.stroke(); nSmallY += (nSize / nSmallGridSize); } nY += nSize; m_kContext.beginPath(); m_kContext.lineWidth = nThick; m_kContext.moveTo(nX, nY); m_kContext.lineTo(nX + (nSize * nGridSize), nY); m_kContext.stroke(); cCanvas.moveToScreenSpace(); } nX = (Math.round(cOffset.X / nSize) * nSize) - (nSize * (nGridSize / 2)); nY = (Math.round(cOffset.Y / nSize) * nSize) - (nSize * (nGridSize / 2)); for(var i = 0; i < nGridSize; i++) { nSmallX = nX; nSmallY = nY; cCanvas.moveToWorldSpace(); for(var j = 0; j < nSmallGridSize; j++) { m_kContext.beginPath(); m_kContext.lineWidth = nThin; m_kContext.moveTo(nSmallX, nSmallY); m_kContext.lineTo(nSmallX, nSmallY + (nSize * nGridSize)); m_kContext.stroke(); nSmallX += (nSize / nSmallGridSize); } nX += nSize; m_kContext.beginPath(); m_kContext.lineWidth = nThick; m_kContext.moveTo(nX, nY); m_kContext.lineTo(nX, nY + (nSize * nGridSize)); m_kContext.stroke(); cCanvas.moveToScreenSpace(); } } } }
2c381960e79ad2851a7a7a84bb19372800775dfa
TypeScript
angrycans/RN-Unity-starter
/src/app/types.ts
2.578125
3
enum ViewType { GOODS = 0, MEMBER, NOCODE, NUMBER_CONFIRM, } /** * 分类item数据 */ interface ICategoryItem { name: string, id: string, parentId: string, subCates: [{ name: string, id: string, parentId: string }], } /** * 商品详情 */ interface IGoodsItem { skuId?: string, spuId?: string, productName?: string, skuBn?: string, stock?: { status: boolean, name: string, stock: number, }, salePrice: string, images: [string], isMaster?: string, groupId?: string, specs?: [ { specialPropName: string, specialValName: string, } ], d2cSort?: string, d2COnSale?: boolean, unit: string; } /** * 购物车cartItem */ interface ICartItem { skuId: string, spuId: string, skuBn: string, productName: string, //名称 originalPrice: number, //基础价格 levelPrice: number, //会员销售价格 activityPrice: number, //活动价格 isNoCodeGoods: boolean, //是否是无码商品 isDiscount?: boolean, //是否有折扣价 isWeightGoods: boolean, //是否称重商品 img: string, quantity: number, //数量 或者 重量 barCode: string, //goodItem?: IGoodsItem, //商品详情 暂时用不到 去掉 unit: string; //商品单位 itemType: number, //s商品类型 specs?: [ //规格 { specialPropName: string, specialValName: string, } ], stock, } /** * 购物车 */ interface ICart { member: string, // memberInfo?: IMemberInfo, memberType?: number, //0:散客 1.会员 cartItems: [ICartItem], totalFee: number, //总价 totalCount: number, //总数 } /** * 会员信息 */ interface IMemberInfo { integral?: number // 积分 levelId?: number //会员等级id levelName?: string //会员等级名称 mobile?: string //会员手机 totalPayCash?: number //会员总消费 userId?: string //会员id nickName: string } /** * 商品cartItem */ interface ICashCartItem { skuId?: string, spuId?: string, productName?: string, //名称 originalPrice?: number, //基础价格 levelPrice?: number, //会员销售价格 isNoCodeGoods?: boolean, //是否是无码商品 itemType?: number, // 1, "标准的自营商品" 3,"称重商品: 如按斤、毫升、米等度量单位卖出的商品" 4, "无条码商品" quantity?: number, //数量 或者 重量 } /** * 提交订单 */ interface ICashCart { userId: string, // mobile: string, levelId: string, //0:散客 1.会员 nickName: string, items: [ICashCartItem], tid?: string, totalTradeCash?: number, totalCount?: number, } /** * 商品营销活动 */ interface IGoodsActivity { openCut: number, openDiscount: number, cuts: [{ type: string, value: number }], discounts: [{ type: string, value: number }], cutType: { cutFen: number, cutJiao: number, cutRound: number, } } export { ViewType, ICategoryItem, IGoodsItem, ICartItem, ICart, IMemberInfo, ICashCart, ICashCartItem, IGoodsActivity, };
faf06e50151ef62f9095c64ea89e50d7d0da28a9
TypeScript
tomaszdworniczak/CodersCamp2020.Project.FullStack-Node-React.TableSoccerTournaments
/frontend/src/restapi/players-profiles/PlayersProfilesRestApi.ts
2.625
3
import axios from "axios"; import { PlayerProfilesListDto } from "./PlayerProfilesListDto"; import { PlayerProfileDto } from "./PlayerProfileDto"; import { PATH_BASE_URL } from "../../components/atoms/constants/apiPaths"; export type UserProfilesRestApiConfig = { readonly baseUrl: string; }; const defaultConfig: UserProfilesRestApiConfig = { baseUrl: PATH_BASE_URL, }; export const UserProfileRestApi = ( config?: Partial<UserProfilesRestApiConfig> ) => { const currentConfig = { ...defaultConfig, config, baseUrl: process.env.REACT_APP_REST_API_BASE_URL ?? config?.baseUrl ?? defaultConfig.baseUrl, }; return { getPlayersProfiles(): Promise<PlayerProfilesListDto> { return axios .get<PlayerProfilesListDto>(`${currentConfig.baseUrl}/players-profiles`) .then((response) => response.data); }, getPlayerProfile(playerId: string): Promise<PlayerProfileDto> { return axios .get<PlayerProfileDto>( `${currentConfig.baseUrl}/players-profiles/${playerId}` ) .then((response) => response.data); }, async postPlayersProfile(playerProfile: PlayerProfileDto): Promise<void> { await axios.post<PlayerProfileDto>( `${currentConfig.baseUrl}/players-profiles`, playerProfile ); }, }; };
b7a5e4d967b9eefd6a0e2350d02788cee528a892
TypeScript
MaxRyabets/angular_ssr
/src/app/infinite-loop-slider/infinite-loop-slider.component.ts
2.578125
3
import { AfterViewInit, ChangeDetectionStrategy, Component, ElementRef, Inject, Input, PLATFORM_ID, } from '@angular/core'; import SwiperCore, { Autoplay, Navigation } from 'swiper/core'; import Swiper from 'swiper'; import { Breakpoint } from './breakpoint'; import { isPlatformBrowser } from '@angular/common'; @Component({ selector: 'app-infinite-loop-slider', templateUrl: './infinite-loop-slider.component.html', styleUrls: ['./infinite-loop-slider.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush, }) /** * Represents a infinite loop slider. * This component provides init swiper and he uses * user setting or default if are they present. * @constructor * @param {ElementRef} elementRef - The element reference of the component * @param {any} platformId - The platformId of the server/browser platform */ export class InfiniteLoopSliderComponent implements AfterViewInit { private readonly defaultBreakPoints = new Map([ [576, 1], [768, 2], [992, 3], [1199, 4], [1200, 5], ]); /** * This are breakpoints which the user set for swiper responsive. * If user doesn't set then use default breakpoint. */ @Input() breakpoints: Map<number, number>; /** * This is delay which the user set for delay between slide changes. */ @Input() delay: number; constructor( private readonly elementRef: ElementRef, @Inject(PLATFORM_ID) private readonly platformId: any ) { SwiperCore.use([Navigation, Autoplay]); } ngAfterViewInit(): void { if (!isPlatformBrowser(this.platformId)) { return; } const breakpoints = this.getBreakpoints(); const swiper = new Swiper(this.elementRef.nativeElement, { loop: true, autoplay: { delay: this.delay, disableOnInteraction: false, }, breakpoints: breakpoints as {}, }); } private getBreakpoints(): Breakpoint { const breakpoints = this.breakpoints.size ? this.breakpoints : this.defaultBreakPoints; return this.transformToBreakpoint(breakpoints); } private transformToBreakpoint(breakpoints: Map<number, number>): Breakpoint { const localBreakpoints: Breakpoint = {}; breakpoints.forEach((slidesPerView, screenSize) => { localBreakpoints[screenSize] = { slidesPerView, }; }); return localBreakpoints; } }
56814426c8a39a0e61f1d3f518e6a825e6f07a3a
TypeScript
Koenkk/zigbee-herdsman
/src/adapter/z-stack/structs/entries/aps-link-key-data-table.ts
2.890625
3
/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ /* eslint-disable @typescript-eslint/explicit-function-return-type */ import {Table} from "../table"; import {StructMemoryAlignment} from "../struct"; import {apsLinkKeyDataEntry} from "./aps-link-key-data-entry"; const emptyKey = Buffer.alloc(16, 0x00); /** * Creates an APS link key data table. * * @param data Data to initialize table with. * @param alignment Memory alignment of initialization data. */ export const apsLinkKeyDataTable = (dataOrCapacity?: Buffer | Buffer[] | number, alignment: StructMemoryAlignment = "unaligned") => { const table = Table.new<ReturnType<typeof apsLinkKeyDataEntry>>() .struct(apsLinkKeyDataEntry) .occupancy(e => !e.key.equals(emptyKey)); return typeof dataOrCapacity === "number" ? table.build(dataOrCapacity) : table.build(dataOrCapacity, alignment); };
ee6a1664ab31543c41105cfc6d35e56dfc87efff
TypeScript
T99/ampel-frontend
/js/ts/helpers/builder-base.ts
3.375
3
/* * Created by Trevor Sears <trevorsears.main@gmail.com>. * 5:59 PM -- January 26th, 2019. * Website: dashboard.ampelfeedback.com */ import InvalidArgumentsError from "../errors/invalid-arguments-error.js"; type BuilderRequirement = { name: string, isOptional: boolean, isFulfilled: boolean; value: any; }; /** * Enumerates the requirements of a given builder pattern. * * @author Trevor Sears <trevorsears.main@gmail.com> * @version v0.1.0 * @since v0.1.0 */ abstract class BuilderBase<E> { private requirements: Map<string, BuilderRequirement> = new Map<string, BuilderRequirement>(); public constructor() { /* Do nothing. */ } protected addRequirements(...requirementNames: string[]): void { for (let requirementName of requirementNames) { this.requirements.set(requirementName, { name: requirementName, isOptional: false, isFulfilled: false, value: null }); } } protected addOptionals(...optionalNames: string[]): void { for (let optionalName of optionalNames) { this.requirements.set(optionalName, { name: optionalName, isOptional: true, isFulfilled: false, value: null }); } } protected fulfillRequirement(requirementName: string, value: any): void { if (this.requirements.has(requirementName)) { let requirement: BuilderRequirement = this.requirements.get(requirementName); requirement.isFulfilled = true; requirement.value = value; } else { throw new InvalidArgumentsError("Attempted to fulfill a requirement that did not exist: '" + requirementName + "'."); } } protected getValueOfRequirement(requirementName: string): any { if (this.requirements.has(requirementName)) return this.requirements.get(requirementName).value; else { throw new InvalidArgumentsError("Attempted to get the value of a requirement that did not exist: '" + requirementName + "'."); } } protected getNamesOfUnfulfilledRequirements(): string[] { let unfulfilledRequirementNames: string[] = []; for (let requirement of this.requirements.values()) { if (requirement.isOptional === false && requirement.isFulfilled === false) { unfulfilledRequirementNames.push(requirement.name); } } return unfulfilledRequirementNames; } protected getNamesOfUnfulfilledOptionalRequirements(): string[] { let unfulfilledOptionalRequirementNames: string[] = []; for (let requirement of this.requirements.values()) { if (requirement.isOptional === true && requirement.isFulfilled === false) { unfulfilledOptionalRequirementNames.push(requirement.name); } } return unfulfilledOptionalRequirementNames; } protected getNamesOfUnfulfilledRequirementsAndOptionalRequirements(): string[] { let unfulfilledRequirementsAndOptionalRequirementNames: string[] = []; for (let requirement of this.requirements.values()) { if (requirement.isFulfilled === false) { unfulfilledRequirementsAndOptionalRequirementNames.push(requirement.name); } } return unfulfilledRequirementsAndOptionalRequirementNames; } protected getErrorMessageForIncompleteBuilder(): string { let errorMessage: string = "Attempted to build from an incomplete builder. Missing fields include: "; let namesOfUnfulfilledRequirements: string[] = this.getNamesOfUnfulfilledRequirements(); for (let index: number = 0; index < namesOfUnfulfilledRequirements.length; index++) { errorMessage += "'" + namesOfUnfulfilledRequirements[index] + "'"; if (index < namesOfUnfulfilledRequirements.length - 2) errorMessage += ", "; else if (index < namesOfUnfulfilledRequirements.length - 1) errorMessage += ", and "; } errorMessage += "."; return errorMessage; } /** * Checks if requirements have been fulfilled. If a requirement name is specified, this method returns true if that * specific requirement has been fulfilled. Otherwise, this method returns true if all non-optional (required) * requirements have been fulfilled. * * @param {string} requirementName The (optional) name of a requirement. * @returns {boolean} If a requirement name is specified, true if that specific requirement has been fulfilled. * Otherwise, true if all non-optional (required) requirements have been fulfilled. */ protected checkFulfillment(requirementName?: string): boolean { if (requirementName) { if (this.requirements.has(requirementName)) return (this.requirements.get(requirementName).isFulfilled === true); else { throw new InvalidArgumentsError("Attempted to check the fulfillment a requirement that did not exist:" + " '" + requirementName + "'."); } } else { for (let requirement of this.requirements.values()) { if (requirement.isOptional === false && requirement.isFulfilled === false) return false; } return true; } } public abstract build(): E; } export default BuilderBase;
aa760cc0ec52881d6154dfc7e3468d330ec4602b
TypeScript
kendricktan/abstracted
/packages/frontend/src/containers/legos/use-legos.ts
2.53125
3
import { createContainer } from 'unstated-next' import { useState } from 'react' export enum LegoType { CompoundSupply, CompoundBorrow, CompoundRepay, CompoundWithdraw, AaveFlashloanStart, AaveFlashloanEnd, UniswapV2SwapExactInToOut, } export interface Lego { id: string type: LegoType args?: any[] } const useLego = function () { const [legos, setLegos]: [Lego[], any] = useState([]) const updateLego = (l: Lego) => { const newLegos = legos.map((x) => { if (x.id === l.id) { return l } return x }) setLegos(newLegos) } const appendLegos = (l: Lego[]) => { setLegos([...legos, ...l]) } const appendLego = (lego: Lego) => { setLegos([...legos, lego]) } const removeLego = (lego: Lego) => { setLegos(legos.filter((x) => x.id !== lego.id)) } return { legos, setLegos, appendLego, appendLegos, updateLego, removeLego, } } export default createContainer(useLego)
addc6cf4974c8d805cf37a7e7ea2d058799759ff
TypeScript
jifeon/sval
/src/state/symbols.ts
3.296875
3
import { hasOwn } from '../share/utils' type VarType = 'var' | 'let' | 'const' interface VarSymbol { type: VarType pointer: number } interface SymbolMap { [name: string]: VarSymbol } export default class SymbolTable { private table: SymbolMap = Object.create(null) private pointer: number = 0 private readonly tableChain: SymbolMap[] = [] private readonly pointerChain: number[] = [] readonly globalVarName: { [pointer: number]: string } = {} type: VarType = null hoist: boolean = false set(name: string, type: VarType = this.type): VarSymbol { if (this.hoist) { // just hoisting variable if (hasOwn(this.table, name)) { const variable = this.table[name] // allow multiple declarations of var if (variable.type !== 'var' || type !== 'var') { throw new SyntaxError(`Identifier '${name}' has already been declared`) } } else if (type === 'var') { const pointer = this.pointer++ // if hoisting var, directly allocate a new pointer this.table[name] = { type: type, pointer } // save names for all top scope var declaration if (!this.tableChain.length) { this.globalVarName[pointer] = name } } else { this.table[name] = null } } else if (type === 'var' && this.table[name]) { // has allocated for var when hoisting, just return return this.table[name] } else { // type === 'const' || type === 'let' // real declaration, allocate a new pointer for const and let return this.table[name] = { type: type, pointer: this.pointer++ } } } get(name: string) { if (this.table[name]) { return this.table[name] } else { throw new ReferenceError(`${name} is not defined`) } } pushScope() { this.tableChain.push(this.table) this.pointerChain.push(this.pointer) this.table = Object.create(this.table) } popScope() { this.table = this.tableChain.pop() this.pointer = this.pointerChain.pop() } }
cbaacce6d4c9eb919a94ed56b055645ae9895288
TypeScript
simrit1/oito
/src/geometry/Tetrahedron.ts
3.03125
3
import UniqueVertexGeo from "./extra/UniqueVertexGeo.js"; import Util from "./extra/Util.js"; class Tetrahedron { static get( div=0, radius=1 ) : TGeo{ //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ const base: TGeo = { texcoord : [], normals : [], indices : [ 2,1,0, 0,3,2, 1,3,0, 2,3,1 ], vertices : [ 1,1,1, -1,-1,1, -1,1,-1, 1,-1,-1 ], }; if( div == 0 ){ Util.normalizeScaleVertices( base, radius, true ); return base; } //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ const uvg = new UniqueVertexGeo(); uvg.subdivGeo( base, div+1 ); // Sub Divide Basic Shape without creating duplicate vertices Util.normalizeScaleVertices( uvg.geo, radius, true ); // Make the shape a sphere & create normals in the process. return uvg.geo; } } export default Tetrahedron;
2a15c1fd8b21a1051210e036387f6926036d8fef
TypeScript
tenna-llc/jest-coverage-report-action
/src/collect/counters.ts
2.859375
3
import { FileCoverage } from '../typings/JsonReport'; export const standardTotalCounter = (key: keyof FileCoverage) => ( value: FileCoverage ) => Object.values(value[key]).length; export const standardCoveredCounter = (key: keyof FileCoverage) => ( value: FileCoverage ) => Object.values(value[key]).filter((hits) => hits > 0).length; export const totalBranchesCounter = (value: FileCoverage) => Object.values(value.b).reduce((acc, branch) => acc + branch.length, 0); export const coveredBranchesCounter = (value: FileCoverage) => Object.values(value.b).reduce( (acc, branch) => acc + branch.filter((hits) => hits > 0).length, 0 ); const lineDiff = (startLine: number, endLine: number, lastEndLine: number) => Math.max(endLine - Math.max(startLine, lastEndLine), 0); export const totalLinesCounter = (value: FileCoverage) => { let lastEndLine = 0; return Object.values(value.statementMap).reduce((acc, statement) => { const newLines = lineDiff( statement.start.line, statement.end.line, lastEndLine ); lastEndLine = Math.max(statement.end.line, lastEndLine); return acc + newLines; }, 0); }; export const coveredLinesCounter = (value: FileCoverage) => { let lastEndLine = 0; const totalLines = totalLinesCounter(value); const notCoveredLines = Object.entries(value.statementMap).reduce( (acc, [key, statement]) => { if (value.s[+key] <= 0) { const newLines = lineDiff( statement.start.line, statement.end.line, lastEndLine ); lastEndLine = Math.max(statement.end.line, lastEndLine); return acc + newLines; } return acc; }, 0 ); return Math.max(0, totalLines - notCoveredLines); };
04f663b08a485b908a44ee5ac77e95c3e9438c99
TypeScript
jogboms/EziNote
/src/app/library/store/store.ts
3.28125
3
import {Observable} from "rxjs/Observable"; import {BehaviorSubject} from "rxjs/BehaviorSubject"; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/scan'; import 'rxjs/add/operator/distinctUntilChanged'; /** * Initial initializer Action for All Reducer functions within the Store * @type {String} */ export const INIT_ACTION = 'INIT_ACTION'; /** * States of state for the Store * @type {Object} */ export type States = {[name: string]: any}; /** * Action-type for Reducer */ export interface Action { type: string; payload?: any; } /** * Reducer-type function * @type {any} */ export type Reducer<T> = (state: T, action: Action) => T; /** * Helper function Factory to create a Store * @param reducers * @param initialStates * @param debug */ export const __createStore = ( reducers: {[name: string] : Reducer<any>}, initialStates: States = {}, debug: number = 3 ) => new Store(reducers, initialStates, debug); export class Store<T> extends BehaviorSubject<T> { /** * An Object of Reducers in the Store */ private reducers: {[name: string]: BehaviorSubject<any>} = {}; /** * Debug mode of the store * @type {number} */ private debug: number; /** * Create a new Store of States * @param {{[name: string]: Reducer<any>}} reducers Object containing Reducer name and Reducer function * @param {T} initialStates Initial States to pass into the Store * @param {number = 3} debug Select debug mode. 0, 1, 2 or 3 */ constructor(reducers: {[name: string]: Reducer<any>}, initialStates: T, debug: number = 3) { super(initialStates); this.debug = debug; if(reducers){ this.reducers = Object.keys(reducers).reduce((p, n) => { const reducer = reducers[n]; if(typeof reducer === 'function'){ const initialState = initialStates.hasOwnProperty(n) ? initialStates[n]: undefined; p[n] = new BehaviorSubject<any>(reducer(initialState, {type: INIT_ACTION})); p[n].scan(reducer).distinctUntilChanged() .subscribe(s => super.next(Object.assign({}, this.state, {[n]: s}))); } return p; }, this.reducers); } } /** * Get a stream of a particular state * @param {string} name Name of state provided at initialization * @return {Observable<any>} Stream of reducer state when new Actions are dispatched */ select(name: string): Observable<any>{ return this.map(states => states[name]).distinctUntilChanged(); } /** * Get all States within the Store * @return {T} States Object */ get state(): T { return this.value; } /** * Dispatch action to the Store's reducers * @param {Action} action Action object to dispatch */ dispatch(action: Action){ switch (this.debug) { case 3: console.trace('%c'+action.type, 'color:green', action.payload, this.state); break; case 2: console.trace('%c'+action.type, 'color:green', action.payload); break; case 1: console.trace('%c'+action.type, 'color:green'); break; } Object.keys(this.reducers).forEach(n => this.reducers[n].next(action)); } }
b5a656e49dff62ee7062cdcde5889d1abecb84ed
TypeScript
masak/taocp
/src/ch2.2.4/ex5/circular-list.ts
3.75
4
export interface CircularList<T> { ptr: ListNode<T> | NullLink; } export interface ListNode<T> { info: T; link: ListNode<T>; } export enum NullLink { NULL, } export const Λ = NullLink.NULL; function nodePointingToItself<T>(info: T): ListNode<T> { let node = { info, link: (Λ as any) as ListNode<T> }; node.link = node; return node; } // Builds a circular list from a set of values. Just a convenience // function so that we don't have to write the object literals out. export function makeCircularList<T>(...values: T[]): CircularList<T> { if (values.length === 0) { return { ptr: Λ }; } let rightmostNode = nodePointingToItself(values[values.length - 1]); let leftmostNode = values.slice(0, values.length - 1).reduceRight( (nextNode: ListNode<T>, info: T): ListNode<T> => ({ info, link: nextNode, }), rightmostNode, ); rightmostNode.link = leftmostNode; return { ptr: rightmostNode, }; }
dfe4dc343dd358d843598ba1d393effc8e4cd391
TypeScript
Tollwood/got-store
/src/model/orderToken/orderToken.d.ts
2.546875
3
import { House } from '../player/house'; import { OrderTokenType } from './orderTokenType'; export declare class OrderToken { private house; private type; private _value; constructor(house: House, type: OrderTokenType); getHouse(): House; getType(): OrderTokenType; readonly value: number; isMoveToken(): boolean; isConsolidatePowerToken(): boolean; isRaidToken(): boolean; isDefendToken(): boolean; private static getValue(type); }
beb70ca832699b0904331ecadd76d00034b354e3
TypeScript
ShenBao/angular-demo
/server/app/app.ts
2.734375
3
import * as express from "express"; import * as path from "path"; import {Server} from "ws"; const app = express(); app.use('/', express.static(path.join(__dirname, '..', 'client'))) app.get('/api/stock', (req, res) => { let result = stocks; let params = req.query; if(params.nam){ result = result.filter(stock => stock.name.indexOf(params.name) !== -1); } res.json(result); }); app.get('/api/stock/:id', (req, res) => { res.json(stocks.find(stock => stock.id == req.params.id)); }); const server = app.listen(8000, 'localhost', () => { console.log('服务器已启动,地址是:http://localhost:8000'); }); var subscriptions = new Set<any>(); const wsServer = new Server({port: 8085}); wsServer.on("connection", websocket => { subscriptions.add(websocket); }); var messageCount = 0; setInterval(() => { subscriptions.forEach(ws => { if(ws.readyState === 1){ ws.send(JSON.stringify({messageCount: messageCount++})); }else{ subscriptions.delete(ws); } }) }, 2000); export class Stock { constructor(public id: number, public name: string, ) { } } const stocks: Stock[] = [ new Stock(1, "第一个"), new Stock(2, "第二个"), new Stock(3, "第三个"), new Stock(4, "第四个"), new Stock(5, "第五个"), new Stock(8, "第八个"), new Stock(9, "第九个"), ];
8fcf7465bf7b3b069136fe29a56a6663c10921ad
TypeScript
mudakikwa/typescript-crash
/app.ts
3.046875
3
let sum:(a:number,b:number,c?:number) => number const calcSum=(number1:number,number2:number) =>{ return number1+number2 } calcSum(1,2,3)
3c8ea309cf570087b810b072d60594310f7b49ea
TypeScript
BDav24/recipe-markdown
/src/recipeToMarkdown/ustensilsToMarkdown.ts
2.671875
3
import { Ustensil } from '../types' import { isEmptyOrEmptyArray, joinNotEmpty, isNotEmpty } from '../utils' import mediaToMarkdown, { getMediaType } from './mediaToMarkdown' export default function ustensilsToMarkdown(ustensils: Ustensil[]): string { if (isEmptyOrEmptyArray(ustensils)) return '' return joinNotEmpty( ['## Ustensils', joinNotEmpty(ustensils.map(ustensilToMarkdown), '\n')], '\n\n' ) } const ustensilToMarkdown = (ustensil: Ustensil): string => { const { media, quantity, label } = ustensil const isMediaLink = isNotEmpty(media) && getMediaType(media) === 'link' return joinNotEmpty( [ '-', isMediaLink ? null : mediaToMarkdown(media), quantity, label, isMediaLink ? mediaToMarkdown(media) : null ], ' ' ) }
1098762659841490d1317b6ba04094a8b0918fbd
TypeScript
nguyer/aws-sdk-js-v3
/clients/node/client-support-node/types/_Attachment.ts
2.8125
3
/** * <p>An attachment to a case communication. The attachment consists of the file name and the content of the file.</p> */ export interface _Attachment { /** * <p>The name of the attachment file.</p> */ fileName?: string; /** * <p>The content of the attachment file.</p> */ data?: ArrayBuffer | ArrayBufferView | string; } export interface _UnmarshalledAttachment extends _Attachment { /** * <p>The content of the attachment file.</p> */ data?: Uint8Array; }
6f1b59f724db2ccb710b5ef9c4e526a09c754a47
TypeScript
Jacks128/tytusx
/20211SVAC/G35/codigof/src/ejecucion/if.ts
2.640625
3
import { Instruccion } from "./instruccion"; export class If { condicion: Instruccion; instrucciones: Array<Instruccion>; constructor(condicion: Instruccion, instrucciones: Array<Instruccion>){ Object.assign(this, {condicion, instrucciones}); } }
06421c7b85fffd69b1ca64880f9081954a4f5dbf
TypeScript
narapov/TypeMonPress
/config/passport.ts
2.671875
3
import passport = require("passport"); import passportLocal = require("passport-local"); import { IUser, userModel } from "../models"; import { Request, Response, NextFunction } from "express"; const LocalStrategy = passportLocal.Strategy; passport.serializeUser<IUser, String>((user, done) => done(undefined, user.id)); passport.deserializeUser<IUser, String>((id, done) => { userModel.findById(id, (err, user) => { if (user) done(err, user); else done(new Error("User Not Found")); }); }); /** * Sign in using Email and Password. */ passport.use( new LocalStrategy({ usernameField: "email" }, (email, password, done) => { userModel.findOne({ email: email.toLowerCase() }, (err, user) => { if (err) return done(err); if (!user) return done(undefined, false, { message: `Email ${email} not found.` }); if (user.password === password) return done(undefined, user); else return done(undefined, false, { message: "Invalid email or password." }); }); }) );
d204b6cb293a044edff25dd793aca84063a4cf7d
TypeScript
ioaNikas/blockframes
/libs/movie/src/lib/movie/+state/movie.query.ts
2.578125
3
import { Injectable } from '@angular/core'; import { QueryEntity } from '@datorama/akita'; import { MovieStore, MovieState } from './movie.store'; import { Movie, MovieSale } from './movie.model'; @Injectable({ providedIn: 'root' }) export class MovieQuery extends QueryEntity<MovieState, Movie> { // @todo #643 call it "form" instead of "akitaForm" as we're already looking into the state. movieFormChanges$ = this.select(state => state.akitaForm as Movie); constructor(protected store: MovieStore) { super(store); } /** * @param internalRef */ public existingMovie(internalRef: string) : Movie { return this.getAll().find(entity => entity.main.internalRef === internalRef ); } /** * Checks if a sale is already existing for a given movie and returns it. * We use internalRef (ie: film code) to retreive movie since this ID is the one used in * spreadsheets files. * @param internalRef * @param sale */ public existingSale(internalRef: string, sale: MovieSale): MovieSale { try { const movie = this.existingMovie(internalRef); return movie.sales.find(entity => entity.operatorName === sale.operatorName && entity.showOperatorName === sale.showOperatorName && new Date(entity.rights.from).getTime() === sale.rights.from.getTime() && new Date(entity.rights.to).getTime() === sale.rights.to.getTime() && entity.exclusive === sale.exclusive && entity.price === sale.price && entity.medias.length === sale.medias.length && entity.medias.slice().sort().every((value, index) => value === sale.medias.sort()[index]) && entity.dubbings.length === sale.dubbings.length && entity.dubbings.slice().sort().every((value, index) => value === sale.dubbings.sort()[index]) && entity.subtitles.length === sale.subtitles.length && entity.subtitles.slice().sort().every((value, index) => value === sale.subtitles.sort()[index]) && entity.territories.length === sale.territories.length && entity.territories.slice().sort().every((value, index) => value === sale.territories.sort()[index]) ); } catch (e) { console.error(e.message); } } }