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
6a01eda2f26ea3d2ca6e6c9963ce484e7c9ef883
TypeScript
catflinger/heating-controller
/test/program/program-spec.ts
2.78125
3
import { IControllerSettings, IProgram, INJECTABLES, ProgramSnapshot } from "../../src/controller/types"; import { Program } from "../../src/controller/program"; import { container } from "./inversify.config.test"; import * as fs from "fs"; import * as chai from "chai"; import "mocha"; const expect = chai.expect; let program: IProgram; let max: number; let min: number; let slotsPerDay = container.get<number>(INJECTABLES.SlotsPerDay); const minHWTemp = 40; const maxHWTemp = 50; describe("program", () => { before(() => { const json: string = '{"id":"id123","name":"some name","maxHWTemp":50,"minHWTemp":40,"slots":[true,false,true,false,true,false,false,false,false,false]}'; program = container.get<IProgram>(INJECTABLES.Program); program.loadFromSnapshot(JSON.parse(json)); min = 0; max = slotsPerDay - 1; }); it("should construct", () => { expect(program).not.to.be.undefined; }); it("shoud have loaded from valid JSON", () => { expect(program.minHWTemp).to.equal(40, "wrong value for minHWTemp"); expect(program.maxHWTemp).to.equal(50, "wrong value for maxHWTemp"); expect(program.getValue(0)).to.equal(true, "wrong value for slot 0"); expect(program.getValue(1)).to.equal(false, "wrong value for slot 1"); expect(program.getValue(9)).to.equal(false, "wrong value for slot 9"); }); it("should return hot water thresholds", () => { expect(program.minHWTemp).to.equal(minHWTemp, "wrong value for min hw teperature"); expect(program.maxHWTemp).to.equal(maxHWTemp, "wrong value for max hw teperature"); }); it("should return a heating slot value in range", () => { // lower bound for index expect(program.getValue(min)).to.equal(true, "wrong value for min slot number"); // in-range index expect(program.getValue(min + 3)).to.equal(false, "wrong value for mid slot number"); // upper bound for index expect(program.getValue(max)).to.equal(false, "wrong value for max slot number"); }); it("should refuse to return a heating slot value out of range", () => { expect(() => program.getValue(min - 1)).to.throw(); expect(() => program.getValue(max + 1)).to.throw(); expect(() => program.getValue(200000)).to.throw(); }); it("should set a range of values", () => { program.setRange([true, true, false, true, true], 1, 5); expect(program.getValue(0)).to.equal(true, "slot 0 set unexpctedly"); expect(program.getValue(1)).to.equal(true, "slot 1 not set"); expect(program.getValue(2)).to.equal(true, "slot 2 not set"); expect(program.getValue(3)).to.equal(false, "slot 3 not set"); expect(program.getValue(4)).to.equal(true, "slot 4 not set"); expect(program.getValue(5)).to.equal(true, "slot 5 not set"); expect(program.getValue(6)).to.equal(false, "slot 6 set unexpectedly"); }); it("should set a single value", () => { program.setRange([true], min, min); expect(program.getValue(min)).to.equal(true, "slot 0 set unexpctedly"); program.setRange([true], min, min); expect(program.getValue(min)).to.equal(true, "slot 0 set unexpctedly"); program.setRange([true], min, min); expect(program.getValue(min)).to.equal(true, "slot 0 set unexpctedly"); }); it("should refuse to set an invalid range", () => { // below start of valid valid expect(() => program.setRange([false], min - 1, min)).to.throw(); // above start of valid values expect(() => program.setRange([false], max, max + 1)).to.throw(); // too few values expect(() => program.setRange([false, false], 1, 3)).to.throw(); // range specified backwards expect(() => program.setRange([false, false, true], 3, 1)).to.throw(); }); it("shoud serialise to JSON", () => { // set some program values program.setRange([true, false], 1, 2); //serialse the program const json: string = program.getSnapshot().toJson(); expect(json).to.be.not.null; expect(json.length).to.be.greaterThan(0, "zero length string produced"); // rehydrate the json to an object const obj: ProgramSnapshot = ProgramSnapshot.fromJson(json); // check the object contains the original program values expect(obj.id).to.equal("id123"); expect(obj.name).to.equal("some name"); expect(obj.minHWTemp).to.equal(minHWTemp); expect(obj.maxHWTemp).to.equal(maxHWTemp); expect(obj.slots.length).to.equal(slotsPerDay); expect(obj.slots[1]).to.equal(true, "wrong value for slot 1"); expect(obj.slots[2]).to.equal(false, "wrong value for slot 2"); }); it("shoud refuse to load from invalid JSON", () => { // slot array missing let json: string = '{"maxHWTemp":55,"minHWTemp":45}'; expect(() => program.loadFromSnapshot(ProgramSnapshot.fromJson(json))).to.throw(); // slot array not an array json = '{"maxHWTemp":55,"minHWTemp":45,"slots": "foo"}'; expect(() => program.loadFromSnapshot(ProgramSnapshot.fromJson(json))).to.throw(); // array too short // json = '{"maxHWTemp":55,"minHWTemp":45,"slots":[true, false]}'; // expect(() => program.loadFromSnapshot(ProgramSnapshot.fromJson(json))).to.throw(); // array contains invalid fields json = '{"maxHWTemp":55,"minHWTemp":45,"slots":[1,0,true,false,true,false,false,false,false,false]}'; expect(() => program.loadFromSnapshot(ProgramSnapshot.fromJson(json))).to.throw(); // minHWTemp missing json = '{"maxHWTemp":45,"slots":[true,false,true,false,true,false,false,false,false,false]}'; expect(() => program.loadFromSnapshot(ProgramSnapshot.fromJson(json))).to.throw(); // minHWTemp not numeric json = '{"maxHWTemp":55,"minHWTemp":"45","slots":[true,false,true,false,true,false,false,false,false,false]}'; expect(() => program.loadFromSnapshot(ProgramSnapshot.fromJson(json))).to.throw(); // minHWTemp too low json = '{"maxHWTemp":55,"minHWTemp":0,"slots":[true,false,true,false,true,false,false,false,false,false]}'; expect(() => program.loadFromSnapshot(ProgramSnapshot.fromJson(json))).to.throw(); // minHWTemp too low json = '{"maxHWTemp":55,"minHWTemp":61,"slots":[true,false,true,false,true,false,false,false,false,false]}'; expect(() => program.loadFromSnapshot(ProgramSnapshot.fromJson(json))).to.throw(); // maxHWTemp missing json = '{"minHWTemp":45,"slots":[true,false,true,false,true,false,false,false,false,false]}'; expect(() => program.loadFromSnapshot(ProgramSnapshot.fromJson(json))).to.throw(); // maxHWTemp not numeric json = '{"maxHWTemp":"55","minHWTemp":45,"slots":[true,false,true,false,true,false,false,false,false,false]}'; expect(() => program.loadFromSnapshot(ProgramSnapshot.fromJson(json))).to.throw(); // maxHWTemp too low json = '{"maxHWTemp":0,"minHWTemp":45,"slots":[true,false,true,false,true,false,false,false,false,false]}'; expect(() => program.loadFromSnapshot(ProgramSnapshot.fromJson(json))).to.throw(); // minHWTemp too low json = '{"maxHWTemp":61,"minHWTemp":45,"slots":[true,false,true,false,true,false,false,false,false,false]}'; expect(() => program.loadFromSnapshot(ProgramSnapshot.fromJson(json))).to.throw(); // minHWTemp and max too close json = '{"maxHWTemp":45,"minHWTemp":45,"slots":[true,false,true,false,true,false,false,false,false,false]}'; expect(() => program.loadFromSnapshot(ProgramSnapshot.fromJson(json))).to.throw(); // minHWTemp and max too close json = '{"maxHWTemp":48,"minHWTemp":45,"slots":[true,false,true,false,true,false,false,false,false,false]}'; expect(() => program.loadFromSnapshot(ProgramSnapshot.fromJson(json))).to.throw(); // minHWTemp and max wrong order json = '{"maxHWTemp":45,"minHWTemp":55,"slots":[true,false,true,false,true,false,false,false,false,false]}'; expect(() => program.loadFromSnapshot(ProgramSnapshot.fromJson(json))).to.throw(); }); });
f2f19e40555cbd56413ded3a44b7e8d8cb1d1bfb
TypeScript
Sergey-lang/Notes-react-app
/src/n-1-Api/api.ts
2.5625
3
import axios from 'axios' import {NoteType} from '../n-2-Redux/notes-reducer'; import {TagType} from '../n-2-Redux/tags-reducer'; const defaultOptions = { withCredentials: true, headers: { Accept: 'application/json', } } const axiosInstance = axios.create(defaultOptions); export const notesAPI = { getNotes() { return axiosInstance.get<NoteType[]>(`/notes`) .then(res => res) }, addNote(newNote: NoteType) { return axiosInstance.post(`/notes`, newNote) .then(res => res) }, deleteNote(id: string) { return axiosInstance.delete(`/notes/${id}`) .then(res => res) }, changeNote(updateNoteObj: NoteType) { return axiosInstance.put(`/notes/${updateNoteObj.id}`, updateNoteObj) .then(res => res) }, } export const tagsAPI = { getTags() { return axiosInstance.get(`/tags`) .then(res => res) }, addTag(tag: TagType) { return axiosInstance.post(`/tags`, tag) .then(res => res) }, deleteTag(tagId: string) { return axiosInstance.delete(`/tags/${tagId}`) .then(res => res) }, }
3aeae887e5464816aaddee9640004c026eabc43f
TypeScript
js/apollo-tooling
/packages/apollo/src/commands/client/push.ts
2.546875
3
import { createHash } from "crypto"; import { printWithReducedWhitespace, sortAST, defaultSignature as engineDefaultSignature } from "apollo-engine-reporting"; import { visit, DocumentNode, IntValueNode, FloatValueNode, StringValueNode } from "graphql"; import { ClientCommand } from "../../Command"; const manifestOperationHash = (str: string): string => createHash("sha256") .update(str) .digest("hex"); const engineSignature = (_TODO_operationAST: DocumentNode): string => { // TODO. We don't currently have access to the operation name since it's // currently omitted by the `apollo-codegen-core` package logic. return engineDefaultSignature(_TODO_operationAST, "TODO"); }; // In the same spirit as the similarly named `hideLiterals` function from the // `apollo-engine-reporting/src/signature.ts` module, we'll do an AST visit // to redact literals. Developers are strongly encouraged to use the // `variables` aspect of the which would avoid these being explicitly // present in the operation manifest at all. The primary area of concern here // is to avoid sending in-lined literals which might contain sensitive // information (e.g. API keys, etc.). export function hideCertainLiterals(ast: DocumentNode): DocumentNode { return visit(ast, { IntValue(node: IntValueNode): IntValueNode { return { ...node, value: "0" }; }, FloatValue(node: FloatValueNode): FloatValueNode { return { ...node, value: "0" }; }, StringValue(node: StringValueNode): StringValueNode { return { ...node, value: "", block: false }; } }); } export default class ServicePush extends ClientCommand { static description = "Push a service to Engine"; static flags = { ...ClientCommand.flags }; async run() { const { clientIdentity, operations, serviceName }: any = await this.runTasks(({ flags, project, config }) => [ { title: "Pushing client information to Engine", task: async ctx => { if (!config.name) { throw new Error("No service found to link to Engine"); } const operations = Object.values( this.project.mergedOperationsAndFragmentsForService ).map(operationAST => { // While this could include dropping unused definitions, they are // kept because the registered operations should mirror those in the // client bundle minus any PII which lives within string literals. const printed = printWithReducedWhitespace( sortAST(hideCertainLiterals(operationAST)) ); return { signature: manifestOperationHash(printed), document: printed, metadata: { engineSignature: engineSignature(operationAST) } }; }); const { name, referenceID, version } = config.client!; if (!name) { throw new Error("Client name is required to push"); } const variables = { clientIdentity: { name: name, identifier: referenceID || name, version }, id: config.name, operations }; await project.engine.registerOperations(variables); // store data for logging ctx.operations = operations; ctx.serviceName = variables.id; ctx.clientIdentity = variables.clientIdentity; } } ]); this.log( `Successfully pushed ${operations.length} operations from the ${ clientIdentity.name } client to the ${serviceName} service in Engine` ); } }
0a2198e1395484be66c3aa8c0c3cc970cebd7b97
TypeScript
dwchiang/aws-cdk
/packages/@aws-cdk/aws-lambda-nodejs/lib/bundling.ts
2.53125
3
import * as fs from 'fs'; import * as path from 'path'; import * as lambda from '@aws-cdk/aws-lambda'; import * as cdk from '@aws-cdk/core'; import { PackageJsonManager } from './package-json-manager'; import { findUp } from './util'; /** * Base options for Parcel bundling */ export interface ParcelBaseOptions { /** * Whether to minify files when bundling. * * @default false */ readonly minify?: boolean; /** * Whether to include source maps when bundling. * * @default false */ readonly sourceMaps?: boolean; /** * The cache directory * * Parcel uses a filesystem cache for fast rebuilds. * * @default - `.cache` in the root directory */ readonly cacheDir?: string; /** * The root of the project. This will be used as the source for the volume * mounted in the Docker container. If you specify this prop, ensure that * this path includes `entry` and any module/dependencies used by your * function otherwise bundling will not be possible. * * @default - the closest path containing a .git folder */ readonly projectRoot?: string; /** * Environment variables defined when Parcel runs. * * @default - no environment variables are defined. */ readonly parcelEnvironment?: { [key: string]: string; }; /** * A list of modules that should be considered as externals (already available * in the runtime). * * @default ['aws-sdk'] */ readonly externalModules?: string[]; /** * A list of modules that should be installed instead of bundled. Modules are * installed in a Lambda compatible environnment. * * @default - all modules are bundled */ readonly nodeModules?: string[]; /** * The version of Parcel to use. * * @default - 2.0.0-beta.1 */ readonly parcelVersion?: string; /** * Build arguments to pass when building the bundling image. * * @default - no build arguments are passed */ readonly buildArgs?: { [key:string] : string }; } /** * Options for Parcel bundling */ export interface ParcelOptions extends ParcelBaseOptions { /** * Entry file */ readonly entry: string; /** * The runtime of the lambda function */ readonly runtime: lambda.Runtime; } /** * Bundling */ export class Bundling { /** * Parcel bundled Lambda asset code */ public static parcel(options: ParcelOptions): lambda.AssetCode { // Find project root const projectRoot = options.projectRoot ?? findUp(`.git${path.sep}`); if (!projectRoot) { throw new Error('Cannot find project root. Please specify it with `projectRoot`.'); } // Bundling image derived from runtime bundling image (AWS SAM docker image) const image = cdk.BundlingDockerImage.fromAsset(path.join(__dirname, '../parcel'), { buildArgs: { ...options.buildArgs ?? {}, IMAGE: options.runtime.bundlingDockerImage.image, PARCEL_VERSION: options.parcelVersion ?? '2.0.0-beta.1', }, }); const packageJsonManager = new PackageJsonManager(path.dirname(options.entry)); // Collect external and install modules let includeNodeModules: { [key: string]: boolean } | undefined; let dependencies: { [key: string]: string } | undefined; const externalModules = options.externalModules ?? ['aws-sdk']; if (externalModules || options.nodeModules) { const modules = [...externalModules, ...options.nodeModules ?? []]; includeNodeModules = {}; for (const mod of modules) { includeNodeModules[mod] = false; } if (options.nodeModules) { dependencies = packageJsonManager.getVersions(options.nodeModules); } } // Configure target in package.json for Parcel packageJsonManager.update({ 'cdk-lambda': `${cdk.AssetStaging.BUNDLING_OUTPUT_DIR}/index.js`, 'targets': { 'cdk-lambda': { context: 'node', includeNodeModules: includeNodeModules ?? true, sourceMap: options.sourceMaps ?? false, minify: options.minify ?? false, engines: { node: `>= ${runtimeVersion(options.runtime)}`, }, }, }, }); // Entry file path relative to container path const containerEntryPath = path.join(cdk.AssetStaging.BUNDLING_INPUT_DIR, path.relative(projectRoot, path.resolve(options.entry))); const parcelCommand = [ '$(node -p "require.resolve(\'parcel\')")', // Parcel is not globally installed, find its "bin" 'build', containerEntryPath.replace(/\\/g, '/'), // Always use POSIX paths in the container '--target', 'cdk-lambda', '--no-autoinstall', '--no-scope-hoist', ...options.cacheDir ? ['--cache-dir', '/parcel-cache'] : [], ].join(' '); let installer = Installer.NPM; let lockfile: string | undefined; let depsCommand = ''; if (dependencies) { // Create a dummy package.json for dependencies that we need to install fs.writeFileSync( path.join(projectRoot, '.package.json'), JSON.stringify({ dependencies }), ); // Use npm unless we have a yarn.lock. if (fs.existsSync(path.join(projectRoot, LockFile.YARN))) { installer = Installer.YARN; lockfile = LockFile.YARN; } else if (fs.existsSync(path.join(projectRoot, LockFile.NPM))) { lockfile = LockFile.NPM; } // Move dummy package.json and lock file then install depsCommand = chain([ `mv ${cdk.AssetStaging.BUNDLING_INPUT_DIR}/.package.json ${cdk.AssetStaging.BUNDLING_OUTPUT_DIR}/package.json`, lockfile ? `cp ${cdk.AssetStaging.BUNDLING_INPUT_DIR}/${lockfile} ${cdk.AssetStaging.BUNDLING_OUTPUT_DIR}/${lockfile}` : '', `cd ${cdk.AssetStaging.BUNDLING_OUTPUT_DIR} && ${installer} install`, ]); } return lambda.Code.fromAsset(projectRoot, { assetHashType: cdk.AssetHashType.BUNDLE, bundling: { image, command: ['bash', '-c', chain([parcelCommand, depsCommand])], environment: options.parcelEnvironment, volumes: options.cacheDir ? [{ containerPath: '/parcel-cache', hostPath: options.cacheDir }] : [], workingDirectory: path.dirname(containerEntryPath).replace(/\\/g, '/'), // Always use POSIX paths in the container }, }); } } enum Installer { NPM = 'npm', YARN = 'yarn', } enum LockFile { NPM = 'package-lock.json', YARN = 'yarn.lock' } function runtimeVersion(runtime: lambda.Runtime): string { const match = runtime.name.match(/nodejs(\d+)/); if (!match) { throw new Error('Cannot extract version from runtime.'); } return match[1]; } function chain(commands: string[]): string { return commands.filter(c => !!c).join(' && '); }
464f3f7a5ab442f8015c44ab1581df2363ea8cda
TypeScript
gaohejin/ynm3000
/src/intersectionWith.ts
3.015625
3
import last from './last' import map from './map' import castArrayLikeObject from './internal/castArrayLikeObject' import baseIntersection from './internal/baseIntersection' /** * 比较数组取相似结果 * @param arrays */ function intersectionWith(...arrays) { let comparator = last(arrays) const mapped = map(arrays, castArrayLikeObject) comparator = typeof comparator === 'function' ? comparator : undefined if (comparator) { mapped.pop() } return arrays.length && arrays[0] === mapped[0] ? baseIntersection(mapped, undefined, comparator) : [] } export default intersectionWith
fa93dae553537e1d24ec2e5f48b413344845dc93
TypeScript
TextC0de/formify
/server/model/user/user.model.ts
2.71875
3
import bcrypt from 'bcrypt'; import { Document, Schema, model } from 'mongoose'; export const UserSchemaName = 'User'; export interface User extends Document { readonly username: string; readonly password: string; readonly forms: [string]; readonly token?: string; readonly created: Date; readonly lastModified: Date; } export const UserSchema = new Schema<User>( { username: { type: String, unique: true, match: /^[a-zA-Z0-9\-]+$/, required: true }, password: { type: String, minlength: 8, required: true }, token: { type: String } }, { timestamps: { createdAt: 'created', updatedAt: 'lastModified' } } ); UserSchema.methods.comparePassword = function (password) { return bcrypt.compareSync(password, this.password); }; const UserModel = model(UserSchemaName, UserSchema); export default UserModel;
27921a0d00cbd7e669fdd9cf7c79be70238771f6
TypeScript
corbanbrook/datapack
/tests/unit/Schema.test.ts
2.921875
3
import { Schema, Component, Type } from '../../src' test('Create schema with diffing', () => { const schema = new Schema( 1, 'thing', [ new Component('loc', Type.Array(Type.Float32, 2)), new Component('vel', Type.Array(Type.Float32, 2)), new Component('rot', Type.Float32) ], { diff: true } ) expect(schema.id).toBe(1) expect(schema.name).toBe('thing') expect(schema.components.size).toBe(3) expect(schema.byteLength).toBe(8 + 8 + 4 + 6) expect(schema.get('loc').flag).toBe(1) expect(schema.get('vel').flag).toBe(2) expect(schema.get('rot').flag).toBe(4) }) test('Create schema without diffing', () => { const schema = new Schema( 1, 'thing', [ new Component('loc', Type.Array(Type.Float32, 2)), new Component('vel', Type.Array(Type.Float32, 2)), new Component('rot', Type.Float32) ], { diff: false } ) expect(schema.id).toBe(1) expect(schema.name).toBe('thing') expect(schema.components.size).toBe(3) expect(schema.byteLength).toBe(8 + 8 + 4 + 4) expect(schema.get('loc').flag).toBe(1) expect(schema.get('vel').flag).toBe(2) expect(schema.get('rot').flag).toBe(4) })
aa443a08f5097acd420df5227eaebacb6aaa4f66
TypeScript
b54690/Final-Assessment
/server/src/students/controller.ts
2.640625
3
import { Authorized, Post, Param, HttpCode, Get, Body, JsonController, Put, NotFoundError, Delete} from 'routing-controllers' import Student from './entity'; import * as request from 'superagent' @JsonController() export default class StudentController { @Get('/students') async all() { const students = await Student.find() if (!students) throw new NotFoundError('There are no students') return { students } } @Get('/studentsbyclass/:id([0-9]+)') @HttpCode(201) getStudentsByClass( @Param('id') batchId: number ) { let studentsByClass = Student.find( {batchId: batchId} ) return studentsByClass } @Authorized() @Post('/students') @HttpCode(201) async addStudent( @Body() student: Student ) { const entity = await student.save() return entity } @Get('/students/:id') async student( @Param('id') id: number ) { const student = await Student.findOne(id) return { student } } @Authorized() @Put('/students/:id') async updateStudent( @Param('id') id: number, @Body() update: Partial<Student> ) { const student = await Student.findOne(id) if (!student) throw new NotFoundError('Student was not found') const studentUpdated = Student.merge(student, update) const entity = await studentUpdated.save() return entity } @Authorized() @Delete('/students/:id') async deleteStudent( @Param('id') id: number ) { const student = await Student.findOne(id) if (!student) throw new NotFoundError('Student was not found') if (student) Student.remove(student) return 'Student was deleted successfully' } }
4ba5aea03ed2c21ffb4b1b9b2ef91b3f8c0ba66c
TypeScript
dillonjason/resume-service
/src/data/schema/experience.ts
2.734375
3
import { Schema, Document, Model, model } from "mongoose"; import { SkillDocument, SkillModel } from "./skill"; interface Experience { company: string; position: string; start: Date; end?: Date; skills: SkillDocument[]; responsibilities: string[]; } export interface ExperienceDocument extends Experience, Document {} export type ExperienceModel = Model<ExperienceDocument>; const ExperienceSchema = new Schema<ExperienceDocument, ExperienceModel>({ company: { type: String, required: true }, position: { type: String, required: true }, start: { type: Date, required: true }, end: { type: Date }, skills: [ { type: Schema.Types.ObjectId, required: true, ref: SkillModel.modelName, }, ], responsibilities: [{ type: String, required: true }], }); export const ExperienceModel = model<ExperienceDocument, ExperienceModel>( "Experience", ExperienceSchema );
5562f2aafadd8e83b41e31677add94dd950b72e1
TypeScript
Ruddickmg/js-wars
/front/javascript/tests/tools/calculations/dotProduct.spec.ts
3.09375
3
import {expect} from "chai"; import dotProduct from "../../../src/tools/calculations/dotProduct"; describe("dotProduct", () => { it("Returns an array containing the product of values found at each index of two arrays", () => { const array: number[] = [1, 2, 3, 4, 5, 6, 7, 8]; expect(dotProduct(array, array)).to.equal(array.reduce((product: number, value: number): number => { return product + (value * value); })); }); });
6f22489fc08720f892e160daecf349f3f086aed3
TypeScript
AugurProject/Augur-Node-Experiment
/src/AccountManager.ts
2.609375
3
import BN = require('bn.js'); import { Account, generate, privateToAccount } from 'ethjs-account'; import { sign } from 'ethjs-signer'; import { Connector } from './Connector'; export interface Transaction { from?: string; to?: string; gas?: number | BN; gasPrice?: number | BN; value?: BN; data?: string; nonce?: BN; } export class AccountManager { private readonly connector: Connector; private readonly accounts = new Map<string, Account>(); public readonly nonces = new Map<string, BN>(); public readonly defaultAddress: string; constructor(connector: Connector, privateKey?: string) { this.connector = connector; const account = generate('non entropic entropy for account seed'); this.accounts.set(account.address, account); this.defaultAddress = account.address; if (typeof privateKey !== 'undefined') { this.defaultAddress = this.addAccount(privateKey); } } public addAccount(privateKey: string): string { const account = privateToAccount(privateKey); this.accounts.set(account.address, account); return account.address; } public async getNonce(address: string): Promise<BN> { if (!this.accounts.has(address)) throw new Error(`Nonce requested for an account not managed by this Account Manager. Requested address: ${address}`); if (this.nonces.has(address)) { const nonce = this.nonces.get(address)!.add(new BN(1)); this.nonces.set(address, nonce); return nonce; } else { let nonce = await this.connector.ethjsQuery.getTransactionCount(address); // check to see if someone else already snagged a nonce before our await returned if (this.nonces.has(address)) { nonce = this.nonces.get(address)!.add(new BN(1)); } this.nonces.set(address, nonce); return nonce; } } public async signTransaction(transaction: Transaction): Promise<string> { const sender = transaction.from || this.defaultAddress; if (typeof transaction.data === 'undefined') throw new Error(`transaction.data was undefined.`); if (typeof transaction.gas === 'undefined') throw new Error(`transaction.gas was undefined.`); if (typeof transaction.gasPrice === 'undefined') throw new Error(`transaction.gasPrice was undefined.`); const nonce = await this.getNonce(sender); const transactionToSend = Object.assign( { from: sender, data: transaction.data, gas: transaction.gas, gasPrice: transaction.gasPrice, nonce: nonce, }, transaction.to ? { to: transaction.to } : <{to:string}>{}, transaction.value ? { value: transaction.value } : <{value:BN}>{}, ); return sign(transactionToSend, this.accounts.get(sender)!.privateKey); } }
6c5b306a458a04449212bd473dc6f3e5c4e95b88
TypeScript
chase-moskal/turtleblog
/source/files/interfaces.ts
2.546875
3
export interface DirectoryItem { name: string path: string isDirectory: boolean }
df42a267a9072e33c30a90ab5744e38d11cf1cbd
TypeScript
humanchimp/tack
/src/findLast.ts
3.296875
3
export function findLast<T>( predicate: (it: T, index: number) => boolean, array: any[], ): T { for (let index = array.length - 1; index >= 0; index--) { const item = array[index]; if (predicate(item, index)) { return item; } } }
41b5604bbc5366b1e8fda5be1cebfc968c9fea9e
TypeScript
heiwais25/mymask-worker
/src/maps.ts
2.578125
3
import axios from "axios"; import configs from "./configs"; import { IPoint, FieldType } from "influx"; import { getMeasurementName } from "./loaders/influxdb"; import { ManualMappingLocation } from "./data"; import _ from "lodash"; export type IRemainStat = "few" | "empty" | "some" | "plenty"; export type IRawStore = { addr: string; name: string; code: string; created_at: string; lat: number; lng: number; stock_at: string; type: string; distance: number; remain_stat: IRemainStat; }; export type IStore = { addr: string; name: string; code: string; created_at: string; lat: number; lng: number; stock_at: string; type: string; distance: number; remain_stat: IRemainStat; latest_click_counts: number; latest_stock_ats: { plenty?: Date; empty?: Date }[]; }; export type StoreResponseData = { count: number; stores: IRawStore[]; }; export type IFetchParams = { lat: number; lng: number; m: number; }; export type IStoreLogTarget = "stock_at" | "remain_stat"; export const getInfluxPoint = (target: IStoreLogTarget, store: IStore): IPoint => { const measurementName = getMeasurementName(target); let fields: { [name: string]: FieldType; }; if (target === "stock_at") { fields = { stockAt: (store.stock_at as unknown) as FieldType.STRING }; } else { fields = { remainStat: (store.remain_stat as unknown) as FieldType.STRING }; } return { measurement: measurementName, tags: { code: store.code }, fields, timestamp: new Date() }; }; export const getStoreDataAPI = async (params: IFetchParams) => { try { const result = await axios.get<StoreResponseData>(configs.storeDataAPI, { params }); return result.data.stores.map(store => { if (!store.lat) { store.lat = ManualMappingLocation[store.code].lat; store.lng = ManualMappingLocation[store.code].lng; } return store; }); } catch (err) { throw err; } }; export async function getStoreDataBatchAPI( latLngs: ILatLng[], { distance = 5000, batchSize = 100 }: { distance?: number; batchSize?: number } ) { const batchedLatLangs = _.chunk(latLngs, batchSize); const batchResults: IRawStore[] = []; for (let batchedLatLang of batchedLatLangs) { let batchResult = await Promise.all( batchedLatLang.map(latLng => getStoreDataAPI({ lat: latLng.lat, lng: latLng.lng, m: distance }) ) ); batchResults.push(..._.flatten(batchResult)); } return batchResults; } export type ILatLng = { lat: number; lng: number; valid?: boolean; };
a7e672ae452c3056b6c41da7247937315371e51c
TypeScript
yoollii/kindness
/app/validator.service.ts
2.84375
3
import { Injectable } from '@angular/core'; import { FormControl } from '@angular/forms'; @Injectable({ providedIn: 'root' }) export class ValidatorService { constructor() { } positiveNumberValidator(control: FormControl): any { if (!control.value) { // 如果输入为空则返回空 return null; } const val = control.value; const num = /^[0-1]*$/; const result = num.test(val); if (result) { return null; } else { return { positiveNumber: true }; // 如果输入为不为0或1,显示错误信息 } } }
970981b9d98d25384589295d68d2265f732c1644
TypeScript
david2tdw/typescript
/classThis2.ts
3.78125
4
interface Card { suit : string, card: number } interface Deck { suits: string [], cards: number[], createCardPicker(this: Deck): () => Card } let deck : Deck = { suits: ["hearts", "spades", "clubs", "diamonds"], cards: Array(35), createCardPicker: function (this: Deck) { return () => { let pickedCard = Math.floor( Math.random() * 52) let pickedSuit = Math.floor( pickedCard / 13) return {suit: this.suits[pickedSuit], card: pickedCard} } } } let pickedCard = deck.createCardPicker() let cardPicked = pickedCard() console.log('card: ' + cardPicked.card + ' of ' + cardPicked.suit)
a2a5951be2abcead57e08e541ece47f6f8fd8a5a
TypeScript
Miguel319/booking-spot
/server/seeder/dummy-db.ts
2.859375
3
const Rental = require("../models/rental"); const User = require("../models/user"); class DummyDb { rentals; users; constructor() { this.createRentals(); this.createUsers(); } private createRentals() { this.rentals = [ { title: "Nice view on ocean", city: "San Francisco", street: "Main street", category: "condo", image: "https://booksync-jerga-prod.s3.amazonaws.com/uploads/rental/image/5/image.jpeg", bedrooms: 4, shared: true, description: "Very nice apartment in center of the city.", dailyRate: 43 }, { title: "Modern apartment in center", city: "New York", street: "Time Square", category: "apartment", image: "https://booksync-jerga-prod.s3.amazonaws.com/uploads/rental/image/5/image.jpeg", bedrooms: 1, shared: false, description: "Very nice apartment in center of the city.", dailyRate: 11 }, { title: "Old house in nature", city: "Spisska Nova Ves", street: "Banicka 1", category: "house", image: "https://booksync-jerga-prod.s3.amazonaws.com/uploads/rental/image/5/image.jpeg", bedrooms: 5, shared: true, description: "Very nice apartment in center of the city.", dailyRate: 23 } ]; } private createUsers() { this.users = [ { username: "Test", email: "test@gmail.com", password: "testtest" }, { username: "John", email: "john@gmail.com", password: "johnjohn" } ]; } private async cleanDb() { await User.deleteMany(); await Rental.deleteMany(); } private async addRentalsToDb() { const user = new User(this.users[0]); const user2 = new User(this.users[1]); for (let rental of this.rentals) { const newRental = new Rental(rental); newRental.user = user; user.rentals.push(newRental); newRental.save(); } await user.save(); await user2.save(); } async seedToDb() { await this.cleanDb(); await this.addRentalsToDb(); } } module.exports = DummyDb;
2de17cda3703931d43099d382a972a4d3dad0477
TypeScript
MichalPiaskowski/oop-typescript
/script.ts
4.1875
4
//Abstraction and encapsulation interface HeroI { name: string; attackPower: number; defence?: number; showWeakness(): string; normalAttack(): number; ultimateAttack(multiplayer: number): number; defend?(): number; } class TypicalHero implements HeroI { name: string; attackPower: number; defence: number; private weakness: string; constructor(name: string, attackPower: number, defence: number, weakness: string) { this.name = name; this.attackPower = attackPower; this.defence = defence; this.weakness = weakness; } showWeakness(): string { return this.weakness; } normalAttack(): number { return this.attackPower } ultimateAttack(multiplayer: number): number { return this.attackPower * multiplayer; } defend(): number { return this.defence } } //Inheritance and polimorphism class Mage extends TypicalHero { constructor(name: string, attackPower: number, defence: number, weakness: string ) { super(name, attackPower, defence, weakness) } mageShield(multiplayer: number): number { return super.defend() * multiplayer } ultimateAttack(): number { return this.attackPower * 6 } findWeakness(hero: TypicalHero) { return hero.showWeakness(); } }
ab566bdacd13d19e19bdcfd66efd19846416e805
TypeScript
hylickipiotr/covid19
/src/components/CardChart/prepareChartData.ts
2.640625
3
import { Moment } from "moment"; import { CachedCoutry } from "../../contexts/Search/search.type"; import { DailyRawData } from "../../types/Data"; import { isToday } from "../../utils/isToday"; import { TCardType } from "../Card/Card"; const getHistoricalSpecificTypeData = ( historical: DailyRawData[], type: TCardType ): Array<number> => historical.map((data) => data[type]); export const prepareChartData = ({ type, date, countryData, }: { type: TCardType; date: Moment; countryData: CachedCoutry; }): Array<number> => { const { today, historical } = countryData; const isTodayDate = isToday(date); const historicalData: DailyRawData[] = []; historical?.forEach((data) => { if (!data.updatedAt.isSameOrBefore(date, "d")) { return; } historicalData.push(data); }); const data = [ ...getHistoricalSpecificTypeData(historicalData, type), ...(isTodayDate && today ? [today[type]] : []), ]; return data.slice(Math.max(data.length - 30)); };
6a4b38bc0bb530d733af0676ec39b3b89ca29dee
TypeScript
kalyan0055/nvipani_UI
/src/app/common/password-validator.ts
2.859375
3
import { FormGroup } from '@angular/forms'; export class RegistrationValidator { static validate(registrationFormGroup: FormGroup) { let password = registrationFormGroup.controls.password.value; let repeatPassword = registrationFormGroup.controls.repeatPassword.value; var re = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}/; let test = re.test(password); if(!test){ return { passwordContain: true } } if (password.length <= 7) { return null; } if (repeatPassword.length <= 0) { return null; } if (repeatPassword !== password) { return { doesMatchPassword: true }; } return null; } }
bc1f0f4447e0a15fd3ef02c4e4d0b2f468a2b7d3
TypeScript
parthavtarfe/CRUD-nodejs-docker
/functions/src/models/product.ts
2.53125
3
import { urlpath } from '../config/environment' var mongo_instance = require('../connection'); let prod = require('../mongo_schemas/product'); export class productModel { public req; public res; public next; constructor(req, res, next){ this.req = req; this.res = res; this.next = next; } public addProduct = async(name, description, quantity, price) => { return new Promise(async(resolve, reject) => { try { const newItem = new prod({ name: name, description : description, quantity : quantity, price : price, }); let promise = newItem.save().then(item => { let responsedata = {"status":true, "data":[], "message" : "Product added."}; return responsedata; }).catch(err => { return err; }); let data = await promise; return resolve(data); } catch(err) { this.next(err); } }) } public listproducts = async() => { return new Promise(async(resolve, reject) => { try { let responsedata; let promise = prod.find().then((items) => { if(items) { console.log(items); responsedata = {"status":true, "data":items, "message":"Product list found."} } else { responsedata = {"status":false, "data":[], "message":"No products found"} } return responsedata }).catch((err) => { return err }); let data = await promise; return resolve(data); } catch(err) { this.next(err); } }) } public editProduct = async(productID, name, description, quantity, price) => { return new Promise(async(resolve, reject) => { try { let responsedata; if(productID == -1) { responsedata = {"status":false, "data":[], "message" : "Please provide proper productID"} return resolve(responsedata); } let updatedItem = { name: name, description : description, quantity : quantity, price : price, }; let promise = prod.findByIdAndUpdate(productID, { $set: updatedItem}) .then((response)=>{ if(response) { responsedata = {"status":true, "data":[], "message" : "Product updated."}; } else { responsedata = {"status":false, "data":[], "message" : "No product found with the given ID"}; } return responsedata }).catch((err)=>{ return err; }) let data = await promise; return resolve(data); } catch(err) { this.next(err); } }) } public getProduct = async(productID) => { return new Promise(async (resolve, reject) => { try { let responsedata; if(productID == -1) { responsedata = {"status":false, "data":[], "message" : "Please provide proper productID"} return resolve(responsedata); } let promise = prod.findById(productID).then((item) => { if(item){ responsedata = { "status":true, "data":item, "message":"Product details found."} } else { responsedata = {"status":false, "data":[], "message":"Product details found with the given product ID."} } return responsedata; }).catch((err) => { return err; }); let data = await promise; return resolve(data) } catch(err) { this.next(err); } }) } public deleteProduct = async(productID) => { return new Promise(async(resolve, reject) => { try { let responsedata; if(productID == -1) { responsedata = {"status":false, "data":[], "message" : "Please provide proper productID"} return resolve(responsedata); } let promise = prod.findByIdAndRemove(productID).then((item) => { if(item) { responsedata = {"status":true, "data":[], "message" : "Product deleted."} } else { responsedata = {"status":false, "data":[], "message" : "Product with the given ID not found."} } return responsedata; }).catch((err) => { return err; }) let data = await promise; return resolve(data); } catch(err) { this.next(err); } }) } }
a51b84c56530c6c218162e7916995692d5b81dec
TypeScript
billyprice1old/base65536
/src/test/parse.spec.ts
2.640625
3
/** Tests for the command line parser, which was a bit annoying */ 'use strict' import Action from './../bin/action' import parse from './../bin/parse' describe('parse', function () { it('helps', function () { expect(parse(['--help'])).toEqual({action: Action.help, ignoreGarbage: false, fileName: undefined}) }) it('versions', function () { expect(parse(['--version'])).toEqual({action: Action.version, ignoreGarbage: false, fileName: undefined}) }) it('encodes', function () { expect(parse([])).toEqual({action: Action.encode, ignoreGarbage: false, fileName: undefined}) expect(parse(['fileName'])).toEqual({action: Action.encode, ignoreGarbage: false, fileName: 'fileName'}) expect(parse(['-'])).toEqual({action: Action.encode, ignoreGarbage: false, fileName: undefined}) expect(parse(['--'])).toEqual({action: Action.encode, ignoreGarbage: false, fileName: undefined}) expect(parse(['--', 'fileName'])).toEqual({action: Action.encode, ignoreGarbage: false, fileName: 'fileName'}) expect(parse(['--', '-'])).toEqual({action: Action.encode, ignoreGarbage: false, fileName: '-'}) expect(parse(['--', '--'])).toEqual({action: Action.encode, ignoreGarbage: false, fileName: '--'}) }) it('decodes', function () { expect(parse(['-d'])).toEqual({action: Action.decode, ignoreGarbage: false, fileName: undefined}) expect(parse(['-d', 'fileName'])).toEqual({action: Action.decode, ignoreGarbage: false, fileName: 'fileName'}) expect(parse(['-d', '-'])).toEqual({action: Action.decode, ignoreGarbage: false, fileName: undefined}) expect(parse(['-d', '--'])).toEqual({action: Action.decode, ignoreGarbage: false, fileName: undefined}) expect(parse(['-d', '--', 'fileName'])).toEqual({action: Action.decode, ignoreGarbage: false, fileName: 'fileName'}) expect(parse(['-d', '--', '-'])).toEqual({action: Action.decode, ignoreGarbage: false, fileName: '-'}) expect(parse(['-d', '--', '--'])).toEqual({action: Action.decode, ignoreGarbage: false, fileName: '--'}) expect(parse(['--decode'])).toEqual({action: Action.decode, ignoreGarbage: false, fileName: undefined}) expect(parse(['--decode', 'fileName'])).toEqual({action: Action.decode, ignoreGarbage: false, fileName: 'fileName'}) expect(parse(['--decode', '-'])).toEqual({action: Action.decode, ignoreGarbage: false, fileName: undefined}) expect(parse(['--decode', '--'])).toEqual({action: Action.decode, ignoreGarbage: false, fileName: undefined}) expect(parse(['--decode', '--', 'fileName'])).toEqual({action: Action.decode, ignoreGarbage: false, fileName: 'fileName'}) expect(parse(['--decode', '--', '-'])).toEqual({action: Action.decode, ignoreGarbage: false, fileName: '-'}) expect(parse(['--decode', '--', '--'])).toEqual({action: Action.decode, ignoreGarbage: false, fileName: '--'}) }) it('ignores garbage', function () { expect(parse(['-d', '-i'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: undefined}) expect(parse(['-d', '-i', 'fileName'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: 'fileName'}) expect(parse(['-d', '-i', '-'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: undefined}) expect(parse(['-d', '-i', '--'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: undefined}) expect(parse(['-d', '-i', '--', 'fileName'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: 'fileName'}) expect(parse(['-d', '-i', '--', '-'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: '-'}) expect(parse(['-d', '-i', '--', '--'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: '--'}) expect(parse(['--decode', '-i'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: undefined}) expect(parse(['--decode', '-i', 'fileName'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: 'fileName'}) expect(parse(['--decode', '-i', '-'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: undefined}) expect(parse(['--decode', '-i', '--'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: undefined}) expect(parse(['--decode', '-i', '--', 'fileName'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: 'fileName'}) expect(parse(['--decode', '-i', '--', '-'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: '-'}) expect(parse(['--decode', '-i', '--', '--'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: '--'}) expect(parse(['-d', '--ignore-garbage'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: undefined}) expect(parse(['-d', '--ignore-garbage', 'fileName'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: 'fileName'}) expect(parse(['-d', '--ignore-garbage', '-'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: undefined}) expect(parse(['-d', '--ignore-garbage', '--'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: undefined}) expect(parse(['-d', '--ignore-garbage', '--', 'fileName'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: 'fileName'}) expect(parse(['-d', '--ignore-garbage', '--', '-'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: '-'}) expect(parse(['-d', '--ignore-garbage', '--', '--'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: '--'}) expect(parse(['--decode', '--ignore-garbage'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: undefined}) expect(parse(['--decode', '--ignore-garbage', 'fileName'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: 'fileName'}) expect(parse(['--decode', '--ignore-garbage', '-'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: undefined}) expect(parse(['--decode', '--ignore-garbage', '--'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: undefined}) expect(parse(['--decode', '--ignore-garbage', '--', 'fileName'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: 'fileName'}) expect(parse(['--decode', '--ignore-garbage', '--', '-'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: '-'}) expect(parse(['--decode', '--ignore-garbage', '--', '--'])).toEqual({action: Action.decode, ignoreGarbage: true, fileName: '--'}) }) it('throws', function () { expect(() => parse(['--help', '-'])).toThrow() expect(() => parse(['--help', '--decode'])).toThrow() expect(() => parse(['--help', '--help'])).toThrow() expect(() => parse(['--help', '--ignore-garbage'])).toThrow() expect(() => parse(['--help', '--version'])).toThrow() expect(() => parse(['--help', '-d'])).toThrow() expect(() => parse(['--help', '-i'])).toThrow() expect(() => parse(['--help', 'fileName'])).toThrow() expect(() => parse(['--version', '-'])).toThrow() expect(() => parse(['--version', '--decode'])).toThrow() expect(() => parse(['--version', '--help'])).toThrow() expect(() => parse(['--version', '--ignore-garbage'])).toThrow() expect(() => parse(['--version', '--version'])).toThrow() expect(() => parse(['--version', '-d'])).toThrow() expect(() => parse(['--version', '-i'])).toThrow() expect(() => parse(['--version', 'fileName'])).toThrow() expect(() => parse(['-d', '--help'])).toThrow() expect(() => parse(['-d', '--version'])).toThrow() expect(() => parse(['-d', '-d'])).toThrow() expect(() => parse(['-d', '--decode'])).toThrow() expect(() => parse(['-d', '-i', '-i'])).toThrow() expect(() => parse(['-d', '-i', '--ignore-garbage'])).toThrow() expect(() => parse(['-d', '--ignore-garbage', '-i'])).toThrow() expect(() => parse(['-d', '--ignore-garbage', '--ignore-garbage'])).toThrow() expect(() => parse(['--decode', '--help'])).toThrow() expect(() => parse(['--decode', '--version'])).toThrow() expect(() => parse(['--decode', '-d'])).toThrow() expect(() => parse(['--decode', '--decode'])).toThrow() expect(() => parse(['--decode', '-i', '-i'])).toThrow() expect(() => parse(['--decode', '-i', '--ignore-garbage'])).toThrow() expect(() => parse(['--decode', '--ignore-garbage', '-i'])).toThrow() expect(() => parse(['--decode', '--ignore-garbage', '--ignore-garbage'])).toThrow() expect(() => parse(['-i'])).toThrow() expect(() => parse(['--ignore-garbage'])).toThrow() expect(() => parse(['fileName', '--help'])).toThrow() expect(() => parse(['fileName', '--version'])).toThrow() expect(() => parse(['fileName', '-d'])).toThrow() expect(() => parse(['fileName', '--decode'])).toThrow() expect(() => parse(['fileName', '-i'])).toThrow() expect(() => parse(['fileName', '--ignore-garbage'])).toThrow() expect(() => parse(['fileName', '--'])).toThrow() expect(() => parse(['fileName', 'fileName'])).toThrow() expect(() => parse(['-d', 'fileName', 'fileName'])).toThrow() expect(() => parse(['-d', '-i', 'fileName', 'fileName'])).toThrow() expect(() => parse(['-d', '--ignore-garbage', 'fileName', 'fileName'])).toThrow() expect(() => parse(['--decode', 'fileName', 'fileName'])).toThrow() expect(() => parse(['--decode', '-i', 'fileName', 'fileName'])).toThrow() expect(() => parse(['--decode', '--ignore-garbage', 'fileName', 'fileName'])).toThrow() expect(() => parse(['--', 'fileName', 'fileName'])).toThrow() }) })
df3cf7480d93279912900994fb3e3a0eca702d08
TypeScript
vibollmc/4c58c0cf20d4dbb8945ae95b2b664fd6
/app/hotel/models/room.ts
2.53125
3
import {MongodbModel} from './metadata/mongodbmodel'; import {RoomStatus} from './enum'; export class Room extends MongodbModel { name: string; roomtype: string; floor: number; roomStatus: RoomStatus; description: string; constructor() { super(); this.name = null; this.roomtype = null; this.floor = null; this.roomStatus = RoomStatus.Undefined; this.description = null; } }
30c7bd9ea934282a620d66b7f182a33872f2d346
TypeScript
electronicSAINT/jabberwock
/packages/plugin-fontawesome/src/FontAwesomeNode.ts
2.78125
3
import { InlineNode } from '../../plugin-inline/src/InlineNode'; import { AbstractNodeParams } from '../../core/src/VNodes/AbstractNode'; export interface FontAwesomeNodeParams extends AbstractNodeParams { htmlTag: string; faClasses: string[]; } export class FontAwesomeNode extends InlineNode { static readonly atomic = true; htmlTag: string; faClasses: string[]; constructor(params: FontAwesomeNodeParams) { super(params); this.htmlTag = params.htmlTag; this.faClasses = params.faClasses; } /** * Return a new VNode with the same type and attributes as this VNode. */ clone(params?: {}): this { const defaults: ConstructorParameters<typeof FontAwesomeNode>[0] = { htmlTag: this.htmlTag, faClasses: this.faClasses, }; return super.clone({ ...defaults, ...params }); } }
f207172507a1755648f6d8540acbbc4b2c5e9230
TypeScript
mmmveggies/rainbow-of-fifths
/src/hooks/use-source-notes.ts
2.6875
3
import React from 'react' import { Input, InputEventNoteon, InputEventNoteoff } from 'webmidi' export type SourceNotes = Record<string, InputEventNoteon> export function useSourceNotes(source: Input) { const [notes, setNotes] = React.useState<SourceNotes>({}) React.useEffect( () => { const onNoteOn = (event: InputEventNoteon) => { setNotes((curr) => { const next = { ...curr, [event.note.number]: event } return next }) } const onNoteOff = (event: InputEventNoteoff) => { setNotes((curr) => { const { [event.note.number]: _, ...next } = curr return next }) } source.addListener('noteon', 'all', onNoteOn) source.addListener('noteoff', 'all', onNoteOff) return () => { source.removeListener('noteon', 'all', onNoteOn) source.removeListener('noteoff', 'all', onNoteOff) } }, [source], ) return notes }
92732aeab873cf648fe75d6c66093e8058215a51
TypeScript
0xrin1/edChat
/ts/messaging/clients/client.ts
2.546875
3
import Greeting from './greeting'; import Id from '../../utilities/id'; import RelayReference from '../relays/relayReference'; export default class Client implements Greeting { id: number; name: string; platform: string; project: string; ip: string; custom_keyboard: boolean; relays: RelayReference; date: Date; constructor(greeting?: Greeting) { if (!greeting) this.new(); else this.set(greeting); this.relays = new RelayReference([], []); } new(): void { const clientId: Id = new Id(); this.id = clientId.get(); this.name = 'dummy'; this.platform = 'dummy'; this.project = 'dummy'; this.date = new Date(); } set(greeting: Greeting): void { this.id = greeting.id; this.name = greeting.name; this.platform = greeting.platform; this.project = greeting.project; this.date = greeting.date; } setTelegram(id: number, name: string, project: string): void { this.id = id; this.name = name; this.platform = 'telegram'; this.project = project; this.custom_keyboard = false; } setBrowser(ip: string): void { this.ip = ip; this.custom_keyboard = false; } setOpenCustomKeyboard(): void { this.custom_keyboard = true; } setClosedCustomKeyboard(): void { this.custom_keyboard = false; } }
3b4dfe549cb29beb6556fa7450409679958cbf9f
TypeScript
2019-B-GR1-JS/js-pirca-escobar-nicole-stephanie
/02-typescript/01-Introduccion.ts
4.0625
4
// Tranpilador // tipo de compilador que transforma de //un lenguaje a otro // TYPESCRIPT // 1) TIPOS DE DATOS (TIPADOS) // 2) DECORADORES // 3) CLASES //const numero =0; const numero: number =0; //let nombre: string= "Nicole"; // DUCK TYPING // INFIREINDO EL TIPO DE DATO let nombre = "Nicole"; // nombre =1; ERROR let fecha: Date; //Date ->Clase // tipo de datos "Date fecha =new Date(); // se puede tipar las variables con clases // se puede tipar tambien con las interfaces que son como las clases let nicol:Estudiante; // donde estudiante es una interfaz // tipo de dato "Estudiante nicol={ nombre: "Nicole", edad: 22, }; interface Estudiante { nombre: string; edad?: number; } function holaMundo(): void { console.log('Hola'); // SIEMPRE TIPAR SIEMPRE // FUNCION NO DEVUELVE NADA } function mensaje(nombre: string): void{ console.log('Hola',nombre) } function calculadora( numUno: number, ...numeros: number[] ): number { console.log('Hola',nombre); return numUno; } function universidad( nombre: string, edad?: number,// sera un parametro OPCIONAL con el signo ): string { return `${nombre} Edad: ${edad}`; } universidad( "Nicole", 22); universidad("Nicole"); // es necesario typar para reducir los errores del programador interface Facultad{ nombre: string; id: number; } interface Departamento { nombre:string; id: number; facultad: Facultad | number; // se puede tomar mas de dos tipos de datos //problema real se puede cambiar con | boolean } const departamentoSistemas={ nombre:"Sistemas", id:1, facultad:{ //Facultad esta relacionada nombre: "Sistemas", id:1, } }; const departamentoSistemasSinRelaciones: Departamento={ nombre:"Sistemas", id:1, facultad: 1 }; function imprimirDepartamento( departamento: Departamento ) { const departamentoId= departamento.facultad as number +1; //const departamentoId= departamento.facultad +1; // se realiza un cast // segundaOpcion del cast const departamentId =<number> departamento.facultad +1; // es muy sencillo }
d72e59fd3be8e61df4d81e5d11d37b69c25545bf
TypeScript
narci2010/typescript-course
/src/pattern/Composite.ts
4.28125
4
// 组合模式 Composite // 特点:以树的形式展示对象的组合,并且可以以类似的方式处理每个枝点。 // 用处:当对象组合以树状存在,有父有子,并且对象的行为差不多时可以考虑组合模式,如菜单,游戏里的技能树。 // 注意:遍历组合的性能要求。 // 下面用TypeScript简单实现一下组合模式: // 技能树麻烦了点,技能激活要引入观察者模式,就以菜单为例吧。 // 菜单可以包括子菜单,点击菜单项时有子菜单则显示子菜单,没有时触发点击事件。 // 先声明一个抽象,包含菜单的名字,点击事件和添加Child,一般情况下Menu会维护一个childs集合,通过这个集合来添加子菜单, // 不过这里没有用这种方式,采用的是继承一个集合来让本身拥有集合的能力,这样更方便,是父还是子可以通过字段来控制,也可以通过是否有child来表示。 abstract class MenuBase extends Array<MenuBase> { name: string abstract click() addChild(...childs: Array<MenuBase>) { childs.forEach(o => this.push(o)) } } // 实现具体MenuItem类,一般情况下可以用两个类,一个代表菜单,一个代表菜单项,不过这里就不需要区别是枝还是叶了,简单一点,只用一个MenuItem代表所有。 // 可以传click处理事件进来,click时会触发click事件,另外如果有子则显示所有子。 class MenuItem extends MenuBase { constructor( public name: string, private clickFunc: () => string | undefined ) { super() } click() { console.log(`click ${this.name}`) if (this.clickFunc) { console.log(this.clickFunc()) } if (this.length > 0) { let childs = this.reduce( (p, c) => <MenuBase>{ name: `${p.name},${c.name}` } ).name console.log(`${this.name}'s childs: ${childs}`) } } } // 现在来运行一下: let root = new MenuItem('root', () => { return 'my name is root' }) let A1 = new MenuItem('A1', () => { return 'my name is A1' }) let A2 = new MenuItem('A2', () => { return 'my name is A2' }) let B1 = new MenuItem('B1', () => { return 'my name is B1' }) let B2 = new MenuItem('B2', () => { return 'my name is B2' }) let B3 = new MenuItem('B3', () => { return 'my name is B3' }) root.push(A1, A2) A1.push(B1, B2, B3) root.click() A1.click() A2.click() B1.click() // 结果: // click root // root's childs: A1,A2 // click A1 // A1's childs: B1,B2,B3 // click A2 // my name is A2 // click B1 // 符合预期行为,这种组合就是非常简单的,但如果组合得非常深且枝非常多时就需要考虑查找枝时的效率问题了, // 通常的办法是采用缓存来把一些常用的查找结果缓存起来,避免频繁遍历。
8a06789769b67e6ea09e478d631dae52d7f1536a
TypeScript
uhyo/resourcebundles
/packages/cli/src/util/handleOptionMultiple.ts
2.828125
3
export function handleOptionMultiple( option: string | string[] | undefined ): string[] { if (option === undefined) { return []; } if (typeof option === "string") { return [option]; } return option; }
51791ef2c0230bf4f232ceb2723319e03ed18ecd
TypeScript
MayorCurley/heros
/src/app/player.ts
2.765625
3
export class Player { firstName: string; lastName: string; team: string; position: string; overall: number; awareness: number; speed: number; acceleration: number; agility: number; strength: number; } /* { "firstName": "Tom", "lastName": "Brady", "team": "New England Patriots", "position": "QB", "overall": "97", "awareness": "99", "speed": "60", "acceleration": "66", "agility": "70", "strength": "64" } */
0d14cb770e6b0d02d6a8bb7c2919a450ab712da9
TypeScript
livyk/motyl
/src/helpers/stripUnit.ts
2.6875
3
const cssRegex = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/; export default function stripUnit(value: string | number): string | number { if (typeof value !== "string") return value; const matchedValue = value.match(cssRegex); return matchedValue ? parseFloat(value) : value; }
1dd71d033696b9251d9832c6f689a580daa96293
TypeScript
7affer/raycast
/src/scripts/sprites/sprite.ts
2.875
3
import { ISettings } from '../isettings'; import { Angle } from '../angle'; import { ISprite } from './isprite'; export class Sprite implements ISprite { public left: number = -1 public width: number = 0 public anglewidth: number = 0.2 public starttexture: number public endtexture: number public distance: number public targeted: boolean = false private height2: number private maxheight: number constructor( public x: number, public y: number, public image: HTMLImageElement, settings: ISettings ) { if (settings != null) { this.height2 = Math.floor(settings.height / 2) this.maxheight = settings.wallheight } } public move(delta:number) { } public settarget(left: number, width: number) { } public ifshoot(fired: boolean, onshoot: () => void) { } public render(ctx: CanvasRenderingContext2D) { let wallheight = Math.ceil(this.maxheight / this.distance) let bottom = Math.floor(this.height2 + wallheight / 2) let texleft = Math.floor(this.starttexture * this.image.width) let texright = Math.floor(this.endtexture * this.image.width) let height = Math.floor(wallheight * 0.4) let swidth = Math.max(1, texright - texleft) let top = bottom - height ctx.drawImage(this.image, texleft, 0, swidth, this.image.height, this.left, top, this.width, height) } }
e35db2f8498a26cf58c647b661d95c1e96b1052d
TypeScript
NichijouCC/web3d
/src/graph/mesh/vertexAttribute.ts
2.984375
3
namespace webGraph { export enum VertexAttTypeEnum { Position ="a_pos", UV0 ="a_texcoord0", Color0 ="a_color", BlendIndex4 ="a_blendindex4", BlendWeight4 = "a_blendweight4", Normal = "a_normal", Tangent = "a_tangent", UV1 = "a_texcoord1", Color1 ="a_color1", instance_pos ="a_InstancePos", instance_scale ="a_InstanceScale", instance_rot ="a_InstanceRot", } export enum VertexAttLocationEnum { Position =1, UV0 = 2, Color0 =3, BlendIndex4 = 4, BlendWeight4 =5, Normal = 6, Tangent = 7, UV1 = 8, Color1 = 9, instance_pos=10, instance_scale=11, instance_rot=12 } export function getCompnentSizeByVertexType(type:VertexAttTypeEnum):number { switch(type) { case VertexAttTypeEnum.UV0: case VertexAttTypeEnum.UV1: return 2; case VertexAttTypeEnum.Position: case VertexAttTypeEnum.Normal: case VertexAttTypeEnum.Tangent: case VertexAttTypeEnum.instance_pos: case VertexAttTypeEnum.instance_scale: return 3; case VertexAttTypeEnum.Color0: case VertexAttTypeEnum.Color1: case VertexAttTypeEnum.BlendIndex4: case VertexAttTypeEnum.BlendWeight4: case VertexAttTypeEnum.instance_rot: return 4; default: console.error("vertex type error!"); } } export class VertexAttribute { beInstanceAtt:boolean=false; type:VertexAttTypeEnum; location:number; componentSize:number; componentDataType:number; normalize:boolean; // /** // * typeByte*componentSize(例如:float3=4 * 3) // */ // byteSize:number; // /** // * arraybufferview 中元素的byte间隔 // */ // viewByteStride:number; // view:Float32Array|Int8Array|Int16Array|Int32Array|Uint8Array|Uint16Array|Uint32Array; // data:any[]=[]; // count:number; vbo:VertexBuffer; /** * 构成离散vbo时候设置的属性,对应vertexattributepointer方法 */ offsetInBytes:number=0; /** * 构成离散vbo时候设置的属性,对应vertexattributepointer方法 */ strideInBytes:number=0; static PrepareVertexAttribute(type:VertexAttTypeEnum,view:Float32Array,componentSize?:number,byteStride?:number):VertexAttribute { let att=new VertexAttribute(); att.type=type; att.location=AttributeSetter.getAttLocationByType(type); att.componentSize=componentSize; att.componentSize=componentSize||getCompnentSizeByVertexType(type); att.componentDataType=GLConstants.FLOAT; att.normalize=false; //att.byteSize=att.componentSize*view.BYTES_PER_ELEMENT; // let stride=byteStride||att.byteSize; //let dataArr=GetDataArr(view,stride,att.componentSize,ViewDataType.FLOAT); // att.view=view; // att.data=dataArr; // att.viewByteStride=stride; // att.count=dataArr.length; att.vbo=new webGraph.VertexBuffer(); att.vbo.bufferData(view); if(type==VertexAttTypeEnum.instance_pos||type==VertexAttTypeEnum.instance_rot||type==VertexAttTypeEnum.instance_scale) { att.beInstanceAtt=true; } return att; } static createByType(type:VertexAttTypeEnum,attinfo?:IAttinfo):VertexAttribute { let att=new VertexAttribute(); att.type=type; att.location=AttributeSetter.getAttLocationByType(type); if(type==VertexAttTypeEnum.instance_pos||type==VertexAttTypeEnum.instance_rot||type==VertexAttTypeEnum.instance_scale) { att.beInstanceAtt=true; } if(attinfo!=null) { att.componentSize=attinfo.componentSize||getCompnentSizeByVertexType(type); att.componentDataType=attinfo.componentDataType||GLConstants.FLOAT; att.normalize=attinfo.normalize||false; }else { att.componentSize=getCompnentSizeByVertexType(type); att.componentDataType=GLConstants.FLOAT; att.normalize=false; } return att; } /** * 动态 vbo */ refreshVboData(vbodata:Float32Array) { this.vbo.bufferData(vbodata); } } export interface IAttinfo { componentSize?:number; componentDataType?:number; normalize?:boolean; viewByteStride?:number; } export enum ViewDataType { /** * Byte */ BYTE = 5120, /** * Unsigned Byte */ UNSIGNED_BYTE = 5121, /** * Short */ SHORT = 5122, /** * Unsigned Short */ UNSIGNED_SHORT = 5123, /** * Unsigned Int */ UNSIGNED_INT = 5125, /** * Float */ FLOAT = 5126, } export function GetDataArr(view:ArrayBufferView,byteStride:number,compoentSize:number,compenttype:ViewDataType=ViewDataType.FLOAT):any[] { let dataArr:any[]=[]; let count=view.byteLength/byteStride; for(let i=0;i<count;i++) { dataArr.push(GetTypedArry(compenttype,view.buffer,view.byteOffset+i*byteStride,compoentSize)); } return dataArr; } export function GetTypedArry(componentType: ViewDataType,buffer:ArrayBuffer,byteOffset:number,Len:number) { switch (componentType) { case ViewDataType.BYTE: return new Int8Array(buffer, byteOffset, Len); case ViewDataType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, Len); case ViewDataType.SHORT: return new Int16Array(buffer, byteOffset, Len); case ViewDataType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, Len); case ViewDataType.UNSIGNED_INT: return new Uint32Array(buffer, byteOffset, Len); case ViewDataType.FLOAT: return new Float32Array(buffer, byteOffset, Len); default: throw new Error(`Invalid component type ${componentType}`); } } export function GetByteSize(componentType:ViewDataType,componentSize:number):number { switch (componentType) { case ViewDataType.BYTE: return componentSize*Int8Array.BYTES_PER_ELEMENT; case ViewDataType.UNSIGNED_BYTE: return componentSize*Uint8Array.BYTES_PER_ELEMENT; case ViewDataType.SHORT: return componentSize*Int16Array.BYTES_PER_ELEMENT; case ViewDataType.UNSIGNED_SHORT: return componentSize*Uint16Array.BYTES_PER_ELEMENT; case ViewDataType.UNSIGNED_INT: return componentSize*Uint32Array.BYTES_PER_ELEMENT; case ViewDataType.FLOAT: return componentSize*Float32Array.BYTES_PER_ELEMENT; default: throw new Error(`Invalid component type ${componentType}`); } } }
b865d5e87ebc146cf0e0ac31ad835e4302d38d82
TypeScript
abbasjnp/MaidsCar
/src/app/admin/practice2/simple-component.ts
2.625
3
import {Component,Input,OnChanges,SimpleChanges} from '@angular/core'; @Component({ selector:'simple', template:`you entered :{{simpleInput}}` }) export class SimpleComponent implements OnChanges{ @Input() simpleInput:string; ngOnChanges(changes :SimpleChanges){ for(let propertyName in changes){ let change = changes[propertyName]; let current = JSON.stringify(change.currentValue); let previous = JSON.stringify(change.previousValue); console.log(propertyName + ':current Value = '+current +' previous Value= '+previous); } } }
e8b365af59366e8b39577c9139ea093352721e04
TypeScript
johnpmcclung/baseballbot
/baseball/events/RunScoredEvent.ts
2.984375
3
import { EventType, Team } from "../enums"; import { GameEvent } from "./event"; export class RunScoredEvent implements GameEvent { type: EventType; properties: RunScoredEventProperties; constructor (team: Team) { this.type = EventType.RunScored; this.properties = { "team": team }; } } export interface RunScoredEventProperties { team: Team; } export function runScoredEventStringify (event: RunScoredEvent): string { return `The ${Team[event.properties.team].toLocaleString()} team has scored a run.`; }
ec50e6f5a7012022ffc1e151e2e5ccbdfd31e4cb
TypeScript
HanLeFS/products-redux-sagas
/project/src/api/fetchProduct.api.ts
2.546875
3
import axios from 'axios'; import { IProductResponse, Product } from 'src/models'; import { isSuccessfulResponse, axiosApi } from 'src/utils'; export const getProduct = async (id: string): Promise<IProductResponse> => { const url = process.env.REACT_APP_API_END_POINT ?? ''; try { const response = await axiosApi.get(`${url}/${id}`, { headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, }); if (isSuccessfulResponse(response)) { return { product: response.data as Product, isSuccessful: true, }; } return { product: undefined, isSuccessful: false, error: new Error('An error has occured'), }; } catch (error) { return { product: undefined, isSuccessful: false, error: axios.isAxiosError(error) ? error : new Error('An error has occured'), }; } };
08367b3df7b38e6d29aa233ad97354bdf9c2b33e
TypeScript
body-link/tachka
/server/common/rxjs-utils.ts
2.765625
3
import { MonoTypeOperatorFunction, Observable, of, OperatorFunction } from 'rxjs'; import { catchError, dematerialize, materialize, tap } from 'rxjs/operators'; import { TOption } from './type-utils'; export const UNDEFINED = of(undefined); export const catchErrorToUndefined = <T>(): OperatorFunction<T, TOption<T>> => { return (source: Observable<T>) => source.pipe(catchError(() => UNDEFINED)); }; // eslint-disable-next-line @typescript-eslint/no-explicit-any export const debug = <T>(...args: any[]): MonoTypeOperatorFunction<T> => { return (source: Observable<T>) => source.pipe( materialize(), tap((n) => console.log(...args, n)), dematerialize() ); };
80aee42726d501d6b2018caa509ec4120fc69029
TypeScript
AxisCommunications/media-stream-library-js
/streams/src/components/auth/www-authenticate.ts
3.109375
3
export type ChallengeParams = Map<string, string> export interface Challenge { type: string params: ChallengeParams } export const parseWWWAuthenticate = (header: string): Challenge => { const [, type, ...challenge] = header.split(' ') const pairs: Array<[string, string]> = [] const re = /\s*([^=]+)="([^"]*)",?/gm let match do { match = re.exec(challenge.join(' ')) if (match !== null) { const [, key, value] = match pairs.push([key, value]) } } while (match !== null) const params = new Map(pairs) return { type: type.toLowerCase(), params } }
1307b7440df00a9bbfede467f100902c59aa52af
TypeScript
kiranbatchu/supersaver
/src/pages/about/about.ts
2.578125
3
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; @Component({ selector: 'page-about', templateUrl: 'about.html' }) export class AboutPage { wholefoods:string = "Savings: $0"; wholefoodDiscount:number = 0; uberDiscount:number = 0; salonDiscount:number = 0; restDiscount:number = 0; retailDiscount:number = 0; random:number = 10; total:number = 0; get formattedMsg():string { return "Savings: $" + this.total; } get formattedWholeFoodsMsg():string { var rate = Math.round((this.wholefoodDiscount/20)); return ("Spend $" + rate + " less a week at Whole Foods"); } get formattedUberMsg():string { var rate = Math.round((this.uberDiscount/33)); return ("Take " + rate + " less Uber a month"); } get formattedSalonMsg():string { var msg1 = "Keep salon budget as minimum as possible"; var msg2 = "Keep salon budget at a moderate level "; if (this.salonDiscount > 50) { return msg1; } else { return msg2; } } get formattedRestMsg():string { var rate = Math.round(this.restDiscount/7); return ("Spend $" + rate + " less a week at restaurants"); } get formattedRetailMsg():string { var rate = Math.round(this.retailDiscount/7); console.log("rate"+rate ); return ("Spend $" + rate + " less a week on retail"); } get formattedMsg2():string { return "Estimated Savings Have Fun in Paris !! " + this.random; } constructor(public navCtrl: NavController) { } wholeFoodsChanged(event) { console.log("Whole Foods: " + event.value); this.wholefoodDiscount = event.value; this.total = this.wholefoodDiscount + this.uberDiscount + this.salonDiscount + this.restDiscount + this.retailDiscount; this.random=4+this.total; } uberChanged(event) { console.log("Uber: " + event.value); this.uberDiscount = event.value; this.total = this.wholefoodDiscount + this.uberDiscount + this.salonDiscount + this.restDiscount + this.retailDiscount; this.random=2+this.total; } salonChanged(event) { console.log("Salon: " + event.value); this.salonDiscount = event.value; this.total = this.wholefoodDiscount + this.uberDiscount + this.salonDiscount + this.restDiscount + this.retailDiscount; this.random=3+this.total; } restChanged(event) { console.log("Restaurent: " + event.value); this.restDiscount = event.value; this.total = this.wholefoodDiscount + this.uberDiscount + this.salonDiscount + this.restDiscount + this.retailDiscount; this.random=5+this.total; } retailChanged(event) { console.log("Retail: " + event.value); this.retailDiscount = event.value; this.total = this.wholefoodDiscount + this.uberDiscount + this.salonDiscount + this.retailDiscount; this.random=1+this.total; } }
3e01bdc9cc9e5504982b421654637da555565678
TypeScript
llorz-o/rich-m
/src/utils/func/arr.ts
3.1875
3
/** @format */ type CommonArray<T> = { [key: number]: T length: number } export function each<T>(arr: CommonArray<T>, cb: (item: T, index: number, self: CommonArray<T>) => void): CommonArray<T> { const len: number = arr.length let i = 0 for (i; i < len; i++) { cb(arr[i], i, arr) } return arr } export function filter<T>(arr: CommonArray<T>, cb: (item: T, index: number, self: CommonArray<T>) => boolean): T[] { const result: T[] = [] each(arr, (item, index, self) => { if (cb(item, index, self)) result.push(item) }) return result } export function indexOf<T>(arr: CommonArray<T>, value: T): number { let _index = -1 each(arr, (item, index) => { if (item === value) _index = index }) return _index } export function map<T, U>(arr: CommonArray<T>, cb: (item: T, index: number, self: CommonArray<T>) => U): U[] { const result: U[] = [] each<T>(arr, (item, index, self) => { const newElement: U = cb(item, index, self) if (newElement !== undefined) result.push(newElement) }) return result }
a8e94a6ce5e0f0fff25524e3cd72f9bae8ae74aa
TypeScript
heshmAhmed/todos-frontend
/src/app/model/todo.model.ts
2.515625
3
export interface Todo{ id?: BigInteger title: string; desc: string; creatDate: Date; endDate?: Date; completed: boolean; }
aeb17014e8301f79dcd1d4a35c2090ca4b45a17b
TypeScript
Codeneos/vlocode
/packages/vscode-extension/src/lib/vlocodeContext.ts
2.90625
3
import * as path from 'path'; import type { ExtensionContext, Memento, ExtensionMode } from 'vscode'; import { singleton, getInstance } from '@vlocode/util'; import type VlocodeService from './vlocodeService'; /** * Minimal version of VScodes extension context. */ class VlocodeContext { constructor( /** * The absolute file path of the directory containing the extension. */ readonly extensionPath: string, /** * A memento object that stores state in the context * of the currently opened {@link workspace.workspaceFolders workspace}. */ readonly workspaceState: Memento, /** * A memento object that stores state independent * of the current opened {@link workspace.workspaceFolders workspace}. */ readonly globalState: Memento, /** * Primary service class */ readonly service: VlocodeService, /** * The mode the extension is running in. */ readonly mode: ExtensionMode) { } /** * Get the absolute path of a resource contained in the extension. * * @param relativePath A relative path to a resource contained in the extension. * @return The absolute path of the resource. */ public asAbsolutePath(relativePath: string): string { return path.join(this.extensionPath, relativePath); } } /** * Get the currently initialized Vlocode context object */ export function getContext() { return getInstance(VlocodeContext); } /** * Create a VlocodeContext from an existing ExtensionContext object. * @param context VS Codes extension context */ export function initializeContext(context: ExtensionContext, service: VlocodeService) { return singleton(VlocodeContext, context.extensionPath, context.workspaceState, context.globalState, service, context.extensionMode ); }
db00e395bdfde5d8c9451ecb1b91df4e63227dd8
TypeScript
jakzo/things
/old-things/src/file-utils/file-types/json.ts
2.734375
3
import fs from 'mz/fs'; import * as goldenFleece from 'golden-fleece'; import { prettifyIfNecessary } from '../util/prettier'; export const readFile = async (filePath: string) => { const contents = await fs.readFile(filePath, 'utf8'); const value = goldenFleece.evaluate(contents); return { contents, value }; }; /** * Set the contents of a JSON file without modifying formatting of existing properties which are * not modified. */ export const updateFile = async (filePath: string, newValue: any, usePrettier?: boolean) => { const { contents } = await readFile(filePath); const newContents = await prettifyIfNecessary(filePath, patch(contents, newValue), usePrettier); await fs.writeFile(filePath, newContents); }; export const patch = (contents: string, newValue: any) => goldenFleece.patch(contents, newValue);
bf3c34cbc3e42e6e8361464aab993ed16942e444
TypeScript
muradkhan101/book-trading
/src/user/user.ts
2.859375
3
export class User { public id : string; public email : string; public password : string; public lastName : string; public firstName : string; constructor(id: string, firstName: string, email: string, password: string) { this.id = id; this.firstName = firstName; this.email = email; this.password = password; } getPassword(): string { return this.password; } }
38dcef81d3dca063f36b09c426847d4d6e91d0d2
TypeScript
xinapxix/invernadero
/main.ts
2.53125
3
basic.forever(function () { while (input.buttonIsPressed(Button.AB)) { if (input.temperature() >= 8 && input.temperature() <= 30) { basic.showString("TN") } else { if (input.temperature() > 30) { basic.showString("TA") music.playTone(988, music.beat(BeatFraction.Double)) } else { basic.showString("TB") music.playTone(131, music.beat(BeatFraction.Breve)) } } if (pins.analogReadPin(AnalogPin.P1) >= 200 && pins.analogReadPin(AnalogPin.P1) <= 600) { basic.showString("HN") } else { if (pins.analogReadPin(AnalogPin.P1) > 600) { basic.showString("HA") music.playTone(587, music.beat(BeatFraction.Double)) } else { basic.showString("HB") music.playTone(247, music.beat(BeatFraction.Breve)) } } } while (input.buttonIsPressed(Button.A)) { if (input.temperature() >= 8 && input.temperature() <= 30) { basic.showString("TN") } else { if (input.temperature() > 30) { basic.showString("TA") music.playTone(988, music.beat(BeatFraction.Double)) } else { basic.showString("TB") music.playTone(131, music.beat(BeatFraction.Breve)) } } } while (input.buttonIsPressed(Button.B)) { if (pins.analogReadPin(AnalogPin.P1) >= 200 && pins.analogReadPin(AnalogPin.P1) <= 600) { basic.showString("HN") } else { if (pins.analogReadPin(AnalogPin.P1) > 600) { basic.showString("HA") music.playTone(587, music.beat(BeatFraction.Double)) } else { basic.showString("HB") music.playTone(247, music.beat(BeatFraction.Breve)) } } } })
54d7995c4abaa704c00e0791bfe997858c4f1431
TypeScript
dhamotharang/node-s9foju
/app/modules/reporting/models/charts/stacked-bar-time-series/report-stacked-bar-time-series.model.ts
2.640625
3
import ReportTimeSeriesDataPoint from '../time-series/report-time-series-data-point'; import {ReportStackedBarTimeSeriesConfiguration} from './report-stacked-bar-time-series-configuration'; export default class ReportStackedBarTimeSeries<T> { public id: string; public displayName: string; public points: Array<ReportTimeSeriesDataPoint<T>>; public configuration: ReportStackedBarTimeSeriesConfiguration; constructor( id: string, displayName: string, points: Array<ReportTimeSeriesDataPoint<T>>, configuration: ReportStackedBarTimeSeriesConfiguration ) { this.id = id; this.points = points; this.displayName = displayName; this.configuration = configuration; } public hasPoints(): boolean { return this.points.length > 0; } }
d14545d5a3d457eee0c8e3667049ab61e31784b1
TypeScript
akhilanil/roster
/roster-frontend/src/app/shared/roster-input/roster-input-validator.ts
2.65625
3
import { ValidatorFn, AbstractControl, FormGroup, FormControl } from "@angular/forms"; import { RosterListCacheService } from '@services/cache-manager' import { ReplaySubject } from "rxjs"; import { CreateRosterRSModel } from "@interfaces/business-interface"; export class RosterInputValidator { constructor() {} /** Validator for duplicate roster */ public static validateForDupRoster( rosterList: Array<CreateRosterRSModel>, formGroup: FormGroup): ValidatorFn { return (control: AbstractControl) => { if(formGroup == null) { return null; } let titleControl = formGroup.get('tc'); let yearControl = formGroup.get('yc'); let monthControl = formGroup.get('mc'); console.log(titleControl, yearControl, monthControl, control.value) if(titleControl == null || yearControl == null || monthControl == null) { return null; } control.value if(control.pristine || rosterList == null || rosterList.length === 0 || titleControl.pristine || yearControl.pristine || monthControl.pristine) { return null; } let title: string = titleControl.value; let year: string = yearControl.value; let month: string = monthControl.value; rosterList.forEach((roster: CreateRosterRSModel) => { let rosterMonth: string; let rosterYear: string; let rosterTitle: string if(typeof roster.month === "number") { rosterMonth = '' + roster.month } if(typeof roster.year === "number") { rosterYear = '' + roster.month } let isDuplicate: boolean = false; console.log(title, year, month); console.log(rosterList) if(title.trim().toUpperCase === rosterTitle.trim().toUpperCase && year.trim().toUpperCase === rosterYear.trim().toUpperCase && month.trim().toUpperCase === rosterMonth.trim().toUpperCase ) { return {'duproster': true}; } }); return null; } } /*Validates for same name */ public static checkForDuplicates(formGroup: FormGroup, checkFor: string ): ValidatorFn { let values: Array<string> = new Array<string>(); return (control: AbstractControl) => { if(control.pristine) { return null; } values = []; Object.keys(formGroup.controls).forEach(key => { let val:string = formGroup.get(key).value if(formGroup.controls[key] != control && val.length != 0 && key.startsWith(checkFor)) { values.push(val.toUpperCase()); } }) return values.includes(control.value.toUpperCase())? {'duplicates': true} : null; } } /* * Validates for conflict in participant and session */ public static checkForNameConflicts(formGroup: FormGroup ): ValidatorFn { let controlMap : Map<String, String> = new Map<String, String>(); let currentGroup: string; return (control: AbstractControl) => { if(control.pristine) { return null; } controlMap.clear(); Object.keys(formGroup.controls).forEach(key => { let val:string = formGroup.get(key).value.toUpperCase(); if(val.trim().length != 0) { if(formGroup.controls[key] == control) { if(key.startsWith('session')) { currentGroup = 'session' } else if(key.startsWith('participant')) { currentGroup = 'participant' } } else { controlMap.set(key, val); } } }) let isNotValid: boolean = false; controlMap.forEach((value, key) => { if(!key.startsWith(currentGroup) && value == control.value.toUpperCase() ) { isNotValid = true; } }) if(isNotValid) { return {'conflict': true} } return null; } } }
c1b19280319d1cec24b284b22d9b80de71f7e1a9
TypeScript
william-gooch/root-rpg-model
/src/model/playbooks/drives.ts
2.796875
3
export interface Drive { name: string; description: string; } const drives = { "justice": { name: "Justice", description: "Advance when you achieve justice for someone wronged by a powerful, wealthy, or high-status individual.", }, "principles": { name: "Principles", description: "Advance when you express or embody your moral principles at great cost to yourself or your allies.", }, "loyalty": { name: "Loyalty", description: "You’re loyal to someone; name them. Advance when you obey their order at a great cost to yourself.", }, "protection": { name: "Protection", description: "Name your ward. Advance when you protect them from significant danger, or when time passes and your ward is safe.", }, "discovery": { name: "Discovery", description: "Advance when you encounter a new wonder or ruin in the forests.", }, "freedom": { name: "Freedom", description: "Advance when you free a group of denizens from oppression.", }, "revenge": { name: "Revenge", description: "Name your foe. Advance when you cause significant harm to them or their interests.", }, "chaos": { name: "Chaos", description: "Advance when you topple a tyrannical or dangerously overbearing figure or order.", }, "thrills": { name: "Thrills", description: "Advance when you escape from certain death or incarceration.", }, "crime": { name: "Crime", description: "Advance when you illicitly score a significant prize or pull off an illegal caper against impressive odds.", }, "infamy": { name: "Infamy", description: "Advance when you decrease your reputation with any faction.", }, "greed": { name: "Greed", description: "Advance when you secure a serious payday or treasure.", }, "ambition": { name: "Ambition", description: "Advance when you increase your reputation with any faction.", }, "clean-paws": { name: "Clean Paws", description: "Advance when you accomplish an illicit, criminal goal while maintaining a believable veneer of innocence.", }, "wanderlust": { name: "Wanderlust", description: "Advance when you finish a journey to a clearing.", } } as const; export default drives;
7d6307cd36db432d1ee78b152c457f3174e61a38
TypeScript
guideofneb/guideofneb_tools
/src/gauss_seidel_solver/shared/areArrayEqual.ts
2.65625
3
const areArrayEqual = (firstArray : any[], secondArray : any[]) : boolean => { let isEqual = true; firstArray.map((v, i) => { if (secondArray[i] !== v) { isEqual = false; } }); return isEqual; }; export default areArrayEqual;
ff0a3e56c9703c31c2bb383c1146905a14722499
TypeScript
Erudition/elm-native
/src/transitions/index.ts
2.671875
3
import { CubicBezierAnimationCurve, Pair } from "@nativescript/core/ui/animation"; import { AnimationCurve } from "@nativescript/core/ui/enums"; import { Animation, AnimationDefinition, Color, View } from "@nativescript/core"; import { ease_in, ease_out, ease, linear, ease_in_out, animation_curve, normalizeCurve, partialCurveFrom, reverseCurve, CubicBezier } from "./bezier" import * as easings from './easing' import { NativeViewElementNode } from "../dom"; enum AnimationDirection { Unknown, In, Out } export interface NativeAnimationDefinition { opacity?: number; backgroundColor?: Color; translate?: Pair; scale?: Pair; rotate?: number; } export function asSvelteTransition(node: NativeViewElementNode<View>, delay: number = 0, duration: number = 300, curve: string | CubicBezierAnimationCurve = AnimationCurve.linear, nativeAnimationProps: (t: number) => NativeAnimationDefinition) { let svelteAnim: any = { delay: delay, duration: duration, } let svelteCurve: CubicBezier; if (typeof curve == "string") { switch (curve) { case AnimationCurve.ease: svelteCurve = ease; break; case AnimationCurve.easeIn: svelteCurve = ease_in; break; case AnimationCurve.easeOut: svelteCurve = ease_out; break; case AnimationCurve.easeInOut: svelteCurve = ease_in_out; break; case AnimationCurve.linear: svelteCurve = linear; break; default: console.warn("Unsupported nativescript animation name, reverting to linear") svelteCurve = linear; } } if (curve instanceof CubicBezierAnimationCurve) { //convert to our bezier format svelteCurve = animation_curve(curve.x1, curve.y1, curve.x2, curve.y2); } //default to linear if (!curve) { svelteCurve = linear } let direction = AnimationDirection.Unknown let animation: Animation = null; let last_t = -1; const cancelNativeAnimation = () => { if (animation && animation.isPlaying) { // console.log("cancelling animation on ", node); let oldanimation = animation; animation = null; oldanimation.cancel(); } animation = null; } //Tick is our hook into sveltes transition system. We want to detect a forward or backward animation, //determine the end value, and do a single native animation for the entire duration. //the spanner in the works is that there is a transistion type (in_out) that can stop mid animation and play in reverse //we need to do some math to generate a curve that can apply to the shortened time that mirrors the intro that has already played. // we note the following svelte behaviour: // "in" animations always get an explicit tick(0, 1) even before any delay. // "out" animations have no such quality, therefore we can expect that if we have not been initialized, and get a t=0 we are an Intro svelteAnim.tick = (t: number) => { //when you cancel an animation, it appears to set the values back to the start. we use this to reapply them at the given time. function applyAnimAtTime(time: number) { let animDef = nativeAnimationProps(time); if (typeof animDef.opacity !== 'undefined') node.nativeView.opacity = animDef.opacity; if (typeof animDef.backgroundColor != 'undefined') node.nativeView.backgroundColor = animDef.backgroundColor; if (typeof animDef.rotate != 'undefined') node.nativeView.rotate = animDef.rotate; if (typeof animDef.scale != 'undefined') { node.nativeView.scaleX = animDef.scale.x; node.nativeView.scaleY = animDef.scale.y; } if (typeof animDef.translate != 'undefined') { node.nativeView.translateX = animDef.translate.x; node.nativeView.translateY = animDef.translate.y; } } //our first frame! are we an in or out if (direction == AnimationDirection.Unknown) { //intro: do an initialize if (t === 0) { applyAnimAtTime(0); direction = AnimationDirection.In last_t = 0; // console.log("forward animation detected!", node); //don't start our full animation yet since this is just the init frame, and there will be a delay. so wait for next frame return; } else { //we must be an outro since all intros get a t==0 // console.log("reverse animation detected!", node); direction = AnimationDirection.Out last_t = t; } } //have we changed direction? if (direction == AnimationDirection.In && last_t > t) { // console.log("animation changed direction (In -> Out)", t, node); direction = AnimationDirection.Out cancelNativeAnimation(); applyAnimAtTime(t); } if (direction == AnimationDirection.Out && last_t < t) { // console.log("animation changed direction (Out -> In)", t, node); direction = AnimationDirection.In cancelNativeAnimation(); applyAnimAtTime(t); } last_t = t; if (!animation) { //create a new animation that will cover us from now to either t=duration or t=0 let target_t = (direction == AnimationDirection.In) ? 1 : 0; let animProps = nativeAnimationProps(target_t) let nsAnimation: AnimationDefinition = { ...animProps } nsAnimation.delay = 0; if (direction == AnimationDirection.Out) { //we need to play in reverse, and we might not be playing the whole thing let forwardCurve = t == 1 ? svelteCurve : partialCurveFrom(svelteCurve, 0, t) let finalCurve = normalizeCurve(reverseCurve(forwardCurve)); nsAnimation.curve = AnimationCurve.cubicBezier(finalCurve.x1, finalCurve.y1, finalCurve.x2, finalCurve.y2); nsAnimation.duration = t * duration; } else { //we might be starting from halfway (intro->outro-intro again) let forwardCurve = t == 0 ? svelteCurve : partialCurveFrom(svelteCurve, t, 1) let finalCurve = normalizeCurve(forwardCurve); nsAnimation.curve = AnimationCurve.cubicBezier(finalCurve.x1, finalCurve.y1, finalCurve.x2, finalCurve.y2); nsAnimation.duration = (1 - t) * duration; } //console.log("animation created", t, (direction == AnimationDirection.In) ? "Intro" : "Outro", nsAnimation, node); // kick it off animation = node.nativeView.createAnimation(nsAnimation); animation.play(); } } return svelteAnim; } /* ported from svelte transitions */ export function fade(node: NativeViewElementNode<View>, { delay = 0, duration = 400 }) { const o = node.nativeView.opacity; return asSvelteTransition(node, delay, duration, AnimationCurve.linear, (t) => ({ opacity: t * o }) ); } export function fly(node: NativeViewElementNode<View>, { delay = 0, duration = 400, easing = AnimationCurve.easeOut, x = 0, y = 0 }) { const opacity = node.nativeView.opacity; const translateX = node.nativeView.translateX; const translateY = node.nativeView.translateY; return asSvelteTransition(node, delay, duration, easing, (t) => ({ opacity: t * opacity, translate: { x: translateX + (1 - t) * x, y: translateY + (1 - t) * y } }) ); } export function slide(node: NativeViewElementNode<View>, { delay = 0, duration = 400, easing = AnimationCurve.easeOut }) { const height = node.nativeView.effectiveHeight; const scaleX = node.nativeView.scaleX; const scaleY = node.nativeView.scaleY; const translateX = node.nativeView.translateX; const translateY = node.nativeView.translateY; return asSvelteTransition(node, delay, duration, easing, t => ({ scale: { x: scaleX, y: t * scaleY }, translate: { x: translateX, y: translateY - t * 0.5 * height } }) ); } export { easings }
0308282389483c4c1ad086c52479f0b2420f80a7
TypeScript
frontend-park-mail-ru/2020_2_JMickhs
/src/components/popup/message-popup/message-popup.ts
2.609375
3
import type { AbstractComponent } from '@interfaces/components'; import * as template from './message-popup.hbs'; import './message-popup.css'; export default class MessagePopup implements AbstractComponent { private place: HTMLDivElement; activate(message: string, isError: boolean): void { if (this.place === undefined) { return; } this.place.innerHTML = template({ text: message, error: isError }); } setPlace(place: HTMLDivElement): void { this.place = place; } deactivate(): void { if (this.place === undefined) { return; } this.place.innerHTML = ''; } }
4d58ebef2dc1008b4fbda4ca3eccc11dfe6cbddb
TypeScript
NathanFlurry/tanks-typescript-canvas-socketio
/shared/Player.ts
2.78125
3
import { Client } from "../client/Client"; import { Game, generateId } from "./Game"; import { Utilities } from "./Utilities"; import { EntityState } from "./Entity"; import { BulletState, createBullet } from "./Bullet"; export interface PlayerState extends EntityState { id: number; positionX: number; positionY: number; aimDir: number; moveX: number; moveY: number; health: number; score: number; } export const PLAYER_MOVE_SPEED: number = 500; export const PLAYER_RADIUS: number = 76; export const BARREL_LENGTH: number = 45; export function createPlayer(game: Game): PlayerState { let state = { id: generateId(game), positionX: Utilities.lerp( -game.arenaSize / 2, game.arenaSize / 2, Math.random() ), positionY: Utilities.lerp( -game.arenaSize / 2, game.arenaSize / 2, Math.random() ), aimDir: 0, moveX: 0, moveY: 0, health: 1, score: 0, }; game.state.players[state.id] = state; return state; } export function updatePlayer(game: Game, state: PlayerState, dt: number) { // Move the player based on the move input state.positionX += state.moveX * PLAYER_MOVE_SPEED * dt; state.positionY += state.moveY * PLAYER_MOVE_SPEED * dt; // Restrain to bounds state.positionX = Math.max( state.positionX, -game.arenaSize / 2 + PLAYER_RADIUS ); state.positionX = Math.min( state.positionX, game.arenaSize / 2 - PLAYER_RADIUS ); state.positionY = Math.max( state.positionY, -game.arenaSize / 2 + PLAYER_RADIUS ); state.positionY = Math.min( state.positionY, game.arenaSize / 2 - PLAYER_RADIUS ); } export function renderPlayer( client: Client, state: PlayerState, ctx: CanvasRenderingContext2D ) { ctx.save(); ctx.translate(state.positionX, -state.positionY); // Draw body ctx.save(); ctx.rotate(Math.atan2(-state.moveY, state.moveX) + Math.PI / 2); let bodyWidth = client.assets.tankBodyRed.width * client.assets.scaleFactor; let bodyHeight = client.assets.tankBodyRed.height * client.assets.scaleFactor; ctx.drawImage( client.assets.tankBodyRed, -bodyWidth / 2, -bodyHeight / 2, bodyWidth, bodyHeight ); ctx.restore(); // Draw barrel ctx.save(); ctx.rotate(state.aimDir + Math.PI / 2); let barrelWidth = client.assets.tankBarrelRed.width * client.assets.scaleFactor; let barrelHeight = client.assets.tankBarrelRed.height * client.assets.scaleFactor; ctx.drawImage( client.assets.tankBarrelRed, -barrelWidth / 2, -barrelHeight * 0.75, barrelWidth, barrelHeight ); ctx.restore(); // Draw health let healthY = -PLAYER_RADIUS - 5; let healthWidth = 80; let healthHeight = 10; let healthPadding = 4; ctx.save(); ctx.fillStyle = "#333"; ctx.fillRect( -healthWidth / 2 - healthPadding, healthY - healthHeight / 2 - healthPadding, healthWidth + healthPadding * 2, healthHeight + healthPadding * 2 ); ctx.fillStyle = "white"; ctx.fillRect( -healthWidth / 2, healthY - healthHeight / 2, healthWidth * state.health, healthHeight ); ctx.restore(); // Draw score let scoreY = healthY - 25; ctx.save(); ctx.fillStyle = "white"; ctx.strokeStyle = "#333"; ctx.lineWidth = 6; ctx.font = Utilities.font(32, 700); ctx.strokeText(state.score.toString(), 0, scoreY); ctx.fillText(state.score.toString(), 0, scoreY); ctx.restore(); ctx.restore(); } export function shoot(game: Game, state: PlayerState): BulletState { let dirX = Math.cos(state.aimDir); let dirY = -Math.sin(state.aimDir); let bulletX = state.positionX + dirX * BARREL_LENGTH; let bulletY = state.positionY + dirY * BARREL_LENGTH; return createBullet( game, state.id, bulletX, bulletY, Math.atan2(dirY, dirX) ); } export function damagePlayer( game: Game, state: PlayerState, amount: number, damagerId?: number ) { state.health -= amount; if (state.health <= 0) { onPlayerKill(game, state, damagerId); } } function onPlayerKill(game: Game, state: PlayerState, killerId?: number) { // Give points to the killer if (killerId) { let killer = game.state.players[killerId]; if (killer) { killer.score += 1; } } // Remove this player delete game.state.players[state.id]; }
0c608edc9a3e73a1fcc832e8cc609faafbe2b4e4
TypeScript
harerakalex/chatti-backend
/src/helpers/__test__/responseHandeler.helper.spec.ts
2.578125
3
import { ResponseHandler, IError } from '../responseHandler.helper'; describe(ResponseHandler, () => { let res: any; res = { status: jest .fn(() => ({ json: jest.fn(), })) .mockReturnValue({ json: jest.fn() }), }; it('Should send error response with provided status', () => { const error: IError = { message: 'An error', statusCode: 400, error: new Error(), }; ResponseHandler.sendErrorResponse(res, error); expect(res.status).toBeCalledWith(400); }); it('Should send error response with 500 if no provided status', () => { const error: IError = { message: 'An error', error: new Error(), }; ResponseHandler.sendErrorResponse(res, error); expect(res.status).toBeCalledWith(500); }); });
fa97e6b76b2651378a260b3880b59878dc707b91
TypeScript
SvetlanaZhak/Aktia
/src/backend/utils.ts
2.5625
3
import fetch, { RequestInit } from 'node-fetch'; export function fetchJson(url: string, method?: string, body?: any) { const options: RequestInit = { method: method || 'GET', headers: { 'Content-Type': 'application/json' } }; if (body) { options.body = JSON.stringify(body); } return fetch(url, options); }
34039617f5b5ef82c7674cfd0ce7dd7561bc5c60
TypeScript
modulexcite/Glimpse.Client.Prototype
/src/request/component-models/LoggingComponentModel.ts
2.625
3
'use strict'; import { ComponentModel } from './ComponentModel'; import { IGlimpse } from '../../IGlimpse'; import { ILoggingComponentModel, ILoggingLevelModel, ILogMessageModel, ILogMessageSpan } from './ILoggingComponentModel'; import { ILoggingComponentState } from './ILoggingComponentState'; import { ILogMessage, ILogMessageReplacedRegion } from '../messages/ILogMessage'; import { IMessageEnvelope } from '../messages/IMessageEnvelope'; import { IRequestDetailStore } from '../stores/IRequestDetailStore'; import _ = require('lodash'); export class LogMessageModel implements ILogMessageModel { private static OBJECT_BRACE_WINDOW = 64; private _isObject: boolean; private _spans: ILogMessageSpan[]; public constructor(private _message: IMessageEnvelope<ILogMessage>, private _ordinal: number) { } public get id(): string { return this._message.id; } public get isObject(): boolean { if (this._isObject === undefined) { this._isObject = LogMessageModel.isMessageObject(this._message.payload.message); } return this._isObject; } public get level(): string { return this._message.payload.level; } public get message(): string { return this._message.payload.message; } public get ordinal(): number { return this._ordinal; } public get replacedRegions(): ILogMessageReplacedRegion[] { return this._message.payload.replacedRegions; } public get spans(): ILogMessageSpan[] { if (!this._spans) { this._spans = LogMessageModel.createSpans(this.message, this.replacedRegions); } return this._spans; } private static indexOf(value: string, term: string, window: number) { for (let i = 0; i < value.length && i < window; i++) { if (value[i] === term) { return i; } } return -1; } private static isMessageObject(message: string): boolean { // // NOTE: Our heuristic for determining whether text represents an object rather simplistic // (to minimize impact on performance). We simply look for starting and ending braces // (i.e. '{' and '}') near the beginning and ending of the text, respectively, allowing // for whitespace and other text that might pre-fix/post-fix the actual object. // if (message) { const length = message.length; if (length > 0) { const startIndex = LogMessageModel.indexOf(message, '{', LogMessageModel.OBJECT_BRACE_WINDOW); const lastIndex = LogMessageModel.lastIndexOf(message, '}', LogMessageModel.OBJECT_BRACE_WINDOW); if (startIndex >= 0 && lastIndex >= 0 && startIndex < lastIndex) { return true; } } } return false; } private static lastIndexOf(value: string, term: string, window: number) { const lastWindowIndex = value.length - window; for (let i = value.length - 1; i >= 0 && i >= lastWindowIndex; i--) { if (value[i] === term) { return i; } } return -1; } private static createSpans(message: string, replacedRegions: ({ start: number, end: number })[]): ILogMessageSpan[] { if (!message || message.length === 0) { return [{ text: '' }]; } replacedRegions = _.sortBy(replacedRegions || [], region => region.start); let messageIndex = 0; const messageStructure = []; for (let i = 0; i < replacedRegions.length; i++) { const region = replacedRegions[i]; if (region.start < 0 || region.start >= message.length) { console.warn('The region [%d,%d) exceeds the bounds of the log message (length === %d).', region.start, region.end, message.length); continue; } if (region.end < 0 || region.end > message.length) { console.warn('The region [%d,%d) exceeds the bounds of the log message (length === %d).', region.start, region.end, message.length); continue; } if (region.end < region.start) { console.warn('The region [%d,%d) is not a contiguous span in the log message (length === %d).', region.start, region.end, message.length); continue; } if (region.start < messageIndex) { console.warn('The region [%d,%d) overlaps a previous span in the log message (length === %d).', region.start, region.end, message.length); continue; } if (region.start === region.end) { // Ignore zero-length regions (to prevent creating three spans when one will do). continue; } if (messageIndex < region.start) { messageStructure.push({ text: message.substring(messageIndex, region.start) }); } messageStructure.push({ text: message.substring(region.start, region.end), wasReplaced: true }); messageIndex = region.end; } if (messageIndex < message.length) { messageStructure.push({ text: message.substring(messageIndex, message.length) }); } return messageStructure; } } class LoggingLevelModel implements ILoggingLevelModel { public constructor(private _level: string, private _messageCount: number) { } public get level(): string { return this._level; } public get messageCount(): number { return this._messageCount; } } export class LoggingComponentModel extends ComponentModel implements ILoggingComponentModel { private _levels: LoggingLevelModel[]; private _messages: ILogMessageModel[]; public constructor(private _glimpse: IGlimpse, private _requestDetailStore: IRequestDetailStore, private _messageProcessor) { super(); } public get levels(): ILoggingLevelModel[] { return this._levels; } public get totalMessageCount(): number { return this._messages.length; } public init(request) { const options = { 'log-write': this._messageProcessor.getTypeMessageList }; const allMessages = this._messageProcessor.getTypeStucture(request, options); if (allMessages) { this._messages = _(allMessages.logWrite) .sortBy<IMessageEnvelope<ILogMessage>>('ordinal') .map((message, index) => new LogMessageModel(message, index + 1)) .value(); const levels: { [key: string]: ILogMessageModel[] } = {}; _.defaults(levels, _.groupBy(this._messages, message => message.level), { Debug: [], Verbose: [], Information: [], Warning: [], Error: [], Critical: [] }); this._levels = _(levels) .transform( (result: LoggingLevelModel[], messages, level) => { result.push(new LoggingLevelModel(level, messages.length)); }, []) .sortBy(level => LoggingComponentModel.getOrderOfLevel(level.level)) .value(); } else { this._levels = []; this._messages = []; }; } public getMessages(): ILogMessageModel[] { const state = this._requestDetailStore.getState().logging.filter; let filteredMessages = _(this._messages); if (state) { _.filter(this._levels, level => { return state[level.level] === false; }) .forEach(level => { filteredMessages = filteredMessages.filter(message => message.level !== level.level); }); } return filteredMessages.value(); } public isShown(level: ILoggingLevelModel): boolean { const state = this._requestDetailStore.getState().logging.filter; return state === undefined || state[level.level] !== false; } public showAll(): void { const state = _.clone(this._requestDetailStore.getState().logging.filter); let updated = false; _.forIn(state, (shown, level) => { if (state[level] === false) { state[level] = true; updated = true; } }); if (updated) { this.emitUpdate(state); } } public toggleLevel(level: ILoggingLevelModel): void { const state = _.clone(this._requestDetailStore.getState().logging.filter); if (state[level.level] === false) { state[level.level] = true; } else { state[level.level] = false; } this.emitUpdate(state); } private emitUpdate(state: ILoggingComponentState) { this._glimpse.emit('data.request.detail.logging.filter', state); } private static getOrderOfLevel(level: string): number { switch (level) { case 'Critical': return 1; case 'Error': return 2; case 'Warning': return 3; case 'Information': return 4; case 'Verbose': return 5; case 'Debug': return 6; default: return 7; } } }
a3658a3728f3bab65c317fd55079f6df39ed0ee7
TypeScript
Ionaru/array-utils
/src/functions/sort-array-by-object-property.spec.ts
3.34375
3
import { beforeEach, describe, expect, it } from 'vitest'; import { sortArrayByObjectProperty } from './sort-array-by-object-property.js'; describe('sortArrayByObjectProperty', () => { let unsortedArray: Array<{ value: number }>; beforeEach(() => { unsortedArray = [ { value: 2 }, { value: 3 }, { value: 0 }, { value: 4 }, { value: 1 }, ]; }); it('sorting an array with only one value', () => { expect.assertions(1); const array = [{ value: 3 }]; sortArrayByObjectProperty(array, (element) => element.value); expect(array).toStrictEqual([{ value: 3 }]); }); it('reverse sorting an array with only one value', () => { expect.assertions(1); const array = [{ value: 3 }]; sortArrayByObjectProperty(array, (element) => element.value, true); expect(array).toStrictEqual([{ value: 3 }]); }); it('sorting an array by object property', () => { expect.assertions(1); sortArrayByObjectProperty(unsortedArray, (element) => element.value); expect(unsortedArray).toStrictEqual([ { value: 0 }, { value: 1 }, { value: 2 }, { value: 3 }, { value: 4 }, ]); }); it('reverse sorting an array by object property', () => { expect.assertions(1); sortArrayByObjectProperty( unsortedArray, (element) => element.value, true, ); expect(unsortedArray).toStrictEqual([ { value: 4 }, { value: 3 }, { value: 2 }, { value: 1 }, { value: 0 }, ]); }); it('sort an array with some equal values', () => { expect.assertions(1); const unsortedArrayWithEqualValue = [ { value: 2 }, { value: 3 }, { value: 2 }, { value: 4 }, { value: 1 }, ]; sortArrayByObjectProperty( unsortedArrayWithEqualValue, (element) => element.value, ); expect(unsortedArrayWithEqualValue).toStrictEqual([ { value: 1 }, { value: 2 }, { value: 2 }, { value: 3 }, { value: 4 }, ]); }); it('sorting an array with only equal values', () => { expect.assertions(1); const unsortedArrayWithEqualValues = [ { value: 2 }, { value: 2 }, { value: 2 }, { value: 2 }, { value: 2 }, ]; sortArrayByObjectProperty( unsortedArrayWithEqualValues, (element) => element.value, ); expect(unsortedArrayWithEqualValues).toStrictEqual([ { value: 2 }, { value: 2 }, { value: 2 }, { value: 2 }, { value: 2 }, ]); }); it('reverse sorting an array with only equal values', () => { expect.assertions(1); const unsortedArrayWithEqualValues = [ { value: 2 }, { value: 2 }, { value: 2 }, { value: 2 }, { value: 2 }, ]; sortArrayByObjectProperty( unsortedArrayWithEqualValues, (element) => element.value, true, ); expect(unsortedArrayWithEqualValues).toStrictEqual([ { value: 2 }, { value: 2 }, { value: 2 }, { value: 2 }, { value: 2 }, ]); }); it('reverse sort an array with some equal values', () => { expect.assertions(1); const unsortedArrayWithEqualValue = [ { value: 2 }, { value: 3 }, { value: 2 }, { value: 4 }, { value: 1 }, ]; sortArrayByObjectProperty( unsortedArrayWithEqualValue, (element) => element.value, true, ); expect(unsortedArrayWithEqualValue).toStrictEqual([ { value: 4 }, { value: 3 }, { value: 2 }, { value: 2 }, { value: 1 }, ]); }); it('attempting to sort an undefined value in an array must throw an error', () => { expect.assertions(1); const unsortedArrayWithUndefinedValue = [ { value: 2 }, { value: 3 }, { value: undefined }, { value: 4 }, { value: 1 }, ]; expect(() => { // @ts-expect-error Should throw an error. sortArrayByObjectProperty( unsortedArrayWithUndefinedValue, (element) => element.value, ); }).toThrow( /^Unable to compare values '(3|undefined)' and '(3|undefined)'$/, ); }); it('attempting to sort a string value in an array must throw an error', () => { expect.assertions(1); const unsortedArrayWithStringValue = [ { value: 2 }, { value: 3 }, { value: '2' }, { value: 4 }, { value: 1 }, ]; expect(() => { sortArrayByObjectProperty( unsortedArrayWithStringValue, (element) => element.value, ); }).toThrow( /^Unable to compare different types: '[23]' \((number|string)\) and '[23]' \((number|string)\)$/, ); }); it('sort an array with string values', () => { expect.assertions(1); const unsortedArrayWithStringValues = [ { value: '2' }, { value: '3' }, { value: '2' }, { value: '4' }, { value: '1' }, ]; sortArrayByObjectProperty( unsortedArrayWithStringValues, (element) => element.value, ); expect(unsortedArrayWithStringValues).toStrictEqual([ { value: '1' }, { value: '2' }, { value: '2' }, { value: '3' }, { value: '4' }, ]); }); it('sort an array with nested values', () => { expect.assertions(1); const unsortedArrayWithEqualValue = [ { value: { value: 2 } }, { value: { value: 3 } }, { value: { value: 2 } }, { value: { value: 4 } }, { value: { value: 1 } }, ]; sortArrayByObjectProperty( unsortedArrayWithEqualValue, (element) => element.value.value, true, ); expect(unsortedArrayWithEqualValue).toStrictEqual([ { value: { value: 4 } }, { value: { value: 3 } }, { value: { value: 2 } }, { value: { value: 2 } }, { value: { value: 1 } }, ]); }); it('sort an array with double nested values', () => { expect.assertions(1); const unsortedArrayWithEqualValue = [ { value: { value: { value: 2 } } }, { value: { value: { value: 3 } } }, { value: { value: { value: 2 } } }, { value: { value: { value: 4 } } }, { value: { value: { value: 1 } } }, ]; sortArrayByObjectProperty( unsortedArrayWithEqualValue, (element) => element.value.value.value, true, ); expect(unsortedArrayWithEqualValue).toStrictEqual([ { value: { value: { value: 4 } } }, { value: { value: { value: 3 } } }, { value: { value: { value: 2 } } }, { value: { value: { value: 2 } } }, { value: { value: { value: 1 } } }, ]); }); });
25838e90554041728e97dc7e717d819fdba9f37f
TypeScript
GongT/stillalive
/src/test.ts
2.71875
3
import { openSync, read } from 'fs'; import 'source-map-support/register'; import { PassThrough, Transform } from 'stream'; import { promisify } from 'util'; import { startWorking } from './index'; const chars = ['i', 'W', '啊', '깦', 'あ', '😂', '👍🏽', '😂\u0300', 'X\u0300', 'Y\u0300', '\uD834\uDD1E']; function getRandom() { return chars[Math.floor(Math.random() * Math.floor(chars.length))]; } export function test_displayEveyCharFullLine() { const split = Buffer.alloc(process.stdout.columns, '-'); chars.forEach((v, i) => { let s = ''; for (let i = 0; i < 100; i++) { s += v; } split.write(s.toString(), 0); console.log(split.toString()); }); console.log(split.fill('=').toString()); } export function test_longRunning() { const output = startWorking(); let i = 0; const pad = Buffer.alloc(process.stdout.columns, '-').toString(); function next() { i++; output.write(`~~${i}~~${pad}\n`); setTimeout(next, Math.ceil(10 + Math.random() * 40)); } next(); } export function test_readRandomInput() { const output = startWorking(); const input = new PassThrough(); input.pipe(output); let pt = 0, tos: NodeJS.Timer[] = []; tos.push(setInterval(() => { output.success('success:' + pt); pt++; if (pt === 5) { tos.forEach(clearInterval); output.end(); return; } }, 1200)); tos.push(setInterval(() => { let s = '['; for (let i = 0; i < 15; i++) { s += getRandom(); } s += ']'; input.write(s); }, 200)); } class RandomDelay extends Transform { _transform(d: Buffer, e: string, cb: Function) { this.push(d, e); setTimeout(() => { cb(); }, Math.ceil(10 + Math.random() * 40)); } } export async function test_fileInput(f: string) { const output = startWorking(); const delay = new RandomDelay(); delay.pipe(output); output.on('end', () => { output.success('file complete.'); }); const fd = openSync(f, 'r'); const pread = promisify(read); while (true) { const buff = Buffer.alloc(1 + Math.random() * 100); const { bytesRead } = await pread(fd, buff, 0, buff.length, null); if (bytesRead === 0) { break; } delay.write(buff); } } // test_displayEveyCharFullLine(); // test_longRunning(); // test_readRandomInput(); // test_fileInput();
f16cffd893c2c4247232660ebf3dbaff8dd1c766
TypeScript
brannonjames/weather
/src/store/settings/settings.reducer.ts
2.65625
3
import {SettingActionType} from "./settings.actions"; const initialState = { showSplash: true, metric: false }; const settingsReducer = (state = initialState, action) => { const { type, payload } = action; switch (type) { case SettingActionType.SET_IS_METRIC: return { ...state, metric: payload }; default: return state; } }; export default settingsReducer;
cf8a462cb8f336ede49080411b403e440b8ca559
TypeScript
glarimy/glarimy-typescript
/glarimy-typescript-11/main.ts
4.15625
4
interface Library { add(book:Book):void; list():Book[]; } class SimpleLibrary implements Library { protected _entries: Book[]; constructor(){ this._entries = []; } add(book: Book): void{ this._entries.push(book); } list(): Book[]{ return this._entries; } } class Book { private _isbn: number; private _title: string; private _price: number; static readonly _currency: string = "Rs"; constructor(isbn:any, title:any, price: number){ if(typeof isbn == "number") this._isbn = isbn; else if(typeof isbn == "string"){ isbn = parseInt(isbn); if(!isNaN(isbn)) this._isbn = isbn; } this._title = title; this._price = price; } public print(): void { console.log(`Book ISBN: ${this._isbn}, title: ${this._title}, price: ${Book._currency} ${this._price}`); } get isbn() { return this._isbn; } get title() { return this._title; } get price() { return this._price; } set isbn(isbn:number) { this._isbn = isbn; } set title(title:string) { this._title = title } set price(price:number) { this._price = price; } } let library:Library = new SimpleLibrary(); library.add(new Book("123", "Java Script", 100)); library.add(new Book("isbn:678", "Type Script", 120)); library.add(new Book(234, "Angular", 80)); library.list().forEach(e=> e.print());
9cf7bc799c459a6072fae54b755e2465589b1e5d
TypeScript
nguyer/aws-sdk-js-v3
/clients/browser/client-mediaconnect-browser/types/_Messages.ts
2.828125
3
/** * Messages that provide the state of the flow. */ export interface _Messages { /** * A list of errors that might have been generated from processes on this flow. */ Errors: Array<string> | Iterable<string>; } export interface _UnmarshalledMessages extends _Messages { /** * A list of errors that might have been generated from processes on this flow. */ Errors: Array<string>; }
fe6f5c0bc34ff3e20630b73df828d2d8e4205b0d
TypeScript
qjebbs/vscode-plantuml
/src/plantuml/formatRules.ts
2.59375
3
import { RulesWriting, RuleBlockWriting, RuleWriting, compile } from './formatter/ruleCompiler'; import { ElementType } from './formatter/analyst'; let ruleVariables = { //line begin LB: /^\s*/.source, //line end LE: /\s*$/.source, ArrowLeft: /(?:(?:(?:\s+[ox]|[+*])|(?:<\|?|<<|\\\\|\\|\/\/|\})|(?:\s+[ox]|[+*])(?:<\|?|<<|\\\\|\\|\/\/|\}))(?=[-.]))/.source, ArrowRight: /(?:(?:\|?>|>>|\\\\|\\|\/\/|\{)|(?:[ox]\s+|[+*])|(?:\|?>|>>|\\\\|\\|\/\/|\{)(?:[ox]\s+|[+*]))/.source, Color: /(?:\#(?:[0-9a-f]{6}|[0-9a-f]{3}|\w+)(?:[-\\\/](?:[0-9a-f]{6}|[0-9a-f]{3}|\w+))?)/.source } let rules = <RulesWriting>{ includes: ["Quoted", "Block"], blocks: [ { name: "Quoted", rules: [ { comment: "quoted string", begin: /"/i, end: /"/i, beginCaptures: { 0: ElementType.punctLeftSpace }, endCaptures: { 0: ElementType.punctRightSpace }, patterns: { type: ElementType.asIs } }, { comment: "quoted activity definition", match: /{{LB}}(:)(.*)([;|<>/\]}]){{LE}}/i, captures: { 1: ElementType.punctLeftSpace, 2: ElementType.asIs, 3: ElementType.punctRightSpace, } }, { comment: "quoted usecase user definition", match: /(:)([^:]+)(:)/i, captures: { 1: ElementType.punctLeftSpace, 2: ElementType.asIs, 3: ElementType.punctRightSpace, } }, { comment: "quoted component definition", match: /(\[)([^\[\]]+)(\])/i, captures: { 1: ElementType.punctLeftSpace, 2: ElementType.asIs, 3: ElementType.punctRightSpace, } }, { comment: "quoted <> <<>>", match: /(<<?)([^<>]+)(>>?)/i, captures: { 1: ElementType.punctLeftSpace, 2: ElementType.asIs, 3: ElementType.punctRightSpace, } }, ] }, { name: "Block", rules: [ { comment: "block multiple note", isBlock: true, begin: /{{LB}}note\s+(left|right){{LE}}/i, end: /{{LB}}end\s*note{{LE}}/i, patterns: { type: ElementType.word, } }, { comment: "block multiple note of over", isBlock: true, begin: /{{LB}}([rh]?note)(?:\s+(right|left|top|bottom))?\s+(?:(?:(of|over)\s*(?:[^\s\w\d]([\w\s]+)[^\s\w\d]|(\w+)))|(on\s+link))\s*(#\w+)?{{LE}}/i, end: /{{LB}}end\s*note{{LE}}/i, patterns: { type: ElementType.word, } }, { comment: "block multi-line header, legend, footer", isBlock: true, begin: /{{LB}}(?:(center|left|right)\s+)?(header|legend|footer){{LE}}/i, end: /{{LB}}end\s*(header|legend|footer){{LE}}/i, patterns: { type: ElementType.word, } }, { comment: "block if-else-if", isBlock: true, begin: /{{LB}}if\s*\(.*?\)(?:\s*then(\s*\(.*?\))?)?{{LE}}/i, again: /(?:{{LB}}elseif\s*\(.*?\)(?:\s*then(\s*\(.*?\))?)?{{LE}})|(?:{{LB}}else(?:\s*\(.*\))?)/i, end: /{{LB}}endif{{LE}}/i, beginCaptures: { 0: ElementType.asIs, }, againCaptures: { 0: ElementType.asIs, }, endCaptures: { 0: ElementType.word, }, patterns: { includes: ["Quoted", "Block"], } }, { comment: "block split fork", isBlock: true, begin: /{{LB}}(split|fork){{LE}}/i, again: /{{LB}}(split|fork)\s+(again){{LE}}/i, end: /{{LB}}(end)\s*(split|fork){{LE}}/i, againCaptures: { 1: ElementType.word, 2: ElementType.word, }, endCaptures: { 1: ElementType.word, 2: ElementType.word, }, patterns: { includes: ["Quoted", "Block"], } }, { comment: "block repeat while", isBlock: true, begin: /{{LB}}repeat{{LE}}/i, end: /{{LB}}(repeat)\s+(while)(?:\s+\((.+?)?\)(?:\s+(is)(?:\s*\((.+?)?\))?)?)?/i, endCaptures: { 1: ElementType.word, 2: ElementType.word, 3: ElementType.asIs, 4: ElementType.word, 5: ElementType.asIs, }, patterns: { includes: ["Quoted", "Block"], } }, { comment: "block while", isBlock: true, begin: /{{LB}}(while)(?:\s+\((.+?)?\)(?:\s+(is)(?:\s*\((.+?)?\))?)?)?/i, end: /{{LB}}(?:(endwhile)|(end)\s*(while))(?:\s*\((.+)\))?{{LE}}/i, beginCaptures: { 1: ElementType.word, 2: ElementType.asIs, 3: ElementType.word, 4: ElementType.asIs, }, endCaptures: { 1: ElementType.word, 2: ElementType.word, 3: ElementType.word, 4: ElementType.asIs, }, patterns: { includes: ["Quoted", "Block"], } }, { comment: "sequence grouping", isBlock: true, begin: /{{LB}}(opt|loop|par|break|critical|group)\b\s*(.+)?{{LE}}/i, end: /{{LB}}(end){{LE}}/i, beginCaptures: { 1: ElementType.word, 2: ElementType.asIs }, endCaptures: { 1: ElementType.word }, patterns: { includes: ["Quoted", "Block"], } }, { comment: "sequence grouping alt-else", isBlock: true, begin: /{{LB}}(alt)\s*(.+)?{{LE}}/i, again: /{{LB}}(else)\s*(.+)?{{LE}}/i, end: /{{LB}}(end){{LE}}/i, againCaptures: { 1: ElementType.word, 2: ElementType.asIs }, beginCaptures: { 1: ElementType.word, 2: ElementType.asIs }, endCaptures: { 1: ElementType.word }, patterns: { includes: ["Quoted", "Block"], } }, // block {} must be the last rule, // to avoid bad format like "note left of Foo {" // or, the "{" is matched by this rule, "note left of Foo " will be matched // to "block multiple note of over", though that rule requires line ending instead of "{" // because "{" has been taken. { comment: "block {}", isBlock: true, begin: /({{LB}}|[^-])\{[!#+T*-/]?/i, end: /\}(?!-)/i, patterns: { includes: ["Quoted", "Block"], } }, ] }, { name: "Formats", rules: [ { comment: "link operator", match: /(?:{{ArrowLeft}}?[-.]+(\[{{Color}}\])(?:(left|right|up|down)(?:[-.]))?[-.]+{{ArrowRight}}?)|(?:{{ArrowLeft}}[-.]+)|(?:[-.]+{{ArrowRight}})|(?:[-.]{2,})/i, captures: { 0: ElementType.operater, } }, //formats { comment: "@start,@end", match: /(@(?:start|end)\w+)(?:\s+.+)?{{LE}}/i, captures: { 1: ElementType.word, 2: ElementType.asIs, } }, { comment: "preprocessing", match: /{{LB}}!\w+/i, captures: { 0: ElementType.word, } }, { comment: "seprate line", match: /[-.=]{2,}/i, captures: { 0: ElementType.word, } }, { comment: "tree indent", match: /\+{2,}/i, captures: { 0: ElementType.word, } } ] }, { name: "Other", rules: [ { comment: "operators", match: /[|]/i, captures: { 0: ElementType.operater, } }, { comment: "punct right", match: /[:,?;)}]/i, captures: { 0: ElementType.punctRightSpace, } }, { comment: "punct left", match: /[({]/i, captures: { 0: ElementType.punctLeftSpace, } }, { comment: "connectors", match: /@/i, captures: { 0: ElementType.connector, } }, { comment: "as is: a.b|a.|\\n", match: /(\.|\\\w)\s?/i, captures: { 0: ElementType.asIs, } }, { comment: "variables", match: /[\w_]+/i, captures: { 0: ElementType.word, } } ] } ] } export const formatRules = compile(rules, ruleVariables);
6c31e4aac29b3d0c498823251e10e9748b3f4a5d
TypeScript
lynxtaa/inoreader-filter-api
/api/models/Rule.ts
2.53125
3
import { prop, modelOptions, getModelForClass } from '@typegoose/typegoose' import { models, Types } from 'mongoose' import { ArticleProp, FilterType } from '../types' @modelOptions({ schemaOptions: { _id: false } }) class RuleDef { @prop({ enum: ArticleProp, type: String }) prop!: ArticleProp @prop({ enum: FilterType, type: String }) type!: FilterType @prop({ default: false }) negate?: boolean @prop({ maxlength: 128, minlength: 2 }) value!: string } @modelOptions({ schemaOptions: { toJSON: { transform(document, returnedObject) { returnedObject.createdAt = returnedObject.createdAt.toISOString() if (returnedObject.lastHitAt) { returnedObject.lastHitAt = returnedObject.lastHitAt.toISOString() } returnedObject._id = returnedObject._id.toString() delete returnedObject.ruleDef._v delete returnedObject._v }, }, }, }) export class Rule { @prop() _id!: Types.ObjectId @prop() createdAt!: Date @prop({ default: 0 }) hits!: number @prop() lastHitAt?: Date @prop() isActive!: boolean @prop() ruleDef!: RuleDef } const ModelForClass = getModelForClass(Rule) export const RuleModel: typeof ModelForClass = models?.Rule || ModelForClass
38feb102848831c8833be1616e3b72623155710c
TypeScript
hocup/space
/client/src/game/EventEmitter.ts
3.34375
3
export class EventEmitter<T> { private subscribers: ((event: T) => void)[] = []; subscribe(subscriber: (event: T) => void){ this.subscribers.push(subscriber); } unsubscribe(subscriberIndex: number) { this.subscribers[subscriberIndex] = null; } emit(event: T) { for(let k in this.subscribers) { if(this.subscribers[k] != null) { this.subscribers[k](event); } } } }
a65a9dee8f63c8119144ddb8e11166a0e2f0f107
TypeScript
mediamonks/seng-router
/src/lib/AbstractRoute.ts
2.953125
3
import { Promise } from "es6-promise"; import RouteRequirement, { Assertion } from "./RouteRequirement"; import RouteParser from "./RouteParser"; import RouteStringifier from "./RouteStringifier"; import GroupName from "./GroupName"; import IRouteTranslator from "./locale/IRouteTranslator"; import RouteValue from "./RouteValue"; import IRoute from "./IRoute"; /** * It's nice for a Rout to be standalone, if stuff passed in constructor is all we need. * However, there might be some stuff we want to define 'globally' once, like: * - translator (where to get the route translations from (confirms to interface) * - prefix (could also be solved via child routes * - popups (see below!, OR could be util function, needs 'clone' the current route and to the pattern + other configs) * - default param validations, so you don't have to pass them over and over again, this will be copied over on route creation * * Also, if we are going to properly implement child routes, how are we going to manage popups? * Could it be as simple as a last step, appending the 'popup tree' as child routes to all 'leafs' in the route tree? * No need for appending/copying over properties * * How to do child route matching? * Normal routes are exact matches (ending with $ in regexp) * But parent routes should be 'open ended' because they only have to match the beginning * - this means changing the regexp when child routes are 'updated' * After matching the parent route, we trim that part of the route, and pass it to the children * - do this recursively * - if no children match, the parent is also invalid, because we couldn't make an exact match * We could add a child route (at last position) with * pattern, that acts as a not-found/catch-all at that level * - currently we don't support * as a pattern, because it's not named (i.e. not a capturing group) * - can we add * as a pattern that expands to .* * * Parse should supply all matched parameters, also from parents */ abstract class AbstractRoute implements IRoute { public name:string; protected _routes:Array<IRoute> = []; protected _parent:IRoute; protected _pattern:string; protected _groupNames:Array<GroupName> = []; protected _requirements:{[key:string]: RouteRequirement;} = {}; protected _defaults:{[key:string]: RouteValue;} = {}; protected _parsers:{[key:string]: RouteParser;} = {}; protected _stringifiers:{[key:string]: RouteStringifier;} = {}; constructor(pattern:string, name:string) { this._pattern = pattern; this.name = name; } public setName(name:string):void { this.name = name; } public setParent(route:IRoute):void { this._parent = route; } /** * Clears the internal regexp so the next time it's needed it will be refreshed */ public abstract update():void /** * Asserts a param by executing a regular expression or a custom check on * the value. If one of the assertions fails, this route will not match when * resolving a route. * * ``` * new Route('/profile/:id') * .assert(Param.ID, '^\\d+$'); * * new Route('/profile/:id') * .assert(Param.ID, /^\d+$/i); * * new Route('/profile/:id') * .assert(Param.ID, (id) => * { * return !!UserModel.getById(id); * }); * ``` * * When using the same assertions for multiple routes, you can use Gaia.router.config().assert() to setup default * assertions. * * Logs a warning when: * - you forget the ^ at the beginning of your match * - you forget the $ at the end of your match * - you use the 'global' flag in the regular expression (this will cause each 2nd match to fail) * * TODO: At the moment the assertion is only ran when resolving a route, not when assembling it. * TODO: So if you pass a incorrect deeplink value to Gaia.api.goto() and reload the page, the current route will fail to match. * * @param name * * @param assertion * Can either be a string (that will be converted to a RegExp), a RegExp itself, or a custom function that should * return a boolean. * * @param setDefaultAfterFail * When set to true, if the assertion fails it will try to set the default value when available. If there is no * default value the route will not match. */ public assert(name:string, assertion:Assertion, setDefaultAfterFail:boolean = false):this { this._requirements[name] = new RouteRequirement(name, assertion, setDefaultAfterFail); return this; } // TODO: should value be used before or after parse? // if before, values should always pass a string as default value, to make // parsing consistent with values from the actual route // if after, values can also contain 'parsed' objects /** * Sets a default value for the param. Setting a value also makes the param optional. * ``` * new Route('/:locale/home') * .value(Param.LOCALE, 'en_US'); * ``` * * The type of the default value is always a string to match the output of a normal match. * You can use parse() to convert a matched param to a different type. * * The default value is set after the assert() is executed, so it's your own responsibility that your code can * handle a possible different type of value. * * @param name The name of the parameter * @param value Sets the default for this parameter * * @param useForAssemble * When set to true, it will use this value when assembling the route and no value for this parameter is passed */ public value(name:string, value:string, useForAssemble:boolean = false):this { this._defaults[name] = new RouteValue(name, value, useForAssemble); this.update(); return this; } /** * Parses the parameter value from the URL to something you can use in your * application, so that you don't have to repeat this in the places you use * this value. * * ``` * // base64 encode and decode your data in the url * new Route('/step1/:data') * .parse(Param.DATA, btoa); * .stringify(Param.DATA, atob); * * // parse/stringify the userid from/to an actual User * new Route('/profile/:userId') * .parse(Param.USER_ID, (userId) => * { * return UserModel.getById(userId); * }) * .stringify(Param.USER_ID, (userId) => * { * return typeof userId === 'object' ? userId.id : userId; * }); * ``` * * @param name * The name of the parameter * @param parser * The function that will be called to parse the value from the URL to a * usable value in your application. Use the {stringify} method to configure * the code to put that value back in the url. */ public parse(name:string, parser:(param:string) => any):this { this._parsers[name] = new RouteParser(name, parser); return this; } /** * Stringifies the value passed in goto() to a string that can be used in * the URL, so that you don't have to repeat this in the places you provide * this value. * * ``` * // base64 encode and decode your data in the url * new Route('/step1/:data') * .parse(Param.DATA, btoa); * .stringify(Param.DATA, atob); * * // parse/stringify the userid from/to an actual User * new Route('/profile/:userId') * .parse(Param.USER_ID, (userId) => * { * return UserModel.getById(userId); * }) * .stringify(Param.USER_ID, (userId) => * { * return typeof userId === 'object' ? userId.id : userId; * }); * ``` * * @param name The name of the parameter * @param stringifier The function that will be called to stingify the value * passed to goto() to a usable value in the url. Use the * {parse} method to configure the code to convert the * url value back. */ public stringify(name:string, stringifier:(param:any) => string):this { this._stringifiers[name] = new RouteStringifier(name, stringifier); return this; } public addChildren(routes:Array<IRoute>):this { routes.forEach(route => this.addChildRoute(route) ); return this; } public addChildRoute(route:IRoute):this { // TODO: // - set configured params / asserts / stringifiers / parsers / values this._routes.push(route); route.setParent(this); this.update(); return this; } public assertParam(param:string, value:any):boolean { var success = !(param in this._requirements) || (param in this._requirements && this._requirements[param].assert(value)); if (DEBUG) { if (!success) { if (param in this._requirements) { console.info('assertion failed for param "' + param + '" failed on requirement "' + this._requirements[param].assertion.toString() + '" - value: ' + value); } } } return success; } protected resolveParams(matches:{[key:string]: string;}, translator?:IRouteTranslator):{[key:string]: string;} { const params = <any>{}; for (let i = 0; i < this._groupNames.length; i++) { let groupName = this._groupNames[i].name; let groupMatch = matches[groupName]; // assert value if (groupMatch) { // get key from translation groupMatch = translator && this._groupNames[i].translated ? translator.getKey(groupMatch) : groupMatch; if (!this.assertParam(groupName, groupMatch)) { // if failed, set to default if we have one if (groupName in this._defaults && groupName in this._requirements && this._requirements[groupName].setDefaultAfterFail) { groupMatch = this._defaults[groupName].value; } else { return null; } } } // check default else if (groupName in this._defaults) { groupMatch = this._defaults[groupName].value; } // parse value if (groupMatch) { if (groupName in this._parsers) { groupMatch = this._parsers[groupName].parser.call(null, groupMatch); } } params[groupName] = groupMatch; } return params; } /** * Checks if the passed url matches this route. Executes the assertions and * optionally sets the default value. */ public abstract isMatch(pathname:string):any public abstract assemble(params?:{[param:string]: any;}):Promise<string> public abstract getMatch():string public getPattern():string { return this._pattern; } public getParams():any { return {}; } public getChildren():Array<IRoute> { return this._routes; } public getRouteByName(name:string):IRoute { if (this.name == name) { return this; } const match = this._routes .map(route => route.getRouteByName(name)) .find(route => !!route) return match || null; } public getGroupNames():Array<GroupName> { return this._groupNames; } public getGroupName(name:string):GroupName { for (var i = 0; i < this._groupNames.length; i++) { var group = this._groupNames[i]; if (group.name == name) return group; } return null; } } export default AbstractRoute;
095660181e41d3d29a49113aed983efdb9ed8eb3
TypeScript
lqxue/JsonToDart
/src/converter.ts
2.65625
3
const camelcase = require('camelcase'); class JsonToDart { classNames: Array<String> = []; classModels: Array<Result> = []; indentText: String; shouldCheckType: boolean; nullSafety: boolean; includeCopyWitMethod: boolean = false; mergeArrayApproach: boolean = true; nullValueDataType: String; handlerSymbol: String; constructor(tabSize: number, shouldCheckType?: boolean, nullValueDataType?: String, nullSafety?: boolean) { this.indentText = " ".repeat(tabSize); this.shouldCheckType = shouldCheckType ?? false; this.nullValueDataType = nullValueDataType ?? "dynamic"; this.nullSafety = nullSafety ?? true; this.handlerSymbol = nullSafety ? "?" : ""; } setIncludeCopyWitMethod(b: boolean) { this.includeCopyWitMethod = b; } setMergeArrayApproach(b: boolean) { this.mergeArrayApproach = b; } addClass(className: String, classModel: String) { this.classModels.splice(0, 0, { code: classModel, className: className, }); } findDataType(key: String, value: any,): TypeObj { let type = "dynamic" as String; const typeObj = new TypeObj(); if (value === null || value === undefined) { type = this.nullValueDataType; typeObj.isPrimitive = true; } else if (Number.isInteger(value)) { type = "int"; typeObj.isPrimitive = true; } else if ((typeof value) === "number") { type = "double"; typeObj.isPrimitive = true; } else if ((typeof value) === "string") { type = "String"; typeObj.isPrimitive = true; } else if ((typeof value) === "boolean") { type = "bool"; typeObj.isPrimitive = true; } else if (value instanceof Array) { const temp = value as Array<any>; typeObj.isArray = true; if (temp.length === 0) { type = "List<dynamic>"; } else { const _type = this.findDataType(key, temp[0]); typeObj.typeRef = _type; typeObj.isPrimitive = _type.isPrimitive; type = `List<${_type.type}>`; } } else if ((typeof value) === "object") { typeObj.isObject = true; type = this.toClassName(key); this.parse(type, value); } typeObj.type = type; return typeObj; } removeNull = (obj: any): any => Object.keys(obj) .filter(key => obj[key] !== null) .reduce((res, key) => ({ ...res, [key]: obj[key] }), {}); parse(className: String, json: any): Array<Result> { className = this.toClassName(className); this.classNames.push(className); const parameters: Array<String> = []; const parametersForMethod: Array<String> = []; const fromJsonCode: Array<String> = []; const toJsonCode: Array<String> = []; const constructorInit: Array<String> = []; const copyWithAssign: Array<String> = []; if (json) { if (Array.isArray(json) && json.length > 0) { json = this.mergeArrayApproach ? json.reduce((p, c) => { return { ...p, ...this.removeNull(c), }; }, {}) : json[0]; } Object.entries(json).forEach(entry => { const key = entry[0]; const value = entry[1]; const typeObj = this.findDataType(key, value); const type = `${typeObj.type}${this.handlerSymbol}`; const paramName = camelcase(key); parameters.push(this.toCode(1, type, paramName)); this.addFromJsonCode(key, typeObj, fromJsonCode); this.addToJsonCode(key, typeObj, toJsonCode); if (this.includeCopyWitMethod) { parametersForMethod.push(this.toMethodParams(2, type, paramName)); copyWithAssign.push(`${this.indent(2)}${paramName}: ${paramName} ?? this.${paramName}`); } constructorInit.push(`this.${paramName}`); }); } const copyWithCode = this.includeCopyWitMethod ? ` ${this.indent(1)}${className} copyWith({ ${parametersForMethod.join("\n")} ${this.indent(1)}}) => ${className}(${copyWithAssign.length ? `{ ${copyWithAssign.join(",\n")}, ${this.indent(1)}}` : ""});` : ''; const parametersCode = parameters.length ? ` ${parameters.join("\n")} `: ""; const code = ` class ${className} {${parametersCode} ${this.indent(1)}${className}(${constructorInit.length ? `{${constructorInit.join(", ")}}` : ""}); ${this.indent(1)}${className}.fromJson(Map<String, dynamic> json) { ${fromJsonCode.join("\n")} ${this.indent(1)}} ${this.indent(1)}Map<String, dynamic> toJson() { ${this.indent(2)}final Map<String, dynamic> data = new Map<String, dynamic>(); ${toJsonCode.join("\n")} ${this.indent(2)}return data; ${this.indent(1)}}${this.includeCopyWitMethod ? copyWithCode : ""} }`; this.addClass(className, code); return this.classModels; } toClassName(name: String): String { name = camelcase(name, { pascalCase: true }); let i = 0; let className = name; while (this.classNames.includes(className)) { ++i; className = `${name}${i}`; } return className; } r = (type: TypeObj): String => { if (type.typeRef !== undefined) { return `(e)=>e==null?[]:(e as List).map(${this.r(type.typeRef)}).toList()`; } return `(e)=>${type.type}.fromJson(e)`; }; p = (type: TypeObj): String => { if (type.typeRef !== undefined) { return `(e)=>e?.map(${this.p(type.typeRef)})?.toList() ?? []`; } return `(e)=>e.toJson()`; }; addFromJsonCode(key: String, typeObj: TypeObj, fromJsonCode: Array<String>) { const type = typeObj.type; const paramName = `this.${camelcase(key)}`; let indentTab = 2; if (this.shouldCheckType && type !== "dynamic") { indentTab = 3; if (typeObj.isObject) { fromJsonCode.push(this.toCondition(2, `if(json["${key}"] is Map)`)); } else if (typeObj.isArray) { fromJsonCode.push(this.toCondition(2, `if(json["${key}"] is List)`)); } else { fromJsonCode.push(this.toCondition(2, `if(json["${key}"] is ${type})`)); } } if (typeObj.isObject) { fromJsonCode.push(this.toCode(indentTab, paramName, "=", `json["${key}"] == null ? null : ${type}.fromJson(json["${key}"])`)); } else if (typeObj.isArray) { if (typeObj.typeRef === undefined) { fromJsonCode.push(this.toCode(indentTab, paramName, "=", `json["${key}"] ?? []`)); } else if (typeObj.isPrimitive) { fromJsonCode.push(this.toCode(indentTab, paramName, "=", `json["${key}"]==null ? null : List<${typeObj.typeRef.type}>.from(json["${key}"])`)); } else { fromJsonCode.push(this.toCode(indentTab, paramName, "=", `json["${key}"]==null ? null : (json["${key}"] as List).map(${this.r(typeObj.typeRef)}).toList()`)); } } else { fromJsonCode.push(this.toCode(indentTab, paramName, "=", `json["${key}"]`)); } } addToJsonCode(key: String, typeObj: TypeObj, fromJsonCode: Array<String>) { const paramName = `this.${camelcase(key)}`; const paramCode = `data["${key}"]`; if (typeObj.isObject) { fromJsonCode.push(this.toCondition(2, `if(${paramName} != null)`)); fromJsonCode.push(this.toCode(3, paramCode, "=", `${paramName}${this.handlerSymbol}.toJson()`)); } else if (typeObj.isArray) { fromJsonCode.push(this.toCondition(2, `if(${paramName} != null)`)); if (typeObj.isPrimitive || typeObj.typeRef === undefined) { fromJsonCode.push(this.toCode(3, paramCode, "=", paramName)); } else { fromJsonCode.push(this.toCode(3, paramCode, "=", `${paramName}${this.handlerSymbol}.map(${this.p(typeObj.typeRef)}).toList()`)); } } else { fromJsonCode.push(this.toCode(2, paramCode, "=", paramName)); } } indent(count: number): String { return this.indentText.repeat(count); } toCode(count: number, ...text: Array<String>): String { return `${this.indent(count)}${text.join(" ")};`; } toMethodParams(count: number, ...text: Array<String>): String { return `${this.indent(count)}${text.join(" ")},`; } toCondition(count: number, ...text: Array<String>): String { return `${this.indent(count)}${text.join(" ")}`; } } class TypeObj { type: String = "dynamic"; defaultValue: String = "''"; typeRef!: TypeObj; isObject: boolean = false; isArray: boolean = false; isPrimitive: boolean = false; } export type Result = { code: String; className: String; }; export default JsonToDart;
ce2d18134cdd5677e13286c410fa37e0b415b3e0
TypeScript
darkmarthur/TestGCF
/functions/src/test.ts
3.3125
3
async function myFunction(): Promise<string> { try { const rank = await myRank() return "firebase " + rank } catch (error) { return "error " + error } } function myRank() { // return Promise.resolve(1) return Promise.reject(":V") }
ec5a6477f8e6de08d422589e36a87e3135d5da15
TypeScript
le-ar/telegram-types-generator
/lib/parsers/parser_parameters.ts
3.0625
3
import { ParserHtml, ParserHtmlType } from "./parser_html"; class ParserParameters implements ParserHtml { parserParameter: ParserHtmlType; constructor(parserParameter: ParserHtmlType) { this.parserParameter = parserParameter; } parseHtmlToObject(html: string): { [key: string]: any } { let result = {}; let startIndexOfBlock = 0; while (startIndexOfBlock < html.length) { let parsed = this.parseBlock(html, startIndexOfBlock); startIndexOfBlock = parsed.endIndex; result[parsed.block.name] = parsed.block; } return result; } private parseBlock(html: string, startIndex: number): { endIndex: number, block: { name: string; type: string; description: string; optional: boolean; } } { let startIndexOfBlock = html.indexOf('<tr>', startIndex); let endIndexOfBlock = html.indexOf('</tr>', startIndexOfBlock); let blockHtml = html.slice(startIndexOfBlock + 4, endIndexOfBlock); let block = this.parserParameter.parseHtmlToObject(blockHtml.trim()); return { endIndex: endIndexOfBlock + 5, block: block }; } } export default ParserParameters
5050f89bf26c70c58f8a69d8ede9e372f2b164e1
TypeScript
Celleb/tsjs-di
/e2e-src/js-providers.ts
2.515625
3
/** * js-providers.ts * * @author Jonas Tomanga <celleb@mrcelleb.com> * @copyright (c) 2018 Jonas Tomanga * All rights reserved * @license MIT */ import { DI } from '../dist'; export class Engine { capacity = 2.5; constructor() { } } export class Car { private _name: string; constructor(public engine) { } get name() { return this._name; } set name(name: string) { this._name = name; } static create(di) { const car = new Car(di.inject('Engine')); car.name = 'Brabus'; return car; } } export class Driver { car: Car; name: string; constructor(name, car = DI.inject('Car')) { this.car = car; this.name = name; } } export class Config { name: string; author: string; } export const config: Config = { name: 'tsjs-di', author: 'Jonas Tomanga' };
378e3cf314b6011777e30c948423af6fd5a5d182
TypeScript
Shopify/quilt
/packages/react-cookie/src/hooks.ts
2.609375
3
import {useContext, useState, useCallback} from 'react'; import type {CookieSerializeOptions} from 'cookie'; import {CookieContext} from './context'; const NO_MANAGER_ERROR = [ 'Could not find react-cookie context.', 'You might be missing the <CookieUniversalProvider />', 'component in your application component tree.', ].join(' '); export function useCookie( key: string, ): [ string | undefined, (value?: string, options?: CookieSerializeOptions) => void, ] { const manager = useContext(CookieContext); if (!manager) { throw new Error(NO_MANAGER_ERROR); } const [cookie, setCookieValue] = useState(() => manager?.getCookie(key)); const setCookie = useCallback( (value?: string, options?: CookieSerializeOptions) => { if (!value) { setCookieValue(''); manager.removeCookie(key); return; } setCookieValue(value); manager.setCookie(key, {value, ...options}); }, [key, manager], ); return [cookie, setCookie]; }
28f3df652abb69a9394e6294219c8ca47171247c
TypeScript
Sevda-HHH/RoomReservationGroupWork
/room_reservation_group_work/src/modules/reservations/reducer/index.ts
2.6875
3
import React from "react"; import { ACTION_TYPES } from "../../models/enumActions"; import { initialState } from "../../models/initalState"; import { IAction } from "../../models/types"; const reducer = (state = initialState, action: IAction) => { switch (action.type) { case ACTION_TYPES.ADD_RESERVATION: return state.map(room => { if (room.id === action.payload.roomId) { room.reservations = [ ...room.reservations, action.payload ] } return room; }); case ACTION_TYPES.UPDATE_RESERVATION: return state.map(room => { if (room.id === action.payload.roomId) { const fres = room.reservations.find(res => res.id === action.payload.id)!; room.reservations.map(res => { if (res === fres) { room.reservations = [ ...room.reservations, action.payload ] } return res; }) } return room; }) default: return state; } }; export default reducer;
c9b220388291f9d7759dee45b398708b6e881bb4
TypeScript
zoxjs/zox
/lib/Responses/RedirectResponse.ts
2.6875
3
import {IResponse} from "./IResponse"; import {OutgoingHttpHeaders, ServerResponse} from "http"; export class RedirectResponse implements IResponse { public statusCode: number; public headers: OutgoingHttpHeaders; public location: string; constructor(location: string, statusCode: number = 303, headers?: OutgoingHttpHeaders) { this.location = location; this.statusCode = statusCode; this.headers = typeof headers == 'object' ? headers : undefined; } public send(response: ServerResponse): void { response.writeHead(this.statusCode, Object.assign({ 'Location': this.location, }, this.headers)); response.end(); } }
9ba80e0941a7815138bacd18ec030669d4dd1906
TypeScript
cschleiden/imperaplus-client
/src/services/eventService.ts
3.109375
3
export interface IEventHandler<TPayload> { (payload?: TPayload): void; } export class EventService { private static _instance: EventService; public static getInstance(): EventService { if (!EventService._instance) { EventService._instance = new EventService(); } return EventService._instance; } private _handlers: { [eventName: string]: IEventHandler<any>[] } = {}; attachHandler<TPayload>( eventName: string, handler: IEventHandler<TPayload> ) { if (!this._handlers[eventName]) { this._handlers[eventName] = [handler]; } else { this._handlers[eventName].push(handler); } } detachHandler<TPayload>( eventName: string, handler: IEventHandler<TPayload> ) { if (this._handlers[eventName]) { const idx = this._handlers[eventName].indexOf(handler); if (idx !== -1) { this._handlers[eventName].splice(idx, 1); } } } fire<TPayload>(eventName: string, payload?: TPayload) { const handlers = this._handlers[eventName]; if (handlers) { for (const handler of handlers) { handler(payload); } } } }
a8863f5e16491c8a4301a6e0e61f9eed7fc19321
TypeScript
LuizCorrea-Dev/my-portfolio-code
/src/services/data/navigation.ts
2.59375
3
/** @format */ import navigationEnglish from '../../assets/data/navigationEnglish'; import navigationPortuguese from '../../assets/data/navigationPortuguese'; import { Language } from '.'; export interface Navigation { name: string; link: string; } export default function getNavigation(language: Language): Navigation[] { if (language === 'PT-BR') return navigationPortuguese; return navigationEnglish; }
546f1879ac43ac0b0f3fbfda1d2f33c9726c9d47
TypeScript
AhmadCR7/SFSU-Market
/application/server/src/database/entities/ListingImage.ts
2.625
3
import { PrimaryGeneratedColumn, Entity, CreateDateColumn, UpdateDateColumn, Column, BaseEntity, OneToMany, ManyToOne, } from 'typeorm' import { Listing } from './Listing' @Entity() // extend allows base sql commands link find() and insert() export class ListingImage extends BaseEntity { @PrimaryGeneratedColumn() id!: number @CreateDateColumn() createdAt = new Date() @UpdateDateColumn() updatedAt = new Date() @Column() name!: string @Column() url!: string @ManyToOne(() => Listing, (listing) => listing.listingImages, { onDelete: 'CASCADE', }) listing: Listing }
65246ebcc701540438174fb30cca0df466e4d67d
TypeScript
ilyesbrh/FarmyAi-Frontend
/src/app/Store/Actions/DetectionList.Action.ts
3.109375
3
import { detection } from '../model'; import { Action } from '@ngrx/store'; /** * For each action type in an action group, make a simple * enum object for all of this group's action types. */ export enum DetectionActionTypes { All = '[Detection] All', Notification = '[Detection] Notification', Add = '[Detection] Add', MarkSeen = '[Detection] MarkSeen' }; /** * Every action is comprised of at least a type and an optional * payload. Expressing actions as classes enables powerful * type checking in reducer functions. */ export class Add implements Add { readonly type = DetectionActionTypes.Add; constructor(public payload: detection) { } } export class All implements Action { readonly type = DetectionActionTypes.All; constructor(public payload: detection[]) { } } export class Notification implements Action { readonly type = DetectionActionTypes.Notification; constructor(public payload: detection) { } } export class MarkSeen implements Action { readonly type = DetectionActionTypes.MarkSeen; constructor(public payload: number) { } } /** * Export a type alias of all actions in this action group * so that reducers can easily compose action types */ export type DetectionActions = All | Add | MarkSeen | Notification;
b34f35d923b549e49abf52f7ca90636faf305e7d
TypeScript
sarathganapathy/javascript-codility
/servers/server/types/auth.ts
2.703125
3
/** * @interface * @def interface for login data */ export interface PassportUserData { expires: string; role: string; username: string; } /** * @interface * @def interface for isAuthenticated object */ export interface IsAuthenticatedObject { isAuthenticated: boolean; username: string; } /** * @interface * @def interface for response object */ export interface LoginResponseObject { message: string; userDetails: { username: string }; }
0fc6777873f2b9c3cc0482468d9fa717ff3e4aeb
TypeScript
hobbydev71/portfolio
/src/pages/api/skills.ts
2.578125
3
import type { NextApiRequest, NextApiResponse } from 'next'; export default (req: NextApiRequest, res: NextApiResponse) => { const technologies = [ 'JavaScript', 'TypeScript', 'GraphQL', 'RESTful APIs', ]; const frameworks = ['React', 'Vue.js', 'Next.js', 'Gatsby', 'Svelte']; const databases = ['MySQL', 'MongoDB', 'Firebase', 'PostgreSQL']; const blockchain = ['Solidity', 'Rust', 'SmartContract', 'Web3 JS', 'Ether JS', 'Solana']; const various = ['Scrum', 'Agile', 'Jira', 'Confluence']; const design = [ 'Adobe Photoshop', 'Adobe XD', 'Sketch', 'Figma', ]; const softSkills = [ 'Strong communicator', 'Leadership', 'Problem solving', 'Creative thinking', 'Flexible and adaptive', 'Team player', 'Always on time', ]; const languages = [ { language: 'English', level: 'bilingual', icon: 'us', }, { language: 'Mandarian', level: 'bilingual', icon: 'zh', }, ]; res.status(200).json({ technologies, frameworks, databases, blockchain, various, design, softSkills, languages, }); };
f474bbe24a867e9b3e0f1c03380bb1f94487b717
TypeScript
VinhoSantos/BattleRoyal
/src/client/src/scripts/player.ts
2.765625
3
import Render from './render'; import { GameHelper } from './helper'; import * as signalR from '@aspnet/signalr'; export class Player { coX: number; coY: number; posX: number; posY: number; gotoCoX: number; gotoCoY: number; vision = 2; speed = 1; private render: Render; isMoving = false; private startTime = -1; private animationLength = 200; constructor(coX: number, coY: number) { this.coX = coX; this.gotoCoX = coX; this.gotoCoY = coY; this.coY = coY; this.posX = GameHelper.GetCell(coX); this.posY = GameHelper.GetCell(coY); this.render = Render.getInstance(); console.log('player init'); } public init() { this.draw(); this.drawVision(); } public moveUp() { this.move(MoveDirection.Up); } public moveDown() { this.move(MoveDirection.Down); } public moveLeft() { this.move(MoveDirection.Left); } public moveRight() { this.move(MoveDirection.Right); } private move(moveDirection: MoveDirection) { switch(moveDirection) { case MoveDirection.Up: this.gotoCoY = this.coY - this.speed; break; case MoveDirection.Down: this.gotoCoY = this.coY + this.speed; break; case MoveDirection.Left: this.gotoCoX = this.coX - this.speed; break; case MoveDirection.Right: this.gotoCoX = this.coX + this.speed; break; } this.movePlayerOnGrid(); } private movePlayerOnGrid() { this.startTime = -1; //reset startTime before each animation requestAnimationFrame(this.playerAnimationLoop.bind(this)); } private playerAnimationLoop(timestamp: number) { let progress = 0; if (this.startTime < 0) { this.startTime = timestamp; } else { progress = timestamp - this.startTime; } const startPosX = this.posX; const startPosY = this.posY; const endPosX = GameHelper.GetCell(this.gotoCoX); const endPosY = GameHelper.GetCell(this.gotoCoY); const difX = endPosX - startPosX; const difY = endPosY - startPosY; const progressPerc = (progress / this.animationLength); const posX = Math.round(startPosX + (difX * progressPerc)); const posY = Math.round(startPosY + (difY * progressPerc)); //console.log('draw animation @ [' + posX + ',' + posY + ']'); if (progressPerc < 1) { this.render.redrawLevel(posX, posY, this.vision); this.render.drawPlayer(posX, posY); this.render.drawPlayerVision(posX, posY, this.vision); } if (progress < this.animationLength) { requestAnimationFrame(this.playerAnimationLoop.bind(this)); } else { this.endPlayerAnimation(); } } private endPlayerAnimation() { this.coX = this.gotoCoX; this.coY = this.gotoCoY; this.posX = GameHelper.GetCell(this.gotoCoX); this.posY = GameHelper.GetCell(this.gotoCoY); this.isMoving = false; this.render.redrawLevel(this.posX, this.posY, this.vision); this.render.drawPlayerAt(this.coX, this.coY); this.render.drawPlayerVision(this.posX, this.posY, this.vision); } public draw() { this.render.drawPlayerAt(this.coX, this.coY); } public drawVision() { this.render.drawPlayerVision(this.posX, this.posY, this.vision); } } enum MoveDirection { Up = 1, Down = 2, Left = 3, Right = 4 }
3cfe0cf4325a5d598d38199d98815f33c920eed1
TypeScript
NerdWalletOSS/shepherd
/src/util/for-each-repo.ts
2.84375
3
import chalk from 'chalk'; import fs from 'fs-extra'; import { IRepo } from '../adapters/base'; import { IMigrationContext } from '../migration-context'; type RepoHandler = (repo: IRepo) => Promise<void>; interface IOptions { warnMissingDirectory?: boolean; } export default async ( context: IMigrationContext, param1: RepoHandler | IOptions, param2?: RepoHandler ) => { const { migration: { repos: migrationRepos, selectedRepos }, logger, adapter, } = context; let handler: RepoHandler; let options: IOptions; if (typeof param1 === 'function') { // No options were provided options = {}; handler = param1; } else { // We got options! options = param1; handler = param2 as RepoHandler; } // We want to show these warnings by default and allow opt-out of them const { warnMissingDirectory = true } = options; // If `selectedRepos` is specified, we should use that instead of the full repo list let repos; if (selectedRepos && selectedRepos.length) { // If this repo was already checked out, it may have additional metadata // associated with it that came from the adapter's mapRepoAfterCheckout // Let's rely on the migrations from the list on disk if at all possible repos = selectedRepos.map((r) => { const existingRepo = (migrationRepos || []).find((repo) => adapter.reposEqual(r, repo)); return existingRepo || r; }); } else { repos = migrationRepos || []; } let index = 0; for (const repo of repos) { index += 1; const indexString = chalk.dim(`${index}/${repos.length}`); logger.info(chalk.bold(`\n[${adapter.stringifyRepo(repo)}] ${indexString}`)); // Quick sanity check in case we're working from user-selected repos const repoDir = adapter.getRepoDir(repo); if (warnMissingDirectory && !(await fs.pathExists(repoDir))) { logger.error(`Directory ${repoDir} does not exist`); } await handler(repo); } };
45dc722d203908d81c2c97d6b8bada3219c94d4c
TypeScript
Iittlefish/toDoList-backend
/src/user.ts
2.8125
3
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm' @Entity() export default class User { @PrimaryGeneratedColumn('increment', { type: 'int', unsigned: true }) uid: number; @Column({ type: 'string' }) account: string; @Column({ type: 'string' }) pwd: string; @Column({ type: 'string' }) isAuth: boolean; constructor(params: User = {} as User) { const { uid, account, pwd, isAuth } = params this.uid = uid; this.account = account; this.pwd = pwd; this.isAuth = isAuth; } }
7b5941c204f2c42ed94ae2fbbb37a18f95f45dc5
TypeScript
lizzzp1/tslint-microsoft-contrib
/src/preferArrayLiteralRule.ts
2.8125
3
import * as ts from 'typescript'; import * as Lint from 'tslint'; import * as tsutils from 'tsutils'; import { AstUtils } from './utils/AstUtils'; import { ExtendedMetadata } from './utils/ExtendedMetadata'; import { isObject } from './utils/TypeGuard'; interface Options { allowTypeParameters: boolean; } export class Rule extends Lint.Rules.AbstractRule { public static metadata: ExtendedMetadata = { ruleName: 'prefer-array-literal', type: 'maintainability', description: 'Use array literal syntax when declaring or instantiating array types.', options: null, // tslint:disable-line:no-null-keyword optionsDescription: '', typescriptOnly: true, issueClass: 'Non-SDL', issueType: 'Warning', severity: 'Moderate', level: 'Opportunity for Excellence', group: 'Clarity', commonWeaknessEnumeration: '398, 710' }; public static GENERICS_FAILURE_STRING: string = 'Replace generic-typed Array with array literal: '; public static CONSTRUCTOR_FAILURE_STRING: string = 'Replace Array constructor with an array literal: '; public apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] { return this.applyWithFunction(sourceFile, walk, this.parseOptions(this.getOptions())); } private parseOptions(options: Lint.IOptions): Options { let value: boolean = false; let ruleOptions: any[] = []; if (options.ruleArguments instanceof Array) { ruleOptions = options.ruleArguments; } if (options instanceof Array) { ruleOptions = options; } ruleOptions.forEach((opt: unknown) => { if (isObject(opt)) { value = opt['allow-type-parameters'] === true; } }); return { allowTypeParameters: value }; } } function walk(ctx: Lint.WalkContext<Options>) { const { allowTypeParameters } = ctx.options; function cb(node: ts.Node): void { if (tsutils.isTypeReferenceNode(node)) { if (!allowTypeParameters) { if ((<ts.Identifier>node.typeName).text === 'Array') { const failureString = Rule.GENERICS_FAILURE_STRING + node.getText(); ctx.addFailureAt(node.getStart(), node.getWidth(), failureString); } } } if (tsutils.isNewExpression(node)) { const functionName = AstUtils.getFunctionName(node); if (functionName === 'Array') { const failureString = Rule.CONSTRUCTOR_FAILURE_STRING + node.getText(); ctx.addFailureAt(node.getStart(), node.getWidth(), failureString); } } return ts.forEachChild(node, cb); } return ts.forEachChild(ctx.sourceFile, cb); }
6ffbd236a76c239fefbe95802ac909908affaae3
TypeScript
vesanieminen/web-components
/packages/app-layout/test/typings/app-layout.types.ts
2.53125
3
import '../../vaadin-app-layout.js'; import { AppLayoutDrawerOpenedChangedEvent, AppLayoutOverlayChangedEvent, AppLayoutPrimarySectionChangedEvent } from '../../vaadin-app-layout.js'; const assertType = <TExpected>(actual: TExpected) => actual; const layout = document.createElement('vaadin-app-layout'); layout.addEventListener('drawer-opened-changed', (event) => { assertType<AppLayoutDrawerOpenedChangedEvent>(event); assertType<boolean>(event.detail.value); }); layout.addEventListener('overlay-changed', (event) => { assertType<AppLayoutOverlayChangedEvent>(event); assertType<boolean>(event.detail.value); }); layout.addEventListener('primary-section-changed', (event) => { assertType<AppLayoutPrimarySectionChangedEvent>(event); assertType<'navbar' | 'drawer'>(event.detail.value); });
70c4fd0c3e9d245cf531672d44aaac5d04a62c91
TypeScript
amulyk/mariam-arabidze-personal-projectt-typescript
/source/main.ts
2.78125
3
import {subjectsModel, LMSModel, teachersModel, pupilsModel, groupsModel, gradebooksModel} from './school'; //test subjectsModel const math = new subjectsModel({title: "math", lessons: 24, description: "kj"}); const physics = new subjectsModel({title: "physics", lessons: 20, description: "kk"}); //console.log(math.subjectID); //console.log(physics.subjectID); //testLMSModel const lms = new LMSModel(); // console.log(lms.add(math)); // console.log(lms.add(physics)); // // console.log(lms.remove(math)); // // console.log(lms.verify(math)); // // console.log(lms.verify(physics)); // console.log(lms.readAll()); //testTeachersModel const teachers = new teachersModel(); const mathteacher1 ={ name: { first: "Amanda", last : "Black" }, image: "someimagehere", dateOfBirth: "15.12.1996", // format date emails: [ { email: "marabidze@sdsu.edu", primary: true }, ], phones: [ { phone: "8727272727", primary: true } ], sex: "female", // male or female subjects: [ { subject : 'math' } ] } const physicsteacher1 ={ name: { first: "Ken", last : "Walsh" }, image: "someimagehere", dateOfBirth: "25.02.1970", // format date emails: [ { email: "marabidze@sdsu.edu", primary: true }, ], phones: [ { phone: "8727272727", primary: true } ], sex: "male", // male or female subjects: [ { subject : 'physics' } ] } let mathteacherID=teachers.add(mathteacher1) // console.log(mathteacherID) // let physicsteacherID=teachers.add(physicsteacher1) // console.log(physicsteacherID) // console.log(teachers.read(mathteacherID)) // console.log(teachers.read(physicsteacherID)) // console.log(teachers.remove(physicsteacherID)) //testPupilsModel const pupils = new pupilsModel(); const pupil1={ name: { first: "Paul", last: "Spitzer" }, image: "someimage", dateOfBirth: "12/05/2000", // format date phones: [ { phone: "9488093093", primary: true } ], sex: "male", // male OR female } const pupil2={ name: { first: "Jim", last: "Frankelfield" }, image: "someimage", dateOfBirth: "02/07/2001", // format date phones: [ { phone: "9488093091", primary: true } ], sex: "male", // male OR female } let pupil_1=pupils.add(pupil1) let pupil_2=pupils.add(pupil2) // console.log(pupils.read(pupil_1)) // console.log(pupils.read(pupil_2)) // console.log(pupils.remove(pupil_1)) //test groupsmodel const room1 = 236; const groups = new groupsModel(); const group_1 = groups.add(room1); console.log(group_1) console.log(groups.addPupils(group_1, pupil1)) console.log(groups.addPupils(group_1, pupil2)) console.log(groups.read(group_1)) console.log(groups.readAll()) //test gradebookModel const pupilId = pupil_1; const teacherId = mathteacherID; const gradebooks = new gradebooksModel(groups, mathteacher1, lms); // Create a new gradebook const level = 1; const gradebookid = gradebooks.add(level, group_1); // Destroy all data inside this gradebook gradebooks.clear(); const record = { pupilId: pupil_1, teacherId: teacherId, subjectId: math.subjectID, lesson: 1, mark: 9 }; console.log(gradebooks.addrecords(gradebookid, record));
72a9528bde818e901fb01926397f2e12c131fe17
TypeScript
stephaneeybert/pierrepapierciseaux
/src/app/views/game/game.component.ts
2.640625
3
import { Component, OnDestroy, OnInit } from '@angular/core'; import { GameService } from '@app/core/service/game.service'; import { timer, Observable, Subscription, of } from 'rxjs'; import { Score } from './score'; import { ScoreStore } from '@app/core/store/score-store'; const WEAPON_ROCK: number = 1; const WEAPON_PAPER: number = 2; const WEAPON_SCISSORS: number = 3; const GAME_WIN = 'WIN'; const GAME_LOSS = 'LOSS'; const GAME_TIE = 'TIE'; const OPPONENT_PLAYTIME: number = 500; @Component({ selector: 'app-game', templateUrl: './game.component.html', styleUrls: ['./game.component.css'], providers: [ GameService ] }) export class GameComponent implements OnInit, OnDestroy { playerWeapon: number = 0; opponentWeapon: number = 0; playerScore: number = 0 opponentScore: number = 0; gameResult: string = ''; waitingForOpponentToPlay: boolean = false; private opponentPickedWeaponSubscription?: Subscription; scores$: Observable<Array<Score>> = of([]); constructor( private gameService: GameService, private scoreStore: ScoreStore ) { } public ngOnInit(): void { this.scores$ = this.scoreStore.state$; } public ngOnDestroy() { if (this.opponentPickedWeaponSubscription != null) { this.opponentPickedWeaponSubscription.unsubscribe(); } } public playerPicksRock(): void { this.playerPicksWeapon(WEAPON_ROCK); } public playerPicksPaper(): void { this.playerPicksWeapon(WEAPON_PAPER); } public playerPicksScissors(): void { this.playerPicksWeapon(WEAPON_SCISSORS); } private playerPicksWeapon(weapon: number): void { if (this.waitingForOpponentToPlay) { return; } this.resetGame(); this.playerWeapon = weapon; this.waitingForOpponentToPlay = true; this.opponentPickedWeaponSubscription = this.opponentPickRandomWeapon().subscribe(() => { this.waitingForOpponentToPlay = false; this.gameResult = this.getGameOutcome(this.playerWeapon, this.opponentWeapon); this.updateScores(this.gameResult); }); } public opponentPickRandomWeapon(): Observable<number> { this.opponentPickWeapon(this.gameService.getRandomWeapon()); return timer(OPPONENT_PLAYTIME); } public opponentPickWeapon(weapon: number): void { this.opponentWeapon = weapon; } public getGameOutcome(playerWeapon: number, opponentWeapon: number): string { if (playerWeapon == opponentWeapon) { // The play is a tie return GAME_TIE; } else if ((playerWeapon - opponentWeapon + 3) % 3 == 1) { // The player wins return GAME_WIN; } else { // The player looses to the opponent return GAME_LOSS; } } public weaponIsRock(weapon: number): boolean { return WEAPON_ROCK == weapon; } public weaponIsPaper(weapon: number): boolean { return WEAPON_PAPER == weapon; } public weaponIsScissors(weapon: number): boolean { return WEAPON_SCISSORS == weapon; } public gameIsTie(gameResult: string): boolean { return GAME_TIE == gameResult; } public gameIsWin(gameResult: string): boolean { return GAME_WIN == gameResult; } public gameIsLoss(gameResult: string): boolean { return GAME_LOSS == gameResult; } private updateScores(gameResult: string): void { if (this.gameIsWin(gameResult)) { this.playerScore = this.playerScore + 1; } else if (this.gameIsLoss(gameResult)) { this.opponentScore = this.opponentScore + 1; } this.gameService.addScore(this.playerScore, this.opponentScore); } private resetGame(): void { this.playerWeapon = 0; this.opponentWeapon = 0; } private resetScore(): void { this.playerScore = 0; this.opponentScore = 0; } public clearScores(): void { this.resetScore(); this.scoreStore.clearScores(); } }
947b7a1403df6c0a20bcc6009f57f00a3d163c8b
TypeScript
frankPairs/parkbee-assessment
/src/store/garages/transactions/types.ts
2.625
3
/* State */ interface GaragesTransactionsState { data: { [doorId: string]: string | undefined } | null; } /* Actions */ enum GaragesTransactionsActionTypes { START_PARK = 'startPark', STOP_PARK = 'stopPark', } interface StartParkAction { type: GaragesTransactionsActionTypes.START_PARK; payload: { doorId: string; transactionId: string }; } interface StopParkAction { type: GaragesTransactionsActionTypes.STOP_PARK; payload: { doorId: string }; } interface StartParkAPIResponse { transactionId: string; } interface StartParkAPIRequest { RegistrationNumber: string; ExternalClientId: string; GarageId: string; DoorId: string; } interface StopParkAPIResponse { transactionAmount: number; } type GaragesTransactionsActions = StartParkAction | StopParkAction; export { GaragesTransactionsActions, GaragesTransactionsActionTypes, GaragesTransactionsState, StartParkAction, StopParkAction, StartParkAPIResponse, StartParkAPIRequest, StopParkAPIResponse, };
2b85413fd0c6abdee04c8aaee4a47a64a70b1001
TypeScript
xiaochengbeier/tetris
/src/Square.ts
2.859375
3
import { IWiver, Point } from "./Types"; export class Square{ private _point:Point; private _color:string; private _IWiver:IWiver ; constructor(point:Point,color:string){ this._point = point; this._color = color; } getColor(){ return this._color; } getPoint(){ return this._point; } setIWiver(iv:IWiver){ this._IWiver = iv; this._IWiver.show(); } getIWiver(){ return this._IWiver; } setPoint(point:Point){ this._point = point; if(this._IWiver){ this._IWiver.show(); } } }
959a7daff88fa506c2585e24801aa50dfc9a8c29
TypeScript
caizhengxin/vscodefileheader
/src/template.ts
2.53125
3
/** * @Author: JanKinCai * @Date: 2021-04-22 23:41:46 * @Last Modified by: JanKinCai * @Last Modified time: 2021-07-06 13:39:42 */ import * as vscode from 'vscode'; import * as path from 'path'; import * as fs from 'fs'; import * as art_template from 'art-template'; import * as editor from './editor'; class Template extends editor.editorObject { default_tmpl_path: string; file_suffix_mapping: any; constructor(editor: any, config: any, file_suffix_mapping: any) { super(editor, config); this.default_tmpl_path = this.getDefaultTemplatePath(); this.file_suffix_mapping = file_suffix_mapping; } /** * getSuffix * * @return string */ getSuffix(): string { let pathobj:any = path.parse(this.editor.document.fileName); return pathobj.ext.toLowerCase() || pathobj.name.toLowerCase(); } /** * getFileName * * @return string */ getFileName(): string { return path.parse(this.editor.document.fileName).name.toLowerCase(); } /** * getDefaultTemplatePath * * @return string */ getDefaultTemplatePath(): string { return path.join(path.dirname(__dirname), "template"); } getDefaultArtTemplate(type: string="header"): string { return path.join(this.default_tmpl_path, "art", type + ".art"); } /** * getTemplatePath * * @param type (string): header/body * * @return string | undefined */ getTemplatePath(type: string="header"): string | undefined { let suffix: string = this.getSuffix(); let name: string = this.getFileName(); let tmpl: string = ""; for (let v in this.config.file_suffix_mapping) { let reg: any = new RegExp("^" + v.replace(".", "\\.").replace("*", ".*") + "$"); if (reg.test(name + suffix) || reg.test(suffix)) { tmpl = this.config.file_suffix_mapping[v] + ".tmpl" break; } } if (!tmpl) { tmpl = (this.file_suffix_mapping[name + suffix] || this.file_suffix_mapping[suffix]) + ".tmpl"; } if (tmpl) { let tmplpath = path.join(this.config.custom_template_path || "", type, tmpl); if (fs.existsSync(tmplpath)) { return tmplpath; } tmplpath = path.join(this.default_tmpl_path, type, tmpl); if (fs.existsSync(tmplpath)) { return tmplpath; } } return undefined; } private _create(name: string, type: string="header"): void { let srcpath = vscode.Uri.file(this.getDefaultArtTemplate(type)); let dstpath = vscode.Uri.file(path.join(this.config.custom_template_path, type, name + ".tmpl")); vscode.workspace.fs.copy(srcpath, dstpath); } private _open(name: string, type: string="header"): void { let tmplpath = path.join(this.config.custom_template_path, type, name + ".tmpl"); let textDocument: any = vscode.workspace.openTextDocument(vscode.Uri.file(tmplpath)); let viewcolumn: number = vscode.ViewColumn.One; if (type === "body") { viewcolumn = vscode.ViewColumn.Two; } vscode.window.showTextDocument(textDocument, viewcolumn); } private _open2(tmplpath: string | undefined, type: string="header"): void { if (tmplpath === undefined || !fs.existsSync(tmplpath)) { vscode.window.showInformationMessage("Template path does not exist"); } else { let textDocument: any = vscode.workspace.openTextDocument(vscode.Uri.file(tmplpath)); let viewcolumn: number = vscode.ViewColumn.One; if (type === "body") { viewcolumn = vscode.ViewColumn.Two; } vscode.window.showTextDocument(textDocument, viewcolumn); } } create(name: string): void { this._create(name, "header"); this._create(name, "body"); this._open(name, "header"); this._open(name, "body"); } open(): void { let tmplpath = this.getTemplatePath("header"); this._open2(tmplpath, "header"); tmplpath = this.getTemplatePath("body"); this._open2(tmplpath, "body"); } private deleteEditorComments(): void { if(this.isSuffix(".php")){ this.deleteEditorComment("<?php", 2); }else if(this.isSuffixList([".py", ".pxd", ".pyx"])){ this.deleteEditorComment("# -*- coding: utf-8 -*-", 1); } } private insertEndComments(): void { let lineCount: number = this.editor.document.lineCount; if(this.config.body && lineCount <= 1){ if(this.isSuffix(".php")){ this.insertEditorComment("?>"); } } } /** * Support Predefined variables: https://code.visualstudio.com/docs/editor/variables-reference */ private predefinedVariables(): any { const rfd: any = this.pathobj.dir.split(path.sep); return { "workspaceFolder": vscode.workspace.rootPath, "workspaceFolderBasename": vscode.workspace.name, "file": this.editor.document.fileName, "relativeFile": path.join(rfd[rfd.length - 1], this.pathobj.base), "relativeFileDirname": rfd[rfd.length - 1], "fileBasename": this.pathobj.base, "fileBasenameNoExtension": this.pathobj.name, "fileDirname": this.pathobj.dir, "fileExtname": this.pathobj.ext, "cwd": vscode.workspace.rootPath, }; } private async _insert() { let lineCount: number = this.editor.document.lineCount; let tmplpath: string | undefined = this.getTemplatePath("header"); let tmplpath_body: string | undefined = this.getTemplatePath("body"); let ret: string = ""; if (tmplpath) { const text = await vscode.workspace.fs.readFile(vscode.Uri.file(tmplpath)); if (text.toString().trim() !== "") { ret = art_template.render(text.toString(), Object.assign( { author: this.config.author, create_time: this.getFileBirthDateTime(), last_modified_by: this.config.author, last_modified_time: this.getDateTime(), template: this.getDefaultTemplatePath(), }, this.config.other_config, this.predefinedVariables(), )); } if (lineCount <= 1 && tmplpath_body) { const bodytext = await vscode.workspace.fs.readFile(vscode.Uri.file(tmplpath_body)); if (bodytext.toString().trim() !== "") { ret += art_template.render(bodytext.toString(), Object.assign( { template: this.getDefaultTemplatePath(), }, this.config.other_config, this.predefinedVariables(), )); } } if (ret.trim() !== "") { this.editor.edit(editobj => { editobj.insert(new vscode.Position(0, 0), ret); }); this.editor.document.save(); } } else { console.debug("Not found fileheader template: " + this.editor.document.fileName); } } insert(): void { if (!this.isHeaderExists()) { this.deleteEditorComments(); this._insert(); this.insertEndComments(); } } private _update(): void { let start: number = 0; let line: number = 0; this.editor.edit(editobj => { line = this.findStringLine("@Last Modified time:"); if (line !== -1) { start = this.editor.document.lineAt(line).text.indexOf(":") + 1; editobj.replace(new vscode.Range(line, start, line, 100), " " + this.getDateTime()); } line = this.findStringLine("@Last Modified by:"); if (line !== -1) { start = this.editor.document.lineAt(line).text.indexOf(":") + 1; editobj.replace(new vscode.Range(line, start, line, 100), " " + this.config.author); } if (vscode.version < "1.43.0") { this.editor.document.save(); } }); } update(): void { if (!this.isIgnore(this.config.ignore)) { if (this.isHeaderExists()) { if (this.editor.document.isDirty) { this._update(); } } else if (this.config.save) { this.insert(); } } } update2(): void { if (!this.isIgnore(this.config.ignore)) { if (this.isHeaderExists()) { if (this.editor.document.isDirty) { this._update(); } } else if (this.config.open) { this.insert(); } } } } export { Template }
9b50fe0b7fdb5a87391a56f895df6ab565b3227a
TypeScript
ThiagoMoraes21/Angular7
/Angular-Crash-Course/Typescript-Fundamentals/variable-declarations/main.ts
4.15625
4
// Studing variable scope // Implementing a function using the 'var' keyword function doSomething() { // the variable 'i' scope looks for the closest function // which means that the variable is avaible to every element on this function for(var i = 0; i < 5; i++) { console.log(i); } console.log('Finally ' + i); } doSomething(); function doAnotherThing() { // let variables look for the closest block // so the variable declared in this for is ONLY available INSIDE the block for(let i = 0; i < 5; i++) { console.log(i); } console.log('Finally ' + i); // catches an error } doAnotherThing();
2cb358b3433e4cd03a0e02701fde9736f29b3660
TypeScript
Reeyou/Reeyou_blog_koa2
/src/controller/comment.ts
2.53125
3
/* eslint-disable no-undef */ import Comment from '../models/comment' import Reply from '../models/reply' import ServerResponse from '../common/serverResponse' export default class CommentController { /** * 获取评论列表 */ static async getCommentList(ctx: any) { const { pageSize, limit } = utils.getPageAndLimit(ctx) logger.debug('get-Comment-List handler start: ') try { const list = await Comment.find() .skip((pageSize - 1) * limit) .limit(Number(limit)) const total = await Comment.count(() => { }) return ServerResponse.SUCCESS(ctx, Constants.MSG_SUCCESS, { list, total }) } catch (e) { logger.error('🔥 request error: ', e) return ServerResponse.ERROR(ctx, Constants.MSG_ERROR, e) } } /** * 添加评论 */ static async addComment(ctx: any) { logger.debug('add-Comment handler start: ') try { const result = await new Comment(ctx.request.body).save() if (result) { return ServerResponse.SUCCESS(ctx, Constants.MSG_SUCCESS_SAVE, {}) } logger.error('🔥 request error: ', result) return ServerResponse.ERROR(ctx, Constants.MSG_ERROR, result) } catch (e) { logger.error('🔥 request error: ', e) return ServerResponse.ERROR(ctx, Constants.MSG_ERROR, e) } } /** * 删除评论 */ static async deleteCommnet(ctx: any) { logger.debug('add-Comment handler start: ') const { commentId } = ctx.request.body try { const result = await Comment.remove({ _id: commentId }) if (result) { return ServerResponse.SUCCESS(ctx, Constants.MSG_SUCCESS_SAVE, {}) } logger.error('🔥 request error: ', result) return ServerResponse.ERROR(ctx, Constants.MSG_ERROR, result) } catch (e) { logger.error('🔥 request error: ', e) return ServerResponse.ERROR(ctx, Constants.MSG_ERROR, e) } } /** * 评论回复 */ static async replyComment(ctx: any) { logger.debug('reply-Comment handler start: ') try { const result = await new Reply(ctx.request.body).save() if (result) { return ServerResponse.SUCCESS(ctx, Constants.MSG_SUCCESS_SAVE, {}) } logger.error('🔥 request error: ', result) return ServerResponse.ERROR(ctx, Constants.MSG_ERROR, result) } catch (e) { logger.error('🔥 request error: ', e) return ServerResponse.ERROR(ctx, Constants.MSG_ERROR, e) } } }
7454850d92c6fefa3d7b299051cb4af4125d547d
TypeScript
rmeja/ngx-callisto
/dist/app/modules/overlay/popup/popup.component.d.ts
2.53125
3
import { TemplateRef, EventEmitter } from '@angular/core'; import { Subject } from 'rxjs'; import { FormGroup } from '@angular/forms'; /** * Display a popup * @example * popup.open().subscibe(result=>{ * | // result = undefined or 'ok' * }) * <popup #popup> * | <div title>Some templating</div> * | <div body>Some templating</div> * </popup> * * formGroup: FormGroup * popupWithBind.bindForm(formGroup).open().subscibe(result=>{ * | // result = undefined or formGroup.value * }) * <popup #popupWithBind> * | <div title>Some templating</div> * | <div body>Some templating with input control etc...</div> * </popup> * * data = { $implicit: 'Hello', name:'world' } * popupWithContext.open(data).subscibe(result=>{ * | // result = undefined or 'ok' * }) * <popup #popupWithContext> * | <div title>Some templating</div> * | <div body>Some templating with context like: {{popupWithContext.context.hello}} {{popupWithContext.context.name}} !</div> * </popup> */ export declare class BodyDirective { templateRef: TemplateRef<any>; constructor(templateRef: TemplateRef<any>); } export declare class PopupComponent { bodyTemplate: any; body: string; title: string; cancelButton: string; validateButton: string; width: string; height: string; mainColor: string; noActions: boolean; openEvent: EventEmitter<{}>; context: any; _open: boolean; state: string; result: Subject<any>; form: FormGroup; open(context?: any): Subject<any>; close($event?: Event): void; bindForm(form: FormGroup): this; stopPropagation($event: Event): void; out(isValidate: any, $event?: Event, value?: any): void; }
fc037eb8809fc751e7702b985598d2f2b2c3bb02
TypeScript
verneleem/slash-boilerplate
/src/utils/onDeleteUpdateCache.ts
2.609375
3
import { ApolloCache, FetchResult } from '@apollo/client'; export function update<TData = Record<string, any>>( cache: ApolloCache<TData>, results: FetchResult<TData, Record<string, any>, Record<string, any>>, ) { const data: { [key: string]: any } = results?.data || {}; for (const [, mutations] of Object.entries(data)) { for (const [, results] of Object.entries(mutations)) { if (Array.isArray(results)) { results.forEach((node) => { const id = cache.identify(node); cache.evict({ id }); }); } } } cache.gc(); } const onDeleteUpdateCache = ( cache: ApolloCache<Record<string, any>>, results: FetchResult, ) => update(cache, results); export default onDeleteUpdateCache;
2f7e921f2cdb0c54f66597c1a37748ed10078348
TypeScript
ECCC-CSSP/CSSPTools
/src/webs/CSSPWebToolsAng/client-apps/src/app/enums/generated/ClassificationTypeEnum.ts
2.640625
3
/* * Auto generated C:\CSSPTools\src\codegen\GenerateAngularEnums\bin\Debug\net6.0\GenerateAngularEnums.exe * * Do not edit this file. * */ import { AppLanguageService } from 'src/app/services/app/app-language.service'; import { EnumIDAndText } from 'src/app/models/generated/models/EnumIDAndText.model'; import { LanguageEnum } from 'src/app/enums/generated/LanguageEnum'; export enum ClassificationTypeEnum { Approved = 1, Restricted = 2, Prohibited = 3, ConditionallyApproved = 4, ConditionallyRestricted = 5, } export function GetClassificationTypeEnum(): typeof ClassificationTypeEnum { return ClassificationTypeEnum; } export function ClassificationTypeEnum_GetOrderedText(appLanguageService: AppLanguageService): EnumIDAndText[] { let enumTextOrderedList: EnumIDAndText[] = []; if (appLanguageService.Language == LanguageEnum.fr) { enumTextOrderedList.push({ EnumID: 1, EnumText: 'Agréé' }); enumTextOrderedList.push({ EnumID: 2, EnumText: 'Restreint' }); enumTextOrderedList.push({ EnumID: 3, EnumText: 'Interdit' }); enumTextOrderedList.push({ EnumID: 4, EnumText: 'Agréé sous condition' }); enumTextOrderedList.push({ EnumID: 5, EnumText: 'Restreint sous condition' }); } else { enumTextOrderedList.push({ EnumID: 1, EnumText: 'Approved' }); enumTextOrderedList.push({ EnumID: 2, EnumText: 'Restricted' }); enumTextOrderedList.push({ EnumID: 3, EnumText: 'Prohibited' }); enumTextOrderedList.push({ EnumID: 4, EnumText: 'Conditionally Approved' }); enumTextOrderedList.push({ EnumID: 5, EnumText: 'Conditionally Restricted' }); } return enumTextOrderedList.sort((a, b) => a.EnumText.localeCompare(b.EnumText)); } export function ClassificationTypeEnum_GetIDText(enumID: number, appLanguageService: AppLanguageService): string { let ClassificationTypeEnumText: string; ClassificationTypeEnum_GetOrderedText(appLanguageService).forEach(e => { if (e.EnumID == enumID) { ClassificationTypeEnumText = e.EnumText; return false; } }); return ClassificationTypeEnumText; }
07ed005027614f826a07aacd1dd1ce24ccb68227
TypeScript
HELL0ANTHONY/REST-API-with-Node-and-Typescript
/src/models/Project.ts
2.609375
3
import { Model, DataTypes as Type } from "sequelize"; import { sequelize } from "../database"; import Task from "./Task"; interface ProjectAttributes { id: number; name: string; priority: number; deliveryDate: Date; description: string | null; } interface ProjectInstance extends Model<ProjectAttributes>, ProjectAttributes { } const Project = sequelize.define<ProjectInstance>("project", { id: { type: Type.INTEGER, autoIncrement: true, primaryKey: true, }, name: { type: Type.STRING, allowNull: false, }, priority: { type: Type.STRING, allowNull: false, }, description: { type: Type.STRING, allowNull: true }, deliveryDate: { type: Type.DATE, allowNull: false } }, { timestamps: false }); Project.hasMany(Task); Task.belongsTo(Project); export default Project;
e0b6fc010a71f27b2c0d86bfd4f2cc6e2241d33a
TypeScript
tsiozos/print-sensors-server
/main.ts
2.671875
3
//initialization let stations: Array<number> let lastsync: Array<number> radio.setGroup(1) radio.setTransmitPower(7) radio.sendValue("SYNC",input.runningTime()/100) radio.sendValue("WAKE", 0) function printStations() { serial.writeLine("Registered Stations \n\r ---------") for (let i=0; i<stations.length; i++) serial.writeLine("STATION: "+ i.toString() +" ID:"+stations[i]) } control.setInterval(function () { led.toggle(2, 2) }, 1000, control.IntervalMode.Interval) radio.onReceivedValue(function (name: string, value: number) { if (name === "STATION") { stations.insertAt(0, value) lastsync.insertAt(0, 0) printStations() } if (name === "SYNCACK") { for (let i=0; i<stations.length; i++) if (stations[i] == value) lastsync[i] = input.runningTime()/100 } }) radio.onReceivedString(function (receivedString: string) { }) basic.forever(function () { })
080a5434d86aba397721acd2738a21e56e8c83ca
TypeScript
McGalanes/clean-node-ts
/src/presentation/controllers/book/BookController.spec.ts
2.65625
3
import { GetBooksUseCase } from "../../../domain/usecases/book"; import { BookController } from "./BookController"; import { BookEntity } from "../../../data/repositories/book"; import { HttpResponse } from "../../protocols/http"; import { mock } from "../../../utils/mock-utils"; describe('BookController', () => { describe('getBooks', () => { it('should call getBooksUseCase', () => { //GIVEN const getBooksUseCase: GetBooksUseCase = mock({execute: jest.fn()}) const controller = new BookController(getBooksUseCase) //WHEN controller.getBooks() //THEN expect(getBooksUseCase.execute).toBeCalled() }) it('should return HTTP 200 with filled data collection when success', async () => { //GIVEN const books = [ new BookEntity("0", "Harry Potter 1", "JK Rowling"), new BookEntity("1", "Harry Potter 2", "JK Rowling") ] const mockGetBooksUseCase: GetBooksUseCase = mock({execute: jest.fn().mockResolvedValue(books)}) const controller = new BookController(mockGetBooksUseCase) //WHEN const actual = await controller.getBooks() //THEN expect(actual).toEqual(HttpResponse.ok(books)) }) it('should return HTTP 200 with empty data collection when success', async () => { //GIVEN const getBooksUseCase: GetBooksUseCase = mock({execute: jest.fn().mockResolvedValue([])}) const controller = new BookController(getBooksUseCase) //WHEN const actual = await controller.getBooks() //THEN expect(actual).toEqual(HttpResponse.ok([])) }) it('should return HTTP 500 when fail', async () => { //GIVEN const getBooksUseCase: GetBooksUseCase = mock({execute: jest.fn().mockRejectedValue(null)}) const controller = new BookController(getBooksUseCase) //WHEN const actual = await controller.getBooks() //THEN expect(actual).toEqual(HttpResponse.serverError()) }) }) })
cbaac926f9c2a4c70f779590ba87314e04272470
TypeScript
elena-roman/calculator
/src/app/calculator/operations/operation.ts
3.296875
3
export class Operation { protected value: number; private _operator: string; constructor(operator: string,value: number) { this._operator = operator; this.value = Number(value); } get operator(): string { return this._operator; } toString(operator: string) { return `${this._operator} ${this.value}` } }
3992ef58c97323a77d1fff561465097931df3854
TypeScript
XuPeiYao/ngx-hm-tree
/src/app/shared/ts/element.insertAfter.ts
2.609375
3
export function insertAfter(newEl, targetEl) { const parentEl = targetEl.parentNode; if (parentEl.lastChild === targetEl) { parentEl.appendChild(newEl); } else { parentEl.insertBefore(newEl, targetEl.nextSibling); } }
4764ffaabe6c2a2634fa10fa651226bcc42118cf
TypeScript
lekiert/quickstep-client
/src/app/components/core/exercise/exercise-forms/brackets/brackets-form.component.ts
2.796875
3
import {Component, Input} from "@angular/core"; import {ExerciseFormInterface} from "../exercise-form.interface"; import {Exercise} from "app/exercise"; const styles = require('./brackets-form.component.scss'); const template = require('./brackets-form.component.html'); @Component({ selector: 'brackets-form', template: template, styles: [ styles ], }) export class BracketsFormComponent implements ExerciseFormInterface { @Input() exercise: Exercise; keys(dict) : Array<string> { return Object.keys(dict); } addSentence() { let lastIndex = 0; let keys = this.keys(this.exercise.data).map((val) => { return parseInt(val) }); if (keys.length > 0) { lastIndex = Math.max(...keys); } let newIndex = lastIndex + 1; this.exercise.data[newIndex] = ''; this.exercise.answers[newIndex] = {}; } deleteSentence(index) { delete this.exercise.data[index]; delete this.exercise.answers[index]; } countSentenceBrackets(sentence) { let count = this.parseSentenceBracket(sentence); let result = []; for (let i = 0; i < count; i++) { result.push(i); } return result; } parseSentenceBracket(sentence) { if (typeof sentence === 'string') { return sentence.split("__").length - 1; } } }
acbd46eaa3db3bb56e813ea59a1326dfa3165abb
TypeScript
saudahabib/quotes
/src/app/quote.ts
2.515625
3
export class Quote { public showAuthor: boolean; public showSubmitter: boolean; constructor( public id: number, public quote: string, public author: string, public submitter: string, public timePassed: Date, public likes: number, public hates: number ){ this.showAuthor= false; this.showSubmitter= false; } }
d5afcb7624eec6f490af625da40ee17594dae583
TypeScript
pagoru/pixi3d
/src/skinning/skin.ts
2.90625
3
import { Mat4 } from "../math/mat4" import { Container3D } from "../container" import { Joint } from "./joint" /** * Represents a skin used for vertex skinning. */ export class Skin { /** * Creates a new skin. * @param parent The parent container node for the skin. * @param joints The array of joints included in the skin. */ constructor(public parent: Container3D, public joints: Joint[]) { this._jointVertexMatrices = new Float32Array(joints.length * 16) this._jointNormalMatrices = new Float32Array(joints.length * 16) for (let i = 0; i < joints.length; i++) { this._arrayVertexMatrices.push(new Float32Array(this._jointVertexMatrices.buffer, 16 * 4 * i, 16)) this._arrayNormalMatrices.push(new Float32Array(this._jointNormalMatrices.buffer, 16 * 4 * i, 16)) } } private _jointVertexMatrices: Float32Array private _arrayVertexMatrices: Float32Array[] = [] private _jointNormalMatrices: Float32Array private _arrayNormalMatrices: Float32Array[] = [] /** * Calculates the joint matrices. */ calculateJointMatrices() { for (let i = 0; i < this.joints.length; i++) { /* The vertices have to be transformed with the current global transform of the joint node. Together with the transformation from the inverseBindMatrix, this will cause the vertices to be transformed only based on the current transform of the node, in the coordinate space of the current joint node. */ Mat4.multiply(<Float32Array><unknown>this.joints[i].node.worldTransform.array, this.joints[i].inverseBindMatrix, this._arrayVertexMatrices[i]) /* The vertices have to be transformed with inverse of the global transform of the node that the mesh is attached to, because this transform is already done using the model-view-matrix, and thus has to be cancelled out from the skinning computation. */ Mat4.multiply(<Float32Array><unknown>this.parent.transform.inverseWorldTransform.array, this._arrayVertexMatrices[i], this._arrayVertexMatrices[i]) Mat4.invert(this._arrayVertexMatrices[i], this._arrayNormalMatrices[i]) Mat4.transpose(this._arrayNormalMatrices[i], this._arrayNormalMatrices[i]) } return { jointVertexMatrices: this._jointVertexMatrices, jointNormalMatrices: this._jointNormalMatrices } } }