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
71f2e545b27fbb3a927660c55c46a20cdcd19bcb
TypeScript
CodeLenny/irontest
/src/decorators/Test.ts
2.625
3
import "reflect-metadata"; import { TestInstance } from "../internal/TestInstance"; import { REGISTERED_TEST } from "../internal/constants"; import { TestClassInstance } from "../internal/TestClassInstance"; /** * Mark a method as being a test. Stores metadata about the method. */ export function Test(): MethodDecorator { return (target: object, key: string | symbol, descriptor: PropertyDescriptor) => { const method = descriptor.value; const instance = TestInstance.ensureMapped(descriptor); instance.setMethodName(key); instance.setTestFunction(method); const parent = TestClassInstance.ensureMapped(target); parent.addTest(instance); instance.setParent(parent); instance.register(); Reflect.defineMetadata(REGISTERED_TEST, instance, descriptor.value); }; }
9ca64916f1bbd072584b730da14d2968e4d53214
TypeScript
ncodedude/web-api-nodejs
/src/repository/UsuarioRepositorio.ts
2.5625
3
import { Usuario } from "../schemas/UsuarioSchema"; import * as bcrypt from "bcrypt"; class UsuarioRepositorio { constructor() {} async verifyUser(email: string, password: string) { let user = await Usuario.findOne({ email: email }).exec(); let senha = user ? user.get("senha") : ""; let validated = bcrypt.compareSync(password, senha); if (validated) { return user; } else { return null; } } } export default new UsuarioRepositorio();
f43bab928445ff61e210f14b027d4700018caddf
TypeScript
iKronyck/puzzle
/src/context/AppContext.ts
2.625
3
import {createContext} from 'react'; import type {TasksProps} from './types'; type TypeAppContext = { tasks: Array<TasksProps>; completedTasks: Array<TasksProps>; unCompletedTasks: Array<TasksProps>; favoriteTasks: Array<TasksProps>; loading: boolean; addTask: (task: TasksProps) => void; actionTask: (id: string, key: 'isFavorite' | 'isFinished') => void; }; export const AppContext = createContext<TypeAppContext>({ tasks: [], loading: false, addTask: () => {}, actionTask: () => {}, completedTasks: [], unCompletedTasks: [], favoriteTasks: [], });
962fc7d0e5c88f377c125057ef982f08246cf6f2
TypeScript
msheila1/layout-frontend-rdo-angular
/src/app/core/utils/date-utils.ts
2.921875
3
import { FormGroup, AbstractControl, ValidatorFn } from '@angular/forms'; export const dateLessThanValidator = (dateControl: AbstractControl): ValidatorFn => { return (control: AbstractControl): { [key: string]: boolean } | null => { if (control.value != null && dateControl.value != null && control.value > dateControl.value) { return { dateLessThan: true }; } return null; }; } export const dateGreaterThanValidator = (dateControl: AbstractControl): ValidatorFn => { return (control: AbstractControl): { [key: string]: boolean } | null => { if (control.value != null && dateControl.value != null && control.value < dateControl.value) { return { dateGreaterThan: true }; } return null; }; } export const dateLessThanTodayValidator = (control: AbstractControl): { [key: string]: boolean } | null => { if (control.value != null && control.value > new Date()) { return { dateLessThanToday: true }; } return null; } export const dateLessThanYearsValidator = (years: number): ValidatorFn => { return (control: AbstractControl): { [key: string]: boolean } | null => { if (control.value != null) { let dateCompare = new Date(); dateCompare.setFullYear(new Date().getFullYear() - years); if (dateCompare > control.value) { return { dateLessThanYears: true }; } } return null; }; } export const dateDiffInDaysLessThanValidator = (toControl: AbstractControl, maxDays: number): ValidatorFn => { return (control: AbstractControl): { [key: string]: boolean } | null => { if (control.value != null && toControl.value != null) { let f:Date = new Date(control.value); let t:Date = new Date(toControl.value); var diff = Math.abs(f.getTime() - t.getTime()); var diffDays = Math.ceil(diff / (1000 * 3600 * 24)); if (diffDays > maxDays) { return { dateDiffInDaysLessThan: true }; } return null; } return null; }; } export const copyTimeValues = (date: Date, time: Date) : Date => { let dateTime = new Date(date); if (dateTime != null) { if (time != null) { dateTime.setHours(time.getHours()); dateTime.setMinutes(time.getMinutes()); dateTime.setSeconds(time.getSeconds()); dateTime.setMilliseconds(time.getMilliseconds()); } else { dateTime.setHours(0); dateTime.setMinutes(0); dateTime.setSeconds(0); dateTime.setMilliseconds(0); } return dateTime; } }
ee6bb6bc84c657c403b5d539190ec28d09c42a8f
TypeScript
isabella232/ota-analyzer
/src/services/echarts_data.ts
3.0625
3
/** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { EChartsOption } from 'echarts' export class EchartsData { statisticData: Map<string, number> trimmedData: Map<string, string> title: string unit: string maximumEntries: number /** * Given a set of [key, value] pairs and title, create an object for further * usage in Vue-Echarts. * @param {Map} statisticData * @param {String} title * @param {String} unit * @param {Number} maximumEntries */ constructor( statisticData: Map<string, number>, title: string, unit: string, maximumEntries = 15 ) { this.statisticData = statisticData this.trimmedData = trimMap(statisticData, maximumEntries) this.title = title this.unit = unit this.maximumEntries = maximumEntries } /** * Convert the raw data into a string. * @return {String} A list of [key, value]. */ listData() { let /** String */ table = '' for (let [key, value] of this.statisticData) { table += key + ' : ' + value.toString() + ' Blocks' + '\n' } return table } /** * Generate necessary parameters (option) for vue-echarts. * Format of the parameters can be found here: * https://echarts.apache.org/en/option.html * @param {String} unit * @return {Object} an ECharts option object. */ getEchartsOption(): EChartsOption { let /** Object */ option: EChartsOption = {} option.title = { text: this.title, left: 'center' } option.tooltip = { trigger: 'item', formatter: '{a} <br/>{b} : {c} ' + this.unit + ' ({d}%)' } option.legend = { orient: 'horizontal', left: 'top', top: '10%', data: Array.from(this.trimmedData.keys()) } option.series = [ { name: this.title, type: 'pie', radius: '55%', center: ['50%', '60%'], data: Array.from(this.trimmedData).map((pair: any) => { return { value: pair[1], name: pair[0] } }), emphasis: { itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } } } ] return option } } /** * When there are too many entries in the map, the pie chart can be very * crowded. This function will return the entries that have high values. * Specifically, the top <maximumEntries> will be stored and the others * will be added into an entry called 'other'. * @param {Map} map * @param {Number} maximumEntries * @return {Map} */ function trimMap(map: Map<string, any>, maximumEntries: number) { if (map.size <= maximumEntries) return map let /** Map */ new_map = new Map() for (let i = 0; i < maximumEntries; i++) { let /** Number */ curr = 0 let /** String */ currKey = '' for (let [key, value] of map) { if (!new_map.get(key)) { if (value > curr) { curr = value currKey = key } } } new_map.set(currKey, curr) } let /** Number */ restTotal = 0 for (let [key, value] of map) { if (!new_map.get(key)) { restTotal += value } } new_map.set('other', restTotal) return new_map }
299f197dae610003df243fc18219498c62d723d8
TypeScript
ZhangJinshan2233/improvee
/src/app/_helper/setIndicatorRecordFormatOfChart.ts
2.8125
3
import { getDaysInMonth, } from 'date-fns'; export function set_month_record_value(indicatorRecordArray, currentMonth) { let daysOfMonth = getDaysInMonth(new Date(currentMonth)); let recordValues = new Array(daysOfMonth); recordValues.fill(null); indicatorRecordArray.forEach(indicatorRecord => { recordValues[(+indicatorRecord.createDate.slice(8, 10)) - 1] = parseFloat((indicatorRecord.value)).toFixed(1) }); return recordValues } export function set_year_record_value(indicatorRecordArray) { let recordValues = new Array(12); recordValues.fill(null); console.log(indicatorRecordArray) indicatorRecordArray.forEach(indicatorRecord => { let sum = 0.0; let averageValue=0; for (let i = 0; i < indicatorRecord.records.length; i++) { sum +=+(parseFloat(indicatorRecord.records[i].value).toFixed(1)) } averageValue = sum /(indicatorRecord.records.length) recordValues[(+indicatorRecord.month) - 1] = averageValue }); return recordValues }
585221c19442fb91ca3a37ff00efd83049960f36
TypeScript
gxy5202/zIndexController
/index.d.ts
2.546875
3
// 需要移动的层级对象 export interface IndexTarget { id: string, // 组件id index: number // 组件在当前层级的下标 } // 扁平化组件对象 export interface ComponentItem { index: number, component: { id: string, children: any[] }, pid: string } export interface FlattenComponentsObject { [key: string]: ComponentItem, }
cad9198ee12b8b5e7eb1d26d1b40a88b3f1b9c5c
TypeScript
Revature-Project2-Team1/Project2_FrontEnd
/Vaxify2/src/app/Validators/Date.ts
2.71875
3
import { FormControl } from '@angular/forms'; export class DateValidator { static ptDate(control: FormControl): { [key: string]: any } { let ptDatePattern = /^(0[1-9]|1[0-2])\-(0[1-9]|1\d|2\d|3[01])\-(19|20)\d{2}$/; if (!control.value.match(ptDatePattern)) return { "ptDate": true }; return null; } static usDate(control: FormControl): { [key: string]: any } { let usDatePattern = /^02\/(?:[01]\d|2\d)\/(?:19|20)(?:0[048]|[13579][26]|[2468][048])|(?:0[13578]|10|12)\/(?:[0-2]\d|3[01])\/(?:19|20)\d{2}|(?:0[469]|11)\/(?:[0-2]\d|30)\/(?:19|20)\d{2}|02\/(?:[0-1]\d|2[0-8])\/(?:19|20)\d{2}$/; if (!control.value.match(usDatePattern)) return { "usDate": true }; return null; } }
7bad46897e6f37af5c562af1951b2c755f12c280
TypeScript
zeoneo/photo-gallery
/src/lib/components/Utils.ts
2.578125
3
export const getNewCarouselActiveIndex = (direction, items, activeIndex) => { if (direction === 'prev') { return activeIndex === 0 ? items.length - 1 : activeIndex - 1; } else if (direction === 'next') { return activeIndex === items.length - 1 ? 0 : activeIndex + 1; } };
d86428868359182f925091f6635b660aa9004453
TypeScript
betbetterapp/authenticator
/src/utils/log.ts
2.59375
3
import chalk from 'chalk'; export namespace log { export function header(message: string) { console.log(); console.log(prefix() + ' ' + chalk.green.bold.underline(message)); } export function info(...message: any[]) { console.log(prefix() + chalk.bgBlue.black.bold('i') + chalk.white(), ...message); } export function err(...message: any[]) { console.log(prefix() + chalk.bgRed.black.bold('!') + chalk.red(), ...message); } export function warn(...message: any[]) { console.log(prefix() + chalk.bgYellow.black.bold('!') + chalk.yellow(), ...message); } function prefix(): string { return chalk.grey('[') + chalk.white(new Date().formatClock(true)) + chalk.grey('] ') + chalk.reset(); } }
946b48fa40ac4774619bc2ba8fb892d884834acf
TypeScript
saitho/telegram-bot
/src/core/discord-client.ts
2.828125
3
import Discord, {Guild, GuildMember} from 'discord.js' interface DiscordConnection { bot_username: string; receiver_id: string; } export class DiscordClient { protected client: Discord.Client; constructor() { this.client = new Discord.Client() } public sendValidationMessage(discordName: string, validationCode: string) { return new Promise<DiscordConnection>((resolve, reject) => { this.client.login(process.env.DISCORD_BOT_TOKEN) .then(async () => { console.log(`Discord connection initialized (user: ${this.client.user.tag})!`); const user = await this.getDiscordUsersByUserName(discordName) if (!user) { this.client.destroy() reject(); } await user.send(`Hey there! I was told to send you your verification code for linking your Discord and Telegram accounts. Please enter the following code over on Telegram: \`${validationCode}\` If you did not request a code, simply ignore this message!`) this.client.destroy() resolve({ bot_username: this.client.user.tag, receiver_id: user.id }) }) .catch(console.log); }) } protected getDiscordUsersByUserName(userName: string): Promise<GuildMember> { return new Promise<GuildMember>(async (resolve, reject) => { const guild = await this.client.guilds.fetch(process.env.DISCORD_SERVER_ID, false, true) const [name, discriminator] = userName.split('#') const members = await guild.members.fetch({query: name}) const member = members.filter((i) => i.user.discriminator === discriminator) if (!member.array().length) { reject('No user found.') return } resolve(member.first()) }) } }
de215ecd8439c030e16cf6362693ca80c16567b5
TypeScript
wan54/datahub
/datahub-web/@nacho-ui/core/addon/utils/lib/is-primitive.ts
2.671875
3
/** * Non-deprecated version of the isPrimitive function available from 'util' library */ export default function isPrimitive(value: unknown): boolean { return (typeof value !== 'object' && typeof value !== 'function') || value === null; }
cf527529eece64571c290b57c8e1d0fe11567333
TypeScript
weonyuan/dOgeS
/source/os/memoryManager.ts
2.703125
3
///<reference path="../globals.ts" /> module DOGES { export class MemoryManager { constructor() {} // Loads the program into memory public static loadProgram(programInput, priority): void { // Create a PCB var newPcb = new Pcb(); // Find free memory to assign the base and limit registers newPcb.base = this.fetchFreeBlock(); newPcb.priority = priority; if (newPcb.base === -1) { var processFilename = ProcessManager.createProcessFilename(newPcb); _FileSystem.createFile(processFilename); newPcb.inFileSystem = true; newPcb.limit = -1; _FileSystem.writeFile(processFilename, programInput); } else { newPcb.limit = newPcb.base + PROGRAM_SIZE - 1; newPcb.inFileSystem = false; // Then load the program into memory this.loadToMemory(programInput, newPcb.base); } // Push the new PCB into the Resident list _ResidentList.push(newPcb); _StdOut.putText("Assigned Process ID: " + newPcb.PID); } public static loadToMemory(programInput, startPoint): void { for (var i = 0; i < programInput.length / 2; i++) { if (i === 0) { var currentCode: number = 0; } else { currentCode = currentCode + 2; } _Memory.memArray[i + startPoint] = programInput.substring(currentCode, currentCode + 2); Control.memoryManagerLog(_Memory.memArray); } } // This function is fundamentally different than loadToMemory // since this is used for values, not the entire program input public static storeToMemory(value, targetAddress): void { value += ""; // Pad the value with leading 0 if (value.length === 1) { value = "0" + value; } if ((targetAddress + _CurrentProgram.base) <= _CurrentProgram.limit) { _Memory.memArray[targetAddress + _CurrentProgram.base] = value.toUpperCase(); Control.memoryManagerLog(_Memory.memArray); } else { // Memory out of bounds _Kernel.krnInterruptHandler(MEMORY_VIOLATION_IRQ, ""); } } // Takes the program out of the file system and puts it in main memory // for continued execution // Returns a boolean of the roll in status public static rollIn(program): boolean { _Kernel.krnTrace("Rolling in process " + program.PID + "."); program.base = this.fetchFreeBlock(); // No free memory available if (program.base === null || program.base === -1) { return false; } // Look up the program from the file system var programFilename = ProcessManager.createProcessFilename(program); var readFile = _FileSystem.readFile(programFilename); // Failed to read data from file if (readFile.status === "ERROR") { return false; } // Then load the program from the file system to main memory this.loadToMemory(readFile.body, program.base); var deleteFile = _FileSystem.deleteFile(programFilename); // File can't be deleted in file system if (deleteFile.status === "ERROR") { return false; } program.limit = program.base + PROGRAM_SIZE - 1; program.inFileSystem = false; return true; } // Takes the program out of main memory and stores it in the file system // for later execution // Returns a boolean of the roll out status public static rollOut(program): boolean { _Kernel.krnTrace("Rolling out process " + program.PID + "."); // Create a new file for the rolled-out program var programFilename = ProcessManager.createProcessFilename(program); var programInput = this.fetchProgramInput(program.base); var createdFile = _FileSystem.createFile(programFilename); // File can't be created in file system if (createdFile.status === "ERROR") { return false; } // Then write the program data into the file system var writtenFile = _FileSystem.writeFile(programFilename, programInput); // File can't be written in file system if (writtenFile.status === "ERROR") { return false; } program.state = PS_READY; program.base = -1; program.limit = -1; program.inFileSystem = true; return true; } // Returns the program input in that particular memory segment public static fetchProgramInput(startAddress): string { var programInput = ""; for (var i = startAddress; i < startAddress + PROGRAM_SIZE; i++) { programInput += _Memory.memArray[i]; } return programInput; } // Finds the next available memory block and returns the appropriate address public static fetchFreeBlock(): number { var freeAddress = 0; if (_ResidentList.length > 0) { for (var i = 0; i < _ResidentList.length; i++) { if ( _ResidentList[i] !== undefined && _ResidentList[i].base === freeAddress && _ResidentList[i].base !== -1) { freeAddress += PROGRAM_SIZE; if (freeAddress >= PROGRAM_SIZE * PROGRAM_LIMIT) { freeAddress = -1; } } } } return freeAddress; } // Returns two bytes already allocated in memory public static fetchTwoBytes(address): string { return _Memory.memArray[_CurrentProgram.base + address]; } // Clears one memory segment in main memory public static clearSegment(startPoint): void { if (startPoint === null || startPoint === undefined || startPoint === -1) { startPoint = 0; } for (var i = startPoint; i < (startPoint + PROGRAM_SIZE); i++) { _Memory.memArray[i] = "00"; } } // Clears all memory partitions public static clearAll(): void { _Memory.init(); _ResidentList = []; Control.memoryManagerLog(_Memory.memArray); } } }
a1dfd88ca45992c91b80cc8c45fe60b089a48dd1
TypeScript
pittst3r/playground
/happy-test/jherkin.ts
2.953125
3
import { InstructionList, Builtin } from "./vm"; import { Browser } from "./opcodes"; export interface IStep {} export type StepDef<Args extends any[]> = ( args: Args, offset: number ) => InstructionList; export type Builder = (offset: number) => InstructionList; export function feature( description: string, ...scenarios: Array<Builder> ): InstructionList { const offset = 0; const [fnDeclarations, fnIndex] = declare(offset, scenarios); const calls: InstructionList = scenarios.reduce( (memo, scenario) => { const scenarioAddr = fnIndex.get(scenario); return [...memo, Builtin.Call, scenarioAddr]; }, [] as InstructionList ); return [ ...fnDeclarations, Builtin.Push, `Feature: ${description}`, Builtin.Log, ...calls, Builtin.Halt ]; } export function scenario( description: string, ...steps: Array<Builder> ): Builder { return offset => { const setup = [Browser.NewBrowser, Browser.NewPage]; const teardown = () => [Browser.ClosePage, Browser.CloseBrowser]; const [teardownDeclaration, teardownIndex] = declare(offset, [teardown]); const [stepDeclarations, stepIndex] = declare( offset + teardownDeclaration.length, steps ); const stepCalls: InstructionList = steps.reduce( (memo, step) => { const stepAddr = stepIndex.get(step); return [...memo, Builtin.Call, stepAddr]; }, [] as InstructionList ); const teardownAddr = teardownIndex.get(teardown); const teardownCall = [Builtin.Call, teardownAddr]; return [ ...teardownDeclaration, ...stepDeclarations, Builtin.Push, ` Scenario: ${description}`, Builtin.Log, ...setup, ...stepCalls, ...teardownCall ]; }; } export function declare( offset: number, fns: Array<Builder> ): [InstructionList, WeakMap<Builder, number>] { const fnIndex = new WeakMap<Builder, number>(); let instructions: InstructionList = []; fns.forEach(fn => { const fnAddr = offset + instructions.length + 2; const offsetFn = fn(fnAddr); const afterFnAddr = fnAddr + offsetFn.length + 1; instructions = instructions.concat([ Builtin.Jump, afterFnAddr, ...offsetFn, Builtin.Return ]); fnIndex.set(fn, fnAddr); }); return [instructions, fnIndex]; } export function step<Args extends any[]>( stepDef: StepDef<Args>, ...args: Args ): Builder { return offset => stepDef(args, offset); } export const given = step; export const when = step; export const then = step; export const and = step; export const should = step;
fd76c3a2e1ea15e38826e8c530055fbfb82284a5
TypeScript
Piket95/CarAnalytics
/src/app/maintenance-details/maintenance-details.component.ts
2.5625
3
import { DetailItem } from './maintenance-details-item'; import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-maintenance-details', templateUrl: './maintenance-details.component.html', styleUrls: ['./maintenance-details.component.css'] }) export class MaintenanceDetailsComponent implements OnInit { title: string = 'Motorschaden'; sum: number = 0; items: DetailItem[] = [ { title: 'Gutachten', price: 55.40 }, { title: 'Neuer Motor', price: 5000 }, { title: 'Einbau', price: 50.15 } ]; constructor() { } ngOnInit() { this.items.forEach(item => { this.sum = this.sum + +item.price; //Das extra "+" vor "item.price" wandelt die Variable in number, falls sie es nicht schon ist }); this.sum = Number(this.sum.toFixed(2)); } }
aac43941767690ae7d59b2da8f3c759855038f87
TypeScript
dbrudner/bdom
/index.ts
2.921875
3
import { b, firstRender } from './lib/bdom'; // 1: Create a function that declares what the DOM should look like function render(count) { return b({ children: ['hey'], tag: 'div', attributes: { style: { textAlign: 'center', lineHeight: 100 + count + 'px', border: '1px solid red', width: 100 + count + 'px', height: 100 + count + 'px' } } }); } // 2: Initialise the document var count = 0; // We need some app data. Here we just store a count. var tree = render(count); // We need an initial tree console.log({ tree }); // var rootNode = createElement(tree); // Create an initial root DOM node ... // document.body.appendChild(rootNode); // ... and it should be in the document // // 3: Wire up the update logic // setInterval(function () { // count++; // var newTree = render(count); // var patches = diff(tree, newTree); // rootNode = patch(rootNode, patches); // tree = newTree; // }, 1000);
125a5d3608cea477d4dc172f6ff28bd1ea07a10c
TypeScript
FabioAntunes/angular2-firebase-todo
/src/app/app.component.ts
2.5625
3
import { Component } from '@angular/core'; import { AngularFire, FirebaseListObservable } from 'angularfire2'; import 'rxjs/add/operator/map'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { text = ''; todos: FirebaseListObservable<any[]>; ourTodosList = []; constructor(af: AngularFire) { this.todos = <FirebaseListObservable<any>>af.database.list('Todos').map(items => { return items.map(item => { item.text = item.text.toUpperCase(); return item; }) }); //alternative way of subscribing this.todos.subscribe(todos => this.ourTodosList = todos); } addTodo() { this.todos.push({ text: this.text, completed: false }); this.text = ''; } changeTodo(key: string, completed){ this.todos.update(key, {completed: !completed}); } }
a8d23bfab63178d7bcea39aacf73558f1e61c456
TypeScript
joe-re/sql-language-server
/packages/sqlint/src/rules/columnNewLine.ts
2.734375
3
import { SelectStatement } from '@joe-re/sql-parser' import { Rule, RuleConfig } from './index' type Options = { allowMultipleColumnsPerLine: boolean } const META = { name: 'column-new-line', type: 'select', options: { allowMultipleColumnsPerLine: Boolean }, } export const columnNewLine: Rule<SelectStatement, RuleConfig<Options>> = { meta: META, create: (context) => { if (Array.isArray(context.node.columns)) { const first = context.node.columns[0] const rest = context.node.columns.slice(1, context.node.columns.length) let previousLine = first.location.start.line let previousOffset = first.location.end.offset let previousColumn = first.location.start.column const invalidColumns = rest .map((v) => { const result = { column: v, previousLine, previousOffset, previousColumn, } previousLine = v.location.start.line previousOffset = v.location.end.offset previousColumn = v.location.start.column return result }) .filter((v) => v.column.location.start.line === v.previousLine) if (invalidColumns.length === 0) { return } return invalidColumns.map((v) => { return { message: 'Columns must go on a new line.', location: v.column.location, fix: (fixer) => { // "," should be at after previousOffset so + 1 to include it const pos = v.previousOffset + 1 // calculate number of spaces to align calumns position to the first const spacesNumber = first.location.start.column - (v.column.location.start.offset - v.previousOffset) return fixer.insertText(pos, '\n' + ''.padStart(spacesNumber, ' ')) }, } }) } }, }
690493616ab4f2f1005e94643f9c6676fffe38a8
TypeScript
hudsonssrosa/tdd-typescript
/ex_tictactoe/test/tictactoe.test.ts
3.359375
3
import { TicTacToe } from "../src/main/tictactoe"; describe("TicTacToe test", () => { it("Should returns the position 1,1 in matrix for Player X", () => { let tictactoe: TicTacToe = new TicTacToe(); const position = { posX: 1, posY: 1 } const matrix = tictactoe.play('X', position) expect(matrix[1][1]).toBe('X') }) it("Should returns the position 2,2 in matrix for Player O", () => { let tictactoe: TicTacToe = new TicTacToe(); const position = { posX: 2, posY: 2 } const matrix = tictactoe.play('O', position) expect(matrix[2][2]).toBe('O') }) it("Should returns the position 2,2 in matrix for Player X", () => { let tictactoe: TicTacToe = new TicTacToe(); let position = { posX: 2, posY: 2 } const matrix = tictactoe.play('O', position) expect(tictactoe.play('O', position)).toBe('Position played') }) it("should determine the winner, when we have 3 X's in a row", ()=>{ let tictactoe: TicTacToe = new TicTacToe(); tictactoe.play('X', {posX: 0, posY: 0 }) tictactoe.play('O', {posX: 1, posY: 0 }) tictactoe.play('X', {posX: 0, posY: 1 }) tictactoe.play('O', {posX: 1, posY: 1 }) tictactoe.play('X', {posX: 0, posY: 2 }) expect(tictactoe.hasAnyBodyWon()).toBe(true) }) it("should determine if nobody won", ()=>{ let tictactoe: TicTacToe = new TicTacToe(); tictactoe.play('O', {posX: 0, posY: 0 }) tictactoe.play('X', {posX: 0, posY: 1 }) tictactoe.play('O', {posX: 0, posY: 2 }) tictactoe.play('O', {posX: 1, posY: 0 }) tictactoe.play('X', {posX: 1, posY: 1 }) tictactoe.play('X', {posX: 1, posY: 2 }) tictactoe.play('X', {posX: 2, posY: 0 }) tictactoe.play('O', {posX: 2, posY: 1 }) tictactoe.play('O', {posX: 2, posY: 2 }) expect(tictactoe.hasAnyBodyWon()).toBe(false) }) it("should determine if has a winner in the board", ()=>{ let tictactoe: TicTacToe = new TicTacToe(); tictactoe.play('X', {posX: 0, posY: 0 }) tictactoe.play('O', {posX: 0, posY: 1 }) tictactoe.play('X', {posX: 0, posY: 2 }) tictactoe.play('O', {posX: 1, posY: 0 }) tictactoe.play('X', {posX: 1, posY: 1 }) tictactoe.play('O', {posX: 1, posY: 2 }) tictactoe.play('X', {posX: 2, posY: 0 }) tictactoe.play('O', {posX: 2, posY: 1 }) tictactoe.play('X', {posX: 2, posY: 2 }) expect(tictactoe.hasAnyBodyWon()).toBe(true) }) });
87627c03a06eafb0fe28e5f4fdbb41ed78af3cdf
TypeScript
Covicake/theam_test
/src/Repository/Customer-Repository.ts
2.546875
3
import { getManager, UpdateResult, DeleteResult } from 'typeorm'; import { Customer } from '../Entity/Customer'; export class CustomerRepository { createCustomer(customer: Customer): Promise<Customer> { return getManager().getRepository(Customer).save(customer); } getCustomersList(): Promise<Customer[]> { return getManager().getRepository(Customer).createQueryBuilder('Customer') .select(['Customer.id', 'Customer.name', 'Customer.lastName']) .getMany(); } getCustomer(customerId: number): Promise<Customer> { return getManager().getRepository(Customer).findOne({ where: { id: customerId } }); } updateCustomer(customerId: number, newCustomerData: Customer): Promise<UpdateResult> { return getManager().getRepository(Customer).update({id: customerId}, newCustomerData); } deleteCustomer(customerId: number): Promise<DeleteResult> { return getManager().getRepository(Customer).delete({id: customerId}); } }
fcb03c636f429cfa934a2021c58792e2ede2b15f
TypeScript
AnuPoudyal/DailyLabCS445
/lab3/exer2.ts
3.921875
4
/*Re-write the following code using TypeScript. Try to be as explicit as possible and add Types to everything you can. When you are done, transpile the TS code to JS code and inspect the JS code. let bankAccount = { money: 2000, deposit(value) { this.money += value; } }; let myself = { name: "Asaad", bankAccount: bankAccount, hobbies: ["Violin", "Cooking"] }; myself.bankAccount.deposit(3000); console.log(myself); */ //solution let bankAccount : { money:number; deposit(value : number):void; } bankAccount = { money : 2000, deposit(value :number):void{ this.money += value; } } let myself:{ name : string; bankAccount :any; hobbies :string[]; } myself = { name : "Asaad", bankAccount : bankAccount, hobbies : ["Violin", "Cooking"] } myself.bankAccount.deposit(3000); console.log(myself)
cf98044634a987b08a83a39d66ad2a58ac9bfd13
TypeScript
shawvyu/deviceone
/ui/do_Label.d.ts
3.046875
3
/* * @Author: shawvyu * @Date: 2020-08-09 16:59:16 * @LastEditTime: 2020-08-09 17:08:09 * @LastEditors: Please set LastEditors * @Description: In User Settings Edit * @FilePath: \deviceone\ui\do_Label.d.ts */ import { UiBasicInstance, FontStyle, TextFlag, TextAlign } from "../base/uiBase"; /** * 一.iOS * 1.height=-1,maxHeight=200,宽度具体数,maxLines=1,最大行数无效(高为-1时maxLines无效,靠maxHeight来控制) * 2.与安卓不一样的地方: * 1).ios的高度是固定值,text超过label的宽,text每行数据特别多,最大行数设置固定值(1、2)等,都有省略号;区别:android的text显示不全都有省略号 * 2).label宽度固定,最大行间距与(字体大小行数)超过label宽度,最后2行数据之间没有行间距,区别:android的,最大行间距与(字体大小行数)超过label宽度,不显示最后几行数据 * 3).ios动态改变textflag=normal,text数据会往下移动,区别:android的不会下移 * 4).label的高度是固定值或者-1,设置最大行数(除-1和0)以外的数,数据是在中间显示的,不是从头显示,区别:android从头显示 * 5).ios的label的border不支持4个角,区别:android的支持4个角不同 * 二.Android * 1.最大高度与最大行数冲突,Android永远都是最大行数优先级高,如果maxLines=1,就是默认值(空),最大高度才起作用。 */ export interface DoLabel extends UiBasicInstance{ /** * 文本显示内容 * @example var do_Label = ui("do_Label_3"); //实例化 do_Label.text = "文本标签框,用于显示文本文字,设置字体样式、大小、内容对齐" * */ text:string /** * 字体颜色 * * 说明 : 设置字体显示颜色,值格式为:8位16进制字符,前6位是RGB颜色值,后两位是透明度(Alpha),例如:000000FF * @default 000000FF * @example do_Label.fontColor = "FF0000FF"; */ fontColor:string /** * 字体风格 * @example do_Label.fontStyle = "italic"; */ fontStyle:FontStyle /** * 字体标示 * * @example do_Label.textFlag = "underline"; */ textFlag:TextFlag /** * 字体大小 * @default 17 * @example do_Label.fontSize = 30; */ fontSize:number /** * 文本对齐方式 * * 编辑类型 : 只允许设计区内修改。 * @default left */ textAlign:TextAlign /** * 最大宽度 * * 编辑类型 : 只允许设计区内修改 * * 说明 : label的width为-1的时候,label会根据text内容自动适配变宽,但是不会宽于maxWidth */ maxWidth:number /** * 最大高度 * * 编辑类型 : 只允许设计区内修改。 * * 说明 : 设置文本框显示最大高度值,只有在设置Height属性值为-1时有效,否则不起作用 */ maxHeight:number /** * 最大行数 * * 编辑类型 : 只允许设计区内修改。 * * 说明 : 最大行数,说明:设置文本内容显示最大行数,如显示内容超过了最大行值则结尾用省略号…表示(iOS只有设置成1时才会显示…);缺省为1行,如果为小于或等于0表示不限行数 * @default 1 */ maxLines:number /** * 行间距 * * 说明 : 设置每行字之间的间距 * @example do_Label.linesSpace = 40; * * 下图为间距为10和间距为40的效果图。 * @link {http://www.appworker.net/awdoc/web/img/20180329/66a65f4c7a92425a99fb316d65cd0339.png} * @link {http://www.appworker.net/awdoc/web/img/20180329/47ed8288531744f0aee7faf45aa56cad.png} */ linesSpace:number /** * 阴影效果 * * 说明 : 添加阴影效果,属性值格式是:“颜色,x位置,y位置,圆角”,如’FF9999FF,30,30,20’,默认值为’000000FF,0,0,0’,若其中某个值不填,需保留逗号,如不填颜色,’,0,0,0’,当圆角为0时为没有阴影效果 * @example do_Label.shadow = "FF0000FF,5,5,5"; * @link {http://www.appworker.net/awdoc/web/img/20180329/c30d70fd951645fbad863204ec3fb2ef.png} * @link {http://www.appworker.net/awdoc/web/img/20180329/e97aee1eddc340bc95704171eb0f02ff.png} * @link {http://www.appworker.net/awdoc/web/img/20180329/6f39eb5c2cd949129139e90a6d51e6cc.png} */ shadow:string }
60cf2c9ed5a69d08ce4380085b8d314dbefc2d79
TypeScript
DataHeaving/orchestration
/scheduler/src/tests/executor.spec.ts
2.78125
3
import * as common from "@data-heaving/common"; import test from "ava"; import * as spec from "../executor"; import * as events from "../events"; test("Job-specific event invoking works", async (t) => { const globalEvents = createEventsTrackerObject(); const job1Events = createEventsTrackerObject(); const job2Events = createEventsTrackerObject(); await spec.runScheduler( { job1: { job: () => common.sleep(100), timeFromNowToNextInvocation: timeFromNowToNextInvocation(1, 0), // Return value of 0 for 1 time, then undefined jobSpecificEvents: createEventBuilderForTrackerObject(job1Events), }, job2: { job: () => common.sleep(100), timeFromNowToNextInvocation: timeFromNowToNextInvocation(1, 0), // Return value of 0 for 1 time, then undefined jobSpecificEvents: createEventBuilderForTrackerObject(job2Events), }, }, createEventBuilderForTrackerObject(globalEvents), ); t.deepEqual( globalEvents, { jobScheduled: 2, jobStarting: 2, jobEnded: 2, }, "Global events must all have been invoked twice: 1 full cycle for both jobs", ); t.deepEqual( job1Events, { jobScheduled: 1, jobStarting: 1, jobEnded: 1, }, "Job1-specific events must all have been invoked only once: 1 full cycle for this job.", ); t.deepEqual( job2Events, { jobScheduled: 1, jobStarting: 1, jobEnded: 1, }, "Job2-specific events must all have been invoked only once: 1 full cycle for this job.", ); }); test("After error, previous value is undefined", async (t) => { let counter = 0; const timeToNextRun = timeFromNowToNextInvocation(4, 0); const seenResults: Array<unknown> = []; await spec.runScheduler({ jobID: { job: () => { ++counter; if (counter === 3) { throw new Error("Dummy"); } return Promise.resolve(counter); }, timeFromNowToNextInvocation: (val) => { seenResults.push(val); return timeToNextRun(); }, }, }); t.deepEqual(seenResults, [undefined, 1, 2, undefined, 4]); }); test("Test that specifying jobs as array works too", async (t) => { let jobCalled = false; function createJobInfo(): spec.JobInfo<unknown> { return { job: () => { jobCalled = true; return Promise.resolve(); }, timeFromNowToNextInvocation: timeFromNowToNextInvocation(1, 0), // Return value of 0 for 1 time, then undefined }; } await spec.runScheduler(["job"], createJobInfo()); t.true(jobCalled); jobCalled = false; let jobFactoryCalled = false; let seenJobID = ""; let seenIdx = -1; await spec.runScheduler(["job"], (jobID, idx) => { jobFactoryCalled = true; seenJobID = jobID; seenIdx = idx; return createJobInfo(); }); t.true(jobFactoryCalled); t.deepEqual(seenJobID, "job"); t.deepEqual(seenIdx, 0); t.true(jobCalled); }); test("Passing duplicate job ID throws an expected error", async (t) => { let jobCalled = false; await t.throwsAsync( () => spec.runScheduler(["jobID", "jobID"], { job: () => { jobCalled = true; return Promise.resolve(); }, timeFromNowToNextInvocation: timeFromNowToNextInvocation(1, 0), // Return value of 0 for 1 time, then undefined }), { instanceOf: spec.DuplicateJobIDError, message: `Duplicate job ID "jobID".`, }, ); t.false(jobCalled); }); test("Passing invalid arguments throws an expected error", async (t) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any await t.throwsAsync(() => spec.runScheduler([], undefined as any), { instanceOf: spec.InvalidParametersError, message: "When giving array as first argument, second argument must be function or job specification.", }); }); test("Test that asynchronous job (factory) works", async (t) => { let jobCalled = false; const createJobInfoAsync = async () => { await common.sleep(200); return { job: async () => { await common.sleep(100); jobCalled = true; }, timeFromNowToNextInvocation: timeFromNowToNextInvocation(1, 0), // Return value of 0 for 1 time, then undefined }; }; await spec.runScheduler({ job1: await createJobInfoAsync(), }); t.true(jobCalled); jobCalled = false; await spec.runScheduler({ job1: createJobInfoAsync, }); t.true(jobCalled); }); function createEventsTrackerObject(): { [P in keyof events.VirtualSchedulerEvents]: number; } { return { jobScheduled: 0, jobStarting: 0, jobEnded: 0, }; } const createEventBuilderForTrackerObject = ( trackerObject: ReturnType<typeof createEventsTrackerObject>, ) => { const retVal = new common.EventEmitterBuilder<events.VirtualSchedulerEvents>(); for (const evtNameString of Object.keys(trackerObject)) { const evtName = evtNameString as keyof events.VirtualSchedulerEvents; retVal.addEventListener(evtName, () => { ++trackerObject[evtName]; }); } return retVal; }; const timeFromNowToNextInvocation = (iterations: number, delay: number) => () => --iterations < 0 ? undefined : delay;
80eb2585a4547caa47b95e1247ab5f303a4a8b9b
TypeScript
buildcom/BossyUI
/src/bossy-ui/components/calendar/calendar.spec.ts
2.5625
3
import {BossyCalendarComponent} from './calendar.component'; let cal: BossyCalendarComponent; describe('the calendar component', () => { it('should display a date', () => { const calendar = new BossyCalendarComponent(); const year = new Date().getFullYear(); const date = new Date(year, 5, 1); calendar.selectMonth(5); expect(calendar.display).toEqual(date); }); }); describe('BossyCalendars month', () => { beforeEach(() => { cal = new BossyCalendarComponent(); cal.ngOnInit(); }); it('should display january after december (nextMonth())', () => { const year = new Date().getFullYear(); cal.display = new Date(year, 11, 25); cal.nextMonth(); expect(cal.display.getMonth()).toEqual(0); }); it('should display December after January (prevMonth())', () => { const year = new Date().getFullYear(); cal.display = new Date(year, 0, 25); cal.previousMonth(); expect(cal.display.getMonth()).toEqual(11); }); it('should have a selected date', () => { expect(cal.selected).toBeTruthy(); }); });
f2fb6b691c5db131ae6ed12fdb70e959dcb8338e
TypeScript
szczypiorofix/SpaceInvaders
/client/src/core/Spaceship.ts
2.90625
3
import { Animation, Bullet, Canvas, Enemy, GameState, SFX, Sprite, StateType} from './'; export class Spaceship { private x: number; private y: number; private width: number = 32; private height: number = 32; private alive: boolean = true; private shoot: boolean = false; private shootMulti: boolean = false; private speedX: number = 5; private speedY: number = 5; private imageOrigin: number = 32; private imageScale: number = 32; private health: number; private maxHealth: number = 10; private sprite: Sprite; private animation: Animation; private bullets: Bullet[]; private maxBullets: number = 20; private skipBulletFrame: number = 4; // dobre do upgradeów ?? private curBulletFrame: number = 0; private curBullet: number = 0; private shootSound: SFX; private shootSound2: SFX; private gameState: GameState; private enemies: Enemy[]; constructor(x: number, y: number, gameState: GameState) { this.x = x; this.y = y; this.health = this.maxHealth; this.gameState = gameState; this.shootSound = new SFX("./music/shot.wav"); this.shootSound2 = new SFX("./music/shot2.wav"); this.bullets = []; for (let i = 0; i < this.maxBullets; i++) { this.bullets.push(new Bullet(this.x, this.y)); } this.curBullet = 0; this.enemies = []; this.sprite = new Sprite('images/spaceship.png'); this.animation = new Animation(this.sprite, 4, 3, this.imageOrigin, this.imageScale); } public getX() { return this.x; } public getY() { return this.y; } public setX(x: number) { this.x = x; } public setY(y: number) { this.y = y; } public setCoord(x: number, y: number) { this.x = x; this.y = y; } public getWidth() { return this.width; } public getHeight() { return this.height; } public moveRight() { this.x += this.speedX; } public moveLeft() { this.x -= this.speedX; } public isShooting() { return this.shoot; } public stopShooting() { this.curBulletFrame = 0; } public setShoot(s: boolean) { this.shoot = s; } public isShootingMulti() { return this.shootMulti; } public setShootMulti(s: boolean) { this.shootMulti = s; } public isAlive() { return this.alive; } public looseHealth() { this.health--; } public setAlive(a: boolean) { this.alive = a; } public getMaxBullets() { return this.maxBullets; } public getBullets(): Bullet[] { return this.bullets; } public setEnemies(e: Enemy[]) { this.enemies = e; } public update() { if (this.health <= 0) { this.alive = false; this.gameState.gameState = StateType.GameLoose; console.log("GAME OVER !!!"); } if (this.alive) { this.animation.nextStep(); for (let i = 0; i < this.bullets.length; i++) { if (this.bullets[i].getY() < 0) { this.bullets[i].setShoot(false); this.bullets[i].setShootMulti(false); this.bullets[i].setY(this.y); } else { this.bullets[i].update(); for (let j = 0; j < this.enemies.length; j++) { if (this.bullets[i].isShoot()) { if (this.bullets[i].getX() > this.enemies[j].getX() && this.bullets[i].getX() < this.enemies[j].getX() + 32 && this.bullets[i].getY() < this.enemies[j].getY() + 32 && this.bullets[i].getY() > this.enemies[j].getY() && this.enemies[j].isAlive() ) { this.enemies[j].setAlive(false); this.bullets[i].setShoot(false); this.bullets[i].setY(this.y); } } } } } if (this.shoot && !this.bullets[this.curBullet].isShoot() && this.curBulletFrame === 0 ) { this.bullets[this.curBullet].setShootMulti(false); this.bullets[this.curBullet].shoot(this.x); this.shootSound.play(); this.curBullet++; if (this.curBullet > this.maxBullets - 1) { this.curBullet = 0; } } if (this.shootMulti && !this.bullets[this.curBullet].isShootMulti() && this.curBulletFrame === 0 ) { this.bullets[this.curBullet].setShoot(false); this.bullets[this.curBullet].shootMulti(this.x); this.shootSound2.play(); this.curBullet++; if (this.curBullet > this.maxBullets - 1) { this.curBullet = 0; } } if (this.shoot || this.shootMulti) { if (this.curBulletFrame < this.skipBulletFrame) { this.curBulletFrame++; } else this.curBulletFrame = 0; } } } public draw(canvas: Canvas) { if (this.alive) { this.animation.drawAnimation(canvas, this.x, this.y); } for (let i = 0; i < this.bullets.length; i++) if (canvas.ctx && (this.bullets[i].isShoot() || this.bullets[i].isShootMulti())) this.bullets[i].draw(canvas.ctx); if (canvas.ctx) { canvas.ctx.fillStyle = "#AA0011"; canvas.ctx.fillRect(20, 20, 10, (this.health * (440)) / this.maxHealth); } } }
0eb0d30c4b630c2d6a85b6b723636013e6f484df
TypeScript
dubzzz/fast-check
/packages/fast-check/test/unit/arbitrary/_internals/helpers/TextEscaper.spec.ts
3.015625
3
import * as fc from 'fast-check'; import { escapeForTemplateString, escapeForMultilineComments, } from '../../../../../src/arbitrary/_internals/helpers/TextEscaper'; describe('escapeForTemplateString', () => { it('should not escape normal characters', () => { expect(escapeForTemplateString('a')).toBe('a'); expect(escapeForTemplateString('z')).toBe('z'); }); it('should escape properly known issues', () => { expect(escapeForTemplateString('`')).toBe('\\`'); expect(escapeForTemplateString('$')).toBe('\\$'); expect(escapeForTemplateString('\\')).toBe('\\\\'); expect(escapeForTemplateString('\r')).toBe('\\r'); }); it('should escape properly string containing multiple issues', () => { expect(escapeForTemplateString('`hello${1}\r')).toBe('\\`hello\\${1}\\r'); }); it('should escape properly single ascii characters', () => { for (let i = 0; i !== 128; ++i) { const character = String.fromCharCode(i); const escapedCharacter = escapeForTemplateString(character); try { expect(eval('`' + escapedCharacter + '`')).toBe(character); } catch (err) { throw new Error(`Failed for i = ${i}, got error: ${err}`); } } }); it('should escape properly any string', () => fc.assert( fc.property(fc.fullUnicodeString(), (text) => { const escapedText = escapeForTemplateString(text); expect(eval('`' + escapedText + '`')).toBe(text); }), )); }); describe('escapeForMultilineComments', () => { it('should not escape normal characters', () => { expect(escapeForMultilineComments('a')).toBe('a'); expect(escapeForMultilineComments('z')).toBe('z'); }); it('should escape properly known issues', () => { expect(escapeForMultilineComments('*/')).toBe('*\\/'); }); it('should escape properly string containing multiple issues', () => { expect(escapeForMultilineComments('*/ */ */')).toBe('*\\/ *\\/ *\\/'); expect(escapeForMultilineComments('*/ /*/ **// * / /*')).toBe('*\\/ /*\\/ **\\// * / /*'); }); it('should escape properly any string', () => fc.assert( fc.property(fc.fullUnicodeString(), (text) => { const escapedText = escapeForMultilineComments(text); expect(eval('/*' + escapedText + '*/"success"')).toBe('success'); }), )); });
2b27bd664343e36adfb11f9b4222543acb9f99c3
TypeScript
apollo-elements/apollo-elements
/packages/hybrids/factories/query.ts
2.515625
3
import type { DocumentNode, TypedDocumentNode } from '@apollo/client/core'; import type { Descriptor } from 'hybrids'; import { controller } from './controller.js'; import { ApolloQueryController, ApolloQueryControllerOptions, } from '@apollo-elements/core/apollo-query-controller'; /** * Hybrids property descriptor factory for GraphQL querys. * * @param queryDocument The query document. * @param options Options to control the query. * @return Hybrids descriptor for a [`ApolloQueryController`](/api/core/controllers/query/) */ export function query<E extends HTMLElement, D, V>( queryDocument?: DocumentNode | null, options?: ApolloQueryControllerOptions<D, V>, ): Descriptor<E, ApolloQueryController<D, V>> export function query<E extends HTMLElement, D extends TypedDocumentNode>( queryDocument?: D | null, options?: ApolloQueryControllerOptions<D> ): Descriptor<E, ApolloQueryController<D>> { return controller<E, ApolloQueryController<D>>(ApolloQueryController, queryDocument, options); }
29da307943570cffbe4ef2f17291eb01727c7d28
TypeScript
kamleshkrjha/LoginLogoutFlow
/client/src/app/_services/authentication.service.ts
2.515625
3
import { HttpClient, HttpBackend } from '@angular/common/http'; import { Injectable } from '@angular/core'; import { map, catchError } from 'rxjs/operators'; import { Observable, of } from 'rxjs'; const config = { apiUrl: 'http://localhost:8000' }; interface Response { success: boolean; errorMessage: string; data?: any; } @Injectable({ providedIn: 'root' }) export class AuthenticationService { constructor(private http: HttpClient) { } login (username: string, password: string) { return this.http.post<any>(`${config.apiUrl}/users/authenticate`, { username: username, password: password }) .pipe(map(res => { if (res && res.success && res.data) { // store user details sessionStorage.setItem('currentUser', JSON.stringify(res.data)); } return res; })) .pipe(catchError(this.handleError('login', []))); } logout (username) { return this.http.get<any>(`${config.apiUrl}/users/logout/${username}`) .pipe(map(res => { sessionStorage.removeItem('currentUser'); return res; })) .pipe(catchError(this.handleError('logout', []))); } private handleError (operation, result) { return (error: any): Observable<Response> => { console.log(`error in ${operation}: ${error}`); return of({ success: false, errorMessage: 'Some error occured!!' } as Response); }; } }
9177db363531127e7f8a91df8e9d5474283e8893
TypeScript
Tschrock/binaryformater-lib
/lib/Records/BinaryArrayRecord.ts
2.9375
3
import { BufferReader } from "../BufferReader"; import { ClassTypeInfo } from "../DataStructures/ClassTypeInfo"; import { Sequence } from "../DataStructures/Sequence"; import { BinaryArrayTypeEnumeration, BinaryArrayType } from "../Enumerations/BinaryArrayTypeEnumeration"; import { BinaryTypeEnumeration, BinaryType } from "../Enumerations/BinaryTypeEnumeration"; import { PrimitiveTypeEnumeration } from "../Enumerations/PrimitiveTypeEnumeration"; import { RecordTypeEnumeration, RecordType } from "../Enumerations/RecordTypeEnumeration"; import { Int32Primitive } from "../PrimitiveTypes/Int32Primitive"; import { LengthPrefixedString } from "../PrimitiveTypes/LengthPrefixedString"; export class BinaryArrayRecord { public readonly RecordTypeEnum: RecordTypeEnumeration = new RecordTypeEnumeration(RecordType.BinaryArray); constructor( public ObjectId: Int32Primitive, public BinaryArrayTypeEnum: BinaryArrayTypeEnumeration, public Rank: Int32Primitive, public Lengths: Sequence<Int32Primitive>, public LowerBounds: Sequence<Int32Primitive> | null, public TypeEnum: BinaryTypeEnumeration, public AdditionalTypeInfo: PrimitiveTypeEnumeration | LengthPrefixedString | ClassTypeInfo | null, ) { } public static read(buffer: BufferReader): BinaryArrayRecord { const objectId = Int32Primitive.read(buffer); const binaryArrayTypeEnum = BinaryArrayTypeEnumeration.read(buffer); const rank = Int32Primitive.read(buffer); const lengths = Sequence.read(buffer, Int32Primitive.read, rank.Value); let lowerBounds: Sequence<Int32Primitive> | null = null; if ( binaryArrayTypeEnum.Value === BinaryArrayType.SingleOffset || binaryArrayTypeEnum.Value === BinaryArrayType.JaggedOffset || binaryArrayTypeEnum.Value === BinaryArrayType.RectangularOffset ) { lowerBounds = Sequence.read(buffer, Int32Primitive.read, rank.Value); } const typeEnum = BinaryTypeEnumeration.read(buffer); let additionalTypeInfo = null; switch (typeEnum.Value) { case BinaryType.Primitive: case BinaryType.PrimitiveArray: additionalTypeInfo = PrimitiveTypeEnumeration.read(buffer); break; case BinaryType.SystemClass: additionalTypeInfo = LengthPrefixedString.read(buffer); break; case BinaryType.Class: additionalTypeInfo = ClassTypeInfo.read(buffer); break; default: break; } return new BinaryArrayRecord(objectId, binaryArrayTypeEnum, rank, lengths, lowerBounds, typeEnum, additionalTypeInfo); } }
57c0bd2a6a0ebc16a90a4b4ea0f9bc69bb036889
TypeScript
Junior-Dollar/thimble-bot
/src/lib/truncate.ts
2.78125
3
const truncate = (str: string, length: number) => { return str.length - 3 > length ? `${str.slice(0, length)}...` : str; }; export default truncate;
7f12abe874a4d44049a405e660dc4971021cf203
TypeScript
GalloDaSballo/token-allowance-checker
/src/utils/logEventVerifier.ts
2.71875
3
export const topicHashApprove = '0x8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925' export const eventABI = [ { indexed: true, internalType: 'address', name: 'owner', type: 'address', }, { indexed: true, internalType: 'address', name: 'spender', type: 'address', }, { indexed: false, internalType: 'uint256', name: 'value', type: 'uint256', }, ] // eslint-disable-next-line @typescript-eslint/no-explicit-any export const checkLogTopic = (logEntry: any) => { // Apparently dfuse query results based on topic sometimes return wrong topics. Double-check that the // logEntry actually is of the expected topic. if (logEntry.topics[0] !== topicHashApprove) { console.log( `Skipping log event. Topic is wrong, expected ${topicHashApprove}, got ${logEntry.topics[0]}.` ) return false } return true } // eslint-disable-next-line @typescript-eslint/no-explicit-any export const decodeLog = (logEntry: any, web3: Web3) => { if (logEntry.data === '0x') { console.log( `Detected bad contract at ${logEntry.address}: LogEntry.data is missing.` ) return false } let decoded try { decoded = web3.eth.abi.decodeLog( eventABI, logEntry.data, logEntry.topics.slice(1) ) } catch (e) { console.log( `Detected bad contract at ${logEntry.address}: Can not decode logEntry:` ) console.log(logEntry) return false } return decoded } export const checkDecodedData = ( spender: string, owner: string, expectedOwner: string ) => { // check if spender is not zero. Some contracts emit logs with spender 0x0... if (!parseInt(spender)) { console.log(`Skipping log event: Invalid spender ${spender}`) return false } if (owner.toLowerCase() !== expectedOwner.toLowerCase()) { console.log( `Skipping log event due to owner mismatch. Expected ${expectedOwner}, got ${owner}` ) return false } return true }
fac358afff116b554f2c2c26d65b2974a6045b8d
TypeScript
Mopiiex20/RNWithCamera
/src/redux/redusers/loginReduser.ts
2.6875
3
// Initial State const initialState = { loginData: Object }; // Redux: Counter Reducer export const loginReducer = (state = initialState, action) => { switch (action.type) { case '@@LOGIN': { const data = action.data; return { ...state, loginData: data }; } default: { return state; } } };
183a50c1d1a91f0dce77f1f874741e59d5e5dfcc
TypeScript
sindhiya1930/fsd-training-samples
/Employees/src/app/pipes/searchemployee.pipe.ts
2.75
3
import {Pipe,PipeTransform} from '@angular/core'; import {Employee} from '../modules/Employee' @Pipe({ name:'searchemployee' }) export class SearchEmployeePipe implements PipeTransform { transform(employees: Array<Employee>, employeeName?: string) { console.log(employees); console.log(employeeName); if(employeeName) { let filteredEmployee: Array<Employee> = null; filteredEmployee= employees.filter(employee => employee.first_name.startsWith(employeeName) ) return filteredEmployee; } return employees; } }
0212e3f71d5cb6a7726e36652790633ca369c839
TypeScript
theabdulmateen/library-reg-pwa
/server/utils/auth-helpers.ts
2.578125
3
import { Response } from 'express' import * as jwt from 'jsonwebtoken' import constants from '../constants' export const generateAccessTokenJWTToken = (userId: Number) => { const expiresIn = '15m' const payload = { sub: userId, iat: Date.now(), } const token = jwt.sign(payload, constants.PRIV_KEY, { expiresIn: expiresIn, algorithm: 'RS256', }) return { token, expiresIn, } } export const generateRefreshTokenJWTToken = (userId: Number) => { const expiresIn = '7d' const payload = { sub: userId, iat: Date.now(), } const token = jwt.sign(payload, constants.REFRESH_SECRET, { expiresIn: expiresIn, }) return { token, expiresIn, } } export const getPayloadFromToken = (token: string, secret: string) => { return jwt.verify(token, secret) } export const refreshAllTokens = (res: Response, userId: Number) => { const refreshTokenJWT = generateRefreshTokenJWTToken(userId) res.cookie('rtk', refreshTokenJWT.token, { httpOnly: true, }) const accessTokenJWT = generateAccessTokenJWTToken(userId) return res.json({ success: true, accessToken: accessTokenJWT.token, accessTokenExpiresIn: accessTokenJWT.expiresIn, }) }
d0104eed907c630f3189ef7b3effc2bb05781f9a
TypeScript
antanas-arvasevicius/elementtype-demo
/src/core/Page.ts
2.53125
3
///<reference path='Component.ts'/> ///<reference path="Layout.ts"/> module core { export abstract class Page<T extends core.Layout<any>> extends Component<T> { constructor() { super(() => { return this.createLayout(); }, (layout) => { this.onInit(layout); }); } protected abstract createLayout(): T; protected abstract onInit(layout: T); public show(): void { this.onShow(); } public hide(): void { this.onHide(); } protected onShow() { } protected onHide() { } } }
07e42a0dda6412b0f403b06b4b8b1bb00986dec0
TypeScript
tkmagesh/Cisco-Angular-Dec-2017
/bug-tracker-app-promise/src/app/bugTracker/services/bugsApi.service.ts
2.515625
3
import * as axios from 'axios'; import { IBug } from '../models/IBug'; import { BugOperationsService } from './bugOperations.service'; import { Injectable } from '@angular/core'; @Injectable() export class BugsApiService{ private baseUrl = 'http://localhost:3000/bugs'; constructor(private bugOperations : BugOperationsService){ console.dir(axios); } getAll() : Promise<IBug[]>{ return axios.get(this.baseUrl) .then(response => response.data); } addNew(bugName : string) : Promise<IBug>{ let newBugData = this.bugOperations.createNew(bugName); return axios.post(this.baseUrl, newBugData) .then(response => { console.log(response); return response.data; }); } toggle(bugToToggle : IBug) : Promise<IBug>{ let toggledBug = this.bugOperations.toggle(bugToToggle); return axios.put(`${this.baseUrl}/${bugToToggle.id}`, toggledBug) .then(response => { return response.data; }); } remove(){ } }
5c64623d1b1d4124bb9a1beea361d0c8dee89e9a
TypeScript
fuath/vscode-lit-plugin
/src/extension.ts
2.515625
3
import * as vscode from "vscode"; const tsLitPluginId = "ts-lit-plugin"; const typeScriptExtensionId = "vscode.typescript-language-features"; const configurationSection = "lit-plugin"; interface Config { disable: boolean; verbose: boolean; format: { disable: boolean }; htmlTemplateTags: string[]; cssTemplateTags: string[]; globalHtmlTags: string[]; globalHtmlAttributes: string[]; skipMissingImports: boolean; skipUnknownHtmlTags: boolean; skipUnknownHtmlAttributes: boolean; skipTypeChecking: boolean; } export async function activate(context: vscode.ExtensionContext) { const extension = vscode.extensions.getExtension(typeScriptExtensionId); if (!extension) { return; } await extension.activate(); if (!extension.exports || !extension.exports.getAPI) { return; } const api = extension.exports.getAPI(0); if (!api) { return; } vscode.workspace.onDidChangeConfiguration( e => { if (e.affectsConfiguration(configurationSection)) { synchronizeConfig(api); } }, undefined, context.subscriptions ); synchronizeConfig(api); } function synchronizeConfig(api: any) { api.configurePlugin(tsLitPluginId, getConfig()); } function getConfig(): Partial<Config> { const config = vscode.workspace.getConfiguration(configurationSection); const outConfig: Partial<Config> = {}; withConfigValue(config, "disable", value => { outConfig.disable = value; }); withConfigValue(config, "verbose", value => { outConfig.verbose = value; }); withConfigValue(config, "logging", value => { if (value === "verbose") outConfig.verbose = true; }); withConfigValue(config, "format.disable", value => { outConfig.format = Object.assign(outConfig.format || {}, { disable: value }); }); withConfigValue(config, "htmlTemplateTags", value => { outConfig.htmlTemplateTags = value; }); withConfigValue(config, "cssTemplateTags", value => { outConfig.cssTemplateTags = value; }); withConfigValue(config, "globalHtmlAttributes", value => { outConfig.globalHtmlAttributes = value; }); // "externalHtmlTagNames" is deprecated, but keep it for now withConfigValue(config, "externalHtmlTagNames", value => { outConfig.globalHtmlTags = value; }); withConfigValue(config, "globalHtmlTags", value => { outConfig.globalHtmlTags = value; }); withConfigValue(config, "skipMissingImports", value => { outConfig.skipMissingImports = value; }); withConfigValue(config, "skipUnknownHtmlTags", value => { outConfig.skipUnknownHtmlTags = value; }); withConfigValue(config, "skipUnknownHtmlAttributes", value => { outConfig.skipUnknownHtmlAttributes = value; }); withConfigValue(config, "skipTypeChecking", value => { outConfig.skipTypeChecking = value; }); return outConfig; } function withConfigValue(config: vscode.WorkspaceConfiguration, key: string, withValue: (value: any) => void): void { const configSetting = config.inspect(key); if (!configSetting) { return; } // Make sure the user has actually set the value. // VS Code will return the default values instead of `undefined`, even if user has not don't set anything. if (typeof configSetting.globalValue === "undefined" && typeof configSetting.workspaceFolderValue === "undefined" && typeof configSetting.workspaceValue === "undefined") { return; } const value = config.get(key, undefined); if (typeof value !== "undefined") { withValue(value); } }
8bbd453ac821cc71c4f26bbe29e7750f8cdc3886
TypeScript
step-ponomarev/data-base-course-project
/packages/decanat-client/src/apollo/requests/mutations.ts
2.625
3
import {DocumentNode} from 'graphql'; import {MutationOptions, TypedDocumentNode} from '@apollo/client'; import {gql, OperationVariables} from '@apollo/client/core'; import {DataType} from '../../data/data-type'; import {ValuedField} from '../../store/valued.fields.reducer'; const UPDATE_PEOPLE = (args: string) => gql` mutation { updatePeople(peopleUpdateDto: ${args}) { id, firstName, lastName, patherName, group { name } type } } `; const CREATE_PERSON = (args: string) => gql` mutation { createPerson(personCreateDto: ${args}) { id, firstName, lastName, patherName, type } } ` const DELETE_PEOPLE = (ids: Array<string | number>) => gql` mutation { deletePeople(ids: [${ids}]) } ` const CREATE_SUBJECT = (args: string) => gql` mutation { createSubject(subjectCreateDto: ${args}) { id, name } } ` export function getCreateMutation(type: DataType, fields: ValuedField[]): DocumentNode | TypedDocumentNode<any, OperationVariables> { switch (type) { case DataType.STUDENT: case DataType.TEACHER: return CREATE_PERSON(`{${fieldsToObj(fields, {group: true, type: true})}}`); case DataType.SUBJECT: return CREATE_SUBJECT(`{${fieldsToObj(fields, {group: true, type: true})}}`); default: return CREATE_PERSON(`{${fieldsToObj(fields, {group: true, type: true})}}`); } } export function getEditMutation(type: DataType, fields: ValuedField[], ids: Array<string | number>): DocumentNode | TypedDocumentNode<any, OperationVariables> { switch (type) { case DataType.STUDENT: case DataType.TEACHER: return UPDATE_PEOPLE(`{${fieldsToObj(fields, {group: true, type: true})}, ids: [${ids}]}`); default: return CREATE_PERSON(`{${fieldsToObj(fields, {group: true, type: true})}}`); } } export function getDeleteMutation(type: DataType, ids: Array<string | number>): DocumentNode | TypedDocumentNode<any, OperationVariables> { switch (type) { case DataType.STUDENT: case DataType.TEACHER: return DELETE_PEOPLE(ids); default: return CREATE_PERSON(`{}`); } } function fieldsToObj(fields: ValuedField[], numberValues: any): string { return fields.filter(field => field.name !== 'id') .map((item: ValuedField) => item.name in numberValues ? `${item.name}: ${item.value}` : `${item.name}: "${item.value}"`) .join(', '); }
d3baf7f521556ee6a2eb91a83233c13a7e229349
TypeScript
hellomac87/rgbchallenge-react-ts
/src/store/question/reducers.ts
2.625
3
import { QuestionState, CREATE_QUESTION, SEND_USER_ANSWER, ADD_SCORE, RESET_GAME, ACTIVE_ITEM, QuestionActionTypes } from "./types"; import { answer, problems } from "./actions"; // initialState const initialState: QuestionState = { answer: answer(), problems: problems(), activeItem: null, userAnswer: null, score: 0 }; // reducer export const questionReducer = ( state = initialState, action: QuestionActionTypes ) => { switch (action.type) { case CREATE_QUESTION: return { ...state, answer: action.answer, problems: action.problems }; case SEND_USER_ANSWER: return { ...state, userAnswer: action.userAnswer }; case ADD_SCORE: return { ...state, score: state.score + 100 }; case ACTIVE_ITEM: return { ...state, activeItem: action.index }; case RESET_GAME: return { ...state, answer: answer(), problems: problems(), activeItem: null, userAnswer: null, score: 0 }; default: return state; } };
662529b4580f5d7635bf7bbd86eaf43704225960
TypeScript
genki-sano/react-todo-app
/src/modules/taskModule/index.ts
2.78125
3
import { createSlice, PayloadAction } from '@reduxjs/toolkit' import { TaskState, Task } from 'types/todos' import { getStrage, setStrage } from 'utils/tasks' const taskInitialState: TaskState = { tasks: [], nextTaskId: 0, focus: false, } const taskModule = createSlice({ name: 'todos', initialState: getStrage() || taskInitialState, reducers: { addTask: (state: TaskState, action: PayloadAction<string>) => { state.tasks.push({ id: state.nextTaskId++, text: action.payload, completed: false, }) state.focus = true setStrage(state) }, editTask: ( state: TaskState, action: PayloadAction<{ id: number; text: string }>, ) => { const { id, text } = action.payload state.tasks.forEach(task => { if (task.id === id) { task.text = text } }) state.focus = false setStrage(state) }, toggleTask: (state: TaskState, action: PayloadAction<number>) => { const id = action.payload state.tasks.forEach(task => { task.completed = task.id === id ? !task.completed : task.completed }) state.focus = false setStrage(state) }, deleteTask: (state: TaskState, action: PayloadAction<number>) => { state.tasks = state.tasks.filter((task: Task) => { return task.id !== action.payload }) state.focus = false setStrage(state) }, }, }) export default taskModule
886ddf445ffbcfe85c74d139c4a7e9564b07d069
TypeScript
thorvaldursaemundsson/infinitedarkness
/src/components/skills/spells.ts
3
3
import { SkillTemplate, UseCase } from "../general/Skills"; const useCases: UseCase[] = [ { name: 'cast spell', attribute: 'willpower', description: 'cast a spell, unless the spell description says otherwise it uses an action, does not restrict movement and has no visible somatic or verbal requirement, you simply will it into existence. Some mutations have active effects that costs mana, these counts as spells.', results: [ 'Spell mana cost depends on how you use them', 'The difficult is 4 + 4 x mana cost (1 mana = 8, 2 mana = 12, 3 mana = 16, etc)', 'If you roll 1-5 points below difficulty you may choose to have it succeed at double mana cost', 'If you roll 10+ points below difficulty the spell fails and you spend 1 additional mana per point of failure below 10 (so if difficulty is 24, you roll 12 you spend 4 + 2 = 6)', 'If you roll 10+ above difficulty the spell costs 1 less mana (minimum 1)' ], type: 'active' }, { name: 'regenerate mana', attribute: 'willpower', description: 'you regenerate 1 mana every 24 hours, if your mana goes into the negatives you can not cast any more spells or actively use mutations that require mana. You also suffer a penalty to all active and passive rolls equal to your negative mana. Mana regeneration does not depend on rest.', type: 'passive' }, { name: 'acquire mutation', attribute: 'willpower', description: 'When you acquire a mutation roll 1d10 and consult the chart (Spells are always acquired immediately). The first time when you acquire a spell or mutation and spend experience points you are allowed to go into negative. However the next time you must have 10 experience points available. The experience points are spent BEFORE you roll and you MUST always take one. Once you have a mutation or spell they can never be removed.', type: 'active', results: [ '1: You acquire the negative effects immediately and after 1d6 days acquire the positive effects', '2: The mutation slowly appears over the course of 1d4 days', '3: The mutation slowly appears over the course of 24 hours', '4: The mutation slowly appears over the course of 2d12 hours', '5: The mutation slowly appears over the course of 10d6 minutes', '6: The mutation appears over the course of 2d6 minutes', '7: The mutation appears over the course of 1d4 rounds', '8: The mutation appears at the end of your turn', '9: The mutation immediately appears', '10: The mutation immediately appears when you choose, you can wait up to 6 days after which it immediately appears at the start of your turn.', ] } ]; const Spells = new SkillTemplate('spells', 'You will a phenomenon into existence or use a mutations benefit.', useCases); export default Spells;
030f157e3dcc77ea32e14abbc6fb8eaf0dbdb42f
TypeScript
christianmalek/vuex-rest-api
/src/Resource.ts
2.890625
3
import axios, { AxiosInstance, AxiosRequestConfig } from "axios" export interface ResourceAction { requestFn: Function, beforeRequest: Function, onSuccess: Function, onError: Function, property: string, dispatchString: string, commitString: string, axios: AxiosInstance, } export interface ResourceActionMap { [action: string]: ResourceAction } export interface ShorthandResourceActionOptions { action: string property?: string path: Function | string beforeRequest?: Function onSuccess?: Function onError?: Function requestConfig?: Object queryParams?: Boolean headers?: Function | Object } export interface ResourceActionOptions extends ShorthandResourceActionOptions { method: string } export interface ResourceOptions { baseURL?: string, state?: Object, axios?: AxiosInstance, queryParams?: Boolean } export class Resource { private baseURL: string private readonly HTTPMethod: Array<string> = ["get", "delete", "head", "options", "post", "put", "patch"] public actions: ResourceActionMap = {} public state: Object public axios: AxiosInstance private queryParams: Boolean constructor(options: ResourceOptions) { this.baseURL = options.baseURL this.actions = {} this.state = options.state || {} this.axios = options.axios || axios this.queryParams = options.queryParams || false } add(options: ResourceActionOptions): Resource { options.method = options.method || "get" options.requestConfig = options.requestConfig || {} options.property = options.property || null const headersFn = this.getHeadersFn(options); if (this.HTTPMethod.indexOf(options.method) === -1) { const methods = this.HTTPMethod.join(", ") throw new Error(`Illegal HTTP method set. Following methods are allowed: ${methods}. You chose "${options.method}".`) } let urlFn: Function if (typeof options.path === "function") { const pathFn: Function = options.path urlFn = (params: Object) => pathFn(params) } else { urlFn = () => options.path } this.actions[options.action] = { requestFn: (params: Object = {}, data: Object = {}) => { let queryParams // use action specific queryParams if set if (options.queryParams !== undefined) { queryParams = options.queryParams // otherwise use Resource-wide queryParams } else { queryParams = this.queryParams } const requestConfig = Object.assign({}, options.requestConfig) const paramsSerializer = options.requestConfig["paramsSerializer"] !== undefined || this.axios.defaults.paramsSerializer !== undefined if (queryParams || paramsSerializer) { requestConfig["params"] = params } if (headersFn) { if (requestConfig["headers"]) { Object.assign(requestConfig["headers"], headersFn(params)) } else { requestConfig["headers"] = headersFn(params) } } // This is assignment is made to respect the priority of the base URL, url, method and data. // It is as following: baseURL > axios instance base URL > request config base URL const fullRequestConfig = Object.assign({ method: options.method as AxiosRequestConfig["method"], url: urlFn(params), baseURL: this.normalizedBaseURL, data: data }, requestConfig) return this.axios.request(fullRequestConfig) }, property: options.property, beforeRequest: options.beforeRequest, onSuccess: options.onSuccess, onError: options.onError, dispatchString: this.getDispatchString(options.action), commitString: this.getCommitString(options.action), axios: this.axios } return this } private getHeadersFn(options: ResourceActionOptions) { if (options.headers) { if (typeof options.headers === "function") { const headersFunction: Function = options.headers return (params: Object) => headersFunction(params) } else { return () => options.headers } } return null } private get normalizedBaseURL(): string { return this.baseURL || this.axios.defaults.baseURL || "" } private getDispatchString(action: string): string { return action } private getCommitString(action: string): string { const capitalizedAction: string = action.replace(/([A-Z])/g, "_$1").toUpperCase() return capitalizedAction } } export default Resource
c2c006c6c77428f69e0332a4486eb03043702f84
TypeScript
ArneCools/best-practices
/src/todo/TodoList.ts
2.984375
3
import TodoService from './services/todoService'; import {askQuestion} from '../util'; export default class TodoList{ todoService: TodoService; quit: boolean; constructor() { this.todoService = new TodoService(); this.quit = false; } async createNewItem(){ let quit = false; console.log("Please enter the task you would like to add.") console.log("Enter a blank line to return to the menu.") do { let item: string; item = String(await askQuestion("New task: ")); if(item != "") { this.todoService.addTask(item); } else quit = true; } while(!quit) } async viewAllItems(){ console.log("All tasks:") const tasks = await this.todoService.getTasks(); tasks.forEach((task, index) => { console.log(index + ":", task); }); } async removeItem(){ console.log("Enter the number of the task you want to delete:") const tasks = await this.todoService.getTasks(); tasks.forEach((task, index) => { console.log(index + ":", task); }); const choice: number = Number(await askQuestion("Task nr: ")); if (isNaN(choice) || choice < 0 || choice >= tasks.length){ console.log("Invalid choice"); } else{ this.todoService.removeTask(tasks[choice]); } } async detectMenuAction(){ let invalidChoice; do { invalidChoice = false; const choice = await askQuestion("Choice: "); switch(choice){ case "1": await this.createNewItem(); break; case "2": await this.viewAllItems(); break; case "3": await this.removeItem(); break; case "0": this.quit = true; break; default: console.log("Invalid choice, try again.") invalidChoice = true; break; } } while(invalidChoice) } async start(){ while (!this.quit){ console.log("=====================================") console.log("============ TO-DO List =============") console.log("=====================================") console.log("1: Create new To-Do item") console.log("2: View all To-Do item") console.log("3: Remove a To-Do item") console.log("0: Quit") await this.detectMenuAction() } console.log("Goodbye and thank you for using the to-do list!"); } }
0b20b9308d2f4c3bf253147577efd431b5369ceb
TypeScript
tewl/depot
/src/priorityQueue.ts
3.296875
3
import {CompareResult} from "./compare"; import {Heap} from "./heap"; interface IPriorityQueueItem<TPayload> { priority: number; payload: TPayload; } function comparePriority<TPayload>( itemA: IPriorityQueueItem<TPayload>, itemB: IPriorityQueueItem<TPayload> ): CompareResult { if (itemA.priority < itemB.priority) { return CompareResult.LESS; } else if (itemA.priority === itemB.priority) { return CompareResult.EQUAL; } else { return CompareResult.GREATER; } } export class PriorityQueue<TPayload> { // region Data Members private readonly _heap: Heap<IPriorityQueueItem<TPayload>>; // endregion public constructor() { this._heap = new Heap<IPriorityQueueItem<TPayload>>(comparePriority); } public get length(): number { return this._heap.length; } public get isEmpty(): boolean { return this._heap.isEmpty; } public push(payload: TPayload, priority: number): void { this._heap.push({priority: priority, payload: payload}); } public peek(): TPayload | undefined { const item = this._heap.peek(); return item === undefined ? undefined : item.payload; } public pop(): TPayload | undefined { const item = this._heap.pop(); return item === undefined ? undefined : item.payload; } }
675d31af7cadf6a1a0ffcb8032dbc62e31ee7158
TypeScript
07yali/vue3-vite2-ts-blog-h5
/src/store/modules/label.ts
2.515625
3
import { apiGetLabelList } from "@/api/label"; import { labelModel } from "@/models/index"; type State = { labelList: Array<labelModel>; }; export default { namespaced: true, state: { labelList: undefined, }, mutations: { setLabelList(state: State, data: Array<labelModel>) { state.labelList = data; }, }, actions: { getLabelList(context: { commit: (arg0: string, arg1: any) => void }) { let params = { pageindex: 1, pagesize: 50, }; return apiGetLabelList(params) .then((res) => { context.commit("setLabelList", res?.data?.list); }) .catch((err) => { console.log(err); }); }, }, getters: { labelList(state: State) { return state.labelList; }, }, };
3efe59ffa1a192ca9530c2d7778d1a4f50795be3
TypeScript
jrgenerative/bebop-bridge-shared
/flightplan.d.ts
3.203125
3
/// <reference types="node" /> import { EventEmitter } from 'events'; /** * Waypoint. */ export declare class Waypoint { latitude: number; longitude: number; altitude: number; orientation: number; radius: number; constructor(latitude: number, longitude: number, altitude: number, orientation: number, radius: number); readonly isValid: boolean; clone(): Waypoint; } /** * Flight plan. * The flightplan implementation must ensure that it can be completely constructed from its mavlink representation. */ export declare class Flightplan extends EventEmitter { private _name; private _mavlink; private _takeOffPosition; private _touchDownPosition; private _waypoints; /** * Construct a flight plan instance. Can throw an error if parsing mavlink fails * @param mavlink If present, parseMavlink is called by the constructor, otherwise an * empty (equal to a cleared) and invalid flight plan is created. */ constructor(mavlink?: string); /** * Clear previously added data. * Invalidates this flight plan. */ clear(): void; /** * Check if this is a valid flight plan. * A cleared flight plan (this.clear()) is not valid. */ readonly isValid: boolean; /** * (Re)generate the mavlink code from internal waypoint data. * @param holdTimeAtWaypoint The time to wait at each waypoint in seconds. * @param velocity The velocity in [m/s]. */ updateMavlink(velocity?: number, holdTimeAtWaypoint?: number): void; /** * Return the name of this flight plan. */ readonly name: string; /** * Return the flight plan in mavlink format. */ readonly mavlink: string; /** * Number of waypoints. Without take-off and touch-down positions. */ readonly numWaypoints: number; /** * Get take-off waypoint. */ readonly takeOffPosition: Waypoint; /** * Get touch-down waypoint. */ readonly touchDownPosition: Waypoint; /** * Get waypoints. Does not include take-off and touch-down waypoints. */ readonly waypoints: Waypoint[]; /** * Set an accuracy radius for each waypoint. * @param radius Radius set for each waypoint. */ setWaypointRadius(radius: number): void; /** * Set the altitude of the flight path. * @param altitude Altitude for all waypoints. */ setAltitude(altitude: number): void; /** * Set a single bearing for all waypoints. * @param bearing Bearing for all waypoints. */ setBearing(bearing: number): void; /** * Set bearings for each waypoint such that the vehicle * is facing the center of the bounding box of the flight path. */ setBearingToCenter(): void; /** * Add waypoints every stepSize meters to the waypoints of this flight path. Latitude, longitude and altitude is interpolated. * Waypoint radius and bearing are taken from the previous waypoint of the respective leg. */ addWaypoints(stepSize: number): void; /** * Parse a flightplan in Bebop mavlink format. * @param flightplan A string in Bebop mavlink format and containing a line with '// (name):{<flightplan-name}. * Throws and error in case a problem is encountered. */ parseMavlink(flightplan: string): void; /** * Load a kmz (Google Earth path) file and parse its coordinate section. * Sets first point as take-off location and last point as touch-down location. * @param kmz The content of a kmz file. * @param name The name to set to the flight plan. */ parseKmz(kmz: string, name: string, bearing?: number, waypointRadius?: number): void; }
d24b6625ad280e5911379d3c9cd0f6a8bf965a34
TypeScript
DACSoftware/pull-request-notifier-server
/lib/factory/project.ts
2.703125
3
import {Project} from "../model/project"; export class ProjectFactory { static create(rawObject: any): Project { const project = new Project(); if (rawObject.hasOwnProperty('uuid')) { project.uuid = rawObject.uuid; } if (rawObject.hasOwnProperty('name')) { project.name = rawObject.name; } if (rawObject.hasOwnProperty('full_name')) { project.fullName = rawObject.full_name; } if (rawObject.hasOwnProperty('links')) { const links = rawObject.links; if (links.hasOwnProperty('pullrequests')) { project.pullRequestsUrl = rawObject.links.pullrequests.href; } } return project; } }
9bd449cc5060159a2e8f78c441e48ba3c73dba16
TypeScript
VictorQueiroz/mff
/src/code-generator/comment-decorator-processor.ts
3.234375
3
export interface ICommentDecorator { name: string; args: string[]; } /** * Processes decorators that are set up through * comments */ export default class CommentDecoratorProcessor { /** * Allowed characters in decorator or * decorator argument */ private allowedCharacters = /[a-zA-Z0-9\_\.]/; private offset = 0; constructor(private comments: string[]) { } public find() { const decorators = new Array<ICommentDecorator>(); const { comments, allowedCharacters } = this; for(const comment of comments) { while(this.offset < comment.length) { this.offset = comment.indexOf('@', this.offset); if(this.offset === -1) { break; } ++this.offset; let decorator = ''; let i; for(i = this.offset; i < comment.length; i++) { if(!allowedCharacters.test(comment[i])) { decorator = comment.substring(this.offset, i); break; } } this.offset = i; const args = new Array<string>(); for(i = this.offset; i < comment.length; i++) { const endOfString = i === (comment.length - 1); if(!allowedCharacters.test(comment[i]) || endOfString) { if(endOfString) { ++i; } const arg = comment.substring(this.offset, i); if(arg.trim() !== '') { args.push(arg.trim()); } this.offset = i; } const ch = comment.charCodeAt(i); if(this.chIsEndOfLine(ch)) { i++; break; } } decorators.push({ name: decorator, args }); this.offset = i; } } return decorators; } private chIsEndOfLine(ch: number) { if(ch === 10) { // \n Line break return true; } return false; } }
4bca8f5c0993f1d0158ed2b6787a3f8ee148a7c8
TypeScript
petervdn/musictime
/test/MusicTime.spec.ts
3.34375
3
import {expect} from 'chai'; import MusicTime, { stringIsValid } from "../src/lib/MusicTime"; describe('MusicTime', () => { it('should not normalize bars', () => { expect(new MusicTime(20,0,0).toString()).to.equal('20.0.0'); }); it('should normalize beats', () => { expect(new MusicTime(0,16,0).toString()).to.equal('4.0.0'); }); it('should normalize sixteenths', () => { expect(new MusicTime(0,0,27).toString()).to.equal('1.2.3'); }); it('should convert to seconds', () => { expect(new MusicTime(0,120,0).toTime(120)).to.equal(60); }); it('should convert from seconds', () => { expect(MusicTime.fromTime(1, 120).toString()).to.equal('0.2.0'); }); it('should add two compatible times', () => { expect(new MusicTime(0,8,0).add(new MusicTime(0,0,17)).toString()).to.equal('3.0.1'); }); it('should multiply a time', () => { expect(new MusicTime(0,8,0).multiply(4).toString()).to.equal('8.0.0'); }); it('should construct from fractional params', () => { expect(new MusicTime(0.5,0,0).toString()).to.equal('0.2.0'); expect(new MusicTime(0,0.5,0).toString()).to.equal('0.0.2'); expect(new MusicTime(0,0,1.5).toString()).to.equal('0.0.1'); }); it('should store remaining time', () => { const t1 = new MusicTime(0,0,1.5); expect(t1.getBarsBeatsSixteenths().remainingSixteenths).to.equal(0.5); }); it('should check validness of strings', () => { const valid = ['0.0.0', '100.100.100']; const invalid = ['-1.0.0', '0.0.-1', 'a.b.c', '1', '1.2', '..', 'test']; const validChecks:boolean[] = valid.map(entry => stringIsValid(entry)); const invalidChecks = invalid.map(entry => stringIsValid(entry)); expect(validChecks.every(entry => entry === true)).to.equal(true); expect(invalidChecks.every(entry => entry === false)).to.equal(true); }); it('should fail when creating an instance from an invalid string', () => { expect(() => { MusicTime.fromString('invalid') }).to.throw(); }); it('should subtract two compatible times', () => { expect(new MusicTime(0,8,0).subtract(new MusicTime(1,0,0)).toString()).to.equal('1.0.0'); }); it('should check equality', () => { const t1 = MusicTime.fromString('1.0.1'); const t2 = MusicTime.fromString('1.0.01'); expect(t1.equals(t2)).to.equal(true); expect(new MusicTime(0,8,0).equals(new MusicTime(2,0,0))).to.equal(true); }); it('should init timeConfig when nothing is set', () => { const conf = new MusicTime(0, 0, 0).getTimeConfig(); expect(conf.sixteenthsPerBeat).to.equal(4); expect(conf.beatsPerBar).to.equal(4); }); it('should set timeConfig from constructor', () => { const conf = new MusicTime(0, 0, 0, {sixteenthsPerBeat: 3, beatsPerBar: 4}).getTimeConfig(); expect(conf.sixteenthsPerBeat).to.equal(3); expect(conf.beatsPerBar).to.equal(4); }); it('should set timeConfig from setter', () => { const time = new MusicTime(0, 0, 0, {sixteenthsPerBeat: 4, beatsPerBar: 4}); const conf = time.getTimeConfig(); expect(conf.sixteenthsPerBeat).to.equal(4); expect(conf.beatsPerBar).to.equal(4); time.setTimeConfig({sixteenthsPerBeat: 3, beatsPerBar: 3}); const conf2 = time.getTimeConfig(); expect(conf2.sixteenthsPerBeat).to.equal(3); expect(conf2.beatsPerBar).to.equal(3); }); it('should fail when setting timeConfig to null', () => { const t1 = new MusicTime(); expect(() => { t1.setTimeConfig(null); }).to.throw(); }); it('should clone when retrieving timeConfig', () => { const time = new MusicTime(0, 0, 0, {sixteenthsPerBeat: 4, beatsPerBar: 4}); const conf = time.getTimeConfig(); expect(conf.sixteenthsPerBeat).to.equal(4); conf.sixteenthsPerBeat = 3; expect(conf.sixteenthsPerBeat).to.equal(3); expect(time.getTimeConfig().sixteenthsPerBeat).to.equal(4); }); it('should convert to full bars', () => { expect(new MusicTime(0,0,16).getTotalBars()).to.equal(1); }); it('should convert to partial bars', () => { expect(new MusicTime(0,0,24).getTotalBars()).to.equal(1.5); }); it('should get beats', () => { expect(new MusicTime(0,0,10).getTotalBeats()).to.equal(2.5); }); it('should convert to full sixteenths', () => { expect(new MusicTime(1,0,0).getTotalSixteenths()).to.equal(16); }); it('should clone', () => { const time = new MusicTime(11,13,58); const clone = time.clone(); expect(time.equals(clone)).to.equal(true); }); it('should convert from valid string', () => { expect(MusicTime.fromString('1.2.3').toString()).to.equal('1.2.3'); }); it('should use default values in constructor', () => { const items = [ new MusicTime().toString(), new MusicTime(1).toString(), new MusicTime(1, 2).toString(), ]; expect(items).to.deep.equal(['0.0.0', '1.0.0', '1.2.0']); }); it('should compare instances', () => { const time1 = new MusicTime(1,0,0); const time2 = new MusicTime(2,0,0); const time9 = new MusicTime(9,0,0); const time11 = new MusicTime(11,0,0); expect(time1 < time2).to.equal(true); expect(time1 > time2).to.equal(false); expect(time2 > time1).to.equal(true); expect(time2 < time1).to.equal(false); expect(time9 > time11).to.equal(false); expect(time11 > time9).to.equal(true); }); });
06c106f8062b2400f6be61039456313e96d10d50
TypeScript
Seikho/multimethods
/src/codegen/emit-selector-function.ts
2.796875
3
import {MMInfo, MMNode} from '../analysis'; import repeat from '../util/string-repeat'; import Emitter, {EnvNames} from './emitter'; // TODO: rewrite doc... /** * Generates a function that, given a discriminant, returns the best-matching route executor from the given list of * candidates. The returned selector function is generated for maximum readability and efficiency, using conditional * constructs that follow the branches of the given `eulerDiagram`. */ export default function emitSelectorFunction(emit: Emitter, mminfo: MMInfo<MMNode>, names: typeof EnvNames) { emit(`function ${names.SELECT_THUNK}(discriminant) {`); emitThunkSelectorBlock(emit, mminfo.rootNode, 1, names); emit('}'); } /** Helper function to generate source code for the thunk selector function. */ function emitThunkSelectorBlock(emit: Emitter, node: MMNode, nestDepth: number, names: typeof EnvNames) { // Make the indenting string corresponding to the given `nestDepth`. let indent = repeat(' ', nestDepth); // Recursively generate the conditional logic block to select among the given predicates. node.childNodes.forEach(childNode => { let condition = `${indent}if (${names.IS_MATCH}ː${childNode.identifier}(discriminant)) `; if (childNode.childNodes.length === 0) { // One-liner if-statement emit(`${condition}return ${names.THUNK}ː${childNode.entryPoint.identifier};`); } else { // Compound if-statement with nested block of conditions emit(`${condition}{`), emitThunkSelectorBlock(emit, childNode, nestDepth + 1, names), emit(`${indent}}`); } }); // Add a line to select the base predicate if none of the more specialised predicates matched the discriminant. emit(`${indent}return ${names.THUNK}ː${node.entryPoint.identifier};`); }
42cf7aad65b9d45d6cbcaaaaae6b7b18566917ec
TypeScript
joseluis8906/restaurantetic-gui
/src/app/notification/notification.service.ts
2.875
3
import { Injectable } from '@angular/core'; import { Subject, Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class NotificationService { private messageSubject: Subject<string>; public message$: Observable<string> private messageType: string; private timeout: number; private timer: number; constructor() { this.messageType = MessageType.Info; this.timeout = 5000; this.messageSubject = new Subject<string>(); this.message$ = this.messageSubject.asObservable(); } getMessageType(): string { return this.messageType; } setTimeout(timeout: number): void { this.timeout = timeout * 1000; } showMessage(message: string, messageType: MessageType, timeout?: number): void { clearTimeout(this.timer); if ([MessageType.Success, MessageType.Info, MessageType.Warn, MessageType.Error].includes(messageType)) { this.messageType = messageType; } if (timeout) { this.setTimeout(timeout); } this.messageSubject.next(message); this.timer = setTimeout(this.closeMessage.bind(this), this.timeout); } closeMessage(): void { this.messageType = MessageType.Info; this.messageSubject.next(null); } } export enum MessageType { Success = "success", Info = "primary", Warn = "warning", Error = "danger" };
83756c35c32da202023f3d84c97617f373ca55c0
TypeScript
WalterLeinert/libraries
/packages/server/src/lib/ts-express-decorators-flx/controllers/base/readonly-controller.ts
2.515625
3
// -------------------------------------- logging -------------------------------------------- // tslint:disable-next-line:no-unused-variable import { getLogger, ILogger, levels, using, XLog } from '@fluxgate/platform'; // -------------------------------------- logging -------------------------------------------- // Fluxgate import { FindByIdResult, IEntity } from '@fluxgate/common'; import { IToString } from '@fluxgate/core'; import { IReadonlyService } from '../../services/readonly-service.interface'; import { ISessionRequest } from '../../session/session-request.interface'; import { CoreController } from './core-controller'; /** * Abstrakte Basisklasse für alle REST-Controller, die nur lesende Zugriffe durchführen (findById) und * auf Entities mit Id arbeiten * * Delegiert alle Controller-Calls an den zugehörigen Service @see{TId}. * * @export * @abstract * @class ReadonlyController * @template T - Entity-Typ * @template TId - Typ der Id-Spalte */ export abstract class ReadonlyController<T extends IEntity<TId>, TId extends IToString> extends CoreController<T> { protected static logger = getLogger(ReadonlyController); constructor(service: IReadonlyService<T, TId>, tableName: string, idName: string) { super(service, tableName, idName); this.getService().idColumnName = idName; } /** * Liefert eine Entity vom Typ {T} für die angegebene id. * * @param {TId} id * @returns {Promise<T>} * * @memberOf ControllerBase */ protected findByIdInternal( request: ISessionRequest, id: TId ): Promise<FindByIdResult<T, TId>> { return Promise.resolve() .then(() => this.getService().findById(request, id)) .then<FindByIdResult<T, TId>>((result) => this.serialize(result)); } protected getService(): IReadonlyService<T, TId> { return super.getService() as IReadonlyService<T, TId>; } }
ee0278e4234276fab73a8522cd2131ccf1e969ae
TypeScript
hearingguo/blog-admin
/src/service/modules/article.ts
2.625
3
import { ax } from '../axios' // post article export function postArticle<T = undefined> ( params: IArticleItem ): Promise<Ajax.AjaxResponse<T>> { return ax.post<Ajax.AjaxResponse<T>>('/article', params) .then(res => res.data) } // get article export function getArticle<T = undefined> ( id: string ): Promise<Ajax.AjaxResponse<T>> { return ax.get<Ajax.AjaxResponse<T>>(`/article/${id}`) .then(res => res.data) } // change article export function putArticle<T = undefined> ( params: IArticleItem ): Promise<Ajax.AjaxResponse<T>> { const { _id, ...rest} = params return ax.put<Ajax.AjaxResponse<T>>(`/article/${_id}`, rest) .then(res => res.data) } // get articles export function getArticles<T = undefined> ( params?: IQuerys ): Promise<Ajax.AjaxResponse<T>> { const querys = params?params:{} return ax.get<Ajax.AjaxResponse<T>>('/article', { params: querys}) .then(res => res.data) } // patch article state export function patchArticle<T = undefined> ( params: IArticleState ): Promise<Ajax.AjaxResponse<T>> { const { _id, ...rest } = params return ax.patch<Ajax.AjaxResponse<T>>(`/article/${params._id}`, rest) .then(res => res.data) } // delete article export function deleteArticle ( id: string ): Promise<Ajax.AjaxResponse> { return ax.delete(`/article/${id}`) .then(res => res.data) } // get articles for date export function getAllArticles<T = undefined> (): Promise<Ajax.AjaxResponse<T>> { return ax.get<Ajax.AjaxResponse<T>>('/allArticle') .then(res => res.data) }
3201f2b84263e25f504d40b28ac84c0d4be7bc5c
TypeScript
BSH-Werkstatt/datatrain-server
/src/models/campaign.ts
3.125
3
export class Campaign { id: string; ownerId: string; /** * @isInt type */ type: CampaignType; name: string; urlName: string; description: string; taxonomy: string[]; image: string; trainingInProgress?: boolean; currentTrainingId?: string; constructor( id: string, ownerId: string, type: CampaignType, name: string, urlName: string, description: string, taxonomy: string[], image: string, trainingInProgress?: boolean, currentTrainingId?: string ) { this.id = id; this.ownerId = ownerId; this.type = type; this.name = name; this.urlName = urlName; this.description = description; this.taxonomy = taxonomy; this.image = image; if (trainingInProgress) { this.trainingInProgress = trainingInProgress; } if (currentTrainingId) { this.currentTrainingId = currentTrainingId; } } static fromObject(object: any) { return new Campaign( object._id ? object._id.toString() : object.id, object.ownerId, object.type, object.name, object.urlName, object.description, object.taxonomy, object.image, object.trainingInProgress ? object.trainingInProgress.toString() : false, object.currentTrainingId ? object.currentTrainingId.toString() : null ); } } export enum CampaignType { /** * @isInt ImageAnnotationCampaign */ ImageAnnotationCampaign = 0 } export interface CampaignCreationRequest { userToken: string; /** * @isInt type */ type: CampaignType; name: string; urlName?: string; description: string; taxonomy: string[]; image: string; ownerId?: string; } export interface CampaignUpdateRequest { userToken: string; campaign: Campaign; }
f104b107d0bea6b3dde28044a8a54078b93573f6
TypeScript
babel/babel
/packages/babel-types/src/validators/isScope.ts
3.234375
3
import { isFunction, isCatchClause, isBlockStatement, isScopable, isPattern, } from "./generated/index.ts"; import type * as t from "../index.ts"; /** * Check if the input `node` is a scope. */ export default function isScope(node: t.Node, parent: t.Node): boolean { // If a BlockStatement is an immediate descendent of a Function/CatchClause, it must be in the body. // Hence we skipped the parentKey === "params" check if (isBlockStatement(node) && (isFunction(parent) || isCatchClause(parent))) { return false; } // If a Pattern is an immediate descendent of a Function/CatchClause, it must be in the params. // Hence we skipped the parentKey === "params" check if (isPattern(node) && (isFunction(parent) || isCatchClause(parent))) { return true; } return isScopable(node); }
ae78dcbef080023a98f511ec31e448c87d175f3c
TypeScript
MyPureCloud/client-app-sdk
/src/utils/envSpec.ts
3.03125
3
import * as envUtils from './env'; export default describe('env utils', () => { it('should provide the default environment', () => { expect(envUtils.DEFAULT_PC_ENV.pcEnvTld).toBe('mypurecloud.com'); expect(envUtils.DEFAULT_PC_ENV.pcAppOrigin).toBe('https://apps.mypurecloud.com'); }); describe('lookupPcEnv', () => { it('should parse a valid TLD and return the environment object', () => { const resolvedEnv = envUtils.lookupPcEnv('mypurecloud.com')!; expect(resolvedEnv).not.toBeNull(); expect(resolvedEnv.pcEnvTld).toBe('mypurecloud.com'); expect(resolvedEnv.pcAppOrigin).toBe('https://apps.mypurecloud.com'); }); it('should resolve a local environment object with a custom dev origin if passed', () => { const env = envUtils.lookupPcEnv('localhost', true, [], 'https://localhost:3000')!; expect(env).not.toBeNull(); expect(env.pcEnvTld).toBe('localhost'); expect(env.pcAppOrigin).toBe('https://localhost:3000'); }); it('should resolve an env when in the list of TLDs passed in via param', () => { const resolvedEnv = envUtils.lookupPcEnv('example.com', true, ['example.com'])!; expect(resolvedEnv).not.toBeNull(); expect(resolvedEnv.pcEnvTld).toBe('example.com'); expect(resolvedEnv.pcAppOrigin).toBe('https://apps.example.com'); }); it('should not resolve an env when it is not in the list of TLDs passed in via param', () => { const env = envUtils.lookupPcEnv('example2.com', true, ['example.com']); expect(env).toBeNull(); }); it('should allow lenient parsing of TLDs and return the environment object', () => { const seedTld = 'mypurecloud.com'; const variations = [ ` ${seedTld}`, // Leading whitespace ` ${seedTld}`, // Leading multi-whitespace `${seedTld} `, // Trailing whitespace `${seedTld} `, // Trailing multi-whitespace ` ${seedTld} `, // Both Leading and Trailing whitespace `.${seedTld}`, // Leading dot ` .${seedTld}`, // Leading whitespace and dot `${seedTld}/`, // Trailing slash `${seedTld}/ `, // Trailing slash and whitespace ` .${seedTld}/ ` // All of the above ]; variations.forEach(currTld => { const resolvedEnv = envUtils.lookupPcEnv(currTld, true)!; expect(resolvedEnv.pcEnvTld).toBe(seedTld); expect(resolvedEnv.pcAppOrigin).toBe(`https://apps.${seedTld}`); }); }); it('should return null if the pcEnvTld cannot be parsed or is unknown', () => { const seedTld = 'mypurecloud.com'; const variations = [ undefined, null, 3, {foo: 1}, [], '', // Empty string ' ', // Blank string `apps.${seedTld}`, // Subdomain `https://apps.${seedTld}`, // FQDN `. ${seedTld} /`, // Inner whitespace 'mypurecloud.io', // Valid TLD, but invalid PC Env TLD 'mypurecloud.com.evil.com', // Evil subdomains 'usw3.pure.cloud' // Valid PC Env TLD, but invalid subdomain ]; variations.forEach(currTld => { // @ts-expect-error let resolvedEnv = envUtils.lookupPcEnv(currTld); expect(resolvedEnv).toBe(null); // Doesn't matter if it's lenient // @ts-expect-error resolvedEnv = envUtils.lookupPcEnv(currTld, true); expect(resolvedEnv).toBe(null); }); }); }); describe('lookupGcEnv', () => { it('should return null if the url cannot be parsed', () => { const variations = [ undefined, null, 3, {foo: 1}, [], '', // Empty string ' ', // Blank string '. https://apps.mypurecloud.io /', // Inner whitespace 'apps.mypurecloud.com', // Missing protocol ]; variations.forEach((currentVariation) => { // @ts-expect-error const resolvedEnv = envUtils.lookupGcEnv(currentVariation, 'prod'); expect(resolvedEnv).toBe(null); }); }); it('should fail if the targetEnv does not point to a valid env name', () => { expect(envUtils.lookupGcEnv('https://localhost:8443', 'prod-noMatch')).toBe(null); expect(envUtils.lookupGcEnv('https://apps.mypurecloud.com', 'prod-noMatch')).toBe(null); }); it('should fail if the targetOrigin does not match a known environment', () => { expect(envUtils.lookupGcEnv('https://apps.mypurecloud.com.nomatch', 'prod')).toBe(null); }); it('should allow localhost origins with a valid targetEnv', () => { expect(envUtils.lookupGcEnv('http://127.0.0.1:8080', 'prod')).toEqual({ pcEnvTld: 'localhost', pcAppOrigin: 'http://127.0.0.1:8080' }); expect(envUtils.lookupGcEnv('https://localhost:8443', 'prod-apne1')).toEqual({ pcEnvTld: 'localhost', pcAppOrigin: 'https://localhost:8443' }); }); it('should enforce that targetEnv matches the matched origin for a given env', () => { const prodApne1Origin = 'https://apps.mypurecloud.jp'; expect(envUtils.lookupGcEnv(prodApne1Origin, 'prod')).toBe(null); expect(envUtils.lookupGcEnv(prodApne1Origin, 'prod-apne1')).toEqual({ pcEnvTld: 'mypurecloud.jp', pcAppOrigin: 'https://apps.mypurecloud.jp' }); }); it('should use the specified url origin as the pcAppOrigin used for communicating with the host app', () => { expect(envUtils.lookupGcEnv('https://app.mypurecloud.jp', 'prod-apne1')).toEqual({ pcEnvTld: 'mypurecloud.jp', pcAppOrigin: 'https://app.mypurecloud.jp' }); // This case of non-standard port is allowed, but, unlikely to be used expect(envUtils.lookupGcEnv('https://apps.mypurecloud.jp:8443', 'prod-apne1')).toEqual({ pcEnvTld: 'mypurecloud.jp', pcAppOrigin: 'https://apps.mypurecloud.jp:8443' }); }); it('should support custom envs provided via environment variables', () => { // Tests assume a prod-unit-testing env has been configured in this unit testing env (see karma.conf.js) expect(envUtils.lookupGcEnv('https://localhost:8443', 'prod-unit-testing')).toEqual({ pcEnvTld: 'localhost', pcAppOrigin: 'https://localhost:8443' }); expect(envUtils.lookupGcEnv('https://apps.unit1.pure.cloud', 'prod-unit-testing')).toEqual({ pcEnvTld: 'unit1.pure.cloud', pcAppOrigin: 'https://apps.unit1.pure.cloud' }); expect(envUtils.lookupGcEnv('https://app.unit1.test.ftw', 'prod-unit-testing')).toEqual({ pcEnvTld: 'unit1.pure.cloud', pcAppOrigin: 'https://app.unit1.test.ftw' }); expect(envUtils.lookupGcEnv('https://app.unit1.test.ftw.nomatch', 'prod-unit-testing')).toBe(null); }); }); });
3b6e2689d39dab97dc56732929df7d3b216132d2
TypeScript
ialaminpro/ialaminpro.github.io.react
/src/Vendor/Functions/Core/ConvertDate.Function.ts
3
3
export function ConvertDate(inputFormat: any, format: 'dd-mm-yyyy' | 'yyyy-mm-dd' = 'dd-mm-yyyy') { function pad(s: number) { return (s < 10) ? '0' + s : s; } if (inputFormat !== null && inputFormat !== '') { let d = new Date(inputFormat); if (format === 'dd-mm-yyyy') { return ([pad(d.getDate()), pad(d.getMonth() + 1), d.getFullYear()].join('-')).toString(); } else if (format === 'yyyy-mm-dd') { return ([d.getFullYear(), pad(d.getMonth() + 1), pad(d.getDate())].join('-')).toString(); } return ([pad(d.getDate()), pad(d.getMonth() + 1), d.getFullYear()].join('-')).toString(); } else { return ''; } }
887750d2068e1753f2b5c950a5b154f3351fe7c2
TypeScript
sandermaas/pastors-line
/src/store/modules/modals/reducers.ts
2.640625
3
import { AnyAction, combineReducers } from 'redux' import types from './types' const modalC = (state = { open: false }, action: AnyAction) => { switch (action.type) { case types.OpenC: return { contact: action.payload.contact, open: true } case types.Close: return { open: false } default: return state } } const reducer = combineReducers({ modalC }) export default reducer
b0cd613605d904d7280f35ee73ba6ae53e6cff63
TypeScript
goeaway/workout-app-web
/src/state/actions/program-actions.ts
2.59375
3
import { ProgramsGetSuccessRequest, PROGRAM_GET, ProgramFailureRequest, PROGRAM_FAILURE, PROGRAM_SUCCESS } from "../requests/program-requests"; import { Program, WeekType } from "../../types"; import { Action } from "redux"; export function getProgramsForUser(userId: number) { return async (dispatch: Function) => { dispatch(requestPrograms()); return fetch("https://httpstat.us/200", { method: "GET", headers: { 'Content-Type': "application/json" } }) .then(response => { if(!response.ok) { dispatch(requestProgramsFailure("")); return Promise.reject(); } else { dispatch(requestProgramsSuccess([])); } }) .catch(err => dispatch(requestProgramsFailure(err))); }; } export function getProgram(id: number) { return async (dispatch: Function) => { dispatch(); } } export function requestPrograms() : Action { return { type: PROGRAM_GET }; } export function requestProgramsFailure(reason: string) : ProgramFailureRequest { return { type: PROGRAM_FAILURE, fetchFailureReason: reason }; } export function requestProgramsSuccess(programs: Array<Program>) : ProgramsGetSuccessRequest { return { type: PROGRAM_SUCCESS, programs }; }
ae12a49f818746da18d02cc3df1885a3cfb1c7ea
TypeScript
jsz315/vue-ts-template
/src/as2ts/views/Food.ts
2.84375
3
export class Food{ color:string; constructor($color:string){ this.color = $color; } show(){ console.log("color: " + this.color); } }
3757f238cf4daa634f73f3ccfc567828809471b8
TypeScript
dreamsaas/packages
/dsaas/packages/flow/src/flow/flow.ts
2.890625
3
import { Action } from '../action'; import { Application } from '../application/application'; import { EventEmitter } from 'events'; import { Transition } from '../transition/transition'; import { FlowActionDefinition, FlowDefinition } from './types'; import { ACTION_STATUS } from '../action/types'; import { TransitionDefinition } from '../transition/types'; export class Flow { actions = new Map<string, Action>(); transitions: Transition[] = []; events = new EventEmitter(); constructor(public definition: FlowDefinition, public application: Application) { definition.actions.forEach(this.registerAction.bind(this)); definition.transitions.forEach(this.registerTransition.bind(this)); } run(input: any) { this.runAction('flowStart', input); return new Promise(resolve => { this.events.on('flowEnd', value => { resolve(value); }); }); } async runAction(id: string, values: any = {}) { const action = this.findActionInstance(id); const transitionsIn = action.transitionsTo; const fromInstances = transitionsIn.map(transition => transition.fromAction); const countOfRunningFromInstances = fromInstances ? this.countInstanceStatus(ACTION_STATUS.running, fromInstances) : 0; // Stop if upstream instances are still running if (countOfRunningFromInstances > 0) return; const countOfNotRunFromInstances = this.countInstanceStatus( ACTION_STATUS.not_run, fromInstances ); // run upstream actions. These will recall this downstream if (countOfNotRunFromInstances > 0) { fromInstances.forEach(instance => { if (instance.status === ACTION_STATUS.not_run) { this.runAction(instance.id); } }); return; } //Assume here all are done, but check just in case for now. if (!fromInstances.every(instance => instance.status === ACTION_STATUS.done)) { throw new Error('shouldnt get here because all instances should be done'); } // get input action outputs const inputValuesFromActions = transitionsIn.reduce( (input, transition) => ({ ...input, ...transition.getInputs() }), {} ); const output = await action.run({ ...values, ...inputValuesFromActions }); const areAllActionsRun = ![...this.actions.values()].reduce( (count, action) => (action.status !== ACTION_STATUS.done ? count + 1 : count), 0 ); // Trigger flow end if it's a flow end action if (action.actionType === 'flowEnd' || areAllActionsRun) { this.events.emit('flowEnd', output); } // Run downflow actions const transitionsOut = action.transitionsFrom; transitionsOut.forEach(transition => this.runAction(transition.toAction.id)); } registerAction(definition: FlowActionDefinition) { const action = new Action(definition, this, this.application); this.actions.set(definition.id, action); } registerTransition(definition: TransitionDefinition) { const fromAction = this.findActionInstance(definition.fromAction); const toAction = this.findActionInstance(definition.toAction); const transition = new Transition(definition, fromAction, toAction, this, this.application); fromAction.transitionsFrom.push(transition); toAction.transitionsTo.push(transition); this.transitions.push(transition); } private findActionInstance(id: string) { const definition = this.actions.get(id); if (!definition) throw new Error(`Action Definition ${id} not found.`); return definition; } private countInstanceStatus(status: ACTION_STATUS, instances: Action[]) { return instances.reduce((count, instance) => { return instance.status === status ? count + 1 : count; }, 0); } }
b66edd212ac4a4f1203f6cb8cedc8f67def3452c
TypeScript
crimx/observable-hooks
/packages/observable-hooks/src/use-observable-get-state.ts
2.640625
3
import { useDebugValue } from 'react' import { Observable } from 'rxjs' import { map } from 'rxjs/operators' import { useObservableState } from './use-observable-state' import { useObservable } from './use-observable' /** * Gets the value at path of state. Similar to lodash `get`. * Only changes of the resulted value will trigger a rerendering. * Errors are thrown on unreachable path. * * @param state$ Output state. */ export function useObservableGetState<TState>( state$: Observable<TState>, initialState: TState | (() => TState) ): TState export function useObservableGetState< TState, TInitial extends null | undefined | void >(state$: Observable<TState>, initialState: TInitial): TState | TInitial export function useObservableGetState<TState, A extends keyof TState>( state$: Observable<TState>, initialState: TState[A] | (() => TState[A]), pA: A ): TState[A] export function useObservableGetState< TState, TInitial extends null | undefined | void, A extends keyof TState >( state$: Observable<TState>, initialState: TInitial, pA: A ): TState[A] | TInitial export function useObservableGetState< TState, A extends keyof TState, B extends keyof TState[A] >( state$: Observable<TState>, initialState: TState[A][B] | (() => TState[A][B]), pA: A, pB: B ): TState[A][B] export function useObservableGetState< TState, TInitial extends null | undefined | void, A extends keyof TState, B extends keyof TState[A] >( state$: Observable<TState>, initialState: TInitial, pA: A, pB: B ): TState[A][B] | TInitial export function useObservableGetState< TState, A extends keyof TState, B extends keyof TState[A], C extends keyof TState[A][B] >( state$: Observable<TState>, initialState: TState[A][B][C] | (() => TState[A][B][C]), pA: A, pB: B, pC: C ): TState[A][B][C] export function useObservableGetState< TState, TInitial extends null | undefined | void, A extends keyof TState, B extends keyof TState[A], C extends keyof TState[A][B] >( state$: Observable<TState>, initialState: TInitial, pA: A, pB: B, pC: C ): TState[A][B][C] | TInitial export function useObservableGetState< TState, A extends keyof TState, B extends keyof TState[A], C extends keyof TState[A][B], D extends keyof TState[A][B][C] >( state$: Observable<TState>, initialState: TState[A][B][C][D] | (() => TState[A][B][C][D]), pA: A, pB: B, pC: C, pD: D ): TState[A][B][C][D] export function useObservableGetState< TState, TInitial extends null | undefined | void, A extends keyof TState, B extends keyof TState[A], C extends keyof TState[A][B], D extends keyof TState[A][B][C] >( state$: Observable<TState>, initialState: TInitial, pA: A, pB: B, pC: C, pD: D ): TState[A][B][C][D] | TInitial export function useObservableGetState< TState, A extends keyof TState, B extends keyof TState[A], C extends keyof TState[A][B], D extends keyof TState[A][B][C], E extends keyof TState[A][B][C][D] >( state$: Observable<TState>, initialState: TState[A][B][C][D][E] | (() => TState[A][B][C][D][E]), pA: A, pB: B, pC: C, pD: D, pE: E ): TState[A][B][C][D][E] export function useObservableGetState< TState, TInitial extends null | undefined | void, A extends keyof TState, B extends keyof TState[A], C extends keyof TState[A][B], D extends keyof TState[A][B][C], E extends keyof TState[A][B][C][D] >( state$: Observable<TState>, initialState: TInitial, pA: A, pB: B, pC: C, pD: D, pE: E ): TState[A][B][C][D][E] | TInitial export function useObservableGetState< TState, A extends keyof TState, B extends keyof TState[A], C extends keyof TState[A][B], D extends keyof TState[A][B][C], E extends keyof TState[A][B][C][D], F extends keyof TState[A][B][C][D][E] >( state$: Observable<TState>, initialState: TState[A][B][C][D][E][F] | (() => TState[A][B][C][D][E][F]), pA: A, pB: B, pC: C, pD: D, pE: E, pF: F ): TState[A][B][C][D][E][F] export function useObservableGetState< TState, TInitial extends null | undefined | void, A extends keyof TState, B extends keyof TState[A], C extends keyof TState[A][B], D extends keyof TState[A][B][C], E extends keyof TState[A][B][C][D], F extends keyof TState[A][B][C][D][E] >( state$: Observable<TState>, initialState: TInitial, pA: A, pB: B, pC: C, pD: D, pE: E, pF: F ): TState[A][B][C][D][E][F] | TInitial export function useObservableGetState< TState, A extends keyof TState, B extends keyof TState[A], C extends keyof TState[A][B], D extends keyof TState[A][B][C], E extends keyof TState[A][B][C][D], F extends keyof TState[A][B][C][D][E], G extends keyof TState[A][B][C][D][E][F] >( state$: Observable<TState>, initialState: | TState[A][B][C][D][E][F][G] | (() => TState[A][B][C][D][E][F][G]), pA: A, pB: B, pC: C, pD: D, pE: E, pF: F, pG: G ): TState[A][B][C][D][E][F][G] export function useObservableGetState< TState, TInitial extends null | undefined | void, A extends keyof TState, B extends keyof TState[A], C extends keyof TState[A][B], D extends keyof TState[A][B][C], E extends keyof TState[A][B][C][D], F extends keyof TState[A][B][C][D][E], G extends keyof TState[A][B][C][D][E][F] >( state$: Observable<TState>, initialState: TInitial, pA: A, pB: B, pC: C, pD: D, pE: E, pF: F, pG: G ): TState[A][B][C][D][E][F][G] | TInitial export function useObservableGetState< TState, A extends keyof TState, B extends keyof TState[A], C extends keyof TState[A][B], D extends keyof TState[A][B][C], E extends keyof TState[A][B][C][D], F extends keyof TState[A][B][C][D][E], G extends keyof TState[A][B][C][D][E][F], H extends keyof TState[A][B][C][D][E][F][G] >( state$: Observable<TState>, initialState: | TState[A][B][C][D][E][F][G][H] | (() => TState[A][B][C][D][E][F][G][H]), pA: A, pB: B, pC: C, pD: D, pE: E, pF: F, pG: G, pH: H ): TState[A][B][C][D][E][F][G][H] export function useObservableGetState< TState, TInitial extends null | undefined | void, A extends keyof TState, B extends keyof TState[A], C extends keyof TState[A][B], D extends keyof TState[A][B][C], E extends keyof TState[A][B][C][D], F extends keyof TState[A][B][C][D][E], G extends keyof TState[A][B][C][D][E][F], H extends keyof TState[A][B][C][D][E][F][G] >( state$: Observable<TState>, initialState: TInitial, pA: A, pB: B, pC: C, pD: D, pE: E, pF: F, pG: G, pH: H ): TState[A][B][C][D][E][F][G][H] | TInitial export function useObservableGetState< TState, A extends keyof TState, B extends keyof TState[A], C extends keyof TState[A][B], D extends keyof TState[A][B][C], E extends keyof TState[A][B][C][D], F extends keyof TState[A][B][C][D][E], G extends keyof TState[A][B][C][D][E][F], H extends keyof TState[A][B][C][D][E][F][G], I extends keyof TState[A][B][C][D][E][F][G][H] >( state$: Observable<TState>, initialState: | TState[A][B][C][D][E][F][G][H][I] | (() => TState[A][B][C][D][E][F][G][H][I]), pA: A, pB: B, pC: C, pD: D, pE: E, pF: F, pG: G, pH: H, pI: I ): TState[A][B][C][D][E][F][G][H][I] export function useObservableGetState< TState, TInitial extends null | undefined | void, A extends keyof TState, B extends keyof TState[A], C extends keyof TState[A][B], D extends keyof TState[A][B][C], E extends keyof TState[A][B][C][D], F extends keyof TState[A][B][C][D][E], G extends keyof TState[A][B][C][D][E][F], H extends keyof TState[A][B][C][D][E][F][G], I extends keyof TState[A][B][C][D][E][F][G][H] >( state$: Observable<TState>, initialState: TInitial, pA: A, pB: B, pC: C, pD: D, pE: E, pF: F, pG: G, pH: H, pI: I ): TState[A][B][C][D][E][F][G][H][I] | TInitial export function useObservableGetState< TState, TInitial extends null | undefined | void, A extends keyof TState, B extends keyof TState[A], C extends keyof TState[A][B], D extends keyof TState[A][B][C], E extends keyof TState[A][B][C][D], F extends keyof TState[A][B][C][D][E], G extends keyof TState[A][B][C][D][E][F], H extends keyof TState[A][B][C][D][E][F][G], I extends keyof TState[A][B][C][D][E][F][G][H], J extends keyof TState[A][B][C][D][E][F][G][H][I] >( state$: Observable<TState>, initialState: TInitial, pA: A, pB: B, pC: C, pD: D, pE: E, pF: F, pG: G, pH: H, pI: I, pJ: J ): TState[A][B][C][D][E][F][G][H][I][J] | TInitial export function useObservableGetState<TState, TInit>( state$: Observable<TState>, initialState: TInit | (() => TInit), ...path: any[] ) { const value = useObservableState( useObservable(() => state$.pipe(map(state => path.reduce(getValue, state))) ), initialState ) useDebugValue(value) return value } function getValue<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key] }
d2a31f2cfeeab9d5679a80b16a0ae6d3c844c059
TypeScript
artalar/reatom
/packages/core-v2/primitives/createMapAtom.ts
2.9375
3
import { AtomOptions } from '@reatom/core-v2' import { createPrimitiveAtom, PrimitiveAtomCreator } from '.' export type MapAtom<Key, Element> = PrimitiveAtomCreator< Map<Key, Element>, { set: [key: Key, el: Element] delete: [key: Key] clear: [] change: [map: (stateCopy: Map<Key, Element>) => Map<Key, Element>] } > let count = 0 export function createMapAtom<Key, Element>( initState = new Map<Key, Element>(), options: AtomOptions<Map<Key, Element>> = `map${++count}`, ): MapAtom<Key, Element> { type State = Map<Key, Element> return createPrimitiveAtom( initState, { set: (state, key: Key, el: Element) => new Map(state).set(key, el), delete: (state, key: Key) => { const newState = (state = new Map(state)) if (!newState.delete(key)) return state return newState }, clear: () => new Map(), change: (state, cb: (stateCopy: State) => State) => cb(new Map(state)), }, options, ) }
bf755af8b2e8b85297749f38431a9827a584df33
TypeScript
darcros/appanino-backend-graphql
/src/validation/MaxPrecision.ts
3.1875
3
import { registerDecorator, ValidationOptions } from 'class-validator'; const countDecimals = (value: number) => { if (Math.floor(value) === value) return 0; return value.toString().split('.')[1].length || 0; }; export const MaxDecimals = (maxDecimals: number, validationOptions?: ValidationOptions) => { // eslint-disable-next-line @typescript-eslint/ban-types return (object: Object, propertyName: string) => { registerDecorator({ name: 'maxDecimals', target: object.constructor, propertyName: propertyName, constraints: [], options: validationOptions, validator: { validate: value => typeof value === 'number' && countDecimals(value) <= maxDecimals, defaultMessage: () => `${propertyName} must have no more than ${maxDecimals} decimal digits`, }, }); }; };
946020fabc8a3942d4fcd1097231a07ddc5167b9
TypeScript
sethkasten/ts-lab2
/tests/code-along.test.ts
2.921875
3
import { Player, Timer } from "../src/code-along"; describe("Player class", () => { test("the constructor properly sets the name property", () => { const result = new Player("Kyrie Irving", 11); expect(result.name).toBe("Kyrie Irving"); expect(result.jersey).toBe(11); }); }); describe("Timer Class", () => { test("the constructor properly sets the name property", () => { const timer = new Timer("track"); expect(timer.name).toBe("track"); }); test("the constructor properly sets time to 0", () => { const timer = new Timer("track"); expect(timer.time).toBe(0); }); });
a07bc45795df96c4c50ac5b285be6ee07ca50506
TypeScript
rauleddie/node-course-2-todo-api
/src/server/server.ts
2.609375
3
// Load Server Config require('./config/config'); // Server dependencies import express = require('express'); import bodyParser = require('body-parser'); import _ = require('lodash'); import {ObjectID} from 'mongodb'; // Database related dependencies import mongoose from './db/mongoose'; import {Todo, Todotype} from './models/todo'; // Start up our server app. const app: express.Application = express(); app.use(bodyParser.json()); const port = process.env.PORT; // We set up our POST routes app.post('/todos', (req: express.Request, res: express.Response) => { const todo = new Todo({ text: req.body.text }); todo.save().then( (doc: any) => { res.send(doc); }).catch((e: mongoose.Error) => { res.status(400).send(e); }) }); // We set up our GET routes app.get('/todos', (req: express.Request, res: express.Response) => { Todo.find().then((todos: any) => { res.send({todos}); }).catch((e: mongoose.Error) => { res.status(400).send(e); }); }); // GET /todos/12345 app.get('/todos/:id', (req: express.Request, res: express.Response) => { const {id} = req.params; if(!ObjectID.isValid(id)) { return res.status(404) .send(); } Todo.findById(id).then( (todo: any) => { if(!todo) { return res.status(404).send(); } res.send({todo}); }).catch( (e: Error) => { res.status(400) .send(e); }); }); // We set up our DELETE routes app.delete('/todos/:id', (req: express.Request, res: express.Response) => { const {id} = req.params; if(!ObjectID.isValid(id)) { return res.status(404) .send(); } Todo.findByIdAndRemove(id).then( (todo: any) => { if(!todo) { return res.status(404).send(); } res.send({todo}); }).catch( (e: Error) => { res.status(400) }); }); // We set up our PATCH routes app.patch('/todos/:id', (req: express.Request, res: express.Response) => { const {id} = req.params; const body: Todotype = _.pick(req.body, ['text', 'completed']); if(!ObjectID.isValid(id)) { return res.status(404).send(); } // Check if the todo is completed. if(_.isBoolean(body.completed) && body.completed) { body.completedAt = new Date().getTime(); } else { body.completed = false; body.completedAt = null; } // We make the query to the database Todo.findByIdAndUpdate(id, {$set: body}, {new: true}).then( (todo: any) => { if(!todo) { return res.status(404).send(); } res.send({todo}); }).catch( (e: mongoose.Error) => { res.status(400).send(); }); }); app.listen(port, () => { console.log('Started on port 3000'); }); export {app};
209c49da7547a50384c9ee892f48cd7f9b506851
TypeScript
cyclosproject/cyclos4-ui
/src/app/core/state-manager.ts
2.765625
3
import { Injectable, Optional } from '@angular/core'; import { AbstractControl } from '@angular/forms'; import { Router } from '@angular/router'; import { DataForFrontendHolder } from 'app/core/data-for-frontend-holder'; import { cloneDeep } from 'lodash-es'; import { BehaviorSubject, Observable, of as observableOf, Subscription } from 'rxjs'; import { tap } from 'rxjs/operators'; /** * Service used to navigate between pages and managing the component state */ @Injectable({ providedIn: 'root', }) export class StateManager { private state = new Map<string, any>(); private subscriptions: Subscription[] = []; private global = new Map<string, any>(); constructor( dataForFrontendHolder: DataForFrontendHolder, @Optional() private router: Router) { dataForFrontendHolder.subscribe(() => this.clear()); } /** * Clears the entire navigation state */ clear(): void { this.subscriptions.forEach(s => s.unsubscribe()); this.subscriptions = []; this.state.clear(); } /** * Caches some data for the current path. * @param key The data key. Is only valid for the current path * @param fetch The observable used to fetch the data in case it is not already cached */ cache<T>(key: string, fetch: Observable<T>): Observable<T> { const k = key + '@' + this.url; if (this.state.has(k)) { return observableOf(this.state.get(k)); } // Save the value whenever the operator is subscribed return fetch.pipe( tap(value => this.state.set(k, value)), ); } /** * Stores the state related to the current path * @param key The key (valid only for the current path) * @param value The state value */ set(key: string, value: any): void { if (value instanceof AbstractControl) { value = value.value; } const k = key + '@' + this.url; this.state.set(k, cloneDeep(value)); } /** * Stores a global shared value */ setGlobal(key: string, value: any): void { this.global.set(key, value); } /** * Returns a global shared value */ getGlobal(key: string): any { return this.global.get(key); } /** * Deletes a global shared value */ deleteGlobal(key: string): any { return this.global.delete(key); } /** * Deletes the state related to the current path */ delete(key: string): any { return this.state.delete(key + '@' + this.url); } /** * Returns the state related to the current path * @param key The key (valid only for the current path) */ get(key: string, producer: () => any = null): any { const k = key + '@' + this.url; let value = this.state.get(k); if (value == null && producer != null) { // If no value, but we have a producer, call it value = producer(); this.state.set(k, value); } return value; } /** * Initializes the control value with the current state, if any, and store the state whenever the value changes * @param control Either the form control or a function that produces it * @returns Whether a previous value was used */ manage<C extends AbstractControl>(control: C | (() => C), key = 'form'): C { const value = this.get(key, control instanceof Function ? control : null); if (control instanceof Function) { control = control(); } if (value) { // When there was a previously stored value, modify the control control.patchValue(value); } else { // Otherwise, store the initial value this.set(key, control.value); } this.subscriptions.push(control.valueChanges.subscribe(val => this.set(key, val))); return control; } /** * Stop managing the form control */ stopManaging(key = 'form') { this.delete(key); } /** * Initializes the given value with the current state, if any, and store the state whenever the value changes * @param value The value holder, as a BehaviorSubject * @returns Whether a previous value was used */ manageValue(subject: BehaviorSubject<any>, key: string): boolean { const value = this.get(key); if (value) { subject.next(value); } this.subscriptions.push(subject.subscribe(val => this.set(key, val))); return value != null; } private get url(): string { return this.router ? this.router.url : 'local'; } }
4e179e2a50347507ae81c246b434322c543de428
TypeScript
tk2rush90/lean-mass-up
/src/app/utils/nutrition.util.ts
2.875
3
import { CARBOHYDRATES_BACKGROUND_COLOR, CARBOHYDRATES_COLOR, CARBOHYDRATES_LABEL_EN, CARBOHYDRATES_LABEL_KO, FATS_BACKGROUND_COLOR, FATS_COLOR, FATS_LABEL_EN, FATS_LABEL_KO, PROTEINS_BACKGROUND_COLOR, PROTEINS_COLOR, PROTEINS_LABEL_EN, PROTEINS_LABEL_KO } from '../constants/nutrition'; export interface NutritionProperties { carbohydrates: string; proteins: string; fats: string; } /** * return nutrition property keys in array */ export function getNutritionKeys(): (keyof NutritionProperties)[] { return [ 'carbohydrates', 'proteins', 'fats', ]; } /** * return nutrition color set as object */ export function getNutritionColorSet(): NutritionProperties { return { carbohydrates: CARBOHYDRATES_COLOR, proteins: PROTEINS_COLOR, fats: FATS_COLOR, }; } /** * return nutrition background color set as object */ export function getNutritionBackgroundColorSet(): NutritionProperties { return { carbohydrates: CARBOHYDRATES_BACKGROUND_COLOR, proteins: PROTEINS_BACKGROUND_COLOR, fats: FATS_BACKGROUND_COLOR, }; } /** * return nutrition English label object */ export function getNutritionEnLabels(): NutritionProperties { return { carbohydrates: CARBOHYDRATES_LABEL_EN, proteins: PROTEINS_LABEL_EN, fats: FATS_LABEL_EN, }; } /** * return nutrition Korean label object */ export function getNutritionKoLabels(): NutritionProperties { return { carbohydrates: CARBOHYDRATES_LABEL_KO, proteins: PROTEINS_LABEL_KO, fats: FATS_LABEL_KO, }; }
2a4d18343ed3731b11093fdbbba0dbc8a8bec908
TypeScript
ChatTriggers/website-frontend
/src/api/raw/modules.ts
2.546875
3
import { IModule, IModuleResponse, ModuleSorting } from '~types'; import { axios, BASE_URL, URLParams } from '../utils'; import { ApiErrors, validateStatusCode } from './ApiErrors'; const MODULES_URL = `${BASE_URL}/modules`; const moduleIdUrl = (id: number | string): string => `${BASE_URL}/modules/${id}`; const TAGS_URL = `${BASE_URL}/tags`; export const getModules = async ( limit?: number, offset?: number, owner?: number, trusted?: boolean, flagged?: boolean, tags?: string, q?: string, sort?: ModuleSorting, ): Promise<IModuleResponse> => { const response = await axios.get<IModuleResponse>(MODULES_URL, { params: { limit, offset, owner, trusted: trusted || undefined, flagged: flagged || undefined, tags, q, sort, }, }); return validateStatusCode(response); }; export const createModule = async ( name: string, description: string, tags: string[], image: string, flagged = false, ): Promise<IModule> => { const searchParams = new URLParams({ name, description, flagged, image, tags, }); const response = await axios.post<IModule>(MODULES_URL, searchParams.toString()); return validateStatusCode(response); }; export const getSingleModule = async (moduleName: string): Promise<IModule> => { const response = await axios.get<IModule>(moduleIdUrl(moduleName)); return validateStatusCode(response, ApiErrors.GetModule); }; export const updateModule = async ( moduleId: number, description?: string, image?: string, flagged?: boolean, tags?: string[], ): Promise<IModule> => { const searchParams = new URLParams({ description, image, flagged, tags }); const response = await axios.patch<IModule>( moduleIdUrl(moduleId), searchParams.toString(), ); return validateStatusCode(response, ApiErrors.UpdateModule); }; export const deleteModule = async (moduleId: number): Promise<undefined> => { const response = await axios.delete<undefined>(moduleIdUrl(moduleId)); return validateStatusCode(response, ApiErrors.DeleteModule); }; export const getTags = async (): Promise<string[]> => { const response = await axios.get<string[]>(TAGS_URL); return validateStatusCode(response); };
e50805fff2f563382354d19d4013aa55016133b1
TypeScript
MeowType/Synph
/src/syntax/utils.ts
2.890625
3
import { ISyntax, syntax, lexical, group, option, range, item } from "./ref_all"; export type unset = (...v: ISyntax[]) => void export function body_func_call(fn: BodyFunc, arr?: ISyntax[]) { if (arr == null) arr = [] if (typeof fn !== 'function') return arr const unsetlist: Set<ISyntax> = new Set if (fn[Symbol.toStringTag] === 'GeneratorFunction') { arr.push(...(fn as any)()) } else { const items = [] const ctx = Maker(i => items.push(i), (...v: ISyntax[]) => v.forEach(v => unsetlist.add(v))) fn.call(ctx, ctx) arr.push(...items) } return unsetlist.size == 0 ? arr : arr.filter(i => !unsetlist.delete(i)) } export type otype = { syntax: typeof syntax, lexical: typeof lexical, group: typeof group, item: typeof item, option: typeof option, range: typeof range } export type BodyFunc = (() => IterableIterator<ISyntax>) | ((this: Make, ctx: Make) => void) export type Make = RemoveParentUnsetObject<otype> export function Maker(push: (v: ISyntax) => void, unset: unset): RemoveParentUnsetObject<otype> { const o: otype = { syntax, lexical, group, item, option, range } for (const key in o) { const element = o[key] if (typeof element === 'function') { o[key] = function () { const r = element.call(this, unset, ...arguments) push(r) return r } } } return o as any } export type Tail<F extends (head: any, ...tails: any[]) => any> = F extends (head: any, ...tails: infer T) => any ? T : any export type TailFn<F extends (head: any, ...tails: any[]) => any> = (...args: Tail<F>) => ReturnType<F> export type RemoveParentUnset<F> = F extends (unset: unset, ...tails: any[]) => any ? TailFn<F>: F export type RemoveParentUnsetObject<O> = { [K in keyof O]: RemoveParentUnset<O[K]> }
03bf23c5eaca5df1d8351199f92a3247b3b61a2b
TypeScript
mogulla3/tidytab
/test/tabSorter.test.ts
2.984375
3
import { describe, expect, test } from '@jest/globals'; import { TabSorter } from "../src/tabSorter"; import { SortOrder } from "../src/sortOrder"; const defaultOptions = { ignoreWwwSubdomainOnSorting: true, preferTagGroupToTabOnSorting: true, removeWwwSubdomainFromTabGroupName: true, }; const buildTab = (props: Pick<chrome.tabs.Tab, "url">): chrome.tabs.Tab => { return Object.assign( { index: 1, windowId: 1, groupId: 1, pinned: false, highlighted: false, active: false, incognito: false, selected: false, discarded: false, autoDiscardable: false, }, props, ); } describe("run with SortOrder.ASC argument", () => { test("returns tabs sorted by URL in asc order", () => { const tabSorter = new TabSorter( [ buildTab({ url: "https://b.com" }), buildTab({ url: "https://c.com/2" }), buildTab({ url: "https://c.com/1" }), buildTab({ url: "https://a.com" }), ], defaultOptions, ) const tabs = tabSorter.run(SortOrder.ASC) expect(tabs[0].url).toBe("https://a.com") expect(tabs[1].url).toBe("https://b.com") expect(tabs[2].url).toBe("https://c.com/1") expect(tabs[3].url).toBe("https://c.com/2") }); describe("when a tab with URL containing `www` subdomain exists", () => { test("returns tabs sorted by URL in asc order ignoring www subdomain", () => { const tabSorter = new TabSorter( [ buildTab({ url: "https://b.com" }), buildTab({ url: "https://www.a.com" }), ], defaultOptions, ) const tabs = tabSorter.run(SortOrder.ASC) expect(tabs[0].url).toBe("https://www.a.com") expect(tabs[1].url).toBe("https://b.com") }); }); describe("when a tab with URL containing `http` scheme exists", () => { test("returns tabs sorted by URL in asc order ignoring schemes", () => { const tabSorter = new TabSorter( [ buildTab({ url: "http://b.com" }), buildTab({ url: "https://a.com" }), ], defaultOptions, ) const tabs = tabSorter.run(SortOrder.ASC) expect(tabs[0].url).toBe("https://a.com") expect(tabs[1].url).toBe("http://b.com") }); }); }); describe("sortTabsOrderByDesc", () => { test("returns tabs sorted by URL in desc order", () => { const tabSorter = new TabSorter( [ buildTab({ url: "https://b.com" }), buildTab({ url: "https://c.com/2" }), buildTab({ url: "https://c.com/1" }), buildTab({ url: "https://a.com" }), ], defaultOptions, ) const tabs = tabSorter.run(SortOrder.DESC) expect(tabs[0].url).toBe("https://c.com/2") expect(tabs[1].url).toBe("https://c.com/1") expect(tabs[2].url).toBe("https://b.com") expect(tabs[3].url).toBe("https://a.com") }); describe("when a tab with URL containing `www` subdomain exists", () => { test("returns tabs sorted by URL in desc order ignoring www subdomain", () => { const tabSorter = new TabSorter( [ buildTab({ url: "https://b.com" }), buildTab({ url: "https://www.a.com" }), ], defaultOptions, ) const tabs = tabSorter.run(SortOrder.DESC) expect(tabs[0].url).toBe("https://b.com") expect(tabs[1].url).toBe("https://www.a.com") }); }); describe("when a tab with URL containing `http` scheme exists", () => { test("returns tabs sorted by URL in desc order ignoring schemes", () => { const tabSorter = new TabSorter( [ buildTab({ url: "http://b.com" }), buildTab({ url: "https://a.com" }), ], defaultOptions, ) const tabs = tabSorter.run(SortOrder.DESC) expect(tabs[0].url).toBe("http://b.com") expect(tabs[1].url).toBe("https://a.com") }); }); });
7fe5b28569ee9fbadc33a005437cab9db7b9954e
TypeScript
bennbollay/asynctest
/src/index.ts
2.53125
3
import { startHooks, dumpRecords, IHookRecord, IHookRecords } from "./asynchooks"; import fs from "fs"; import async_hooks from "async_hooks"; import { fullTest } from "./test"; type IHookRecordKey = keyof IHookRecord; const perfToFlame = (records: IHookRecords): object => { let data: any = {}; let result = []; const convert = (e: IHookRecord): any => { let tooltip = e.name; //`init: ${e.isInit} before: ${e.isBefore} after: ${e.isAfter} destroy: ${e.isDestroy} promise: ${e.isPromiseResolve} misaligned: ${e.misaligned} earlyDestroy: ${e.earlyDestroy}\n${e.name}`; return { name: e.name.split("\n")[1], tooltip, timing: { onInit: Number(e.onInit), onBefore: Number(e.onBefore), onAfter: Number(e.onAfter), onPromiseResolve: Number(e.onPromiseResolve), onDestroy: Number(e.onDestroy), duration: Number(e.duration) }, children: [], value: Number(e.duration) }; }; let hKey: IHookRecordKey = "executionAsyncId"; // Build hierarchy for (let key in records) { let recKey: IHookRecord = records[key]; // Filter out anything that didn't take any time. if (recKey.duration == 0n) { console.log(`Skipped entry ${recKey.asyncId} - ${JSON.stringify(convert(recKey), null, 2)}`); continue; } // Add this item if (!data[recKey.asyncId]) { data[recKey.asyncId] = convert(recKey); } if ((recKey[hKey] as number) > 1) { let recTrigger: IHookRecord = records[recKey[hKey] as number]; // Add the parent if (!data[recTrigger.asyncId]) { data[recTrigger.asyncId] = convert(recTrigger); } // Relate the two. data[recTrigger.asyncId].children.push(data[recKey.asyncId]); } else { // Add the top level objects. result.push(data[recKey.asyncId]); } } const adjustValue = (e: any): number => { let s = e.children.reduce((a: number, v: number): number => a + adjustValue(v), 0); e.value = Math.max(s, e.timing.duration); return e.value; }; return { name: "root", value: result.reduce((a: any, v: any): number => a + adjustValue(v), 0), children: result }; }; (async () => { const stopHooks: any = await startHooks(); await fullTest(); await stopHooks(); fs.writeFile("flame.json", JSON.stringify(perfToFlame(dumpRecords()), null, 2), err => console.log(err)); })(); console.log("pending");
fc1433520721dcddd5a52ecf11cb6d1fbef0d6e1
TypeScript
munna/ApexSchool
/src/resolvers/PersonResolver.ts
2.78125
3
import { Arg, FieldResolver, Query, Resolver, Root } from "type-graphql"; import { personDatas, PersonData,studentsDatas,StudentData} from "../data"; import Person from "../schema/Person"; import Student from "../schema/Student"; @Resolver(of => Person) export default class { @Query(returns => [Person]) fetchTasks(): PersonData[] { return personDatas; } @Query(returns => Person, { nullable: true }) personByName(@Arg("name") name: string): PersonData | undefined { return personDatas.find(person => (person.firstName === name || person.lastName == name) ); } @Query(returns => Student, { nullable: true }) getStudents(@Arg("id") id: number): StudentData | undefined { return studentsDatas.find(student => student.person_id === id); } // @FieldResolver() // student(@Root() personData: PersonData) { // return studentsDatas.find(student => { // return student.person.id === personData.id; // }); // } }
9543e5b57455ffbb324a535a467e344f3b0743f1
TypeScript
noob0192/bluetooth-device
/src/index.ts
3.046875
3
import PCancelable from 'p-cancelable'; import noble, { Peripheral } from '@abandonware/noble'; import { after, before, debounce, retry, semaphore, timeout } from 'ts-async-decorators'; const DEFAULT_TIMEOUT_IDLE = 120000; const DEFAULT_TIMEOUT_DISCOVERY = 30000; const DEFAULT_TIMEOUT = 10000; const DEFAULT_NUMBER_OF_RETRIES = 3; /** * Bluetooth Device Options. */ interface BluetoothDeviceOptions { /** * Device discovery timeout in milliseconds. * By default, it equals 30 seconds. */ discoveryTimeout?: number; /** * Device idle timeout in milliseconds. After that, the connection will be destroyed. * By default, it equals to 2 minutes. */ idleTimeout?: number; /** * The number of retries on failed operations. * By default, it is 3. */ retries?: number; /** * Device operations timeout, namely, connection, read, and write. * By default, it equals 10 seconds. */ timeout?: number; } /** * Bluetooth Device Abstraction. */ export class BluetoothDevice { private peripheral?: Peripheral; /** * @param address Bluetooth address. * @param options Device options. */ constructor(readonly address: string, private options: BluetoothDeviceOptions = {}) {} /** * Discovers peripheral device by address. * @returns Discovery promise. */ @semaphore({ limit: 1 }) @timeout({ timeout(this: BluetoothDevice) { return this.options.discoveryTimeout ?? DEFAULT_TIMEOUT_DISCOVERY; }, reason: 'Discovery timeout.', }) discover(): PCancelable<void> { return new PCancelable(async (resolve, reject, onCancel) => { if (this.peripheral) { resolve(); } const stop = () => { noble.stopScanning(); /* eslint-disable no-use-before-define */ noble.removeListener('stateChange', onStateChange); noble.removeListener('discover', onDiscover); /* eslint-enable no-use-before-define */ }; const onDiscover = (peripheral: Peripheral) => { if (peripheral.address !== this.address.toLowerCase()) { return; } this.peripheral = peripheral; stop(); resolve(); }; const onStateChange = (state: string) => state === 'poweredOn' ? noble.startScanningAsync() : noble.stopScanning(); onCancel(stop); noble.on('discover', onDiscover); noble.on('stateChange', onStateChange); if (noble.state === 'poweredOn') { await noble.startScanningAsync(); } }); } /** * Tries to establish a connection with the device. * If the device was not previously discovered, the discovery operation will be performed before. * @returns Connection promise. */ @before({ action: (device: BluetoothDevice) => device.discover(), wait: true }) @after({ action: (device: BluetoothDevice) => device.disconnect() }) @timeout({ timeout(this: BluetoothDevice) { return this.options.timeout ?? DEFAULT_TIMEOUT; }, reason: 'Connection timeout.', }) connect(): PCancelable<void> { return new PCancelable((resolve, reject, onCancel) => { if (this.peripheral?.state === 'connected') { return resolve(); } const onConnect = (error?: string) => (error ? reject(new Error(error)) : resolve()); const onDisconnect = () => this.peripheral?.connect(onConnect); onCancel(() => { this.peripheral?.removeListener('connect', onConnect); this.peripheral?.removeListener('disconnect', onDisconnect); }); if (this.peripheral?.state === 'connecting') { return this.peripheral?.once('connect', onConnect); } if (this.peripheral?.state === 'disconnecting') { return this.peripheral?.once('disconnect', onDisconnect); } return onDisconnect(); }); } /** * Destroys a connection with the device. * @returns Disconnect promise. */ @debounce({ timeout(this: BluetoothDevice) { return this.options.idleTimeout ?? DEFAULT_TIMEOUT_IDLE; }, }) @retry({ retries(this: BluetoothDevice) { return this.options.retries ?? DEFAULT_NUMBER_OF_RETRIES; }, }) @timeout({ timeout(this: BluetoothDevice) { return this.options.timeout ?? DEFAULT_TIMEOUT; }, reason: 'Disconnect timeout.', }) disconnect(): PCancelable<void> { return new PCancelable((resolve, reject, onCancel) => { if (!this.peripheral || this.peripheral.state === 'disconnected') { resolve(); return; } onCancel(() => this.peripheral?.removeListener('disconnect', resolve)); this.peripheral?.disconnect(resolve); }); } /** * Waits for the next notification. * If the device was not previously connected, the connection will be established automatically. * @param handle The notification handle. * @returns The notification data buffer. */ @retry({ retries(this: BluetoothDevice) { return this.options.retries ?? DEFAULT_NUMBER_OF_RETRIES; }, }) @before({ action: (device: BluetoothDevice) => device.connect(), wait: true }) @timeout({ timeout(this: BluetoothDevice) { return this.options.timeout ?? DEFAULT_TIMEOUT; }, reason: 'Notify timeout.', }) notify(handle: number): PCancelable<Buffer> { return new PCancelable((resolve, reject, onCancel) => { // eslint-disable-next-line no-use-before-define const unsubscribe = () => this.peripheral?.removeListener('handleNotify', onNotify); const onNotify = (notificationHandle: number, data: Buffer) => { if (notificationHandle !== handle) { return; } unsubscribe(); resolve(data); }; onCancel(unsubscribe); this.peripheral?.on('handleNotify', onNotify); }); } /** * Reads data from the device. * If the device was not previously connected, the connection will be established automatically. * @param handle The handle to read from. * @returns The data buffer. */ @retry({ retries(this: BluetoothDevice) { return this.options.retries ?? DEFAULT_NUMBER_OF_RETRIES; }, }) @before({ action: (device: BluetoothDevice) => device.connect(), wait: true }) @timeout({ timeout(this: BluetoothDevice) { return this.options.timeout ?? DEFAULT_TIMEOUT; }, reason: 'Read timeout.', }) read(handle: number): PCancelable<Buffer> { return new PCancelable((resolve, reject, onCancel) => { const onRead = (error: string, data: Buffer) => (error ? reject(new Error(error)) : resolve(data)); onCancel(() => this.peripheral?.removeListener(`handleRead${handle}`, onRead)); this.peripheral?.readHandle((handle as unknown) as Buffer, onRead); }); } /** * Writes data to the device. * If the device was not previously connected, the connection will be established automatically. * @param handle The write handle. * @param data The data buffer. * @returns Writing promise. */ @retry({ retries(this: BluetoothDevice) { return this.options.retries ?? DEFAULT_NUMBER_OF_RETRIES; }, }) @before({ action: (device: BluetoothDevice) => device.connect(), wait: true }) @timeout({ timeout(this: BluetoothDevice) { return this.options.timeout ?? DEFAULT_TIMEOUT; }, reason: 'Write timeout.', }) write(handle: number, data: Buffer): PCancelable<void> { return new PCancelable((resolve, reject, onCancel) => { const onWrite = () => resolve(); onCancel(() => this.peripheral?.removeListener(`handleWrite${handle}`, onWrite)); this.peripheral?.writeHandle((handle as unknown) as Buffer, data, false, onWrite); }); } }
b88dc919e7843372af7fa65e08dc248c6f883b32
TypeScript
Taha-1993/AutomationUI
/src/ngrx-store/reducers/error-handler.reducer.ts
2.734375
3
import { ActionReducer } from '@ngrx/store'; import * as types from '../actions/action-types'; import { ErrorHandlerActions } from '../actions'; export interface State { errorHandlerObject: any; } const initialState: State = { errorHandlerObject: null, }; export const reducer: ActionReducer<State> = (state = initialState, action: ErrorHandlerActions) => { switch (action.type) { case types.SET_ERROR_OBJECT: { const errorHandlerObject = action.payload; return Object.assign({}, state, { errorHandlerObject }); } default: return state; } }; export const getErrorHandlerObjectState = (state: State) => state.errorHandlerObject;
14aa6b9017ac64562a9bee72689abb76d21a1458
TypeScript
mjbryan10/chat-app
/src/shared/Api/__tests__/UserApi.test.ts
2.71875
3
import axios from 'axios'; import UserApi from '../UserApi'; import BaseApi from '../BaseApi'; jest.mock('axios'); describe('UserApi', () => { afterEach(() => { (axios.get as jest.Mock).mockClear(); }); const errorMessage = 'request rejected'; const userApi = new UserApi(); const baseApi = new BaseApi(); describe('FetchById', () => { it('fetches successfully data from an API', async () => { const data = { id: 1, name: 'Wessel', }; (axios.get as jest.Mock).mockImplementationOnce(() => Promise.resolve(data)); const userInfo = await userApi.fetchById(1); expect(userInfo).toEqual({ id: 1, name: 'Wessel' }); expect(axios.get).toHaveBeenCalledTimes(1); expect(axios.get).toHaveBeenCalledWith(`${baseApi.baseUrl}/user/1`); }); it('handles if user id is not present in database', async () => { (axios.get as jest.Mock).mockImplementationOnce(() => Promise.resolve(false)); const userInfo = await userApi.fetchById(42); expect(userInfo).toEqual(false); expect(axios.get).toHaveBeenCalledTimes(1); expect(axios.get).toHaveBeenCalledWith(`${baseApi.baseUrl}/user/42`); }); it('fetches erroneously data from an API', async () => { (axios.get as jest.Mock).mockImplementationOnce(() => Promise.reject(new Error(errorMessage)) ); await expect(userApi.fetchById(42)).rejects.toThrow(errorMessage); expect(axios.get).toHaveBeenCalledTimes(1); expect(axios.get).toHaveBeenCalledWith(`${baseApi.baseUrl}/user/42`); }); }); describe('authenticateUserById', () => { it('finds user in database matching credentials given', async () => { const response = { data: { id: 1, name: 'Wessel', }, }; (axios.get as jest.Mock).mockImplementationOnce(() => Promise.resolve(response)); const apiResponse = await userApi.authenticateUser(1, 'Wessel'); expect(apiResponse.isAuthenticated).toEqual(true); expect(axios.get).toHaveBeenCalledTimes(1); expect(axios.get).toHaveBeenCalledWith(`${baseApi.baseUrl}/user/1`); }); it('informs user is not authenticated if wrong details given', async () => { const response = { data: { id: 1, name: 'Wessel', }, }; (axios.get as jest.Mock).mockImplementationOnce(() => Promise.resolve(response)); const apiResponse = await userApi.authenticateUser(1, 'bob'); expect(apiResponse.isAuthenticated).toEqual(false); expect(axios.get).toHaveBeenCalledTimes(1); expect(axios.get).toHaveBeenCalledWith(`${baseApi.baseUrl}/user/1`); }); it('fetches erroneously data from an API', async () => { (axios.get as jest.Mock).mockImplementationOnce(() => Promise.reject(new Error(errorMessage)) ); await expect(userApi.authenticateUser(1, 'Wessel')).rejects.toThrow( errorMessage ); expect(axios.get).toHaveBeenCalledTimes(1); expect(axios.get).toHaveBeenCalledWith(`${baseApi.baseUrl}/user/1`); }); }); describe('FetchAll', () => { it('fetches successfully data from an API', async () => { const data = [ { id: 1, name: 'Wessel', }, { id: 2, name: 'Quint', }, { id: 3, name: 'Mani', }, { id: 4, name: 'Menno', }, { id: 5, name: 'Patrick', }, ]; const response = { data }; (axios.get as jest.Mock).mockImplementationOnce(() => Promise.resolve(response)); const users = await userApi.fetchAll(); expect(users).toEqual(data); expect(axios.get).toHaveBeenCalledTimes(1); expect(axios.get).toHaveBeenCalledWith(`${userApi.baseUrl}/users`); }); it('fetches erroneously data from an API', async () => { (axios.get as jest.Mock).mockImplementationOnce(() => Promise.reject(new Error(errorMessage)) ); console.log('errorMessage', errorMessage); await expect(userApi.fetchAll()).rejects.toThrow(errorMessage); expect(axios.get).toHaveBeenCalledTimes(1); expect(axios.get).toHaveBeenCalledWith(`${userApi.baseUrl}/users`); }); }); });
20bf516e39edbde6286ade88b774fc96b211c94f
TypeScript
lelandmiller/micro-signals
/test/suites/promisify-suite.ts
2.703125
3
import test = require('tape'); import {LeakDetectionSignal} from '../lib/leak-detection-signal'; import { ReadableSignal, Signal, } from '../../src'; export type PromisifyFunction = <T>(resolveSignal: ReadableSignal<T>, rejectSignal?: ReadableSignal<any>) => Promise<T>; export function promisifySuite(prefix: string, promisifyFunction: PromisifyFunction) { test(`${prefix} created promise resolves with the signal payload if resolve signal is fired`, t => { const rejectSignal = new Signal<string>(); const resolveSignal = new Signal<string>(); promisifyFunction<string>(resolveSignal, rejectSignal).then(payload => { t.equal(payload, 'foo'); t.end(); }); resolveSignal.dispatch('foo'); }); test(`${prefix} created promise rejects with the payload if reject signal is fired`, t => { const rejectSignal = new Signal<string>(); const resolveSignal = new Signal<string>(); promisifyFunction<string>(resolveSignal, rejectSignal).catch(reason => { t.equal(reason, 'foo'); t.end(); }); rejectSignal.dispatch('foo'); }); test(`${prefix} should not leak given only an acceptSignal`, t => { const acceptSignal = new LeakDetectionSignal<void>(); const acceptedPromise = promisifyFunction(acceptSignal); acceptedPromise.then(() => { /* empty callback */ }); acceptSignal.dispatch(undefined); t.equal(acceptSignal.listenerCount, 0); t.end(); }); test(`${prefix} should not leak on accept`, t => { const acceptSignal = new LeakDetectionSignal<void>(); const rejectSignal = new LeakDetectionSignal<void>(); const promise = promisifyFunction(acceptSignal, rejectSignal); promise.then(() => { /* empty callback */ }); acceptSignal.dispatch(undefined); t.equal(acceptSignal.listenerCount, 0); t.equal(rejectSignal.listenerCount, 0); t.end(); }); test(`${prefix} should not leak on reject`, t => { const acceptSignal = new LeakDetectionSignal<void>(); const rejectSignal = new LeakDetectionSignal<void>(); const promise = promisifyFunction(acceptSignal, rejectSignal); promise.catch(() => { /* used to suppress unhandled promise error */ }); rejectSignal.dispatch(undefined); t.equal(acceptSignal.listenerCount, 0); t.equal(rejectSignal.listenerCount, 0); t.end(); }); }
f6c618b9ee368be63e35828e8865aa921f061da3
TypeScript
andrii1509/08_algorithms_and_data_structures_1
/src/helpers/sort-jobs.ts
2.921875
3
import {Job} from '../interfaces/job-interface'; export function sortJobs(jobs: Job[]): Job[] { if (jobs.length < 2) return jobs; let pivot = jobs[0]; const left = []; const right = []; for (let i = 1; i < jobs.length; i++) { if (pivot.priority > jobs[i].priority) { left.push(jobs[i]); } else { right.push(jobs[i]); } } return sortJobs(left).concat(pivot, sortJobs(right)); }
8eb9a4e65dc67f79f9a05678f52f183342d7f89b
TypeScript
zeno60/tree-view-backend
/src/services/factoryService.ts
2.625
3
import { Factory } from "../models/Factory"; import { CreateFactoryRequest } from "../interfaces/CreateFactoryRequest"; import { getConnection } from "typeorm"; import { Tree } from "../models/Tree"; import { getRandomNumber } from "../utils/randomUtil"; export interface FactoryService { addFactoryToTree(tree: Tree, createFactoryRequest: CreateFactoryRequest): Promise<Factory>; updateFactory(factory: Factory, updateFactoryRequest: CreateFactoryRequest): Promise<Factory>; getFactoryById(factoryId: number): Promise<Factory>; deleteFactoryById(factoryId: number): Promise<void>; } export class FactoryServiceImpl implements FactoryService { public async deleteFactoryById(factoryId: number): Promise<void> { const factory = await this.getFactoryById(factoryId); const factoryRepository = getConnection().getRepository(Factory); await factoryRepository.remove(factory); } public async getFactoryById(factoryId: number): Promise<Factory> { const factoryRepository = getConnection().getRepository(Factory); return await factoryRepository.findOne({ where: { id: factoryId }, relations: ["tree"]}); } public async updateFactory(factory: Factory, updateFactoryRequest: CreateFactoryRequest): Promise<Factory> { const factoryRepository = getConnection().getRepository(Factory); const { min, max, number, name } = updateFactoryRequest; const values: number[] = []; for(let i = 0; i < number; i++) { values.push(getRandomNumber(min, max)); } factory.name = name; factory.min = min; factory.max = max; factory.values = values; return factoryRepository.manager.save(factory); } public async addFactoryToTree(tree: Tree, createFactoryRequest: CreateFactoryRequest): Promise<Factory> { const treeRepository = getConnection().getRepository(Tree); const factoryRepository = getConnection().getRepository(Factory); const { min, max, number, name } = createFactoryRequest; const values: number[] = []; for(let i = 0; i < number; i++) { values.push(getRandomNumber(min, max)); } let factory = new Factory(); factory.name = name; factory.values = values; factory.min = min; factory.max = max; factory = await factoryRepository.manager.save(factory); if (!tree.factories) { tree.factories = [factory]; } else { tree.factories.push(factory); } await treeRepository.manager.save(tree); return factory; } }
7099c9d8350d55367629372ae762cc41d9349ddb
TypeScript
giorgospetkakis/vscode-write-good
/src/extension.ts
2.53125
3
'use strict'; import { workspace, ExtensionContext, TextDocument, languages, Uri, Diagnostic, DiagnosticCollection, TextDocumentContentChangeEvent } from 'vscode'; import { isNullOrUndefined } from 'util'; import { lintText } from './linter'; let diagnosticCollection: DiagnosticCollection; let diagnosticMap: Map<string, Diagnostic[]>; export function activate(context: ExtensionContext) { console.log("Write-Good Linter active..."); diagnosticCollection = languages.createDiagnosticCollection("Write-Good Lints"); diagnosticMap = new Map(); if (context == null) return; function isWriteGoodLanguage(languageId: string) { let wgLanguages: string = workspace.getConfiguration('write-good').get('languages'); return (wgLanguages.indexOf(languageId) > -1 || wgLanguages === '*'); } // full lint when document is saved context.subscriptions.push(workspace.onDidSaveTextDocument(document => { if (isWriteGoodLanguage(document.languageId)) { doLint(document); } })); // attempt to only lint changes on motification context.subscriptions.push(workspace.onDidChangeTextDocument(event => { if (isWriteGoodLanguage(event.document.languageId)) { // this doesn't work yet, instead, check for a setting? // doPartialLint(event.document, event.contentChanges); const onlyLintOnSave: Boolean = workspace.getConfiguration('write-good').get('only-lint-on-save'); if (!onlyLintOnSave) { doLint(event.document); } } })); // full lint on a new document/opened document context.subscriptions.push(workspace.onDidOpenTextDocument(event => { if (isWriteGoodLanguage(event.languageId)) { doLint(event); } })); // clean up any lints when the document is closed context.subscriptions.push(workspace.onDidCloseTextDocument(event => { if (diagnosticMap.has(event.uri.toString())) { diagnosticMap.delete(event.uri.toString()); } resetDiagnostics(); })); } export function deactivate() { console.log("Write-Good Linter deactivating...") } function resetDiagnostics() { diagnosticCollection.clear(); diagnosticMap.forEach((diags, file) => { diagnosticCollection.set(Uri.parse(file), diags); }); } function getWriteGoodConfig() : object { var wgConfig: object = workspace.getConfiguration('write-good').get('write-good-config'); if (isNullOrUndefined(wgConfig)) { wgConfig = {}; } return wgConfig; } function doPartialLint(document: TextDocument, changes: TextDocumentContentChangeEvent[]) { const wgConfig = getWriteGoodConfig(); let diagnostics: Diagnostic[] = diagnosticMap.get(document.uri.toString()); changes.forEach((changeEvent, index) => { // remove any overlapping diagnostics let toRemove: number[] = []; diagnostics.forEach((diagnostic, index) => { // if the diagnostic range intersects with the change event, we assume the diagnostic should be removed // and will be re-added with the change event. if (diagnostic.range.intersection(changeEvent.range) != undefined) { toRemove.push(index); } }); toRemove.forEach((i) => diagnostics.splice(i, 1)); // skip linting if there's content if(changeEvent.text.length > 0) { const lineOffset = changeEvent.range.start.line; lintText(changeEvent.text, wgConfig, lineOffset, diagnostics); } }); } function doLint(document: TextDocument) { const wgConfig = getWriteGoodConfig(); let diagnostics: Diagnostic[] = []; lintText(document.getText(), wgConfig, 0, diagnostics); diagnosticMap.set(document.uri.toString(), diagnostics); resetDiagnostics(); }
9ff0bd79a5961047cd4b283c78e75bc9482362a7
TypeScript
Rokt33r/typed-remark
/packages/unist-util-stringify-position/src/lib/index.ts
3.28125
3
import { Point, Position, Node } from 'typed-unist' export function stringifyPosition (position: Position): string { return `${stringifyPoint(position.start)}-${stringifyPoint(position.end)}` } export function stringifyPoint (point: Point): string { return `${point.line}:${point.column}` } export function stringifyNode (node: Node): string { const position = node.position if (position == null) { return stringifyPoint({ line: 1, column: 1, }) } return stringifyPosition(position) } export function stringify (input: Point | Position | Node): string { if ((input as Node).type != null) return stringifyNode((input as Node)) if ((input as Position).start != null) return stringifyPosition((input as Position)) if ((input as Point).line != null) return stringifyPoint((input as Point)) throw new Error(`Invalid argument: the argument must be Point, Position or Node. But got ${input}`) }
30906c15987de1ca33481152cb2332d0686ad811
TypeScript
sudhakar29495/React-with-TS-boiler-plate
/src/utils/storage.ts
3.390625
3
export interface IStorageObject { key: string, value: any } interface IStorageService { setItem : (key: string, value: any) => void , setItems : (storageObjects: IStorageObject[]) => void } /** * Util Class to handle storage services * Localstorage, SessionStorage can be handled */ class StorageService implements IStorageService { public setItem(key: string, value: any): void { localStorage.setItem(key, value); } public setObject(key: string, value: object): void { localStorage.setItem(key, JSON.stringify(value)); } public getObject(key: string): object { return JSON.parse(this.getItem(key)); } public setItems(storageObjects: IStorageObject[]) : void { storageObjects.forEach((storageObject: IStorageObject) => { this.setItem(storageObject.key, storageObject.value); }); } public getItem(key: string) : any { return localStorage.getItem(key); } public deleteItem(key: string) : void { localStorage.removeItem(key); } } export default new StorageService();
751fcc3137ebcc2556078c97220f3165470ee866
TypeScript
ax1/a1-util
/src/util.ts
2.9375
3
import { promisify } from 'util' import { exec, spawn } from 'child_process' const execPromise = promisify(exec) import { fileURLToPath, URL } from 'url' type executeOptions = { /** detach COMPLETELY by:1-new independent process, 2-stdout stderr are also different than the parent*/ unref?: boolean } /** * See https://bashitout.com/2013/05/18/Ampersands-on-the-command-line.html * Generic call to an external process (ie: calling an executable file). * Use with CAUTION. Check or sanitize the input (otherwise someone could perform rogue commands by adding data to the expected input string ). * If stderr but exit was 0, the response is treated as Error * Detached mode is automatically detected, but the stdout is lost as well. Example `sleep 10 &` * @param {string} command The instruction typed in the same way as typed in a terminal window. Examples: "ls -la | grep node" or "cat file.txt" * @param {executeOptions} options unref: makes stdio and process to be independent completely */ export async function execute(command: string, options?: executeOptions): Promise<string> { const detach = command.endsWith('&') // 'detached' symbol in command is not handle by node/libuv, use unref() if (options && options.unref) exec(command).unref() // start and forget. The app can crash and the process would continue to live else if (detach) spawn(command, { stdio: 'inherit', shell: true }) //'stdio' to pipe to parent (so logs are shown in journalctl), 'shell' to allow command parameters else { const { stdout, stderr } = await execPromise(command) if (stderr.toString()) throw new Error(stderr.toString()) return stdout.toString() } return '0' } /** * Async sleep. This function will be deprecad in the future * because it can be performed by timers.timeout() added in V15 https://nodejs.org/api/timers.html#timers_timers_promises_api * @param millis * @returns */ export async function sleep(millis: number): Promise<void> { return new Promise(resolve => setTimeout(resolve, millis)) } /** * ESM replacement for __dirname. * When using bundlers, the dirname can be a .js file, so this function also patches it.* * @returns {string} */ export function dirname() { let __dirname = fileURLToPath(new URL('.', import.meta.url)) if (__dirname.endsWith('.js')) __dirname = __dirname.substring(0, __dirname.lastIndexOf('/') + 1) return dirname } export function log(type: string, message?: any): void { const t = (type && type.toLowerCase) ? type.toLowerCase() : '' const prefix = (t == 'ok' || t == 'info') ? '\x1b[32m%s\x1b[0m' : t == 'error' ? '\x1b[31m%s\x1b[0m' : '' console.log(prefix, message) } export function printMatrix(matrix: Array<Array<any>>) { return matrix.map(row => row.toString()).reduce((acc, el) => acc + '\n' + el) } /** * @deprecated * Use log(type, msg) instead */ export function logOK(message?: any): void { console.log('\x1b[32m%s\x1b[0m', message) } /** * @deprecated * Use log(type, msg) instead */ export function logError(message?: any): void { console.log('\x1b[31m%s\x1b[0m', message) }
d298e3ea4b4510965b4eac12c8f6000ce0a97cf5
TypeScript
ISKCON-Cultural-Centre/eICS-ws
/client/src/app/shared/sdk/models/DevoteeAsrama.ts
2.703125
3
/* tslint:disable */ import { AsramaMaster, Devotee } from '../index'; declare var Object: any; export interface DevoteeAsramaInterface { "devoteeId": string; "asramaMasterId": string; "entryDate": Date; fkTable1AsramaMaster1rel?: AsramaMaster; fkTable1Devotee3rel?: Devotee; } export class DevoteeAsrama implements DevoteeAsramaInterface { "devoteeId": string; "asramaMasterId": string; "entryDate": Date; fkTable1AsramaMaster1rel: AsramaMaster; fkTable1Devotee3rel: Devotee; constructor(data?: DevoteeAsramaInterface) { Object.assign(this, data); } /** * The name of the model represented by this $resource, * i.e. `DevoteeAsrama`. */ public static getModelName() { return "DevoteeAsrama"; } /** * @method factory * @author Jonathan Casarrubias * @license MIT * This method creates an instance of DevoteeAsrama for dynamic purposes. **/ public static factory(data: DevoteeAsramaInterface): DevoteeAsrama{ return new DevoteeAsrama(data); } /** * @method getModelDefinition * @author Julien Ledun * @license MIT * This method returns an object that represents some of the model * definitions. **/ public static getModelDefinition() { return { name: 'DevoteeAsrama', plural: 'DevoteeAsramas', path: 'DevoteeAsramas', idName: 'devoteeId', properties: { "devoteeId": { name: 'devoteeId', type: 'string' }, "asramaMasterId": { name: 'asramaMasterId', type: 'string' }, "entryDate": { name: 'entryDate', type: 'Date' }, }, relations: { fkTable1AsramaMaster1rel: { name: 'fkTable1AsramaMaster1rel', type: 'AsramaMaster', model: 'AsramaMaster', relationType: 'belongsTo', keyFrom: 'asramaMasterId', keyTo: 'id' }, fkTable1Devotee3rel: { name: 'fkTable1Devotee3rel', type: 'Devotee', model: 'Devotee', relationType: 'belongsTo', keyFrom: 'devoteeId', keyTo: 'id' }, } } } }
6d113bed819677961397836e80093ba046971ac2
TypeScript
blackstrip/infinite-minesweeper
/src/Cell.ts
3.046875
3
/** * Created by sisc0606 on 19.08.2017. */ export class Cell { x: number; y: number; isOpen: boolean; isMine?: boolean; isFlagged: boolean; constructor( x: number, y: number, isFlagged: boolean = false, isMine?: boolean ) { this.x = x; this.y = y; this.isOpen = false; this.isMine = isMine; this.isFlagged = isFlagged; } toJSON() { const open = this.isOpen ? "1" : "0"; const mine = this.isMine === undefined ? "2" : this.isMine ? "1" : "0"; const flagged = this.isFlagged ? "1" : "0"; return open + mine + flagged; } }
25701c46b6e9a6dddbffa386d16d4f93a102b711
TypeScript
Super-Projetos-Engenharia-Unicesumar/card_game_on_terminal
/src/Game.ts
2.953125
3
import Input from "./Input.ts"; export default class Game { start(): void { Input.cleanScreen(); this.gameLoop(); } private gameLoop(): void { let isPlaying = true; while (isPlaying) { const result = this.mainMenu(); switch (result) { case 1: this.playGame(); break; case 2: this.showRules(); break; case 3: this.quitGame(); isPlaying = false; break; default: Input.cleanScreen(); console.log("Não entendi"); break; } } } private playGame(): void { Input.cleanScreen(); console.log("Escolheu jogar"); console.log("Iniciar jogo"); console.log("Mostrar total de pontos"); console.log("Mostrar cartas disponíveis"); console.log("Escolher carta"); console.log("Escolher valor"); console.log("Verificar vencedor da rodada"); console.log("Verificar vencedor da partida"); Input.waitForKey("Jogo encerrado"); Input.cleanScreen(); } private showRules(): void { Input.cleanScreen(); console.log("Escolheu regras"); Input.waitForKey("Regras encerradas"); Input.cleanScreen(); } private quitGame(): void { Input.cleanScreen(); console.log("Escolheu sair"); } private mainMenu(): number { console.log("*=================*"); console.log("Bem-vindo"); console.log("[1] Jogar"); console.log("[2] Regras"); console.log("[3] Sair"); console.log("*=================*"); return Input.askForNumber("Escolha a opção"); } }
da48dccb51631db930e7db01a2941c3667066b9b
TypeScript
mingkaic/RocnnetViser
/app/electron.app.ts
2.640625
3
/// <reference path="../typings/index.d.ts" /> import { BrowserWindow, globalShortcut } from 'electron'; import { join } from 'path'; import { format } from 'url'; // app class export default class ElectronApp { static mainWindow: Electron.BrowserWindow; static application: Electron.App; static browserWindow; static main(app: Electron.App, browserWindow: typeof BrowserWindow) { // we pass the Electron.App object and the Electron.BrowserWindow into this function // so this class1 has no dependencies. This // makes the code easier to write tests for ElectronApp.browserWindow = browserWindow; ElectronApp.application = app; ElectronApp.application.on('ready', ElectronApp.createWindow); ElectronApp.application.on('activate', ElectronApp.onActivate); ElectronApp.application.on('will-quit', ElectronApp.onQuit); ElectronApp.application.on('window-all-closed', ElectronApp.onWindowAllClosed); } private static createWindow() { // create the browser window. ElectronApp.mainWindow = new BrowserWindow({width: 800, height: 600}); // and load the index.html of the app. ElectronApp.mainWindow.loadURL(format({ pathname: join(__dirname, './index.html'), protocol: 'file:', slashes: true })); // open DevTools // // ElectronApp.mainWindow.webContents.openDevTools(); // emitted when the window is closed. ElectronApp.mainWindow.on('closed', ElectronApp.onClose); } private static onClose() { // dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. ElectronApp.mainWindow = null; } private static onWindowAllClosed() { // on OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { ElectronApp.application.quit(); } } private static onActivate() { // on OS X it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (ElectronApp.mainWindow === null) { ElectronApp.createWindow(); } } private static onQuit() { // unregister all shortcuts. globalShortcut.unregisterAll(); } }
c5af45ae80040b9705d3fd84ce044dd21020476e
TypeScript
jmerle/deskdocs
/src/common/config/BaseConfig.ts
2.65625
3
import ElectronStore from 'electron-store'; import { defaultConfig } from './defaults'; import { ConfigEvent, OnAnyChangeCallback, OnAnyChangeEvent, OnChangeCallback, OnChangeEvent, OnChangeKeyEvent, } from './types'; export abstract class BaseConfig extends ElectronStore<any> { protected eventChannel = 'configEvent'; private onChangeCallbacks: Map<string, OnChangeCallback[]> = new Map(); private onAnyChangeCallbacks: OnAnyChangeCallback[] = []; private knownOnChangeKeys: string[] = []; constructor() { super({ defaults: defaultConfig }); (this as any).events.setMaxListeners(50); } protected abstract initListeners(): void; protected abstract sendEvent(event: ConfigEvent): void; public init(): void { this.onDidAnyChange((newValue, oldValue) => { this.sendEvent({ type: 'onAnyChange', payload: { newValue, oldValue, }, }); }); this.initListeners(); this.sendEvent({ type: 'newClient', }); } public onChange(key: string, callback: OnChangeCallback): void { this.sendEvent({ type: 'onChangeKey', payload: { key, }, }); if (!this.onChangeCallbacks.has(key)) { this.onChangeCallbacks.set(key, []); } this.onChangeCallbacks.get(key).push(callback); } public onAnyChange(callback: OnAnyChangeCallback): void { this.onAnyChangeCallbacks.push(callback); } protected handleEvent(event: ConfigEvent): void { switch (event.type) { case 'onChange': this.handleOnChange(event); break; case 'onAnyChange': this.handleOnAnyChange(event); break; case 'onChangeKey': this.handleOnChangeKeyEvent(event); break; case 'newClient': this.handleNewClientEvent(); break; } } private handleOnChange(event: OnChangeEvent): void { const { key, newValue, oldValue } = event.payload; for (const callback of this.onChangeCallbacks.get(key) || []) { callback(newValue, oldValue); } } private handleOnAnyChange(event: OnAnyChangeEvent): void { const { newValue, oldValue } = event.payload; for (const callback of this.onAnyChangeCallbacks) { callback(newValue, oldValue); } } private handleOnChangeKeyEvent(event: OnChangeKeyEvent): void { const { key } = event.payload; if (this.knownOnChangeKeys.includes(key)) { return; } this.onDidChange(key, (newValue, oldValue) => { this.sendEvent({ type: 'onChange', payload: { key, newValue, oldValue, }, }); }); this.knownOnChangeKeys.push(key); } private handleNewClientEvent(): void { for (const key of this.knownOnChangeKeys) { this.sendEvent({ type: 'onChangeKey', payload: { key, }, }); } } }
f5b8c8cbc9b71ee564c530d95335b13759ef0031
TypeScript
syfxlin/xkeditor-tiptap
/src/utils/nodeLinePasteRule.ts
2.734375
3
import { Fragment, Node, NodeType, Plugin, Slice } from "@/utils/prosemirror"; export default function( regexp: RegExp, type: NodeType, getContent: | (( match: RegExpExecArray, attrs: { [attr: string]: any }, childNode: Node ) => string | Node | null) | Node | string | null | number = 0, getAttrs: | ((match: RegExpExecArray, childNode: Node) => { [attr: string]: any }) | { [attr: string]: any } = {} ) { const handler = (fragment: Fragment): Fragment => { const nodes: Node[] = []; fragment.forEach(child => { const text = child.textContent; const match = regexp.exec(text); if (match) { const start = match.index; const end = start + match[0].length; if (start > 0) { nodes.push(child.cut(0, start)); } const childNode = child.cut(start, end); const attrs = getAttrs instanceof Function ? getAttrs(match, childNode) : getAttrs; let content: Node | string | null; if (getContent instanceof Function) { content = getContent(match, attrs, childNode); } else if (typeof getContent === "number") { content = match[getContent]; } else { content = getContent; } if (content === null) { content = type.create(attrs); } if (typeof content === "string") { content = type.create(attrs, type.schema.text(content), child.marks); } nodes.push(content); if (end < text.length) { nodes.push(child.cut(end)); } } else { nodes.push(child); } }); if (nodes.length !== 0 && nodes[nodes.length - 1].isAtom) { nodes.push(type.schema.node("paragraph")); } return Fragment.fromArray( nodes.map(node => node.isInline || node.isText ? type.schema.node("paragraph", {}, node) : node ) ); }; return new Plugin({ props: { transformPasted: slice => new Slice(handler(slice.content), slice.openStart, slice.openEnd) } }); }
7248dbbe9933bf336698b421d15ffdeaa9664783
TypeScript
warrenxxx/pruebagit
/global/common/src/utils/Validation.ts
2.765625
3
import validate from 'validate.js'; import {ValidationError} from '../errorHandling/Exceptions/validation.error'; import moment = require('moment'); import {ObjectId} from 'bson'; export async function Validate(x: any, constraint: any): Promise<any> { try { return isValid(x, constraint); } catch (e) { throw e; } } export function isString(inp: any, min = 0, max = 300): null | any { return validate.isString(inp) && (<string>inp).length >= min && (<string>inp).length <= max ? inp : null; } export function isStringRegex(inp: any, pattern: RegExp): null | any { return validate.isString(inp) && pattern.test(inp) ? inp : null; } export function isNumber(inp: any): null | any { return validate.isNumber(inp) ? inp : null; } export function isBoolean(inp: any): null | any { return validate.isBoolean(inp) ? inp : null; } export function isObjectId(inp: any): null | any { return ObjectId.isValid(inp) ? new ObjectId(inp) : null; } export function isDate(inp: any): null | any { const date = moment(inp, 'DD-MM-YYYY', true); return date.isValid() ? date.toDate() : null; } export function isDateTime(inp: any): null | any { const date = moment(inp, 'DD-MM-YYYY HH:mm:ss', true); return date.isValid() ? date.toDate() : null; } export function isValid(object: any, rules: any): any { const res: any = {}; for (const param in rules) { if (validate.isArray(rules[param])) { if (validate.isArray(object[param])) { const tmp = []; if (validate.isFunction(rules[param][0])) for (const paramItem of object[param]) { const r = rules[param][0](paramItem); if (r) tmp.push(r); else throw ValidationError.ValidateObjectException(param); } else for (const paramItem of object[param]) tmp.push(isValid(paramItem, rules[param][0])); res[param] = tmp; } else throw ValidationError.ValidateObjectException(param); } else if (validate.isFunction(rules[param])) { const r = rules[param](object[param]); if (r) res[param] = r; else throw ValidationError.ValidateObjectException(param); } else { res[param] = isValid(object[param], rules[param]); } } return res; }
02d83bcb3abc9b3afb8b0a1c97d8ba948d755eee
TypeScript
Dcivan226/my-games
/光的反射/RayLine/src/Mirrors.ts
2.703125
3
/*镜子*/ class Mirror extends egret.Sprite { private _stage:egret.Stage; private _mirror:egret.Bitmap; private _mirrorLength:number=200; public static POSITION_CHANGE:string="position_change"; private _line:Line; public constructor(stage:egret.Stage) { super(); this._stage=stage; this._line=new Line(); this.drawMirror(); this.updateLine(); } public get line():Line{ return this._line; } public set x(value:number){ this._mirror.x=value; ObjectDecorator.get(this._mirror).updateRotateHandlePosition(); this.updateLine(); } public set y(value:number){ this._mirror.y=value; ObjectDecorator.get(this._mirror).updateRotateHandlePosition(); this.updateLine(); } private drawMirror(){ this._mirror=this.createBitmapByName("mirror_png"); this._mirror.anchorOffsetX=this._mirror.width/2; this.addChild(this._mirror); let rotate=this.createBitmapByName("rotate_png"); rotate.anchorOffsetX=rotate.width/2; rotate.anchorOffsetY=rotate.height/2 this.addChild(rotate); ObjectDecorator.get(this._mirror).addRotateAction(this._stage,rotate,150,0).moveHandler(function(){ this.updateLine(); this.dispatchEvent(new egret.Event(Mirror.POSITION_CHANGE)); }.bind(this)); ObjectDecorator.get(this._mirror).addDragAction(this._stage).moveHandler(function(){ this.updateLine(); this.dispatchEvent(new egret.Event(Mirror.POSITION_CHANGE)); }.bind(this)); } private updateLine(){ let angle=this._mirror.rotation*Math.PI/180; let dx=(this._mirrorLength/2)*Math.cos(angle); let dy=(this._mirrorLength/2)*Math.sin(angle); this.line.startPoint.x=this._mirror.x-dx; this.line.startPoint.y=this._mirror.y-dy; this.line.endPoint.x=this._mirror.x+dx; this.line.endPoint.y=this._mirror.y+dy; } private createBitmapByName(name: string) { let result = new egret.Bitmap(); let texture: egret.Texture = RES.getRes(name); result.texture = texture; return result; } }
1ae46a89db43a5e30ee8e6d12bb7a14aaee6c328
TypeScript
KaushikShivam/sl-challenge
/src/api/models/card.model.ts
2.546875
3
export interface Card { id: string; name: string; imageUrl: string; count: { total: number; }; } export interface EditCardDto { name?: string; imageUrl?: string; }
475a4542ec2ab4cbb1fd3aa4920e81192ddb5462
TypeScript
damducthoai/linksport
/backend-base/src/launcher.ts
2.609375
3
import * as events from 'events'; import * as fs from 'fs'; import * as winston from 'winston'; import { CoreVerticle } from './core-verticle'; export abstract class AppLauncher { protected readonly config:any; protected readonly globalEvents = new events.EventEmitter(); protected readonly verticles : CoreVerticle[] = []; private readonly logger: any; /** * */ constructor(private name: string) { this.logger = winston.createLogger({ transports: [ new winston.transports.Console() ] }); const args = process.argv.slice(2); if(args.length < 1){ throw Error('args missing'); } const config = fs.readFileSync(args[0], 'utf8'); this.config = JSON.parse(config); this.info(`launching ${this.config.profile}`); setTimeout(async () => { await this.deploy(); this.info(`deployed ${this.verticles.length} verticle(s)`); }, 1) } public abstract deploy():Promise<number>; protected info(msg: string){ this.logger.info(`${this.name} | ${msg}`); } protected warn(msg: string) { this.logger.warn(`${this.name} | ${msg}`); } protected error(msg: string) { this.logger.error(`${this.name} | ${msg}`); } }
97fc684b325204debc7cebdcab774af01f3d95b3
TypeScript
Siusarna/Pichupido
/src/utils/passwords.ts
2.65625
3
import crypto from 'crypto'; import config from 'config'; const hash: { iterations: number, length: number } = config.get('crypto'); const salt: { length: number } = config.get('salt'); export const checkPassword = ( inputPassword: string, passwordFromDb: string, salt: string ): boolean => { if (!inputPassword || !passwordFromDb) return false; return ( crypto .pbkdf2Sync(inputPassword, salt, hash.iterations, hash.length, 'sha1') .toString('base64') === passwordFromDb ); }; export const genSalt = (): string => crypto .randomBytes(salt.length) .toString('base64'); export const genHash = (password: string, salt: string): string => crypto .pbkdf2Sync(password, salt, hash.iterations, hash.length, 'sha1') .toString('base64');
ab8367c8bc74bbc9e38de7851e05e089225e2d70
TypeScript
MeowSound-Idols/bilibili-live-toolkit
/src/services/storage.ts
3.03125
3
import { get, set } from "lodash"; export default class Storage { static getSetting<T>( name: string, defaultValue: string | boolean | number | undefined ): T { const settings = localStorage.getItem("settings") ? JSON.parse(localStorage.getItem("settings") as string) : {}; return get(settings, name) === undefined ? defaultValue : get(settings, name); } static setSetting( name: string, value: string | boolean | number | undefined ) { const settings = localStorage.getItem("settings") ? JSON.parse(localStorage.getItem("settings") as string) : {}; set(settings, name, value); localStorage.setItem("settings", JSON.stringify(settings)); } static deleteSetting(name: string) { Storage.setSetting(name, undefined); } }
8cd2139de6beb92885b4b40ad58e3d8f2c63af1a
TypeScript
theCodeCampus/tcc-cli
/src/utils/git.spec.ts
2.75
3
import { checkRepoStatus } from "./git"; import { SimpleGit, StatusResult } from 'simple-git/promise'; describe("checking repository status", function () { describe("on a clean repository", () => { it("should return a resolved promise", () => { const repository: Partial<SimpleGit> = { status: function (): Promise<StatusResult> { const result: Partial<StatusResult> = { isClean: () => true}; return Promise.resolve(result as StatusResult); } }; const actual = checkRepoStatus(repository as SimpleGit); expect(actual).toBeDefined(); expect(typeof actual.then).toBe("function"); return actual; }); }); describe("on a dirty repository", () => { it("should return a rejected promise", done => { const repository: Partial<SimpleGit> = { status: function (): Promise<StatusResult> { const result: Partial<StatusResult> = { isClean: () => false}; return Promise.resolve(result as StatusResult); } }; const actual = checkRepoStatus(repository as SimpleGit); expect(actual).toBeDefined(); expect(typeof actual.then).toBe("function"); actual.then( function () { done.fail(); }, function () { done(); } ); }); }); });
5dee29024a946e26baa569fe2b9e3ae9ac301989
TypeScript
SongFuZhen/egret
/code/Time/src/Timer.ts
2.671875
3
class Timer extends egret.DisplayObjectContainer { public constructor() { super(); this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this); } private onAddToStage() { this.showTimerGame().catch(e => { console.log(e); }) } private n: number = 6; private num: egret.TextField; private con: egret.TextField; private img: egret.Bitmap; private timer: egret.Timer; private startTime: number; private stopTime: number; private finalTime: number; private async showTimerGame() { this.drawText(); this.drawContent(); this.onButtonComp(); this.timer = new egret.Timer(1000, 8); this.timer.addEventListener(egret.TimerEvent.TIMER, this.timerFunc, this); this.timer.addEventListener(egret.TimerEvent.TIMER_COMPLETE, this.timerComFunc, this); this.returnMainPage(); } private returnButton(): void { // const returnImg = Main.createBitmapByName("egret_icon_png"); // // returnImg.x = 120; // returnImg.y = 200; const returnTextField = new egret.TextField(); returnTextField.text = '重新玩游戏'; returnTextField.x = 160; returnTextField.y = 200; this.addChild(returnTextField); returnTextField.touchEnabled = true; returnTextField.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onReturnTouch, this, true); } private onReturnTouch(): void { this.n = 6; this.removeChildren(); this.showTimerGame().catch(e => { console.log(e); }) } private onButtonComp(): void { this.img = Main.createBitmapByName("play_png"); const rect: egret.Rectangle = new egret.Rectangle(10, 10, 15, 15); this.img.scale9Grid = rect; this.img.y = 180; this.img.x = 120; this.addChild(this.img); this.img.touchEnabled = true; this.img.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouch, this, true); } private onTouch(): void { this.startTime = new Date().getTime(); this.img.alpha = 0; this.timer.start(); this.drawText(); this.touchEnabled = true; this.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchSRP, this, true); } private drawText() { this.num = new egret.TextField(); this.num.text = this.n.toString(); this.num.size = 100; this.num.width = 480; this.num.textColor = 0x00ff00; this.num.textAlign = egret.HorizontalAlign.CENTER; this.addChild(this.num); } private drawContent(): void { this.con = new egret.TextField(); this.con.text = "默默倒数6秒,迅速点击文字"; this.con.width = 480; this.con.textColor = 0x00ff00; this.con.textAlign = egret.HorizontalAlign.CENTER; this.con.y = 120; this.addChild(this.con); } private timerFunc(): void { if (this.n <= 3) { this.num.text = '?'; } else { this.removeChildren(); this.drawText(); } this.n--; } private timerComFunc(): void { if (this.n <= -2) { this.drawContent(); this.con.text = "别迷糊了,赶紧醒醒;"; this.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchSRP, this, true); this.img.alpha = 1; } } private onTouchSRP(evt: egret.Event) { this.removeEventListener(egret.TouchEvent.TOUCH_TAP, this.onTouchSRP, this, true); this.timer.stop(); this.stopTime = new Date().getTime(); this.finalTime = this.startTime - this.stopTime; this.num.text = (this.finalTime / 1000 + 6).toFixed(3); this.drawContent(); switch (Math.floor(Math.abs(this.finalTime / 1000 + 6))) { case 0: this.con.text = "帅气的专注"; break; case 1: this.con.text = "很专注,还需继续努力"; break; case 2: this.con.text = "别摸糊了,赶紧醒醒"; break; default: break; } this.returnButton(); } private returnMainPage(): void { const returnMain: egret.TextField = new egret.TextField(); returnMain.x = 180; returnMain.y = 320; returnMain.textColor = 0x000000; returnMain.textAlign = egret.HorizontalAlign.CENTER; returnMain.text = "返回主界面"; this.addChild(returnMain); returnMain.touchEnabled = true; returnMain.addEventListener(egret.TouchEvent.TOUCH_TAP, this.returnMain, this); } private returnMain(): void { window.location.reload(); } }
0001925a2fcf27bda0b6324c35dbffb69c22c1a8
TypeScript
lysycyn/calendar
/src/typings/index.ts
2.796875
3
export interface DayInfo { date?: string; color?: string; } export interface MonthInfo { month: number; year: number; } export type DaysColorsInfo = Record<string, string>; export enum MonthType { PREV_MONTH = 'PREV_MONTH', NEXT_MONTH = 'NEXT_MONTH' }
bc72ee7d2d4896bc90bd92d45aab2b269eb2f1fb
TypeScript
brianhadley/rxjs_kata
/src/app/services/feature-request-service/feature-request.service.spec.ts
2.859375
3
import { TestBed, async } from '@angular/core/testing'; import { FeatureRequestService } from './feature-request.service'; import { FeatureRequest } from 'src/app/model/feature-request'; import { of, from, Observable, BehaviorSubject } from 'rxjs'; describe('FeatureRequestService', () => { const feat1 = new FeatureRequest(100,"Do most things really well",5,10); const feat2 = new FeatureRequest(200,"Do all things well",5,10); const feat3 = new FeatureRequest(300,"Do all things amazing",5,10); const feat4 = new FeatureRequest(400,"Never ever screw up...EVER",5,10); const requests = [feat1,feat2,feat3,feat4]; const failEveryTimeObs = any => { return new BehaviorSubject<any>(null); } beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: FeatureRequestService = TestBed.get(FeatureRequestService); expect(service).toBeTruthy(); }); //kata test 1 //replace 'failEveryTimeObs with correct rxjs operator it('should NOT USE THE SERVICE and use some rxjs operator to create an observable that emits a single value for each feature element in an array', async(() => { let i = 0; from(requests).subscribe(request=>{ expect(request.id).toBe(requests[i].id); i++; }); })); //kata test 2 //replace 'failEveryTimeObs with correct rxjs operator it('should NOT USE THE SERVICE and use some rxjs operator to create an observable that emits an array of values matching the array', async(() => { of(requests).subscribe(r=>{ expect(r).toBe(requests); }); })); //kata test 3 it('should emit a value when a singular value is passed to the newRequest() method while already observing', () => { const service: FeatureRequestService = TestBed.get(FeatureRequestService); service.getSubscribableNewRequests().subscribe(newRequest=>expect(newRequest).toBe(feat1)); service.newRequest(feat1); }); //kata test 4 it('should emit the last value of an array of requests passed via the newRequests() method', () => { const service: FeatureRequestService = TestBed.get(FeatureRequestService); service.newRequests(requests); service.getSubscribableWithLatestItem().subscribe(r=>expect(r).toBe(feat4)); }); //kata test 5 it('should emit the last 3 values that were passed to it via newRequests(), as well as a new singular value passed via newRequest()', () => { const service: FeatureRequestService = TestBed.get(FeatureRequestService); service.newRequests(requests); let newFeat = new FeatureRequest(500,"Special Sauce",6,3); let i = 1; // service.getSubscribableWithFullHistory().subscribe(feat=>{ // console.log('NEW:',feat); service.getSubscribableWithLastThree().subscribe(feat=>{ if (i<4) { expect(feat).toBe(requests[i]); } else { expect(feat).toBe(newFeat); } i++; }); service.newRequest(newFeat); }); });
40e7e8df519e569230452644dfd122f69ad71571
TypeScript
dy51ex/c1-request-api
/$/reportsGet/reportData.ts
2.578125
3
import { components } from '../../types'; import c1request from '../base/c1request'; import LogAction from '../base/LogAction'; /** * Возвращает данные отчета, с условиями фильтров, если передано * @example $.reportsGet.reportData({ ReportMetadataId: uuid, { Дата: ['2020-01-01', '2020-01-30'], 'Тип дела':['Продажи'] }}) */ export default async function (params: { ReportMetadataId: string; Filters?: { [key: string]: string | string[] }; Page?: number | undefined; PageSize?: number | undefined; }): Promise<components['schemas']['CaseMap.Modules.Reports.Response.ReportCellResponse'][][]> { const logic = async () => { const reportRun = await c1request<components['schemas']['CaseMap.Modules.Reports.Response.ReportResultResponse']>({ type: 'post', url: '/api/Reports/Run', body: { ReportMetadataId: params.ReportMetadataId }, }); const possibleFilters = reportRun.Filters ?? []; const requestFilters = Object.entries(params.Filters ?? []); const fullFilters = requestFilters.map((filter) => { const filterData = possibleFilters.find((pFilter) => pFilter.Name === filter[0]); if (!filterData) { throw `$.ReportsGet.reportData(reportRun)(filterData) - no filter found by name - ${filter[0]}`; } if (filterData.Type === 'Date') { return { BeginValue: filter[1][0], EndValue: filter[1][1], ReportFieldId: filterData.Id, }; } else { return { SearchValues: filter[1], ReportFieldId: filterData.Id, }; } }); return c1request<components['schemas']['CaseMap.Modules.Reports.Response.ReportCellResponse'][][]>({ type: 'post', url: '/api/Reports/GetFixedReportData', body: Object.assign({ PageSize: 100 }, params ? Object.assign(params, { Filters: fullFilters }) : {}), }); }; return LogAction('$.reportsGet.reportData', logic); }