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
f8461716118cd40c40343e5930fd16ae2f15c7f6
TypeScript
telega/mpxl
/src/components/MPXLTools.ts
2.984375
3
import { MPXLSketch } from './P5Sketch'; import { Store, ToolType } from '../stores/store'; const marchingAntsOffset = 0.5; /** Class for displaying various plugin-accessible tools using store data */ export class MPXLTools { public p: MPXLSketch; public store: Store; constructor(store: Store) { this.store = store; } /** initialise the class so it can act on the p5 sketch * @param p - the sketch */ public init(p: MPXLSketch) { this.p = p; } /** indicates a single point */ private drawToolPoint = () => { const { p, store } = this; p.noFill(); p.drawingContext.setLineDash([]); p.stroke('white'); p.ellipse(store.point.x, store.point.y, 3, 3); p.drawingContext.setLineDash([4, 4]); p.drawingContext.lineDashOffset += marchingAntsOffset; p.stroke('black'); p.ellipse(store.point.x, store.point.y, 3, 3); }; /** indicates a rectangle */ private drawToolSquare = () => { const { p, store } = this; p.rectMode(p.CORNERS); p.noFill(); p.drawingContext.setLineDash([]); p.stroke('white'); p.rect(store.point.x, store.point.y, store.endPoint.x, store.endPoint.y); p.drawingContext.setLineDash([4, 4]); p.drawingContext.lineDashOffset += marchingAntsOffset; p.stroke('black'); p.rect(store.point.x, store.point.y, store.endPoint.x, store.endPoint.y); p.rectMode(p.CORNER); }; /** indicates a circle */ private drawToolCircle = () => { const { p, store } = this; p.noFill(); p.drawingContext.setLineDash([]); p.stroke('white'); p.ellipse( store.point.x, store.point.y, 2 * store.distance, 2 * store.distance ); p.drawingContext.setLineDash([4, 4]); p.drawingContext.lineDashOffset += marchingAntsOffset; p.stroke('black'); p.ellipse( store.point.x, store.point.y, 2 * store.distance, 2 * store.distance ); }; /** indicates a line */ private drawToolLine = () => { const { p, store } = this; p.noFill(); p.drawingContext.setLineDash([]); p.stroke('white'); p.line(store.point.x, store.point.y, store.endPoint.x, store.endPoint.y); p.drawingContext.setLineDash([4, 4]); p.drawingContext.lineDashOffset = marchingAntsOffset; p.stroke('black'); p.line(store.point.x, store.point.y, store.endPoint.x, store.endPoint.y); }; /** Used in the draw loop to show the selected tool */ public drawToolArea = () => { const { store } = this; if (!store.imageLoaded) { return false; } if (!store.selectedTool) { return false; } switch (store.selectedTool) { case ToolType.Point: this.drawToolPoint(); break; case ToolType.Square: this.drawToolSquare(); break; case ToolType.Line: this.drawToolLine(); break; case ToolType.Circle: this.drawToolCircle(); break; default: return false; } return false; }; }
66f2039e689f95b477bbfc940475c37ed97124dc
TypeScript
SethDavenport/webpack-angularjs-demo
/src/utils/inject.decorator.ts
2.890625
3
/** * Convenience function for setting $inject on a class. */ export default function Inject(...injectableNames: string[]): ClassDecorator { return function decorate(constructor: Function): void { constructor.$inject = injectableNames; } }
42363d7332bb1e320caed83cc046d27254a7dc93
TypeScript
kaisalmon/proceduralPuzzle
/main/orbPuzzleGenerator.ts
2.953125
3
import {OrbPuzzle, Orb, Tile, OrbMove} from './orbPuzzle' import {tryUntilSuccess, localFetch} from './lib'; export interface puzzleConfig { seed?:number, size: number; fragile: boolean; orbs: number; pits: boolean; crystal: boolean; bombs: boolean; portals: boolean; depth: number; mindepth: number; decoy_pits: boolean; decoy_orbs: boolean; decoy_bombs: boolean; decoy_portals: boolean; brick_density: number; fragile_brick_density: number; pit_density: number; } interface OrbPuzzleJson{ grid: string[][]; orbs: any[], "criticalTiles":any[]; "use_crystals"?:boolean; "use_pits"?:boolean; "use_portals"?:boolean; "use_fragile"?:boolean; "no_basic"?:boolean; "width":number; "height":number; } export async function load_level_from_file(fn: string): Promise<[OrbPuzzle[], OrbMove[]]>{ let json = await localFetch("levels/"+fn); let level = await from_json(json, true); return level } let level_index:{[l:string]:any, default:any}|null = null; export async function createLevel(args:{level: number|string, seed?:number}): Promise<[OrbPuzzle[], OrbMove[]]|undefined>{ let stack:[OrbPuzzle[], OrbMove[]]|undefined = undefined; let {level, seed} = args; if(level_index === null){ level_index = await localFetch("levels/level_index.json"); if(!level_index){ throw "Couldn't load level index"; } } let level_data; if(typeof level === "number"){ for(var i = 0; i<20; i++){ level_data = level_index[level] if(level_data === undefined){ level--; } } }else{ level_data = level_index[level]; } if(level_data === undefined){ throw "Level not found" } if(level_data.fn){ stack = await load_level_from_file(level_data.fn); }else{ level_data = Object.assign({},level_index.default, level_data) level_data.seed = seed; stack = await tryUntilSuccess(createOrbPuzzle, level_data, true, 100); if(!stack){return} } return stack; } export async function from_json(json:OrbPuzzleJson, solve:boolean = true, maxDepth?:number): Promise<[OrbPuzzle[], OrbMove[]]>{ let o = new OrbPuzzle(json.width, json.height); for(var i = 0; i< json.grid.length; i++){ for(var j = 0; j< json.grid[0].length; j++){ o.grid[i][j] = json.grid[i][j] as Tile; } } for(let orb of json.orbs){ o.orbs.push(new Orb(orb.x, orb.y)); } if(solve){ let s = await o.solve(maxDepth); if(s === null){ throw "Unsolvable"; } return [s[0] as OrbPuzzle[], s[1]] }else{ return [[o], []] } } export async function createOrbPuzzle(args:puzzleConfig): Promise<[OrbPuzzle[], OrbMove[]]> { try{ let p = new OrbPuzzle(args.size, args.size, args.seed) for (let i = 0; i < p.width * p.height / 100 * args.fragile_brick_density; i++) { let x = p.randInt(0, p.width); let y = p.randInt(0, p.height); p.grid[x][y] = Tile.Fragile; } for (let i = 0; i < p.width * p.height / 100 * args.brick_density; i++) { let x = p.randInt(0, p.width); let y = p.randInt(0, p.height); p.grid[x][y] = Tile.Brick; } if(args.decoy_pits){ for (let i = 0; i < p.width * p.height / 100 * args.pit_density; i++) { let x = p.randInt(0, p.width); let y = p.randInt(0, p.height); p.grid[x][y] = Tile.Pit; } } let bomb_density = 3; if(args.decoy_bombs){ for (let i = 0; i < p.width * p.height / 100 * bomb_density; i++) { let x = p.randInt(0, p.width); let y = p.randInt(0, p.height); p.grid[x][y] = Tile.Bomb; } } if(args.decoy_portals){ for (let i = 0; i < 2; i++) { let x = p.randInt(0, p.width); let y = p.randInt(0, p.height); p.grid[x][y] = Tile.Portal; } } if(args.decoy_orbs){ let x = p.randInt(0, p.width); let y = p.randInt(0, p.height); p.grid[x][y] = Tile.Empty; let o = new Orb(x, y); o.decoy = true; p.orbs.push(o) } for (let i = 0; i < args.orbs; i++) { let x = p.randInt(0, p.width); let y = p.randInt(0, p.height); p.grid[x][y] = Tile.Target p.orbs.push(new Orb(x, y)) } p.use_fragile = args.fragile; p.use_crystals = args.crystal; p.use_pits = args.pits; p.use_bombs = args.bombs; p.use_portals = args.portals; let stack = p.getStack(args.depth) //var t0 = performance.now(); let solutionResult = await stack[0][0].solve(args.depth); //var t1 = performance.now(); //alert("Call to solve took " + (t1 - t0)/1000 + "seconds.") if(!solutionResult){ throw "Couldn't solve"; } let solutionStates = solutionResult[0]; console.log(">>>>>>\n",p.toString()); let fastestSolvedState = solutionStates[solutionStates.length - 1] as OrbPuzzle; if(fastestSolvedState){ if(!args.decoy_bombs){ if (fastestSolvedState.grid.some(line => line.some(tile => tile == Tile.Bomb))) { throw "Unused Bombs" } } } let solution:OrbMove[]; solution = solutionResult[1] if (!solution || solution.length < args.mindepth - 1) { console.error("too short", solution.length, args.mindepth); throw "too short " } if(new Set(solution).size === 1 && solution.length > 1){ throw "Only one move type" } let board: OrbPuzzle = stack[0][0] as OrbPuzzle; if (args.crystal && !board.grid.some(line => line.some(tile => tile == Tile.Crystal))) { throw "No crystals" } if(board.orbs.some(o => o.reversed_move_count === 0)){ throw "At least one orb did not move"; } if(args.depth > 2){ if (args.pits && !board.grid.some(line => line.some(tile => tile == Tile.Pit))) { throw "No Pits" } if (p.use_bombs && !board.grid.some(line => line.some(tile => tile == Tile.Bomb))) { throw "No Bombs" } if ((p.use_portals || args.decoy_portals) && !board.grid.some(line => line.some(tile => tile == Tile.Portal))) { throw "No Portals" } if (p.use_portals && fastestSolvedState.grid.some(line => line.some(tile => tile == Tile.Portal))) { throw "Unused Portals after fasted solution" } if (args.pits && !stack[1].some((m => [OrbMove.DownPit, OrbMove.UpPit, OrbMove.LeftPit, OrbMove.RightPit].indexOf(m) !== -1))) { throw "No Pit USED in solution" } if (p.use_bombs && !stack[1].some((m => [OrbMove.DownBomb, OrbMove.UpBomb, OrbMove.LeftBomb, OrbMove.RightBomb].indexOf(m) !== -1))) { throw "No Bombs" } } return [solutionStates as OrbPuzzle[], solution] }catch(e){ if(args.seed) args.seed++; throw e; } }
01979d134c7da6b9948d539284cf6f6f9054f8eb
TypeScript
rociornav/dwec_2021
/Unidad 8/u8t3-DelRealRocio/src/app/generic-table/generic-table.component.ts
2.515625
3
import { Component, OnInit, Input } from '@angular/core'; import Utils from '../utils.component'; import { Ciclo } from './../interfaces'; @Component({ selector: 'app-generic-table', templateUrl: './generic-table.component.html', styleUrls: ['./generic-table.component.sass'] }) export class GenericTableComponent implements OnInit { @Input() data: Array<Ciclo>; @Input() filters: Object; constructor() { } //observable para crear tabla filteredData: Array<Ciclo> = []; provincias: Object = Utils.provincias; displayedColumns: string[] = [ 'centro', 'nombre_ciclo', 'tipo', 'turno', 'bilingue', 'dual' ]; ngOnInit(): void { console.log("Soy la supuesta tabla y tengo estos datos: "); console.log(this.data); console.log(this.filters); this.filtrarDatos(); // (window as any).filters = this.filters; para comprobar la actualizacion de los filtros. } filtrarDatos() { this.data.map((dato) => { const entra = []; Object.keys(this.filters).map((key) => { let dataToCheck = ''; if (key == "centro.codigo_provincia") { dataToCheck = dato.centro.codigo_provincia; } else { dataToCheck = dato[key]; } if (key == 'turno' && this.filters[key] == 'Ambos') dataToCheck = 'Ambos'; entra.push(this.filters[key] == '' || this.filters[key] == dataToCheck); }) // entra.push(this.filters['familia'] == '' || this.filters['familia'] == dato.familia); // entra.push(this.filters['nombre_ciclo'] == '' || this.filters['nombre_ciclo'] == dato.nombre_ciclo); // entra.push(this.filters['centro.codigo_provincia'] == '' || this.filters['centro.codigo_provincia'] == dato.centro.codigo_provincia); // entra.push(this.filters['tipo'] == '' || this.filters['tipo'] == dato.tipo); // entra.push(this.filters['turno'] == '' || this.filters['turno'] == dato.turno); // entra.push(this.filters['bilingue'] == '' || this.filters['bilingue'] == dato.bilingue); // entra.push(this.filters['dual'] == '' || this.filters['dual'] == dato.dual); if (entra.filter((si) => si == false).length == 0) this.filteredData.push(dato); }); console.warn(this.filteredData); } // filterValues = { // 'familia': '', // 'nombre_ciclo': '', // 'centro.codigo_provincia': '', // 'tipo': '', // 'turno': '', // 'bilingue': '', // 'dual': '' // }; }
2a7f57e9231d5a36e9e1876114471fbd9e893065
TypeScript
def-codes/the-better-thing
/packages/meld-demo/extend.ts
2.734375
3
import { datafy_protocol } from "@def.codes/datafy-nav"; datafy_protocol.extend("@imaginary", imaginary => { console.log("My beloved", imaginary); }); // Reify primitives const PRIMITIVE: PropertyDescriptorMap = { "@context": { // Not sure if I want to see this // enumerable: true, value: { rdf: "http://rdf..syntax", xsd: "http://xml/schema", value: "rdf:value", }, }, }; for (const [type, Protocol] of Object.entries({ "xsd:boolean": Boolean, "xsd:double": Number, "xsd:string": String, })) datafy_protocol.extend(Protocol, value => Object.assign(Object.create(PRIMITIVE), { "@type": type, value }) ); // Anyway, can we do this automatically if these are built-ins? const EVENT_PROTOTYPE = { "@type": "browser:Event" }; const KEYBOARD_EVENT_PROTOTYPE = { // In normal practice, if these are subclasses, only most specific will be listed "@type": ["browser:KeyboardEvent", "browser:Event"], }; const MOUSE_EVENT_PROTOTYPE = { // In normal practice, if these are subclasses, only most specific will be listed "@type": ["browser:MouseEvent", "browser:Event"], }; const DRAG_EVENT_PROTOTYPE = { // In normal practice, if these are subclasses, only most specific will be listed "@type": ["browser:DragEvent", "browser:MouseEvent", "browser:Event"], }; const DATA_TRANSFER_PROTOTYPE = { "@type": "browser:DataTransfer" }; const DATA_TRANSFER_ITEM_LIST_PROTOTYPE = { "@type": "browser:DataTransferItemList", }; const DATA_TRANSFER_ITEM_PROTOTYPE = { "@type": "browser:DataTransferItem" }; datafy_protocol.extend(Event, event => Object.assign(Object.create(EVENT_PROTOTYPE), { bubbles: event.bubbles, cancelable: event.cancelable, composed: event.composed, }) ); datafy_protocol.extend(KeyboardEvent, event => Object.assign(Object.create(MOUSE_EVENT_PROTOTYPE), { key: event.key, shift: event.shiftKey, ctrl: event.ctrlKey, alt: event.altKey, meta: event.metaKey, }) ); datafy_protocol.extend(MouseEvent, event => Object.assign(Object.create(MOUSE_EVENT_PROTOTYPE), { x: event.clientX, y: event.clientY, }) ); datafy_protocol.extend(DragEvent, event => Object.assign(Object.create(DRAG_EVENT_PROTOTYPE), { dataTransfer: event.dataTransfer, }) ); datafy_protocol.extend(DataTransfer, transfer => Object.assign(Object.create(DATA_TRANSFER_PROTOTYPE), { // So is it your job to datafy here? [`co:hasPart`]: transfer.items, [`co:hasType`]: transfer.types, }) ); datafy_protocol.extend(DataTransferItemList, list => Object.assign(Object.create(DATA_TRANSFER_ITEM_LIST_PROTOTYPE), { [`co:count`]: list.length, }) ); datafy_protocol.extend(DataTransferItem, item => Object.assign(Object.create(DATA_TRANSFER_ITEM_PROTOTYPE), { // Kind versus type? [`kind`]: item.kind, [`type`]: item.type, }) ); export const hello = "world";
7047bbf6e965e9ce14aff6d610114a6254f4e840
TypeScript
AugustoDeveloper/maav
/src/maav.app/src/app/shared/models/user/role.model.ts
2.71875
3
export class Role { private internalRoleName: string = ''; public teamId: string; public get name(): string { return this.internalRoleName; } constructor(roleName: string) { this.internalRoleName = roleName; } public static user: Role = new Role("user"); public static admin: Role = new Role("admin"); public static teamLeader: Role = new Role("team-leader"); public static developer: Role = new Role("developer"); public static integration: Role = new Role("integration"); }
1e49dfd28e8fdb4c693f830aad08d3afcb84d594
TypeScript
canalplus/rx-player
/src/parsers/manifest/utils/update_segment_timeline.ts
2.59375
3
/** * Copyright 2015 CANAL+ Group * * 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 { MediaError } from "../../../errors"; import log from "../../../log"; import { getIndexSegmentEnd, IIndexSegment, } from "./index_helpers"; /** * Update a complete array of segments in a given timeline with a [generally] * smaller but [generally] newer set of segments. * * Returns a boolean: * - If set to `true`, the old timeline was emptied and completely replaced by * the content of the newer timeline. * This could happen either if a problem happened while trying to update or * when the update is actually bigger than what it is updating. * - If set to `false`, the older timeline was either updated to add the newer * segments, or untouched. * * @param {Array.<Object>} oldTimeline * @param {Array.<Object>} newTimeline * @returns {boolean} */ export default function updateSegmentTimeline( oldTimeline : IIndexSegment[], newTimeline : IIndexSegment[] ) : boolean { if (oldTimeline.length === 0) { oldTimeline.push(...newTimeline); return true; } else if (newTimeline.length === 0) { return false; } const prevTimelineLength = oldTimeline.length; const newIndexStart = newTimeline[0].start; const oldLastElt = oldTimeline[prevTimelineLength - 1]; const oldIndexEnd = getIndexSegmentEnd(oldLastElt, newTimeline[0]); if (oldIndexEnd < newIndexStart) { throw new MediaError("MANIFEST_UPDATE_ERROR", "Cannot perform partial update: not enough data"); } for (let i = prevTimelineLength - 1; i >= 0; i--) { const currStart = oldTimeline[i].start; if (currStart === newIndexStart) { // replace that one and those after it const nbEltsToRemove = prevTimelineLength - i; oldTimeline.splice(i, nbEltsToRemove, ...newTimeline); return false; } else if (currStart < newIndexStart) { // first to be before const currElt = oldTimeline[i]; if (currElt.start + currElt.duration > newIndexStart) { // The new Manifest overlaps a previous segment (weird) // In that improbable case, we'll just completely replace segments log.warn("RepresentationIndex: Manifest update removed all previous segments"); oldTimeline.splice(0, prevTimelineLength, ...newTimeline); return true; } else if (currElt.repeatCount === undefined || currElt.repeatCount <= 0) { if (currElt.repeatCount < 0) { currElt.repeatCount = Math.floor((newIndexStart - currElt.start) / currElt.duration) - 1; } oldTimeline.splice(i + 1, prevTimelineLength - (i + 1), ...newTimeline); return false; } // else, there is a positive repeat we might want to update const eltLastTime = currElt.start + currElt.duration * (currElt.repeatCount + 1); if (eltLastTime <= newIndexStart) { // our new index comes directly after // put it after this one oldTimeline.splice(i + 1, prevTimelineLength - (i + 1), ...newTimeline); return false; } const newCurrRepeat = ((newIndexStart - currElt.start) / currElt.duration) - 1; if (newCurrRepeat % 1 === 0 && currElt.duration === newTimeline[0].duration) { const newRepeatCount = newTimeline[0].repeatCount < 0 ? -1 : // === maximum possible repeat newTimeline[0].repeatCount + newCurrRepeat + 1; // replace that one and those after it oldTimeline.splice(i, prevTimelineLength - i, ...newTimeline); oldTimeline[i].start = currElt.start; oldTimeline[i].repeatCount = newRepeatCount; return false; } log.warn("RepresentationIndex: Manifest update removed previous segments"); oldTimeline[i].repeatCount = Math.floor(newCurrRepeat); // put it after this one oldTimeline.splice(i + 1, prevTimelineLength - (i + 1), ...newTimeline); return false; } } // if we got here, it means that every segments in the previous manifest are // after the new one. This is unusual. // Either the new one has more depth or it's an older one. const prevLastElt = oldTimeline[oldTimeline.length - 1]; const newLastElt = newTimeline[newTimeline.length - 1]; if (prevLastElt.repeatCount !== undefined && prevLastElt.repeatCount < 0) { if (prevLastElt.start > newLastElt.start) { log.warn("RepresentationIndex: The new index is older than the previous one"); return false; } else { // the new has more depth log.warn("RepresentationIndex: The new index is \"bigger\" than the previous one"); oldTimeline.splice(0, prevTimelineLength, ...newTimeline); return true; } } const prevLastTime = prevLastElt.start + prevLastElt.duration * (prevLastElt.repeatCount + 1); const newLastTime = newLastElt.start + newLastElt.duration * (newLastElt.repeatCount + 1); if (prevLastTime >= newLastTime) { log.warn("RepresentationIndex: The new index is older than the previous one"); return false; } // the new one has more depth. full update log.warn("RepresentationIndex: The new index is \"bigger\" than the previous one"); oldTimeline.splice(0, prevTimelineLength, ...newTimeline); return true; }
d6f8211e872c31b6c4786f2ea71dbe78ab44f15e
TypeScript
brehaut/arachne
/src/ts/common/chord.ts
3.03125
3
import { Note } from "./notes"; import { Scale, ScaleSeries } from "./scales"; import { cycleGet } from "./array"; export type Degree = 1 | 2 | 3 | 4 | 5 | 6 | 7; export type Chord = { root: Note, tones: Note[] } function newChord(tones: Note[]):Chord { return { root: tones[0], tones: tones } } export function triad(scale: Scale, degree: Degree): Chord { return chord(scale, degree, [1,3,5]); } export function chord(scale: Scale, degree: Degree, intervals: Degree[]): Chord { const rootIndex = degree - 1; const intervalsOffsets = intervals.map(d => d - 1); return newChord(intervalsOffsets.map(degreeOffset => cycleGet(scale, rootIndex + degreeOffset))); }
a92fa4160fe2d830a454c29d401c9050989f0ecb
TypeScript
jovotech/jovo-framework
/common/src/Input.ts
2.609375
3
import { EnumLike, UnknownObject } from '.'; export interface Intent { name: string; global?: boolean; } export interface Entity { id?: string; resolved?: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any value?: any; // eslint-disable-next-line @typescript-eslint/no-explicit-any native?: any; // raw API response from the NLU service } export interface EntityMap<ENTITY_TYPE extends Entity = Entity> { [key: string]: ENTITY_TYPE | undefined; } export interface AsrData extends UnknownObject { text?: string; } export interface NluData extends UnknownObject { intent?: Intent | string; entities?: EntityMap; // eslint-disable-next-line @typescript-eslint/no-explicit-any native?: any; // raw API response from the NLU service } export enum InputType { Launch = 'LAUNCH', End = 'END', Error = 'ERROR', Intent = 'INTENT', Text = 'TEXT', TranscribedSpeech = 'TRANSCRIBED_SPEECH', Speech = 'SPEECH', } export type InputTypeLike = EnumLike<InputType> | string; export interface AudioInput { base64: string; sampleRate: number; } export interface Input { type?: InputTypeLike; text?: string; audio?: AudioInput; asr?: AsrData; nlu?: NluData; intent?: Intent | string; entities?: EntityMap; }
95af2df30c2460b616136e703978361ca87016ab
TypeScript
adobe/react-spectrum
/packages/@react-stately/table/src/TableUtils.ts
3.140625
3
/* * Copyright 2022 Adobe. All rights reserved. * This file is licensed to you 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 REPRESENTATIONS * OF ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ import {ColumnSize} from '@react-types/table'; import {Key} from 'react'; // numbers and percents are considered static. *fr units or a lack of units are considered dynamic. export function isStatic(width: number | string): boolean { return width != null && (!isNaN(width as number) || (String(width)).match(/^(\d+)(?=%$)/) !== null); } export function parseFractionalUnit(width: string): number { if (!width) { return 1; } let match = width.match(/^(.+)(?=fr$)/); // if width is the incorrect format, just default it to a 1fr if (!match) { console.warn(`width: ${width} is not a supported format, width should be a number (ex. 150), percentage (ex. '50%') or fr unit (ex. '2fr')`, 'defaulting to \'1fr\''); return 1; } return parseFloat(match[0]); } export function parseStaticWidth(width: number | string, tableWidth: number): number { if (typeof width === 'string') { let match = width.match(/^(\d+)(?=%$)/); if (!match) { throw new Error('Only percentages or numbers are supported for static column widths'); } return tableWidth * (parseFloat(match[0]) / 100); } return width; } export function getMaxWidth(maxWidth: number | string, tableWidth: number): number { return maxWidth != null ? parseStaticWidth(maxWidth, tableWidth) : Number.MAX_SAFE_INTEGER; } // cannot support FR units, we'd need to know everything else in the table to do that export function getMinWidth(minWidth: number | string, tableWidth: number): number { return minWidth != null ? parseStaticWidth(minWidth, tableWidth) : 0; } export interface IColumn { minWidth?: number | string, maxWidth?: number | string, width?: number | string, defaultWidth?: number | string, key?: Key } /** * Implements the flex algorithm described in https://www.w3.org/TR/css-flexbox-1/#layout-algorithm * It makes a few constraint/assumptions: * 1. All basis values are 0 unless it is a static width, then the basis is the static width * 2. All flex grow and shrink values are equal to the FR specified on the column, grow and shrink for the same column are equal * 3. We only have one row * An example of the setup can be seen here https://jsfiddle.net/snowystinger/wv0ymjaf/61/ where I let the browser figure out the * flex of the columns. * Note: We differ in one key aspect, all of our column widths must be whole numbers, so we avoid browser * sub pixel rounding errors. To do this, we use a cascading rounding algorithm to ensure that the sum of the widths is maintained * while distributing the rounding remainder across the columns. * * As noted in the chrome source code, this algorithm is very accurate, but has the potential to be quadratic. * They have deemed this to be acceptable because the number of elements is usually small and the flex factors * are usually not high variance. I believe we can make the same assumptions. Particularly once resizing is * started, it will convert all columns to the left to static widths, so it will cut down on the number of FR columns. * * There are likely faster ways to do this, I've chosen to stick to the spec as closely as possible for readability, accuracy, and for the * note that this behaving quadratically is unlikely to be a problem. * @param availableWidth - The visible width of the table. * @param columns - The table defined columns. * @param changedColumns - Any columns we want to override, for example, during resizing. * @param getDefaultWidth - A function that returns the default width of a column by its index. * @param getDefaultMinWidth - A function that returns the default min width of a column by its index. */ export function calculateColumnSizes(availableWidth: number, columns: IColumn[], changedColumns: Map<Key, ColumnSize>, getDefaultWidth, getDefaultMinWidth) { let hasNonFrozenItems = false; let flexItems = columns.map((column, index) => { let width = changedColumns.get(column.key) != null ? changedColumns.get(column.key) : column.width ?? column.defaultWidth ?? getDefaultWidth?.(index) ?? '1fr'; let frozen = false; let baseSize = 0; let flex = 0; let targetMainSize = null; if (isStatic(width)) { baseSize = parseStaticWidth(width, availableWidth); frozen = true; } else { flex = parseFractionalUnit(width); if (flex <= 0) { frozen = true; } } let min = getMinWidth(column.minWidth ?? getDefaultMinWidth?.(index) ?? 0, availableWidth); let max = getMaxWidth(column.maxWidth, availableWidth); let hypotheticalMainSize = Math.max(min, Math.min(baseSize, max)); // 9.7.1 // We don't make use of flex basis, it's always 0, so we are always in 'grow' mode. // 9.7.2 if (frozen) { targetMainSize = hypotheticalMainSize; } else if (baseSize > hypotheticalMainSize) { frozen = true; targetMainSize = hypotheticalMainSize; } // 9.7.3 if (!frozen) { hasNonFrozenItems = true; } return { frozen, baseSize, hypotheticalMainSize, min, max, flex, targetMainSize, violation: 0 }; }); // 9.7.4 // 9.7.4.a while (hasNonFrozenItems) { // 9.7.4.b /** * Calculate the remaining free space as for initial free space, * above (9.7.3). If the sum of the unfrozen flex items’ flex factors is * less than one, multiply the initial free space by this sum (of flex factors). * If the magnitude of this value is less than the magnitude of * the remaining free space, use this as the remaining free space. */ let usedWidth = 0; let flexFactors = 0; flexItems.forEach(item => { if (item.frozen) { usedWidth += item.targetMainSize; } else { usedWidth += item.baseSize; flexFactors += item.flex; } }); let remainingFreeSpace = availableWidth - usedWidth; // we only support integer FR's, and because of hasNonFrozenItems, we know that flexFactors > 0 // so no need to check for flexFactors < 1 // 9.7.4.c /** * If the remaining free space is zero * - Do nothing. * Else // remember, we're always in grow mode * - Find the ratio of the item’s flex grow factor to the * sum of the flex grow factors of all unfrozen items on * the line. Set the item’s target main size to its flex * base size plus a fraction of the remaining free space * proportional to the ratio. */ if (remainingFreeSpace > 0) { flexItems.forEach((item) => { if (!item.frozen) { let ratio = item.flex / flexFactors; item.targetMainSize = item.baseSize + (ratio * remainingFreeSpace); } }); } // 9.7.4.d /** * Fix min/max violations. Clamp each non-frozen item’s * target main size by its used min and max main sizes * and floor its content-box size at zero. If the item’s * target main size was made smaller by this, it’s a max * violation. If the item’s target main size was made * larger by this, it’s a min violation. */ let totalViolation = 0; flexItems.forEach(item => { item.violation = 0; if (!item.frozen) { let {min, max, targetMainSize} = item; item.targetMainSize = Math.max(min, Math.min(targetMainSize, max)); item.violation = item.targetMainSize - targetMainSize; totalViolation += item.violation; } }); // 9.7.4.e /** * Freeze over-flexed items. The total violation is the * sum of the adjustments from the previous step * ∑(clamped size - unclamped size). If the total violation is: * Zero * - Freeze all items. * * Positive * - Freeze all the items with min violations. * * Negative * - Freeze all the items with max violations. */ hasNonFrozenItems = false; flexItems.forEach(item => { if (totalViolation === 0 || Math.sign(totalViolation) === Math.sign(item.violation)) { item.frozen = true; } else if (!item.frozen) { hasNonFrozenItems = true; } }); } return cascadeRounding(flexItems); } function cascadeRounding(flexItems): number[] { /* Given an array of floats that sum to an integer, this rounds the floats and returns an array of integers with the same sum. */ let fpTotal = 0; let intTotal = 0; let roundedArray = []; flexItems.forEach(function (item) { let float = item.targetMainSize; let integer = Math.round(float + fpTotal) - intTotal; fpTotal += float; intTotal += integer; roundedArray.push(integer); }); return roundedArray; }
c5ac8e4076c00f4c95881c85dd77e6c04ccd38b9
TypeScript
anmartin114/Gear.it
/src/app/services/packing-list.service.ts
2.65625
3
import { Injectable } from "@angular/core"; import { PackingList } from "../interfaces/packing-list"; import { Subject } from "rxjs"; @Injectable({ providedIn: "root" }) export class PackingListService { private subject = new Subject<any>(); listItems: PackingList[] = [ { item: "Toiletries", complete: false }, { item: "Wallet/ID", complete: false }, { item: "Phone Charger", complete: false } ]; added: boolean = false; newItem: PackingList = { item: "", complete: false }; newItemText: string = ""; addItem() { this.listItems = [ ...this.listItems, { item: this.newItemText, complete: false } ]; this.sendMessageAdd(); } completeItem(item: PackingList): void { item.complete = !item.complete; } delete(item: PackingList): void { this.listItems = this.listItems.filter(x => x !== item); console.log(this.listItems); this.sendMessageAdd(); } // addItemFromGear(item){ // this.listItems = [ // ...this.listItems, // { item: } // ] // } setCustomWords(item) { this.newItemText = item; } getList() { console.log(this.listItems); return this.listItems; } sendMessageAdd() { this.subject.next(this.listItems.length); return this.subject.asObservable(); } sendMessageDelete() { this.subject.next("subtract counter"); } getMessage() { return this.subject.asObservable(); } constructor() {} }
96e44d86b737c9ddf35fe569c0edc172295632a1
TypeScript
AlecAivazis/graphql-ws-client
/src/message.ts
3.234375
3
/** * * message * */ import type { GraphQLError, ExecutionResult } from 'graphql'; import { ID } from './types'; import { isObject, areGraphQLErrors, hasOwnProperty, hasOwnObjectProperty, hasOwnStringProperty, } from './utils'; /** Types of messages allowed to be sent by the client/server over the WS protocol. */ export enum MessageType { ConnectionInit = 'connection_init', // Client -> Server ConnectionAck = 'connection_ack', // Server -> Client Subscribe = 'subscribe', // Client -> Server Next = 'next', // Server -> Client Error = 'error', // Server -> Client Complete = 'complete', // bidirectional } export interface ConnectionInitMessage { readonly type: MessageType.ConnectionInit; readonly payload?: Record<string, unknown>; } export interface ConnectionAckMessage { readonly type: MessageType.ConnectionAck; readonly payload?: Record<string, unknown>; } export interface SubscribeMessage { readonly id: ID; readonly type: MessageType.Subscribe; readonly payload: SubscribePayload; } export interface SubscribePayload { readonly operationName?: string | null; readonly query: string; readonly variables?: Record<string, unknown> | null; } export interface NextMessage { readonly id: ID; readonly type: MessageType.Next; readonly payload: ExecutionResult; } export interface ErrorMessage { readonly id: ID; readonly type: MessageType.Error; readonly payload: readonly GraphQLError[]; } export interface CompleteMessage { readonly id: ID; readonly type: MessageType.Complete; } export type Message< T extends MessageType = MessageType > = T extends MessageType.ConnectionAck ? ConnectionAckMessage : T extends MessageType.ConnectionInit ? ConnectionInitMessage : T extends MessageType.Subscribe ? SubscribeMessage : T extends MessageType.Next ? NextMessage : T extends MessageType.Error ? ErrorMessage : T extends MessageType.Complete ? CompleteMessage : never; /** Checks if the provided value is a message. */ export function isMessage(val: unknown): val is Message { if (isObject(val)) { // all messages must have the `type` prop if (!hasOwnStringProperty(val, 'type')) { return false; } // validate other properties depending on the `type` switch (val.type) { case MessageType.ConnectionInit: // the connection init message can have optional payload object return ( !hasOwnProperty(val, 'payload') || val.payload === undefined || isObject(val.payload) ); case MessageType.ConnectionAck: // the connection ack message can have optional payload object too return ( !hasOwnProperty(val, 'payload') || val.payload === undefined || isObject(val.payload) ); case MessageType.Subscribe: return ( hasOwnStringProperty(val, 'id') && hasOwnObjectProperty(val, 'payload') && (!hasOwnProperty(val.payload, 'operationName') || val.payload.operationName === undefined || val.payload.operationName === null || typeof val.payload.operationName === 'string') && hasOwnStringProperty(val.payload, 'query') && (!hasOwnProperty(val.payload, 'variables') || val.payload.variables === undefined || val.payload.variables === null || hasOwnObjectProperty(val.payload, 'variables')) ); case MessageType.Next: return ( hasOwnStringProperty(val, 'id') && hasOwnObjectProperty(val, 'payload') ); case MessageType.Error: return hasOwnStringProperty(val, 'id') && areGraphQLErrors(val.payload); case MessageType.Complete: return hasOwnStringProperty(val, 'id'); default: return false; } } return false; } /** Parses the raw websocket message data to a valid message. */ export function parseMessage(data: unknown): Message { if (isMessage(data)) { return data; } if (typeof data !== 'string') { throw new Error('Message not parsable'); } const message = JSON.parse(data); if (!isMessage(message)) { throw new Error('Invalid message'); } return message; } /** Stringifies a valid message ready to be sent through the socket. */ export function stringifyMessage<T extends MessageType>( msg: Message<T>, ): string { if (!isMessage(msg)) { throw new Error('Cannot stringify invalid message'); } return JSON.stringify(msg); }
c4123a7c918647fad252bd1b699e6f0b0206a4cb
TypeScript
sneakwolf777/CS465pFall2019-InClassAssignments
/assignment#6/typescript-tutorial/app3.ts
3.6875
4
const numbers = [12,23,62,34,19,40,4,9]; console.log(numbers.filter(function(n: number){ return n > 30; })); // Or use shorthand function notation. // (Also called arrow function) console.log( numbers.filter(n => n > 30) );
4f39fb142caa16dc8703ec0ac7839e0452926ddb
TypeScript
Flamdoodle/angular-2-twitter-challenge
/app/like.component.ts
2.65625
3
import { Component, Input } from "angular2/core"; @Component ({ selector: "like", template: `<i class="glyphicon glyphicon-heart" [class.grey]="!isLiked" [class.pink]="isLiked" (click)=onClick()> </i> <span>{{ likes }}</span>`, styles: [` .glyphicon-heart { cursor: pointer; } .grey { color: #ccc; } .pink { color: deeppink; } `] }) export class LikesComponent { @Input("TotalLikes") likes = 0; @Input("IsLike") isLiked = false; onClick() { this.isLiked = !this.isLiked; this.likes += this.isLiked ? 1 : -1; } }
b74858e32719dc8041c6d172cead18ecff4ff401
TypeScript
Falieson/tsx-interview-prep
/src/modules/binary-tree-mode/binary-tree-mode.ts
3.765625
4
/* Find the greatest mode in the binary tree. or... find the largest most common number 4 / \ / \ 2 7 / \ / \ 1 3 3 7 The answer is 7, not 3 */ interface ILeaf { left?: ILeaf, right?: ILeaf, value: number, } export default function findBinaryTreeMaxMode(tree: ILeaf): number { let greatestMode = -Infinity let greatestCount = -Infinity const counts: {[value: string]: number} = {} function walkTree(leaf: ILeaf) { if (leaf.left) walkTree(leaf.left) if (leaf.right) walkTree(leaf.right) // set the count counts[leaf.value] = counts[leaf.value] ? counts[leaf.value] + 1 : 1 // set the new greatest count if (counts[leaf.value] > greatestCount) { greatestCount = counts[leaf.value] // set the new mode if (leaf.value > greatestMode) { greatestMode = leaf.value } } } walkTree(tree) return greatestMode }
6ad102b2ceb3b443d6a0f07ad43b7e054f39a910
TypeScript
AssemblyScript/assemblyscript
/tests/compiler/infer-type.ts
3.4375
3
const i = 10; // infers i32 because it fits into i32 as the default i; const I = 0x100000000; // infers i64 because the value doesn't fit into 32 bits I; const F = 1.5; // infers f64 because of float notation F; function locals(): void { var li = 10; var lI = 0x100000000; var lF = 1.5; var ai = i; var aI = I; var aF = F; } locals(); function reti(): i32 { return 0; } var ri = reti(); ri; function retI(): i64 { return 0; } var rI = retI(); rI; function retf(): f32 { return 0; } var rf = retf(); rf; function refF(): f64 { return 0; } var rF = refF(); rF; for (var a = 0, b = 10; a < b; ++a) { ; } var inferi = 0x80000000; // infers u32 assert(!isSigned(inferi)); var inferu = 0x7fffffff; // infers i32 assert(isSigned(inferu));
e6c9cd4a896ea4dd8c3032d3373878cf94286679
TypeScript
Maxinth/Toyora-clone-with-react
/src/features/MobileDropDown/ownersSlice.ts
2.71875
3
import { createSlice } from "@reduxjs/toolkit"; export interface ownersViewState { showOwners: boolean; } const initialState: ownersViewState = { showOwners: false, }; export const ownersSlice = createSlice({ name: "owners", initialState, reducers: { //show all owners goToAllOwners: (state) => { state.showOwners = true; }, // return to initial view from all owners view backFromAllOwners: (state) => { state.showOwners = false; }, }, }); // Action creators are generated for each case reducer function export const { goToAllOwners, backFromAllOwners } = ownersSlice.actions; export default ownersSlice.reducer;
46d34662978bc1fe82f03a5030fd2c04b7eff5e1
TypeScript
caroso1222/logo-quiz
/apps/logo-quiz/src/store/levels/types.ts
2.53125
3
import { Level } from '@logo-quiz/models'; import { AxiosError } from 'axios'; export const REQUEST_LEVELS = 'REQUEST_LEVELS'; export const REQUEST_LEVELS_SUCCESS = 'REQUEST_LEVELS_SUCCESS'; export const REQUEST_LEVELS_ERROR = 'REQUEST_LEVELS_ERROR'; export interface LevelsState { levels: Partial<Level>[]; isLoading: boolean; } interface RequestLevelsAction { type: typeof REQUEST_LEVELS; } interface RequestLevelSuccessAction { type: typeof REQUEST_LEVELS_SUCCESS; levels: Level[]; } interface RequestLevelErrorAction { type: typeof REQUEST_LEVELS_ERROR; error: AxiosError; } export type LevelsActionTypes = RequestLevelsAction | RequestLevelSuccessAction | RequestLevelErrorAction;
15b59e4c074384339ef0902e4673753424d7189f
TypeScript
ansabor/Netron
/Source/IHoverable.ts
2.59375
3
module Netron { export interface IHoverable { hover: bool; getCursor(point: Point): string; } }
b635e65f3cf9936db334909a05383bac9d7cc644
TypeScript
pidmad92/appAngular
/src/app/fruta/fruta.component.ts
3.046875
3
import { Component } from '@angular/core'; @Component({ selector: 'fruta', templateUrl: './fruta.component.html' /* Template en Linea template: `<h2>{{nombre_componente}}</h2><p>{{listado_frutas}}</p>` */ }) export class FrutaComponent{ public nombre_componente = 'Componente de fruta'; public listado_frutas = 'Naranja, Manzana, Pera y Sandia'; public stringEjemplo: string; public numeroEjemplo: number; public arrayStringEjemplo: Array<String>; public arrayAnyEjemplo: Array<any>; public booleanEjemplo: boolean; constructor(){ this.stringEjemplo = 'Ejemplo de String'; this.numeroEjemplo = 25; this.arrayStringEjemplo = ['String1', 'String2']; this.arrayAnyEjemplo = ['String1', 2]; this.booleanEjemplo = true; } ngOnInit() { this.funcionEjemplo(); this.funcionEjemplo2(100); alert('Numero Ejemplo ' + this.numeroEjemplo); console.log(this.stringEjemplo + ' ' + this.numeroEjemplo); var uno = 8; var dos = 15; if( uno === 8){ let uno = 3 var dos = 88 console.log("Dentro del IF: " + uno + " " + dos); } console.log("Fuera del IF: " + uno + " " + dos); } funcionEjemplo(){ this.nombre_componente = 'Refruta xD'; alert('Nombre Componente ' + this.nombre_componente); } funcionEjemplo2(numeroEjemplo) { this.numeroEjemplo = numeroEjemplo; } }
52e5f89ec4eba64e04496aba58bbb978cd629945
TypeScript
em2046/data-structure-0.1
/src/shared/assert.ts
3.09375
3
/*** * Reference: * https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions */ /** * @public * Assertion function. * * That throw an error if something unexpected happened. * * @param condition - Expected. * @param msg - Error message. */ export function assert(condition: boolean, msg?: string): asserts condition { if (!condition) { throw new Error(msg); } }
58a2881847c1d8cdf9a6501026d61a022696e9ac
TypeScript
badjilounes/exo1
/src/app/components/doctors/doctors.component.ts
2.75
3
import { Component, OnInit } from '@angular/core'; import { UserInterface } from 'src/model/user.interface'; import { PageEvent } from '@angular/material/paginator'; import { ListService } from 'src/app/services/list/list.service'; import { ApiService } from 'src/app/services/api/api.service'; @Component({ selector: 'app-doctors', templateUrl: './doctors.component.html', styleUrls: ['./doctors.component.scss'] }) export class DoctorsComponent implements OnInit { // Notre liste d'éléments statiques doctors: UserInterface[] = [ {id: 1, firstName: 'Pascal', lastName: 'Ladal'}, {id: 2, firstName: 'Éric', lastName: 'Judor'}, {id: 3, firstName: 'Jamel', lastName: 'Dridi'}, {id: 4, firstName: 'Ramzi', lastName: 'Bédia'}, {id: 5, firstName: 'Professeur', lastName: 'Strauss'}, {id: 6, firstName: 'Professeur', lastName: 'Test'}, {id: 7, firstName: 'Professeur', lastName: 'Lounès'}, {id: 8, firstName: 'Julien', lastName: ''}, {id: 9, firstName: 'Hichem', lastName: ''}, {id: 10, firstName: 'Franck', lastName: ''}, {id: 11, firstName: 'Alexis', lastName: ''}, {id: 12, firstName: 'Théo', lastName: ''}, {id: 13, firstName: 'Jean-Christophe', lastName: ''}, {id: 14, firstName: 'Zaïr', lastName: ''}, {id: 15, firstName: 'Khalil', lastName: ''}, {id: 16, firstName: 'Patrick', lastName: ''}, ]; displayedDoctors = []; //La liste quiest liée à la vue (celle qui est affichée) paginatorInfo: PageEvent = {pageSize: 5, pageIndex: 0, length: this.doctors.length}; //Les informations que l'on lie au paginateur constructor(private readonly listSrv: ListService, private readonly api: ApiService) {} ngOnInit() { this.api.post('doctors', {q: 'test'}).toPromise() .then(success => console.log(success), error => console.log(error)); //À l'initialisation du composant on pagine nos éléments this.displayedDoctors = this.listSrv.paginateElements<UserInterface>(this.doctors, this.paginatorInfo); } //Méthode déclenchée lorsqu'une recherche est faite dans notre composant de recherche search(query: string): void { //Si la recherche est vide on affecte tous les éléments à la liste que l'on affiche this.displayedDoctors = this.doctors; //Sinon on filtre les éléments dont le nom ou le prénom ne commence pas par la chaîne recherchée if (query !== ''){ this.displayedDoctors = this.doctors.filter((doctor) => { const len = query.length; // On récupère la taille de la chaîne recherchée const firstName = doctor.firstName.substr(0, len).toLocaleLowerCase(); // On crée une sous chaîne du prénom de la même taille que celle recherchée const lastName = doctor.lastName.substr(0, len).toLowerCase(); // Idem ave cle nom //On vérifie ensuite l'égalité des chaînes (on transforme ces chaînes en minuscule pour ne pas être sensible à la casse) const firstNameMatched = firstName === query.toLowerCase(); const lastNameMatched = lastName === query.toLowerCase(); //On conserve les éléments si la sous-chaîne créée avec le prénom ou celle créée avec le nom correspond return firstNameMatched || lastNameMatched; }); } this.paginatorInfo.pageIndex = 0; //On remet la paginateur à la première page this.paginatorInfo.length = this.displayedDoctors.length; //On affecte la taille des éléments trouvés à la taille du paginateur this.displayedDoctors = this.listSrv.paginateElements<UserInterface>(this.displayedDoctors, this.paginatorInfo); // On pagine nos éléments qui correspondent à la recherche } //Méthode déclenchée lorsque l'utilisateur change de page ou change la taille du paginateur pageChange(event: PageEvent): void { this.paginatorInfo = event; //On met à jour la variable qui contient les informations du paginateur this.displayedDoctors = this.listSrv.paginateElements<UserInterface>(this.doctors, this.paginatorInfo); // On pagine nos éléments affichés } }
1f863c3ebc543a901a503c01aafbcad3f7f1521b
TypeScript
favourMusenga/weather-app
/src/reducers/settingReducer.ts
3.28125
3
export interface SetttingState { timeFormat: string; temperatureFormat: string; } const initialState: SetttingState = { temperatureFormat: '', timeFormat: '', }; export type ActionsTypes = { type: 'UPDATE'; payload: SetttingState; }; export const settingReducer = ( state: SetttingState = initialState, actions: ActionsTypes ) => { switch (actions.type) { case 'UPDATE': return { timeFormat: actions.payload.timeFormat, temperatureFormat: actions.payload.temperatureFormat, }; default: return state; } };
05725029936a6368e721f9b5d8357537f2e0b90d
TypeScript
Alko-li/Aurora
/src/UI/worldScreen/WorldScreen.ts
2.6875
3
import UI from "../UI.js"; import MapUI from "./MapUI.js"; import TileSidebar from "./TileSidebar.js"; import GridCoordinates from "../../world/GridCoordinates.js"; import Game from "../../Game.js"; import InventorySidebar from "./InventorySidebar.js"; import WorldScreenHeader from "./WorldScreenHeader.js"; /* The class associated with the "world screen" * which shows the map grid, available resources, and options for the selected structure */ export default class WorldScreen { private mapUI: MapUI; private inventorySidebar: InventorySidebar; private tileSidebar: TileSidebar; private header: WorldScreenHeader; private worldScreenHTML: HTMLElement; constructor(run: Game) { this.mapUI = new MapUI(this, run.world); this.tileSidebar = new TileSidebar(this, run); const mapHTML = this.mapUI.getViewCanvas(); this.inventorySidebar = new InventorySidebar(run); const tileSidebarHTML = this.tileSidebar.getHTML(); const inventoryHTML = this.inventorySidebar.getHTML(); this.header = new WorldScreenHeader(run); this.worldScreenHTML = UI.makeDivContaining([ this.header.getHTML(), UI.makeDivContaining([ inventoryHTML, UI.makeDivContaining([mapHTML], ['world-screen-map-box']), tileSidebarHTML, ], ['world-screen-hbox']), ], ['flex-vertical']); } public getHTML(): HTMLElement { return this.worldScreenHTML; } refreshComponents() { this.mapUI.refreshViewableArea(); this.tileSidebar.refresh(); this.inventorySidebar.refresh(); this.header.refresh(); } // keyboard events for this page are passed to the map ui, which uses arrow keys or wasd to move around the map handleKeyDown(ev: KeyboardEvent) { this.mapUI.handleKeyDown(ev); } changeSidebarTile(position: GridCoordinates | null) { this.tileSidebar.changeTile(position); } }
967d43aebe08809f525ffd3998edf4b56f8e8581
TypeScript
XavierGerD/irregular.expert
/src/RhythmPractice/reducer/figuresUtils.ts
2.5625
3
import { tupletCodes, TupletValues } from "../../UnicodeAssignment"; import { RhythmicUnitKeys, RHYTHMIC_UNITS } from "../RhythmicUnits"; import { CheckedRhythmicUnits, CheckedTupletValues, RhythmicEvent, RhythmicUnit, } from "./slice"; export const getFigure = ( rhythmicUnit: RhythmicUnit, allowEmptyBars: boolean ): RhythmicEvent[][] => rhythmicUnit.map((subdivision: number) => getRhythmicEvents(subdivision, allowEmptyBars) ); export const sum = (accumulator: number, currentValue: number) => accumulator + currentValue; export const getRandomTupletValue = ( rhythmicGroups: TupletValues[] ): TupletValues => rhythmicGroups[Math.floor(Math.random() * rhythmicGroups.length)]; export const getRandomTimeSig = ( rhythmicGroups: RhythmicUnit[] ): RhythmicUnit => rhythmicGroups[Math.floor(Math.random() * rhythmicGroups.length)]; const getRandomRhythmicEvent = (): RhythmicEvent => { //generate a random int between 0 and 1 const min = Math.ceil(0); const max = Math.floor(2); return (Math.floor(Math.random() * (max - min)) + min) as RhythmicEvent; }; export const getRhythmicEvents = ( max: number, allowEmptyBars: boolean ): RhythmicEvent[] => { const bar = [...new Array(max)].map(() => getRandomRhythmicEvent()); if (!allowEmptyBars) { // if the bar is empty, return a new bar const isBarEmpty = bar.every((value) => value === 0); if (isBarEmpty) { return getRhythmicEvents(max, allowEmptyBars); } } return bar; }; const getRhthmicUnits = (checkedRhythmicUnits: CheckedRhythmicUnits) => (unitKey: string) => { if (checkedRhythmicUnits[unitKey as RhythmicUnitKeys]) { return RHYTHMIC_UNITS[unitKey as RhythmicUnitKeys]; } }; const filterUndefinedRhythmicUnits = ( rhythmicUnit: RhythmicUnit | undefined ): rhythmicUnit is RhythmicUnit => !!rhythmicUnit; export const getSelectedRhythmicUnits = ( checkedRhythmicGroups: CheckedRhythmicUnits ) => Object.keys(checkedRhythmicGroups) .map(getRhthmicUnits(checkedRhythmicGroups)) .filter(filterUndefinedRhythmicUnits); const filterUndefinedTupletValues = ( tupletValue: TupletValues | undefined ): tupletValue is TupletValues => !!tupletValue; const getTupletValues = (checkedTupletValues: CheckedTupletValues) => (tupletValue: string) => { if (checkedTupletValues[parseInt(tupletValue) as TupletValues]) { return parseInt(tupletValue) as TupletValues; } }; export const getSelectedTupletValues = ( checkedTupletValues: CheckedTupletValues ) => Object.keys(checkedTupletValues) .map(getTupletValues(checkedTupletValues)) .filter(filterUndefinedTupletValues);
90cff6ac50795ec7ab906b3aa55f63cacdd4f796
TypeScript
Ricardope3/digichips-backend
/src/utils/existsInArray.ts
2.75
3
export const existsInArray = (id: string, array: any[]) => { return array.filter((e) => e._id === id)[0]; }
3677aeec360b5d5facf60b9003fc54dba479c698
TypeScript
NarHakobyan/awesome-nest-boilerplate
/src/decorators/validator.decorators.ts
2.828125
3
import type { ValidationOptions } from 'class-validator'; import { IsPhoneNumber as isPhoneNumber, registerDecorator, ValidateIf, } from 'class-validator'; import { isString } from 'lodash'; export function IsPassword( validationOptions?: ValidationOptions, ): PropertyDecorator { return (object, propertyName: string) => { registerDecorator({ propertyName, name: 'isPassword', target: object.constructor, constraints: [], options: validationOptions, validator: { validate(value: string) { return /^[\d!#$%&*@A-Z^a-z]*$/.test(value); }, }, }); }; } export function IsPhoneNumber( validationOptions?: ValidationOptions & { region?: Parameters<typeof isPhoneNumber>[0]; }, ): PropertyDecorator { return isPhoneNumber(validationOptions?.region, { message: 'error.phoneNumber', ...validationOptions, }); } export function IsTmpKey( validationOptions?: ValidationOptions, ): PropertyDecorator { return (object, propertyName: string) => { registerDecorator({ propertyName, name: 'tmpKey', target: object.constructor, options: validationOptions, validator: { validate(value: string): boolean { return isString(value) && /^tmp\//.test(value); }, defaultMessage(): string { return 'error.invalidTmpKey'; }, }, }); }; } export function IsUndefinable(options?: ValidationOptions): PropertyDecorator { return ValidateIf((obj, value) => value !== undefined, options); } export function IsNullable(options?: ValidationOptions): PropertyDecorator { return ValidateIf((obj, value) => value !== null, options); }
e4a4a0aba50c86f7f927c655eff636d08e37f716
TypeScript
hombredequeso/lift-kata
/src/lift.test.ts
2.78125
3
import { Option, None} from 'tsoption' import { LiftRequests, Lift, processFloorRequestEventForLift, processLiftArrivedEventForLift, processLiftArrivedEventForLiftRequests, processLiftRequestEvent, SystemState, getLiftMoveStrategy1, applyLiftArrivedEvent, applyFloorRequestEvent, applyLiftRequestEvent} from './lift.functional' import { Direction, Floor, LiftRequestButtonPressedEvent, FloorRequestButtonPressedEvent, LiftArrivedEvent } from './events' test('applyLiftRequestEvent updates SystemState correctly', () => { const initialState: SystemState = { lift: { floor: 0, availableFloors: [0,1,2,3], floorRequests: [] }, liftRequests: [] }; const event: LiftRequestButtonPressedEvent = { onFloor: 1, direction: Direction.Up, timeEpoch: 999 }; const newState = applyLiftRequestEvent(initialState, event); expect(newState).toEqual( { lift: { floor: 0, availableFloors: [0,1,2,3], floorRequests: [] }, liftRequests: [event] } ); }); test('sets', () => { const s = new Set([1,2,3]); expect(s.size).toEqual(3); }) test('applyFloorRequestEvent updates SystemState correctly', () => { const initialState: SystemState = { lift: { floor: 0, availableFloors: [0,1,2,3], floorRequests: [] }, liftRequests: [] }; const event: FloorRequestButtonPressedEvent = { floor: 6 } const newState = applyFloorRequestEvent(initialState, event); expect(newState).toEqual( { lift: { floor: 0, availableFloors: [0,1,2,3], floorRequests: [] }, liftRequests: [] } ); }); test('applyLiftArrivedEvent updates SystemState', () => { const initialState: SystemState = { lift: { floor: 0, availableFloors: [0,1,2,3], floorRequests: [{floor: 2}] }, liftRequests: [{ onFloor: 2, direction: Direction.Up, timeEpoch: 999 }] }; const event: LiftArrivedEvent = { floor: 2 } const newState = applyLiftArrivedEvent(initialState, event); expect(newState).toEqual( { lift: { floor: 2, availableFloors: [0,1,2,3], floorRequests: [] }, liftRequests: [] } ); }); test('processFloorRequestEventForLift adds floor request if lift goes to that floor and return some lift', () => { const lift: Lift = { floor: 0, availableFloors: [0,1,2,3], floorRequests: [] }; const floorRequest = { floor: 2 }; const result = processFloorRequestEventForLift(lift, floorRequest); expect(result).toEqual( Option.of<Lift>({ floor: 0, availableFloors: [0,1,2,3], floorRequests: [{floor: 2}] })); }); test('processFloorRequestEventForLift returns None if lift is not available on the floor', () => { const lift: Lift = { floor: 0, availableFloors: [0,1,2,3], floorRequests: [] }; const floorRequest = { floor: 4 }; const result = processFloorRequestEventForLift(lift, floorRequest); expect(result).toEqual(new None<Lift>()); }); test('Can create a valid lift', () => { const lift: Lift = { floor: 0, availableFloors: [0,1,2,3], floorRequests: [] }; expect(lift.floor).toBe(0); }); test('LiftArrivedEvent returns new lift state', () => { const initialLift: Lift= { floor: 1, availableFloors: [1,2,3], floorRequests: [{floor: 2}, {floor: 3}] }; const event: LiftArrivedEvent = { floor: 2 }; const newLift: Option<Lift> = processLiftArrivedEventForLift(initialLift, event); expect(newLift).toEqual(Option.of<Lift>({ floor: 2, availableFloors: [1,2,3], floorRequests: [{floor: 3}] })); }) test('LiftArrivedAtEvent returns new LiftRequests state, empty state', () => { const initialState: LiftRequests = [] const event: LiftArrivedEvent = { floor: 0 }; const newState: LiftRequests = processLiftArrivedEventForLiftRequests(initialState, event); expect(newState).toEqual([]); expect(initialState).toEqual([]); }) test('LiftArrivedAtEvent returns new LiftRequests state, removing all floor events', () => { const initialState: LiftRequests = [{ onFloor: 0, direction: Direction.Up, timeEpoch: 123 }, { onFloor: 1, direction: Direction.Up, timeEpoch: 999 }]; const event: LiftArrivedEvent = { floor: 1, }; const newState: LiftRequests = processLiftArrivedEventForLiftRequests(initialState, event); expect(newState).toEqual( [{ onFloor: 0, direction: Direction.Up, timeEpoch: 123 }]); }) test('processLiftRequestEvent returns new LiftRequests state', () => { const initialState: LiftRequests = []; const buttonPress: LiftRequestButtonPressedEvent = { onFloor: 0, direction: Direction.Up, timeEpoch: 999 }; const newState: LiftRequests = processLiftRequestEvent(initialState, buttonPress); expect(newState).toEqual([buttonPress]); expect(initialState).toEqual([]); }) test('getLiftMove returns oldest request of floor lift is not at', () => { const lift: Lift = { floor: 1, availableFloors: [1,2,3,4], floorRequests: [] }; const liftRequests = [ { onFloor: 1, direction: Direction.Up, timeEpoch: 10 }, { onFloor: 5, direction: Direction.Up, timeEpoch: 20 }, { onFloor: 3, direction: Direction.Up, timeEpoch: 30 }, { onFloor: 4, direction: Direction.Up, timeEpoch: 40 } ]; const result = getLiftMoveStrategy1( { lift: lift, liftRequests: liftRequests }); expect(result).toBe(3); })
1af4df2ed75f376496f06d1a70492849c92d1b8c
TypeScript
GaetanCesaro/echange.nc
/src/app/ad/ad.model.ts
2.625
3
export interface Ad { id?: number; title: string; description: string; price: number; imageUrl: string; category: string; owner: User; } export interface Category { value: string; text: string; } export interface User { id: number; email: string; firstName: string; lastName: string; } export type Query = { findAllUsers: User[]; findAllAds: Ad[]; } export type Mutation = { newAd: Ad; }
02345f1f7c2aec91b44eea301c8785145ee1ec41
TypeScript
MaxwellHenderson/ILP-Capstone
/Frontend/GroceryStore/src/app/shared/cart-item.model.ts
2.8125
3
export interface CartItem { productId: number; productName: string; productPrice: number; productQuantity: number; //Represents the number of items in the cart }
e0f444eb9be293d22c42c8787a7d7f3244bafbdd
TypeScript
muxy/extensions-js
/dist/types/src/messenger.d.ts
2.546875
3
import { DebugOptions } from './debug'; export declare enum MessengerType { Pusher = 0, Twitch = 1, Server = 2, Unknown = 3 } export declare class CallbackHandle { target: string; cb: (t: any, datatype: string, message: string) => void; } export interface Messenger { channelID: string; extensionID: string; send(id: any, event: any, target: any, body: any, client: any): void; listen(id: any, topic: any, callback: (parsedObject: object) => void): CallbackHandle; unlisten(id: any, CallbackHandle: any): void; close(): void; } export declare type ListenCallback<Payload> = (p: Payload, event: string) => void; export interface MessageEnvelope<Payload> { data: Payload; event: string; } export default function DefaultMessenger(debug: DebugOptions): Messenger;
eb2432a86b7bcebfdc7baea15c8b75da9e459dab
TypeScript
guidoeckelt/ge
/src/game/input/InputWatcher.ts
2.90625
3
import InputBinding from "./InputBinding"; // import HashMap from "../HashTable"; abstract class InputWatcher<EventType extends Object, Binding extends InputBinding<Event>>{ protected _element : Element; protected _body : HTMLElement; protected _bindingMap : Object; // private _bindingMap : HashMap = new HashMap(); constructor(_element : HTMLElement){ this._element = _element; this._body = document.getElementsByTagName("body")[0]; this._bindingMap = {}; this._watch(); } public addBinding(eventType : EventType, binding : Binding){ // if(!this._bindingMap.containsKey(eventType)){ // this._bindingMap.put(eventType, new Array<KeyBinding>()); // } // this._bindingMap.get(eventType).push(keyBinding); if(this._bindingMap[eventType.toString()] == null){ this._bindingMap[eventType.toString()] = new Array<Binding>(); } this._bindingMap[eventType.toString()].push(binding); } public removeBinding(eventType : EventType, binding : Binding){ // let list = this._bindingMap.get(eventType); // if(list == null) return; // list.splice(list.indexOf(keyBinding),1); let list = this._bindingMap[eventType.toString()]; if(list == null) return; list.splice(list.indexOf(binding),1); } protected abstract _watch() : void; protected _checkBindings(eventType : EventType, event : Event){ // let list = this._bindingMap.get(eventType); // if(list == null) return; // for(let keyBinding of list){ // this._callKeyBindingIfTriggered(keyBinding, event); // } let bindingList = this._bindingMap[eventType.toString()]; if(bindingList == null) return; for(let binding of bindingList){ this._callBindingIfTriggered(binding, event); } } private _callBindingIfTriggered(binding : Binding, event : Event){ if(binding.isTriggered(event)){ binding.call(); // console.log("event dispatched"); event.preventDefault(); } } } export default InputWatcher;
6647690977571b10bd5112611d10aa4c49effaa8
TypeScript
cc-modules/util-action
/util-action.d.ts
3.03125
3
/** * 保存node的属性,返回一个还原的action * * @export * @param {cc.Node} node * @param {string[]} props * @returns {cc.ActionInstant} */ export function saveProps(node: cc.Node, props: string[]): cc.ActionInstant; /** * 震动的动画Promise版本 * * @export * @param {cc.Node} node * @param {number} [amplitudeX=20] * @param {number} [amplitudeY=0] * @param {number} [duration=0.1] * @param {number} [times=2] * @returns {Promise<void>} */ export function shake1(node: cc.Node, amplitudeX: number = 20, amplitudeY: number = 0, duration: number = 0.1, times = 2): Promise<void>; /** * 放大动画Promise版本 * * @export * @param {cc.Node} node * @param {number} initScale * @param {number} scaleUpDuration * @param {number} scaleUpTo * @param {number} bounceDuration * @returns {Promise<void>} */ export function zoomIn0(node: cc.Node, initScale: number, scaleUpDuration: number, scaleUpTo: number, bounceDuration: number): Promise<void>; /** * 淡入 * * @export * @param {cc.Node} node * @param {number} dir * @param {number} duration * @param {number} distance * @returns {Promise<void>} */ export function fadeIn0(node: cc.Node, dir: number, duration: number, distance: number): Promise<void>; /** * 淡出Promise版本 * * @export * @param {cc.Node} node * @param {number} dir * @param {number} duration * @param {number} distance * @returns {Promise<void>} */ export function fadeOut0(node: cc.Node, dir: number, duration: number, distance: number): Promise<void>; /** * 震动的动画 * * @export * @param {cc.Node} node * @param {number} [amplitudeX=20] * @param {number} [amplitudeY=0] * @param {number} [duration=0.1] * @param {number} [times=2] * @returns {cc.Action[]} */ export function shake1_(node: cc.Node, amplitudeX: number = 20, amplitudeY: number = 0, duration: number = 0.1, times = 2): cc.Action[]; /** * 放大动画 * * @export * @param {cc.Node} node * @param {number} initScale * @param {number} scaleUpDuration * @param {number} scaleUpTo * @param {number} bounceDuration * @returns {cc.Action[]} */ export function zoomIn0_(node: cc.Node, initScale: number, scaleUpDuration: number, scaleUpTo: number, bounceDuration: number): cc.Action[]; /** * 摇摆动画 * * @export * @param {cc.Node} node * @param {number} [degree=15] * @param {number} [duration=0.1] * @param {number} [times=2] * @returns {cc.Action[]} */ export function wobble_(node: cc.Node, degree: number = 15, duration: number = 0.1, times: number = 2): cc.Action[]; /** * 先淡出,等待,再淡入 * * @export * @param {cc.Node} node * @param {number} [inDur=0.5] * @param {number} [stayDur=0.5] * @param {*} [outDur=inDur] * @returns {cc.Action[]} */ export function flash_(node: cc.Node, inDur: number = 0.5, stayDur: number = 0.5, outDur: number = inDur): cc.Action[]; /** * 移动到指定坐标 * * @export * @param {cc.Node} node * @param {number} x * @param {number} y * @param {number} duration * @returns {cc.Action[]} */ export function moveTo_(node: cc.Node, x: number, y: number, duration: number): cc.Action[]; /** * 移动指定的距离 * * @export * @param {cc.Node} node * @param {number} x * @param {number} y * @param {number} duration * @returns {cc.Action[]} */ export function moveBy_(node: cc.Node, x: number, y: number, duration: number): cc.Action[]; /** * * * @export等待指定时间 * @param {cc.Node} node * @param {number} duration * @returns {cc.Action[]} */ export function wait_(node: cc.Node, duration: number): cc.Action[]; /** * 摇摆动画 * * @export * @param {cc.Node} node * @param {number} [degree=15] * @param {number} [duration=0.1] * @param {number} [times=2] * @returns {Promise<void>} */ export function wobble(node: cc.Node, degree: number = 15, duration: number = 0.1, times: number = 2): Promise<void>; /** * 先淡出,等待,再淡入 * * @export * @param {cc.Node} node * @param {number} [inDur=0.5] * @param {number} [stayDur=0.5] * @param {*} [outDur=inDur] * @returns {cc.Action[]} */ export function flash(node: cc.Node, inDur: number = 0.5, stayDur: number = 0.5, outDur: number = inDur): Promise<void>; /** * 水平震动 * * @export * @param {cc.Node} node * @param {number} [ax=20] * @param {number} [dur=0.2] * @param {number} [times=2] * @returns {Promise<void>} */ export function shakeH(node: cc.Node, ax = 20, dur = 0.2, times = 2): Promise<void>; /** * * * @export垂直震动 * @param {cc.Node} node * @param {number} [ay=20] * @param {number} [dur=0.2] * @param {number} [times=2] * @returns {Promise<void>} */ export function shakeV(node: cc.Node, ay: number = 20, dur: number = 0.2, times: number = 2): Promise<void>; /** * 放大 * * @export * @param {cc.Node} node * @param {number} [dur=0.5] * @param {boolean} [isBounce=true] * @returns {Promise<void>} */ export function zoomIn(node: cc.Node, dur: number = 0.5, isBounce: boolean = true): Promise<void>; /** * 淡入 * * @export * @param {cc.Node} node * @param {number} [duration=0.5] * @returns {Promise<void>} */ export function fadeIn(node: cc.Node, duration: number = 0.5): Promise<void>; /** * 淡出 * * @export * @param {cc.Node} node * @param {number} [duration=0.5] * @returns {Promise<void>} */ export function fadeOut(node: cc.Node, duration: number = 0.5): Promise<void>; /** * 淡入,从上移动到下 * * @export * @param {cc.Node} node * @param {number} [duration=0.5] * @returns {Promise<void>} */ export function fadeInDown(node: cc.Node, duration: number = 0.5): Promise<void>; /** * 淡入,从下移动到上 * * @export * @param {cc.Node} node * @param {number} [duration=0.5] * @returns {Promise<void>} */ export function fadeInUp(node: cc.Node, duration: number = 0.5): Promise<void>; /** * 移动到指定坐标 * * @export * @param {cc.Node} node * @param {number} x * @param {number} y * @param {number} [duration=0.5] * @returns {Promise<void>} */ export function moveTo(node: cc.Node, x: number, y: number, duration: number = 0.5): Promise<void>; /** * 移动指定距离 * * @export * @param {cc.Node} node * @param {number} x * @param {number} y * @param {number} [duration=0.5] * @returns {Promise<void>} */ export function moveBy(node: cc.Node, x: number, y: number, duration: number = 0.5): Promise<void>; /** * 等待指定时间 * * @export * @param {cc.Node} node * @param {number} [duration=0.5] * @returns {Promise<void>} */ export function wait(node: cc.Node, duration: number = 0.5): Promise<void>; /** * action给node注入动画函数 * * @export * @param {(cc.Noce | cc.Node[])} nodes * @param {string} [prefix=''] */ export function $inject(nodes: cc.Node | cc.Node[], prefix: string = ''); /** * [NodeEx description] */ export interface NodeEx extends cc.Node { /** * 摇摆动画 * * @param {number} [degree=15] * @param {number} [duration=0.1] * @param {number} [times=2] * @returns {Promise<void>} */ wobble(degree: number = 15, duration: number = 0.1, times: number = 2): Promise<void>; /** * 先淡出,等待,再淡入 * * @param {number} [inDur=0.5] * @param {number} [stayDur=0.5] * @param {*} [outDur=inDur] * @returns {cc.Action[]} */ flash(inDur: number = 0.5, stayDur: number = 0.5, outDur: number = inDur): Promise<void>; /** * 水平震动 * * @param {number} [ax=20] * @param {number} [dur=0.2] * @param {number} [times=2] * @returns {Promise<void>} */ shakeH(ax = 20, dur = 0.2, times = 2): Promise<void>; /** * * 垂直震动 * @param {number} [ay=20] * @param {number} [dur=0.2] * @param {number} [times=2] * @returns {Promise<void>} */ shakeV(ay: number = 20, dur: number = 0.2, times: number = 2): Promise<void>; /** * 放大 * * @param {number} [dur=0.5] * @param {boolean} [isBounce=true] * @returns {Promise<void>} */ zoomIn(dur: number = 0.5, isBounce: boolean = true): Promise<void>; /** * 淡入 * * @param {number} [duration=0.5] * @returns {Promise<void>} */ fadeIn(duration: number = 0.5): Promise<void>; /** * 淡出 * * @param {number} [duration=0.5] * @returns {Promise<void>} */ fadeOut(duration: number = 0.5): Promise<void>; /** * 淡入,从上移动到下 * * @param {number} [duration=0.5] * @returns {Promise<void>} */ fadeInDown(duration: number = 0.5): Promise<void>; /** * 淡入,从下移动到上 * * @param {number} [duration=0.5] * @returns {Promise<void>} */ fadeInUp(duration: number = 0.5): Promise<void>; /** * 移动到指定坐标 * * @param {number} x * @param {number} y * @param {number} [duration=0.5] * @returns {Promise<void>} */ moveTo(x: number, y: number, duration: number = 0.5): Promise<void>; /** * 移动指定距离 * * @param {number} x * @param {number} y * @param {number} [duration=0.5] * @returns {Promise<void>} */ moveBy(x: number, y: number, duration: number = 0.5): Promise<void>; /** * 等待指定时间 * * @param {number} [duration=0.5] * @returns {Promise<void>} */ wait(duration: number = 0.5): Promise<void>; }
742f582535cdb48a43d743cbc0d99cbc2e3016ff
TypeScript
K0R0VA/portal-chat
/client/src/app/interfaces/message.ts
2.703125
3
import {Deserializer, Serialize} from './websocket'; import {ClientMessage, ServerMessage} from '../../../messages/message'; export enum MessageType { CONTACT = 0, GROUP = 1 } export interface Message { readonly senderName: string; readonly senderAvatar: string; readonly text: string; } export interface IClientMessage { readonly senderId: number, readonly text: string, readonly media?: Uint8Array, readonly requestType: MessageType, readonly recipientId: number, } export class Request implements IClientMessage, Serialize { encode(): Uint8Array { return ClientMessage.encode(this).finish() } readonly recipientId!: number; readonly requestType!: MessageType; readonly senderId!: number; readonly text!: string; readonly media?: Uint8Array; } export interface IServerMessage { readonly senderId: number, readonly text: string, readonly requestType: MessageType, } export class ResponseDeserializer implements Deserializer<IServerMessage> { decode(binary: Uint8Array): IServerMessage { const bytes = Array.prototype.slice.call(binary, 0); return ServerMessage.decode(bytes as unknown as Uint8Array); } }
9efacc65dff62ebbfa2d7090664402bc53432f80
TypeScript
ABEgame/ABEgame.github.io
/GameController.ts
2.71875
3
/// <reference path="GameLoop.ts" /> /// <reference path="Model.ts" /> /// <reference path="GameOne.ts" /> /// <reference path="GameTwo.ts" /> module Game{ export class GameController{ gameloop; canvas; width; height; model; gamma; alpha; beta; gameShallStart; gameLength; //printing startX; startY; endX; endY; startingHeight; fingerLifted; oldY; constructor(gameloop,canvas,width,height,model){ this.gameloop = gameloop; this.canvas = canvas; this.width = width; this.height = height; this.model = model; this.gameShallStart = false; this.gamma = 0; this.gameLength=60; } takeInput(){ if(this.model instanceof GameOne){ this.gameOneTakeInput(); } if(this.model instanceof GameTwo){ this.gameTwoTakeInput(); } } gameOneTakeInput(){ this.startGameOne(); } endGameInput(){ this.fingerLifted = false; this.startingHeight = 0; this.startingHeight = 0; this.oldY = 0; this.ScrollingEnd = <any>this.ScrollingEnd.bind(this); this.endScrollingEnd = <any>this.endScrollingEnd.bind(this); this.startClickEnd = <any>this.startClickEnd.bind(this); //this.canvas.addEventListener("touchstart",this.startClickEnd); this.canvas.addEventListener("touchmove",this.ScrollingEnd); this.canvas.addEventListener("touchend",this.endScrollingEnd); } startClickEnd(event){ event.preventDefault(); var canvas_x = event.targetTouches[0].pageX; var canvas_y = event.targetTouches[0].pageY; this.startX = canvas_x; this.startY = canvas_y; this.endY = canvas_y; this.endX = canvas_x; } ScrollingEnd(event){ event.preventDefault(); var screenHeight = this.height - (this.height/4); //var buttonHeight = screenHeight/7; var maxHeight = 23 * this.model.playedWords.length; var canvas_x = event.targetTouches[0].pageX; var canvas_y = event.targetTouches[0].pageY; console.log(this.startingHeight + "sh"); if(this.fingerLifted){ this.startX = canvas_x; this.startY = canvas_y; } if(!this.fingerLifted){ var difference = this.oldY - canvas_y; var newStartingHeight = this.startingHeight+difference; if(newStartingHeight < 0){ this.startingHeight = 0; } else{ this.startingHeight = newStartingHeight; } //this.categoriesView.renderCategories(Math.round(this.startingHeight),this.model.chosenCategories); } this.oldY = canvas_y; this.endY = canvas_y; this.endX = canvas_x; this.model.setEndGameStartingHeight(this.startingHeight); this.fingerLifted = false; } endScrollingEnd(event){ this.fingerLifted = true; console.log(this.startX + " " + this.endX); if(Math.abs(this.startX - this.endX)< 5){ if(Math.abs(this.startY - this.endY) < 5){ //this.updateGame(this.endY) } } } startGameOne(){ this.model.beginGame(); var self = this; this.mobileClick = <any>this.mobileClick.bind(this); this.canvas.addEventListener("click",this.mobileClick); var mostRecentState = 0; var mostRecentTimeItWasBeingHeldSideways; window.ondeviceorientation = function(event) { self.gamma = Math.round(event.gamma); self.alpha = Math.round(event.alpha); self.beta = Math.round(event.beta); //Game.GameView.apply("drawNumber", event.gamma); //document.open(); //this.canvas. //console.log(event.gamma); //document.write("gamma, " + event.gamma); //document.write("alpha, " + event.alpha); //document.write("beta, " + event.beta); //document.close() //new begins here // if(mostRecentState >270){ // mostRecentState = 1; //this is to prevent the game from reading another pass after gamma goes from 0 to 359 // } if( Math.abs(self.gamma) < 60){ mostRecentTimeItWasBeingHeldSideways = new Date().getTime(); } // if (self.gamma > 55 && mostRecentState <= 125 && self.gamma < 270){ //redundant if statement if(self.gamma < 60 && mostRecentState >60){//self.gamma > -30 && self.gamma <30){ mostRecentTimeItWasBeingHeldSideways = new Date().getTime(); } /* if(self.gamma > 90){ while(true){} // testing iphone for gamma > 90 }*/ //outside of forehead range and recent state inside of forehead range if ( ((self.gamma <= 45 && self.gamma > 0 && mostRecentState >45) || (self.gamma > -45 && self.gamma <0 && mostRecentState <-45)) ){ // (self.gamma > 30 || self.gamma < -30) && (mostRecentState > -30 || mostRecentState < 30)){ // pass or correct if( Math.abs(self.beta) > 100){ // correct self.model.setRecentPassOrFail(true);//they got the answer right } else{ //pass, gamma > 30 self.model.setRecentPassOrFail(false);//they got the answer wrong } self.gameShallStart = true;//new self.model.heldSideways = true; }else if (self.gamma > 45 || self.gamma <= -45){ // outside of normal range //currently don't know the point of this self.gameShallStart = true; /* while((new Date().getTime()) - mostRecentTimeItWasBeingHeldSideways < 1000){ //doNothing }*/ self.model.heldSideways = false; /* original if(mostRecentState >270){ mostRecentState = 1; //this is to prevent the game from reading another pass after gamma goes from 0 to 359 } if(self.gamma>125 || self.gamma < 55){ mostRecentTimeItWasBeingHeldSideways = new Date().getTime(); } if (self.gamma > 125 && mostRecentState <= 125 && self.gamma < 270){ self.model.setRecentPassOrFail(true);//they got the answer right self.model.heldSideways = true; }else if(self.gamma< 55 && mostRecentState >= 55 && self.gamma>0){ self.model.setRecentPassOrFail(false);//they got the answer wrong self.model.heldSideways = true; }else if (self.gamma >= 55 && self.gamma <= 125){ self.gameShallStart = true; while((new Date().getTime()) - mostRecentTimeItWasBeingHeldSideways < 1000){ //doNothing } self.model.heldSideways = false; */ } mostRecentState = self.gamma; } this.waitForGameOver(); this.startDaGame(); } startDaGame(){ var self = this; var t; if(!this.model.gameStarted && this.gameShallStart){ console.log(this.model.gameCount); this.model.countdown(); this.startAnothaGame(); } else{ var f = function(){self.startDaGame();}; t = setTimeout(f,100); } } startAnothaGame(){ if(this.model.canChange){ this.model.newItem = false; this.model.startGame(this.gameLength); }else{ var self = this; var f = function(){self.startAnothaGame();}; var t = setTimeout(f,100); } } gameCanStart():boolean{ return this.model.gameCanStart; } mobileClick(e){ var mobileClickY = (event as any).y; mobileClickY -= this.canvas.offsetTop; var mobileClickX = (event as any).x; mobileClickX -= this.canvas.offsetLeft; if(this.model.gameOver){ //this.endGameInput(); this.gameOverClickOne(mobileClickX,mobileClickY); }else if(this.model.gameStarted){ this.BackToMenuClick(mobileClickX,mobileClickY); } } gameOverClickOne(X,Y){ var menuButton = (550/667)*this.height; if(Y>menuButton){ this.switchToMenuState() } } BackToMenuClick(X,Y){ var menuButtonY = (530/667)*this.height; var menuButtonX = (70/375)*this.width; if(Y>menuButtonY && X<menuButtonX){ this.model.endGame(); this.switchToMenuState() } } gameTwoTakeInput(){ this.startGameTwo(); } startGameTwo(){ this.mobileClickTwo = <any>this.mobileClickTwo.bind(this); this.canvas.addEventListener("click",this.mobileClickTwo); this.model.beginGame(this.height); //this.inMenu = false; } mobileClickTwo(event){ var mobileClickY = event.y; mobileClickY -= this.canvas.offsetTop; var mobileClickX = event.x; mobileClickX -= this.canvas.offsetLeft; if(this.model.inBetweenRounds){ this.clickNextRoundOption(mobileClickX,mobileClickY); }else if(this.model.playingGame){ this.clickTwo(mobileClickX,mobileClickY); }else if(this.model.gameOver){ this.clickMenuOption(mobileClickX,mobileClickY); }else{ this.clickSelectTotalRounds(mobileClickX,mobileClickY); } } clickNextRoundOption(X,Y){ var menuButton = (550/667)*this.height; if(Y>menuButton){ this.model.startGame(); } if(X < 150*this.width/375 && Y < 100*this.height/667){ this.switchToMenuState(); } } waitForGameOver(){ if(this.model.gameOver){ this.endGameInput(); } else{ var t; var self = this; var f = function(){self.waitForGameOver();}; t = setTimeout(f,50); } } clickMenuOption(X,Y){ var menuButton = (550/667)*this.height; if(Y>menuButton){ this.switchToMenuState(); } } clickSelectTotalRounds(X,Y){ var leftArrowStartingX = (260/375) * this.width; var leftArrowStartingY = (250/667) * this.height; var leftArrowEndingY = (340/667)* this.height; if(X < 150*this.width/375 && Y < 100*this.height/667){ this.model.stopBouncingAnimations(); this.switchToMenuState(); } if(X > leftArrowStartingX && X < this.width ){ if(Y > leftArrowStartingY && Y < leftArrowEndingY){ this.model.clickRightArrow(this.width,this.height); } }else if(X > 0 && X < (150/375)*this.width ){ if(Y > leftArrowStartingY && Y < leftArrowEndingY){ this.model.clickLeftArrow(this.width,this.height); } }else{ if(Y > 550/667 * this.height){ this.model.setTotalRounds(); this.model.selectedRoundNumber(); this.model.startGame(); } } } clickTwo(X,Y){ var buttonStartingX = 290/375 * this.width; var buttonEndingX = 360/375 * this.width; var CorrectStartingY = 10/667 * this.height; var CorrectEndingY = 330/667 * this.height; var PassStartingY = 370/667 * this.height; var PassEndingY = 650/667 * this.height; if(X > buttonStartingX && X < buttonEndingX ){ if(Y > CorrectStartingY && Y < CorrectEndingY){ this.model.changeActiveTeam(); }else if(Y > PassStartingY && Y < PassEndingY){ this.model.changeItem(); } } this.BackToMenuClick(X,Y); } switchToMenuState(){ this.switchStates(); this.gameloop.switchToMenuState(); } switchStates(){ this.model.clearVariables(); if(this.model instanceof GameOne){ this.canvas.removeEventListener("click",this.mobileClick); this.canvas.removeEventListener("touchmove",this.ScrollingEnd); this.canvas.removeEventListener("touchend",this.endScrollingEnd); } else{ this.canvas.removeEventListener("click",this.mobileClickTwo); var m = this.model; var gv = m.gameView; console.log("gameView"+gv); gv.inMenu = true; } } } }
ebf2c208cc3b413d8a123ca1ad2a2e1ef300f921
TypeScript
ohmpzz/pre-order-food-frontend
/pre-order-food/src/app/core/store/actions/pre-order.action.ts
2.546875
3
import { Action } from '@ngrx/store'; import { PreOrders } from '../../models/pre-order.model'; export enum PreOrderActionTypes { LoadPreOrders = '[Core] Load PreOrders', LoadPreOrdersFail = '[Core] Load PreOrders Fail', LoadPreOrdersSuccess = '[Core] Load PreOrders Success', LoadPreOrderById = '[Core] Load PreOrder By Id', LoadPreOrderByIdFail = '[Core] Load PreOrder By Id Fail', LoadPreOrderByIdSuccess = '[Core] Load PreOrder By Id Success', LoadPreOrdersByOwner = '[Core] Load PreOrders By Owner', LoadPreOrdersByOwnerFail = '[Core] Load PreOrders By Owner Fail', LoadPreOrdersByOwnerSuccess = '[Core] Load PreOrders By Owner Success', RemovePreOrderByOwner = '[Core] Remove PreOrder By Owner', RemovePreOrderByOwnerFail = '[Core] Remove PreOrder By Owner Fail', RemovePreOrderByOwnerSuccess = '[Core] Remove PreOrder By Owner Success', } export class LoadPreOrders implements Action { readonly type = PreOrderActionTypes.LoadPreOrders; constructor(public payload: string) {} } export class LoadPreOrdersFail implements Action { readonly type = PreOrderActionTypes.LoadPreOrdersFail; constructor(public payload: any) {} } export class LoadPreOrdersSuccess implements Action { readonly type = PreOrderActionTypes.LoadPreOrdersSuccess; constructor(public payload: PreOrders[]) {} } // load PreOrder by id export class LoadPreOrderById implements Action { readonly type = PreOrderActionTypes.LoadPreOrderById; constructor(public payload: string) {} } export class LoadPreOrderByIdFail implements Action { readonly type = PreOrderActionTypes.LoadPreOrderByIdFail; constructor(public payload: any) {} } export class LoadPreOrderByIdSuccess implements Action { readonly type = PreOrderActionTypes.LoadPreOrderByIdSuccess; constructor(public payload: PreOrders) {} } export class LoadPreOrdersByOwner implements Action { readonly type = PreOrderActionTypes.LoadPreOrdersByOwner; } export class LoadPreOrdersByOwnerFail implements Action { readonly type = PreOrderActionTypes.LoadPreOrdersByOwnerFail; constructor(public payload: any) {} } export class LoadPreOrdersByOwnerSuccess implements Action { readonly type = PreOrderActionTypes.LoadPreOrdersByOwnerSuccess; constructor(public payload: PreOrders[]) {} } // remove by owner export class RemovePreOrderByOwner implements Action { readonly type = PreOrderActionTypes.RemovePreOrderByOwner; constructor(public payload: PreOrders) {} } export class RemovePreOrderByOwnerFail implements Action { readonly type = PreOrderActionTypes.RemovePreOrderByOwnerFail; constructor(public payload: any) {} } export class RemovePreOrderByOwnerSuccess implements Action { readonly type = PreOrderActionTypes.RemovePreOrderByOwnerSuccess; constructor(public payload: PreOrders) {} } export type PreOrderAction = | LoadPreOrders | LoadPreOrdersFail | LoadPreOrdersSuccess | LoadPreOrderById | LoadPreOrderByIdFail | LoadPreOrderByIdSuccess | LoadPreOrdersByOwner | LoadPreOrdersByOwnerFail | LoadPreOrdersByOwnerSuccess | RemovePreOrderByOwner | RemovePreOrderByOwnerFail | RemovePreOrderByOwnerSuccess;
ca214685c8649bc27d5d34612a0112968a75fb0e
TypeScript
yaritaft/algorithms
/quickSort.ts
2.671875
3
function quickSort(array2: number[]){ let pivot = Math.floor(array2.length/2); }
5614aabab180402fae1d5985eedc7def0b939109
TypeScript
stormseed/tidy-config
/src/lib/ConfigFunctions.ts
2.71875
3
import * as path from 'path' import { promises as fsPromises } from 'fs' import { AbsolutePath, RelativePath, ListOfFileNames } from './SharedTypesAndVars' import output from './OutputFunctions' import { PathFunctions } from './PathFunctions' import { PackageFileFunctions } from './PackageFileFunctions' export class ConfigFunctions { projectRootPath: AbsolutePath = '' configFolderRelativePath: RelativePath = 'config' pathFunctions: PathFunctions = new PathFunctions() packageFileFunctions: PackageFileFunctions = new PackageFileFunctions() constructor() { this.pathFunctions.setProjectRootPath(process.cwd()) } async moveListOfFiles( fileList: ListOfFileNames, options?: { restore?: boolean; hydrate?: boolean } ) { try { await this.pathFunctions.configFolderExistsOrCreate() } catch (err) { return err } const configAbsolutePath = this.pathFunctions.getConfigFolderAbsolutePath() for (let fileName of fileList) { let pathToFileInRootDir = this.pathFunctions.getAbsolutePathFromRoot(fileName) if (options?.restore) { let pathToFileInConfigDir = this.pathFunctions.getAbsolutePath(configAbsolutePath, fileName) output.debug({ pathToFileInRootDir, pathToFileInConfigDir }) if ( (await this.linkExists(pathToFileInRootDir)) && (await this.fileExistsAndNotALink(pathToFileInConfigDir)) ) { output.info(`Restoring file ${fileName}`) await this.restoreFile(pathToFileInConfigDir, this.projectRootPath) } else { output.debug('restoring file did not pass tests') output.debug( 'this.linkExists(pathToFileInRootDir)', await this.linkExists(pathToFileInRootDir) ) } } else if (options?.hydrate) { let pathToFileInConfigDir = this.pathFunctions.getAbsolutePath(configAbsolutePath, fileName) if ( !(await this.linkExists(pathToFileInRootDir)) && (await this.fileExistsAndNotALink(pathToFileInConfigDir)) ) { output.info(`Creating root symlink for ${pathToFileInConfigDir}`) await this.createRelativeSymlink(pathToFileInRootDir, pathToFileInConfigDir) } } else { if (await this.fileExistsAndNotALink(pathToFileInRootDir)) { output.info(`Moving file ${fileName}`) await this.moveAndLeaveSymlink(pathToFileInRootDir, configAbsolutePath) } } } } async createRelativeSymlink( originalFilePath: AbsolutePath, newPath: AbsolutePath ): Promise<void> { return fsPromises.symlink( path.join( this.pathFunctions.getRelativePathFromAbsoluteFilePaths(originalFilePath, newPath), path.basename(originalFilePath) ), originalFilePath ) } async fileExistsAndNotALink(filePath: AbsolutePath): Promise<boolean> { let fileStat try { fileStat = await fsPromises.stat(filePath) } catch (e) { return false } return !fileStat.isSymbolicLink() } async linkExists(filePath: AbsolutePath): Promise<boolean> { let fileStat try { fileStat = await fsPromises.lstat(filePath) } catch (e) { return false } return fileStat.isSymbolicLink() } async moveAndLeaveSymlink( originalFilePath: AbsolutePath, targetFolder: AbsolutePath ): Promise<void> { output.debug('moveAndLeaveSymlink called', { originalFilePath, targetFolder, }) const newPath = this.calculateNewFilePath(originalFilePath, targetFolder) output.debug('New file location = ', newPath) await fsPromises.rename(originalFilePath, newPath) output.debug('calling symlink with ', { path: path.join( this.pathFunctions.getRelativePathFromAbsoluteFilePaths(originalFilePath, newPath), path.basename(originalFilePath) ), target: originalFilePath, }) // await fsPromises.symlink( // path.join( // this.pathFunctions.getRelativePathFromAbsoluteFilePaths(originalFilePath, newPath), // path.basename(originalFilePath) // ), // originalFilePath // ) await this.createRelativeSymlink(originalFilePath, newPath) return } async restoreFile(movedFilePath: AbsolutePath, targetFolder: AbsolutePath): Promise<void> { const newPath = this.calculateNewFilePath(movedFilePath, targetFolder) output.debug('restoreFile newPath: ', newPath) await fsPromises.unlink(newPath) await fsPromises.rename(movedFilePath, newPath) return } calculateNewFilePath( originalFileNamePath: AbsolutePath, targetDirectory: AbsolutePath ): AbsolutePath { return path.join(targetDirectory, path.basename(originalFileNamePath)) } async fullMoveFilesToConfigFolder(): Promise<void> { try { const listOfPackages = await this.packageFileFunctions.getListOfFilesFromPackage() await this.moveListOfFiles(listOfPackages) } catch (err) { output.error(err) return err } } async fullRestoreFilesFromConfigFolder(): Promise<void> { try { const listOfPackages = await this.packageFileFunctions.getListOfFilesFromPackage() await this.moveListOfFiles(listOfPackages, { restore: true }) } catch (err) { output.error(err) return err } } async hydrateSymlinksFromConfigFolder(): Promise<void> { try { const listOfPackages = await this.packageFileFunctions.getListOfFilesFromPackage() await this.moveListOfFiles(listOfPackages, { hydrate: true }) } catch (err) { output.error(err) return err } } }
9536ec35bdf3b36056e4aadad198f58144cf1492
TypeScript
AtelyPham/procon-server-dev
/src/v1/types/classes/TilePoint.ts
2.953125
3
import Point from "./Point" export default class TilePoint extends Point { _point: number = 0 TilePoint(point: number = 0) { this._point = point } setPoint(point: number) { this._point = point return this } get point() { return this._point } }
c7358ab20c7c5b3701ecdfd5243bc6fb4d5b3c10
TypeScript
QScore/qscore-serverless
/src/util/encryption/encryptor.ts
3.109375
3
import crypto from 'crypto' const secretKey = process.env.SECRET_KEY as string // Must be 256 bits (32 characters) const ivLength = 16 // For AES, this is always 16 const bufferEncoding: BufferEncoding = "base64" const algorithm = 'aes-256-cbc' export function encrypt(text: string): string { const iv = crypto.randomBytes(ivLength) const cipher = crypto.createCipheriv(algorithm, Buffer.from(secretKey), iv) let encrypted = cipher.update(text) encrypted = Buffer.concat([encrypted, cipher.final()]) return iv.toString(bufferEncoding) + ':' + encrypted.toString(bufferEncoding) } export function decrypt(text: string): string { const textParts = text.split(':') const iv = Buffer.from(textParts.shift() as string, bufferEncoding) const encryptedText = Buffer.from(textParts.join(':'), bufferEncoding) const decipher = crypto.createDecipheriv(algorithm, Buffer.from(secretKey), iv) let decrypted = decipher.update(encryptedText) decrypted = Buffer.concat([decrypted, decipher.final()]) return decrypted.toString() }
33654eddfd71346e73a98323082a9b7662a6c7ec
TypeScript
aitheon-karma/ai-smart-infrastructure
/client/src/app/infrastructure-map/utils/get-area-bounding-rect.ts
3
3
import { Coordinates } from '../shared/interfaces/coordinates.interface'; import { BoundingRect } from '../shared/interfaces/bounding-rect.interface'; export const getAreaBoundingRect = (points: Coordinates[] = []): BoundingRect => { const areaRect: BoundingRect = points.reduce((rect, { x, y }) => { return { left: x < rect.left ? x : rect.left, top: y < rect.top ? y : rect.top, bottom: y > rect.bottom ? y : rect.bottom, right: x > rect.right ? x : rect.right, }; }, { left: points[0].x, top: points[0].y, bottom: points[0].y, right: points[0].x }); areaRect.left = Math.round(areaRect.left); areaRect.right = Math.round(areaRect.right); areaRect.top = Math.round(areaRect.top); areaRect.bottom = Math.round(areaRect.bottom); areaRect.width = areaRect.right - areaRect.left; areaRect.height = areaRect.bottom - areaRect.top; return areaRect; };
91e9a912987a190724e65489e9e755dda55de7a1
TypeScript
citizenfx/fxcode
/src/vs/editor/browser/controller/textAreaState.ts
2.546875
3
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import * as strings from 'vs/base/common/strings'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import { EndOfLinePreference } from 'vs/editor/common/model'; export const _debugComposition = false; export interface ITextAreaWrapper { getValue(): string; setValue(reason: string, value: string): void; getSelectionStart(): number; getSelectionEnd(): number; setSelectionRange(reason: string, selectionStart: number, selectionEnd: number): void; } export interface ISimpleModel { getLineCount(): number; getLineMaxColumn(lineNumber: number): number; getValueInRange(range: Range, eol: EndOfLinePreference): string; } export interface ITypeData { text: string; replacePrevCharCnt: number; replaceNextCharCnt: number; positionDelta: number; } export class TextAreaState { public static readonly EMPTY = new TextAreaState('', 0, 0, null, null); public readonly value: string; public readonly selectionStart: number; public readonly selectionEnd: number; public readonly selectionStartPosition: Position | null; public readonly selectionEndPosition: Position | null; constructor(value: string, selectionStart: number, selectionEnd: number, selectionStartPosition: Position | null, selectionEndPosition: Position | null) { this.value = value; this.selectionStart = selectionStart; this.selectionEnd = selectionEnd; this.selectionStartPosition = selectionStartPosition; this.selectionEndPosition = selectionEndPosition; } public toString(): string { return '[ <' + this.value + '>, selectionStart: ' + this.selectionStart + ', selectionEnd: ' + this.selectionEnd + ']'; } public static readFromTextArea(textArea: ITextAreaWrapper): TextAreaState { return new TextAreaState(textArea.getValue(), textArea.getSelectionStart(), textArea.getSelectionEnd(), null, null); } public collapseSelection(): TextAreaState { return new TextAreaState(this.value, this.value.length, this.value.length, null, null); } public writeToTextArea(reason: string, textArea: ITextAreaWrapper, select: boolean): void { if (_debugComposition) { console.log('writeToTextArea ' + reason + ': ' + this.toString()); } textArea.setValue(reason, this.value); if (select) { textArea.setSelectionRange(reason, this.selectionStart, this.selectionEnd); } } public deduceEditorPosition(offset: number): [Position | null, number, number] { if (offset <= this.selectionStart) { const str = this.value.substring(offset, this.selectionStart); return this._finishDeduceEditorPosition(this.selectionStartPosition, str, -1); } if (offset >= this.selectionEnd) { const str = this.value.substring(this.selectionEnd, offset); return this._finishDeduceEditorPosition(this.selectionEndPosition, str, 1); } const str1 = this.value.substring(this.selectionStart, offset); if (str1.indexOf(String.fromCharCode(8230)) === -1) { return this._finishDeduceEditorPosition(this.selectionStartPosition, str1, 1); } const str2 = this.value.substring(offset, this.selectionEnd); return this._finishDeduceEditorPosition(this.selectionEndPosition, str2, -1); } private _finishDeduceEditorPosition(anchor: Position | null, deltaText: string, signum: number): [Position | null, number, number] { let lineFeedCnt = 0; let lastLineFeedIndex = -1; while ((lastLineFeedIndex = deltaText.indexOf('\n', lastLineFeedIndex + 1)) !== -1) { lineFeedCnt++; } return [anchor, signum * deltaText.length, lineFeedCnt]; } public static selectedText(text: string): TextAreaState { return new TextAreaState(text, 0, text.length, null, null); } public static deduceInput(previousState: TextAreaState, currentState: TextAreaState, couldBeEmojiInput: boolean): ITypeData { if (!previousState) { // This is the EMPTY state return { text: '', replacePrevCharCnt: 0, replaceNextCharCnt: 0, positionDelta: 0 }; } if (_debugComposition) { console.log('------------------------deduceInput'); console.log('PREVIOUS STATE: ' + previousState.toString()); console.log('CURRENT STATE: ' + currentState.toString()); } let previousValue = previousState.value; let previousSelectionStart = previousState.selectionStart; let previousSelectionEnd = previousState.selectionEnd; let currentValue = currentState.value; let currentSelectionStart = currentState.selectionStart; let currentSelectionEnd = currentState.selectionEnd; // Strip the previous suffix from the value (without interfering with the current selection) const previousSuffix = previousValue.substring(previousSelectionEnd); const currentSuffix = currentValue.substring(currentSelectionEnd); const suffixLength = strings.commonSuffixLength(previousSuffix, currentSuffix); currentValue = currentValue.substring(0, currentValue.length - suffixLength); previousValue = previousValue.substring(0, previousValue.length - suffixLength); const previousPrefix = previousValue.substring(0, previousSelectionStart); const currentPrefix = currentValue.substring(0, currentSelectionStart); const prefixLength = strings.commonPrefixLength(previousPrefix, currentPrefix); currentValue = currentValue.substring(prefixLength); previousValue = previousValue.substring(prefixLength); currentSelectionStart -= prefixLength; previousSelectionStart -= prefixLength; currentSelectionEnd -= prefixLength; previousSelectionEnd -= prefixLength; if (_debugComposition) { console.log('AFTER DIFFING PREVIOUS STATE: <' + previousValue + '>, selectionStart: ' + previousSelectionStart + ', selectionEnd: ' + previousSelectionEnd); console.log('AFTER DIFFING CURRENT STATE: <' + currentValue + '>, selectionStart: ' + currentSelectionStart + ', selectionEnd: ' + currentSelectionEnd); } if (couldBeEmojiInput && currentSelectionStart === currentSelectionEnd && previousValue.length > 0) { // on OSX, emojis from the emoji picker are inserted at random locations // the only hints we can use is that the selection is immediately after the inserted emoji // and that none of the old text has been deleted let potentialEmojiInput: string | null = null; if (currentSelectionStart === currentValue.length) { // emoji potentially inserted "somewhere" after the previous selection => it should appear at the end of `currentValue` if (currentValue.startsWith(previousValue)) { // only if all of the old text is accounted for potentialEmojiInput = currentValue.substring(previousValue.length); } } else { // emoji potentially inserted "somewhere" before the previous selection => it should appear at the start of `currentValue` if (currentValue.endsWith(previousValue)) { // only if all of the old text is accounted for potentialEmojiInput = currentValue.substring(0, currentValue.length - previousValue.length); } } if (potentialEmojiInput !== null && potentialEmojiInput.length > 0) { // now we check that this is indeed an emoji // emojis can grow quite long, so a length check is of no help // e.g. 1F3F4 E0067 E0062 E0065 E006E E0067 E007F -- flag of England // Oftentimes, emojis use Variation Selector-16 (U+FE0F), so that is a good hint // http://emojipedia.org/variation-selector-16/ // > An invisible codepoint which specifies that the preceding character // > should be displayed with emoji presentation. Only required if the // > preceding character defaults to text presentation. if (/\uFE0F/.test(potentialEmojiInput) || strings.containsEmoji(potentialEmojiInput)) { return { text: potentialEmojiInput, replacePrevCharCnt: 0, replaceNextCharCnt: 0, positionDelta: 0 }; } } } if (currentSelectionStart === currentSelectionEnd) { // composition accept case (noticed in FF + Japanese) // [blahblah] => blahblah| if ( previousValue === currentValue && previousSelectionStart === 0 && previousSelectionEnd === previousValue.length && currentSelectionStart === currentValue.length && currentValue.indexOf('\n') === -1 ) { if (strings.containsFullWidthCharacter(currentValue)) { return { text: '', replacePrevCharCnt: 0, replaceNextCharCnt: 0, positionDelta: 0 }; } } // no current selection const replacePreviousCharacters = (previousPrefix.length - prefixLength); if (_debugComposition) { console.log('REMOVE PREVIOUS: ' + (previousPrefix.length - prefixLength) + ' chars'); } return { text: currentValue, replacePrevCharCnt: replacePreviousCharacters, replaceNextCharCnt: 0, positionDelta: 0 }; } // there is a current selection => composition case const replacePreviousCharacters = previousSelectionEnd - previousSelectionStart; return { text: currentValue, replacePrevCharCnt: replacePreviousCharacters, replaceNextCharCnt: 0, positionDelta: 0 }; } public static deduceAndroidCompositionInput(previousState: TextAreaState, currentState: TextAreaState): ITypeData { if (!previousState) { // This is the EMPTY state return { text: '', replacePrevCharCnt: 0, replaceNextCharCnt: 0, positionDelta: 0 }; } if (_debugComposition) { console.log('------------------------deduceAndroidCompositionInput'); console.log('PREVIOUS STATE: ' + previousState.toString()); console.log('CURRENT STATE: ' + currentState.toString()); } if (previousState.value === currentState.value) { return { text: '', replacePrevCharCnt: 0, replaceNextCharCnt: 0, positionDelta: currentState.selectionEnd - previousState.selectionEnd }; } const prefixLength = Math.min(strings.commonPrefixLength(previousState.value, currentState.value), previousState.selectionEnd); const suffixLength = Math.min(strings.commonSuffixLength(previousState.value, currentState.value), previousState.value.length - previousState.selectionEnd); const previousValue = previousState.value.substring(prefixLength, previousState.value.length - suffixLength); const currentValue = currentState.value.substring(prefixLength, currentState.value.length - suffixLength); const previousSelectionStart = previousState.selectionStart - prefixLength; const previousSelectionEnd = previousState.selectionEnd - prefixLength; const currentSelectionStart = currentState.selectionStart - prefixLength; const currentSelectionEnd = currentState.selectionEnd - prefixLength; if (_debugComposition) { console.log('AFTER DIFFING PREVIOUS STATE: <' + previousValue + '>, selectionStart: ' + previousSelectionStart + ', selectionEnd: ' + previousSelectionEnd); console.log('AFTER DIFFING CURRENT STATE: <' + currentValue + '>, selectionStart: ' + currentSelectionStart + ', selectionEnd: ' + currentSelectionEnd); } return { text: currentValue, replacePrevCharCnt: previousSelectionEnd, replaceNextCharCnt: previousValue.length - previousSelectionEnd, positionDelta: currentSelectionEnd - currentValue.length }; } } export class PagedScreenReaderStrategy { private static _getPageOfLine(lineNumber: number, linesPerPage: number): number { return Math.floor((lineNumber - 1) / linesPerPage); } private static _getRangeForPage(page: number, linesPerPage: number): Range { const offset = page * linesPerPage; const startLineNumber = offset + 1; const endLineNumber = offset + linesPerPage; return new Range(startLineNumber, 1, endLineNumber + 1, 1); } public static fromEditorSelection(previousState: TextAreaState, model: ISimpleModel, selection: Range, linesPerPage: number, trimLongText: boolean): TextAreaState { const selectionStartPage = PagedScreenReaderStrategy._getPageOfLine(selection.startLineNumber, linesPerPage); const selectionStartPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionStartPage, linesPerPage); const selectionEndPage = PagedScreenReaderStrategy._getPageOfLine(selection.endLineNumber, linesPerPage); const selectionEndPageRange = PagedScreenReaderStrategy._getRangeForPage(selectionEndPage, linesPerPage); const pretextRange = selectionStartPageRange.intersectRanges(new Range(1, 1, selection.startLineNumber, selection.startColumn))!; let pretext = model.getValueInRange(pretextRange, EndOfLinePreference.LF); const lastLine = model.getLineCount(); const lastLineMaxColumn = model.getLineMaxColumn(lastLine); const posttextRange = selectionEndPageRange.intersectRanges(new Range(selection.endLineNumber, selection.endColumn, lastLine, lastLineMaxColumn))!; let posttext = model.getValueInRange(posttextRange, EndOfLinePreference.LF); let text: string; if (selectionStartPage === selectionEndPage || selectionStartPage + 1 === selectionEndPage) { // take full selection text = model.getValueInRange(selection, EndOfLinePreference.LF); } else { const selectionRange1 = selectionStartPageRange.intersectRanges(selection)!; const selectionRange2 = selectionEndPageRange.intersectRanges(selection)!; text = ( model.getValueInRange(selectionRange1, EndOfLinePreference.LF) + String.fromCharCode(8230) + model.getValueInRange(selectionRange2, EndOfLinePreference.LF) ); } // Chromium handles very poorly text even of a few thousand chars // Cut text to avoid stalling the entire UI if (trimLongText) { const LIMIT_CHARS = 500; if (pretext.length > LIMIT_CHARS) { pretext = pretext.substring(pretext.length - LIMIT_CHARS, pretext.length); } if (posttext.length > LIMIT_CHARS) { posttext = posttext.substring(0, LIMIT_CHARS); } if (text.length > 2 * LIMIT_CHARS) { text = text.substring(0, LIMIT_CHARS) + String.fromCharCode(8230) + text.substring(text.length - LIMIT_CHARS, text.length); } } return new TextAreaState(pretext + text + posttext, pretext.length, pretext.length + text.length, new Position(selection.startLineNumber, selection.startColumn), new Position(selection.endLineNumber, selection.endColumn)); } }
57f70538676951e0d6a9c23d6f8dfacd65b8ec9c
TypeScript
microsoft/vscode-postgresql
/src/prompts/progressIndicator.ts
2.625
3
'use strict'; // This code is originally from https://github.com/DonJayamanne/bowerVSCode // License: https://github.com/DonJayamanne/bowerVSCode/blob/master/LICENSE import {window, StatusBarItem, StatusBarAlignment} from 'vscode'; export default class ProgressIndicator { private _statusBarItem: StatusBarItem; constructor() { this._statusBarItem = window.createStatusBarItem(StatusBarAlignment.Left); } private _tasks: string[] = []; public beginTask(task: string): void { this._tasks.push(task); this.displayProgressIndicator(); } public endTask(task: string): void { if (this._tasks.length > 0) { this._tasks.pop(); } this.setMessage(); } private setMessage(): void { if (this._tasks.length === 0) { this._statusBarItem.text = ''; this.hideProgressIndicator(); return; } this._statusBarItem.text = this._tasks[this._tasks.length - 1]; this._statusBarItem.show(); } private _interval: any; private displayProgressIndicator(): void { this.setMessage(); this.hideProgressIndicator(); this._interval = setInterval(() => this.onDisplayProgressIndicator(), 100); } private hideProgressIndicator(): void { if (this._interval) { clearInterval(this._interval); this._interval = undefined; } this.ProgressCounter = 0; } private ProgressText = ['|', '/', '-', '\\', '|', '/', '-', '\\']; private ProgressCounter = 0; private onDisplayProgressIndicator(): void { if (this._tasks.length === 0) { return; } let txt = this.ProgressText[this.ProgressCounter]; this._statusBarItem.text = this._tasks[this._tasks.length - 1] + ' ' + txt; this.ProgressCounter++; if (this.ProgressCounter >= this.ProgressText.length - 1) { this.ProgressCounter = 0; } } }
4ab2a920675df7e6cf9a74d7c8c62e7626259000
TypeScript
xyhdgh/algorithm022
/Week_01/189.旋转数组.ts
3.234375
3
/** Do not return anything, modify nums in-place instead. */ function rotate(nums: number[], k: number): void { const len = nums.length; if (len === 0 || !len) return; let r = k % len; while (r--) { nums.unshift(nums.pop()); } }
42212f164f207c3fd2cf9385d0fe3f09e1c79a30
TypeScript
future4code/cruz-labenu-system19
/src/endpoints/criarTurma.ts
2.90625
3
import {Request, Response} from 'express'; import connection from '../connection'; import {Class} from '../types' export default async function criarTurma( req: Request, res: Response ): Promise<void> { try { const {nome, data_inicio, data_final, modulo} = req.body; if(!nome || !data_inicio || !data_final || !modulo) { throw new Error("Campos estão vazios! Por favor, informe os dados corretamente."); }; //trava para data_inicio e data_final const turma = await connection("class") .insert({nome, data_inicio, data_final, modulo}); res.status(201).send( "Turma criada com sucesso!" ); } catch (err) { console.log(err) res.status(500).send("Ocorreu um erro inesperado!"); }; };
b88383fcca063f67d96e92a32800408b41ad90cd
TypeScript
sheinsight/shineout
/src/Gap/Props.ts
2.625
3
import * as React from 'react' import { ReactNode } from 'react' import { StandardProps } from '../@types/common' /** * @title Gap */ export interface GapProps extends StandardProps { /** * @en column spacing in the horizontal direction * @cn 水平方向的列间距 * @default 8 */ column?: number | string /** * @en vertical line spacing * @cn 垂直方向的行间距 * @default 8 */ row?: number | string /** * @en the styles of child elements * @cn 子元素自定义样式 */ itemStyle?: React.CSSProperties /** * @en children * @cn 子元素 */ children?: ReactNode }
fcbddd2b546a72904c59c8028ee37511c5da62e7
TypeScript
dkaluza/NeuralNetworkVisualization
/frontend/NNVisualization/src/app/build/layers/pool/pool.ts
3.15625
3
import { Layer } from '../layer/layer'; import { Padding, StrToPadding } from '../conv/conv'; export enum Pool { Max, Average } export function StrToPool(str: string): Pool { switch (str) { case 'Max': return Pool.Max; case 'Average': return Pool.Average; default: return Pool.Max; } } export class PoolLayer extends Layer { private _kernelShape: string; private _strides: string; private _padding: Padding; private _pool: Pool; constructor(id: number, label: string, kernelShape = '2, 2', strides = '2, 2', padding = Padding.Valid, pool = Pool.Max) { super(id, label, 'pool'); this._kernelShape = kernelShape; this._strides = strides; this._padding = padding; this._pool = pool; } static fromDict(dict): PoolLayer { return new PoolLayer( dict.id, dict.label, String(dict.params.kernelShape), String(dict.params.strides), StrToPadding(dict.params.padding), StrToPool(dict.params.pool) ); } get kernelShape(): string { return this._kernelShape; } set kernelShape(kernelShape: string) { this._kernelShape = kernelShape; } get strides(): string { return this._strides; } set strides(strides: string) { this._strides = strides; } get padding(): Padding { return this._padding; } set padding(padding: Padding) { this._padding = padding; } get pool(): Pool { return this._pool; } set pool(pool: Pool) { this._pool = pool; } addAttributes(dict) { dict['kernelShape'] = this.strToArray(this._kernelShape); dict['strides'] = this.strToArray(this._strides); dict['padding'] = Padding[this._padding]; dict['pool'] = Pool[this._pool]; return dict; } getMinNumOfInputs(): number { return 1; } getMaxNumOfInputs(): number { return 1; } calculateOutputShape(shapes: number[][]): number[] { const shape = shapes[0]; let x = 0, y = 0; const s = this.strToArray(this._strides); if (this._padding === Padding.Same) { x = Math.ceil(shape[1] / s[0]); y = Math.ceil(shape[2] / s[1]); } else { // this._padding === Padding.Valid x = Math.ceil((shape[1] - s[0] + 1) / s[0]); y = Math.ceil((shape[2] - s[1] + 1) / s[1]); } return [shape[0], x, y, shape[3]]; } validateInputShapes(shapes: number[][]): boolean { if (shapes.length !== 1) { return false; } if (shapes[0].length !== 4) { return false; } return true; } }
e19f5f007ff73cb3a7f93cc50d536e7f1f79bfc8
TypeScript
havandenberg/react-fitness-club
/src/types/program.ts
2.546875
3
export interface Division { id: string; name: string; } export interface Instructor { bio?: React.ReactNode; name: string; logoSrc?: string; photoSrc?: string; } export interface Program { aboutUrl: string; divisions: Division[]; eventBackground: string; eventColor: string; id: string; logoSrc: string; name: string; } export interface ProgramContent { description: React.ReactNode; id: string; instructors: Instructor[]; name: string; }
1b6b38e255b6b3bf3d47a76e01afe8a0d5afb387
TypeScript
Byzanthelio/nem2-input-forms
/src/formElements/inputPassword.ts
2.78125
3
export class inputPassword{ public readonly type:string = "inputPassword"; public readonly options:undefined; constructor(public readonly label : string, public readonly description: string) { }; public static create(label: string, description: string) : inputPassword{ return new inputPassword(label,description); }; }
52397b8a40b732b2ea5e3e2d80bd4e57d41888aa
TypeScript
willy20040711/nextjs-grandstack-starter-typescript
/app/apollo/type-defs.ts
2.78125
3
// Describe our GraphQL schema with type definitions export const typeDefs = ` type User { userId: ID! name: String reviews: [Review] @relation(name: "WROTE", direction: "OUT") avgStars: Float @cypher( statement: "MATCH (this)-[:WROTE]->(r:Review) RETURN toFloat(avg(r.stars))" ) numReviews: Int @cypher(statement: "MATCH (this)-[:WROTE]->(r:Review) RETURN COUNT(r)") recommendations(first: Int = 3): [Business] @cypher( statement: "MATCH (this)-[:WROTE]->(r:Review)-[:REVIEWS]->(:Business)<-[:REVIEWS]-(:Review)<-[:WROTE]-(:User)-[:WROTE]->(:Review)-[:REVIEWS]->(rec:Business) WHERE NOT EXISTS( (this)-[:WROTE]->(:Review)-[:REVIEWS]->(rec) ) WITH rec, COUNT(*) AS num ORDER BY num DESC LIMIT $first RETURN rec" ) } type Business { businessId: ID! name: String! address: String city: String state: String location: Point avgStars: Float @cypher( statement: "MATCH (this)<-[:REVIEWS]-(r:Review) RETURN coalesce(avg(r.stars),0.0)" ) reviews: [Review] @relation(name: "REVIEWS", direction: "IN") categories: [Category] @relation(name: "IN_CATEGORY", direction: "OUT") } type Review { reviewId: ID! stars: Float text: String date: Date business: Business @relation(name: "REVIEWS", direction: "OUT") user: User @relation(name: "WROTE", direction: "IN") } type Category { name: ID! businesses: [Business] @relation(name: "IN_CATEGORY", direction: "IN") } type RatingCount { stars: Float! count: Int! } type Mutation { mergeBusinessCategory(categories: [String!]!, businessId: ID!): Business @cypher( statement: "MATCH (b:Business {businessId: $businessId}) UNWIND $categories AS cat MERGE (c:Category {name: cat}) MERGE (b)-[:IN_CATEGORY]->(c) RETURN b" ) } type Query { """ A sample query to verify that our GraphQL server is online. It returns a friendly greeting with the current timestamp. """ hello: String!, userCount: Int! @cypher(statement: "MATCH (u:User) RETURN COUNT(u)") ratingsCount: [RatingCount] @cypher( statement: "MATCH (r:Review) WITH r.stars AS stars, COUNT(*) AS count ORDER BY stars RETURN {stars: stars, count: count}" ) } `
600901e6a3782f93c40b66df316bedf078f69f7c
TypeScript
nickzinn/circles
/src/gamelib/sprites/TitleSprite.ts
2.875
3
import { Sprite } from "./Sprite"; import { Point } from "../types/Point"; import { Size } from "../types/Size"; export class TitleSprite implements Sprite{ name: string = 'Title'; position: Point = {x:0,y:0}; size: Size = {width:1, height:1}; speed =0; angle =0; isAlive: boolean = true; zOrder: number = 100; canCollide: boolean = false; isFixedPosition = true; title:string; subtitle1:string; subtitle2:string; constructor(title:string, subtitle1:string, subtitle2:string){ this.title = title; this.subtitle1 = subtitle1; this.subtitle2 = subtitle2; } paint(location: Point, ctx: CanvasRenderingContext2D, timeSinceLastAnimation: number): void { //ctx.measureText const w = ctx.canvas.width, h = ctx.canvas.height; const oldFont = ctx.font; function shadowText(txt:string, x:number,y:number, i:number){ ctx.fillStyle = "grey"; ctx.fillText(txt, x+i, y+i); ctx.fillStyle = "white"; ctx.fillText(txt, x,y); } ctx.font = (w>400) ? (w>500) ? (w>800) ? (w>1000) ? "110px Electrolize": "80px Electrolize": "60px Electrolize" : "40px Electrolize": "30px Electrolize"; let measure = ctx.measureText(this.title); let hpos = h/3; shadowText(this.title, (w-measure.width)/2, hpos, 3); const subHeight = (w>500) ? (w>800) ? 30: 24 : 18; ctx.font = `${subHeight}px Electrolize`; measure = ctx.measureText(this.subtitle1); hpos += subHeight*2; shadowText(this.subtitle1, (w-measure.width)/2,hpos, 1); measure = ctx.measureText(this.subtitle2); hpos += subHeight*2; shadowText(this.subtitle2, (w-measure.width)/2,hpos,1); ctx.font = oldFont; } }
c3fde82cf6fe81800f4b20b48e585103fcf4e9a0
TypeScript
leonel-aguirre/react-native-animations
/dvd-animation/withBouncing.ts
2.796875
3
import { AnimationState, defineAnimation } from "react-native-redash"; interface BouncingAnimationState extends AnimationState { lastTimestamp: number; direction: -1 | 1; } export const withBouncing = ( velocity: number, lowerBound: number, upperBound: number, onBounce?: () => void ): number => { "worklet"; return defineAnimation<BouncingAnimationState>(() => { "worklet"; const onFrame = (state: BouncingAnimationState, now: number) => { const delta = now - state.lastTimestamp; const translation = (delta / 1000) * velocity; state.current += state.direction * translation; if (state.current >= upperBound || state.current < lowerBound) { state.direction *= -1; onBounce?.(); } state.lastTimestamp = now; return false; }; const onStart = ( state: BouncingAnimationState, value: number, now: number ) => { state.current = lowerBound + Math.random() * upperBound; state.lastTimestamp = now; state.direction = 1; }; return { onFrame, onStart, }; }); };
7000d31d899b36c11e019832f888ef5d0ed1a1dd
TypeScript
espenja/radtools
/packages/bundle/src/configs/plugins/CleanTerminalPlugin.ts
2.921875
3
interface CleanTerminalPluginOptions { /** * Message to be printed */ message?: string /** * Only clear the screen if webpack is in watch mode * @default true */ onlyInWatchMode?: boolean /** * Don't clear the screen on first webpack run * @default true */ skipFirstRun?: boolean /** * Clear screen before compiling instead of after (v3 and above) * @default true */ beforeCompile?: boolean } const defaultOptions = (options: CleanTerminalPluginOptions) => ({ onlyInWatchMode: true, skipFirstRun: true, beforeCompile: true, ...options }) /** * Clears the terminal between dev server compilations. * * Code borrowed from: * https://github.com/danillouz/clean-terminal-webpack-plugin#readme MIT License Copyright (c) 2017 Daniël Illouz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ export class CleanTerminalPlugin { public readonly options: CleanTerminalPluginOptions public firstRun = true public constructor(options: CleanTerminalPluginOptions = {}) { this.options = defaultOptions(options) } public apply(compiler: any) { let hook = compiler.hooks.afterCompile if (this.options.beforeCompile) { hook = compiler.hooks.beforeCompile } hook.tap("CleanTerminalPlugin", () => { if (this.shouldClearConsole(compiler)) { this.clearConsole() } }) } public shouldClearConsole(compiler: any) { if (this.firstRun) { this.firstRun = false if (this.options.skipFirstRun) { return false } } if (this.options.onlyInWatchMode) { return Boolean(compiler.watchMode) } const isNodeEnvProduction = process.env.NODE_ENV === "production" const isOptionsModeProduction = Boolean(compiler.options && compiler.options.mode === "production") return !isNodeEnvProduction && !isOptionsModeProduction } public clearConsole() { const clear = "\x1B[2J\x1B[3J\x1B[H" const output = this.options.message ? `${clear + this.options.message}\n\n` : clear process.stdout.write(output) } }
c3596759c067fc41c298b87528914fc2964398cd
TypeScript
kravchis/just-dating
/frontend/projects/core/src/store/reducers/chat-message.reducer.ts
2.546875
3
import {EntityAdapter, createEntityAdapter} from '@ngrx/entity'; import * as Actions from '../actions/chat-message.action'; import {ChatMessageState, ChatMessageListState, defaultState} from '../states/chat-message.state'; export const adapter: EntityAdapter<ChatMessageState> = createEntityAdapter<ChatMessageState>(); export const initialState: ChatMessageListState = adapter.getInitialState(defaultState); export function ChatMessageReducer(state = initialState, action: Actions.ActionsUnion) { switch (action.type) { case Actions.ChatMessageActionTypes.UpdateChatMessages: return adapter.upsertMany(action.payload, {...state }); case Actions.ChatMessageActionTypes.UpdateChatMessage: return adapter.upsertOne(action.payload, {...state }); default: return state; } }
7b24fc838b3cd4d3dbda76d4cf5aab2f977ba7b4
TypeScript
Innovic-io/typescript-learning
/src/company.class.ts
2.8125
3
import { IUser } from "./user.interface"; import { ICompany } from "./company.interface"; import { resolve } from "url"; export class Company{ private company: ICompany[] = [] ; /** * */ constructor(){ } addCompany(comp: ICompany) { this.company.push(comp); return this; } getCompany(){ return this.company; } getById(id: string){ return this.company.find(value => value._id === id) } deleteById(id: string){ return this.company.filter(value => value._id!==id) } addUserById(id: string, user: IUser){ const result = this.company.find(value => value._id === id); (!result.users) ? result.users = [user] : result.users.push(user); return this.company; } getCompanyUsers(id: string){ const result = this.company.find(value => value._id === id).users; return new Promise((resolve, reject)=>{ if(!result) { return reject('no users') } return resolve(result); }) /**/ } }
9e6f724ba6432b811bcbc6d73a2854caca10f92f
TypeScript
matheuscasavechia/music-player-app-test
/music-player/src/app/services/Auth/auth.service.ts
2.578125
3
import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { query } from '@angular/animations'; @Injectable({ providedIn: 'root' }) export class AuthService { private spotifyUri: string = 'https://accounts.spotify.com'; private clientId: string = '21e20feab36a4ca899df92d09f011fea'; private redirectUrl: string = 'http://localhost:4200/callback'; private scopes: Array<string> = [ "user-read-currently-playing", "user-read-playback-state", ]; constructor(private Http: HttpClient) { // @to-do definir header da request const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.getToken()}` }) }; } /** * access_token do usuario * @return {string} */ private getToken(): string { const localToken = localStorage.getItem('access_token'); const paramToken = this.getQueryParam('access_token', window.location.href); return localToken || paramToken; }; /** * Retorna o valor do parametro desejado caso exista na URL * @param {string} queryParam, parametro da query string * @return {string} Valor do parametro */ public getQueryParam(path, queryParam): string { const url = path.split('?'); let token = ''; if (url.length <= 1) { return token; } const urlParams = url[url.length - 1].split('&'); for (let i = 0; i < urlParams.length; i += 1) { const paramValue = urlParams[i].split('='); if (paramValue[0] === queryParam) { token = paramValue[1]; } } return token; } /** * Retorna a url de autenticação * @return {string} */ private authUrl(): string { const params = { redirect_uri: `${this.redirectUrl}`, scope: `${this.scopes}`, client_id: `${this.clientId}`, response_type: 'token', }; const queryString = Object.keys(params).map((key) => { return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]) }).join('&'); return `${this.spotifyUri}/authorize?${queryString}`; }; /** * Direciona o usuario para a tela de login * @return {void} */ public login(): void { window.open(this.authUrl()); }; }
53544d60ff3bfd368e4ee209c1ff03236fecdc8e
TypeScript
MasterJoe2ez/bncb-master
/src/app/setup/set-price/set-price.ts
2.578125
3
export class SetPrice { code?: string = 'N/A'; type?: string | null | undefined; price?: string | null | undefined; constructor(params: SetPrice) { Object.assign(this, params); } }
abf84113e1f35334ec92dfe0e38ccfcd56b99154
TypeScript
delasteve/cling
/src/commands/admin/grant-permissions.command.ts
2.71875
3
import { IUserRepository } from '../../repositories/user.respository'; import { IMessenger } from '../../messengers/messenger.interface'; import { AbstractCommand } from '../abstract.command'; export class GrantPermissionsCommand extends AbstractCommand { private readonly userRepository: IUserRepository; private readonly messenger: IMessenger; private readonly validPermissions: string[]; constructor(userRepository: IUserRepository, messenger: IMessenger) { const commandPattern = /^\!p(?:ermission(?:s)?)?\s+<\@(U\d+\w+)>\s+(.*)/i; super(commandPattern); this.userRepository = userRepository; this.messenger = messenger; // TODO: put this in the database this.validPermissions = [ 'admin', 'open', 'close', 'label', 'assign', 'review', 'lock', 'issue', 'issue:open', 'issue:close', 'issue:label', 'issue:assign', 'issue:lock', 'pr', 'pr:open', 'pr:close', 'pr:label', 'pr:assign', 'pr:review', 'pr:lock', 'ci', 'travis', 'appveyor' ]; } public async canExecute(payload: any): Promise<boolean> { if (!(await super.canExecute(payload))) { return false; } const hasPermission = await this.userRepository.hasPermissions(payload.user, ['admin']); if (!hasPermission) { await this.messenger.sendMessage('You do not have permission to use this command.', payload); } return hasPermission; } public async execute(payload: any): Promise<void> { const userId = this.getUserId(payload.text); const permissions = this.getPermissionChanges(payload.text); await this.userRepository.addPermissions(userId, permissions.add); await this.userRepository.removePermissions(userId, permissions.remove); if (permissions.add.length > 0 || permissions.remove.length > 0) { await this.messenger.sendMessage('Successfully updated permissions.', payload); } else { await this.messenger.sendMessage('No permissions were updated.', payload); } } private getUserId(text: string) { const matches = this.commandPattern.exec(text); return matches[1]; } private getPermissionChanges(text: string) { const matches = this.commandPattern.exec(text)[2]; const allPermissions: string[] = matches.split(' '); const permissionsToAdd = allPermissions .filter(permission => this.validPermissions.includes(permission)); const permissionsToRemove = allPermissions .map(permission => permission.substring(1)) .filter(permission => this.validPermissions.includes(permission)); return { add: permissionsToAdd, remove: permissionsToRemove }; } }
b67d36024fd75e61cc8a3894bf9d94827dd31866
TypeScript
OrfeasZ/tua
/src/parser/constructs/expressions/boolExpression.ts
2.703125
3
import {BoolExprContext} from "../../../grammar/TuaParser"; import {Type} from "../../types/type"; import {Construct} from "../construct"; import {Expression} from "../expression"; export class BoolExpression extends Expression { public readonly boolValue: boolean; constructor(ctx: BoolExprContext, parent: Construct) { super(parent); this.indexStart = ctx.start.startIndex; this.indexEnd = ctx.stop!.stopIndex + 1; this.boolValue = ctx.text === "true"; } public type(): Type { return Type.Bool; } }
7a4fdee04280dd85952d4fc2c334a4895683f65c
TypeScript
m93enbah/AngularToutarial
/Angular2021/Section16 NGRX Introduction/Youtube/my-app/src/app/Store/Effects/movie.effects.ts
2.515625
3
import { Injectable } from '@angular/core'; import { createEffect, Actions, ofType } from '@ngrx/effects'; import { EmptyError } from 'rxjs'; import { catchError, concatMap, exhaustMap, map, tap } from 'rxjs/operators'; import { Movie } from 'src/app/Models/movie'; import { DataService } from 'src/app/Service/data.service'; import { getMovies, getMoviesSuccess, addMovies, addMoviesSuccess, } from '../Actions/movie.action'; @Injectable() export class MovieEffects { //in effect we pass the action as input then call the data servcie to return respone and then execute another action //we will create effect in order to call services to return response from it loadMovie$ = createEffect(() => this.action$.pipe( ofType(getMovies), //source items are ignored while the previous Observable is not completed exhaustMap(() => this.dataService.getMovies().pipe( map((movies) => getMoviesSuccess(movies)), // catchError(() => EmptyError) ) ) ) ); //in effect we pass the action as input then call the data servcie to return respone and then execute another action //we will create effect in order to call services to return response from it addMovie$ = createEffect(() => this.action$.pipe( ofType(addMovies), tap((movie) => console.log(movie)), //waits for the previous Observable to complete before creating the next one concatMap(({ movie }) => this.dataService.addMovies(movie).pipe( map((newMovie) => addMoviesSuccess(newMovie)), // catchError(() => EmptyError) ) ) ) ); constructor(private action$: Actions, private dataService: DataService) {} }
6890698ceb7c62df8e2340e72afe1d51e975982f
TypeScript
emeraldwalk/slate-playground
/packages/0.5x/src/util/command.ts
2.5625
3
import { Editor } from 'slate' import { Method } from '../data/editor' export function buildArg( methods: Method[], arg: Method['args'][0], value: string, ) { if (arg.type === 'string') { return value } let parsed try { parsed = JSON.parse(value) } catch (e) { parsed = value } return value ? parsed : undefined } export function isArgValid( arg: Method['args'][0], value: string, ): boolean { if (arg.type === 'string') { return true } let parsed try { parsed = JSON.parse(value) } catch (e) { parsed = value } return (arg.isOptional && value === '') || parsed } export function runCommand( name: string, editor: Editor, ...args: unknown[] ) { console.log('runCommand:', name, '[editor]', ...args) return (Editor as any)[name](editor, ...args) }
dff87b0a36e7648c7fefba4ef517ea0a9cafaecd
TypeScript
NatalieNunez/CodeSignal
/reverse-in-parentheses.ts
3.390625
3
function reverseInParentheses(inputString: string): string { while (inputString.includes('(')) { inputString = inputString.replace(/\(([^()]*)\)/, (_, str) => [...str].reverse().join('')); } return inputString; }
83a48a023ceb461fad9b9ec0e6b89cbea7c9d85c
TypeScript
Nevoss/server-up
/src/utils/log.ts
2.84375
3
const chalk = require('chalk') /** * run an error message and close the program * * @param message */ export const error = (message: string) => { console.error(chalk.bold.red(message)) process.exit() } /** * Print a success message. * * @param message */ export const success = (message: string) => { console.log(chalk.bold.green(message)) }
8ee686fe10657b02ef2e6b9cfd03f67e2a5e3ea9
TypeScript
ethan-qin/leetcode
/240.ts
4.0625
4
// 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target 。该矩阵具有以下特性: // 每行的元素从左到右升序排列。 // 每列的元素从上到下升序排列。 // 示例 1: // 输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5 // 输出:true // 输入:matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20 // 输出:false // 来源:力扣(LeetCode) // 链接:https://leetcode-cn.com/problems/search-a-2d-matrix-ii // 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 function searchMatrix_2(matrix: number[][], target: number): boolean { let row = matrix.length let col = matrix[0].length let i = row - 1 let j = 0 while (i >= 0 && j < col) { if (matrix[i][j] > target) { i-- } else if (matrix[i][j] < target) { j++ } else { return true } } return false }; const matrix_2 = [[1, 4, 7, 11, 15], [2, 5, 8, 12, 19], [3, 6, 9, 16, 22], [10, 13, 14, 17, 24], [18, 21, 23, 26, 30]], target_2 = 6 console.log(searchMatrix(matrix_2, target_2))
68be4f1379fe83157835fe642ddfd650d620f66e
TypeScript
green-fox-academy/BalazsSipos
/week-02/day-03/03Diagonals.ts
2.96875
3
'use strict'; const canvas = document.querySelector('.main-canvas') as HTMLCanvasElement; const ctx = canvas.getContext('2d') as CanvasRenderingContext2D; // DO NOT TOUCH THE CODE ABOVE THIS LINE // Draw the canvas' diagonals. // If it starts from the upper-left corner it should be green, otherwise it should be red. let x: number = 0; ctx.beginPath(); ctx.moveTo(x, 0); ctx.strokeStyle = x === 0 ? 'green' : 'red'; ctx.lineTo(canvas.width, canvas.height); ctx.stroke(); x = canvas.width; ctx.beginPath(); ctx.moveTo(x, 0); ctx.strokeStyle = x === 0 ? 'green' : 'red'; ctx.lineTo(0, canvas.height); ctx.stroke();
7e84fb8b1d1342843cb30fcf6b4f17a223ecebd1
TypeScript
HathorNetwork/hathor-wallet-lib
/src/utils/utxo.ts
3.09375
3
/** * Copyright (c) Hathor Labs and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { IStorage, IUtxo, IUtxoFilterOptions, UtxoSelectionAlgorithm } from '../types'; export enum UtxoSelection { FAST = 'fast', BEST = 'best', }; /** * Get the algorithm function from the enum value. * * @param algorithm The algorithm to get * @returns {UtxoSelectionAlgorithm} The algorithm function */ export function getAlgorithmFromEnum(algorithm: UtxoSelection): UtxoSelectionAlgorithm { switch (algorithm) { case UtxoSelection.FAST: return fastUtxoSelection; case UtxoSelection.BEST: return bestUtxoSelection; default: throw new Error(`Unknown algorithm ${algorithm}`); } } /** * Select utxos to fill the amount required. * This method should be faster since it stops the iteration once the target amount is reached. * Obs: Does not work with authority utxos. * * @param {IStorage} storage The wallet storage to select the utxos * @param {string} token The token uid to select the utxos * @param {number} amount The target amount of tokens required * @returns {Promise<{ utxos: IUtxo[], utxosAmount: number}> */ export async function fastUtxoSelection( storage: IStorage, token: string, amount: number, ): Promise<{ utxos: IUtxo[], amount: number}> { const utxos: IUtxo[] = []; let utxosAmount = 0; const options: IUtxoFilterOptions = { token, authorities: 0, target_amount: amount, only_available_utxos: true, order_by_value: 'desc', }; for await (const utxo of storage.selectUtxos(options)) { // We let selectUtxos to filter the utxos for us and stop after target amount is reached utxosAmount += utxo.value; utxos.push(utxo); } if (utxosAmount < amount) { // Not enough funds to fill the amount required. return { utxos: [], amount: 0, }; } return { utxos, amount: utxosAmount }; } /** * Select utxos to fill the amount required. * This method will select the smallest utxos that are bigger than the amount required. * Obs: this will iterate on all available utxos to choose the best suited selection. * Obs: Does not work with authority utxos. * * @param {IStorage} storage The wallet storage to select the utxos * @param {string} token The token uid to select the utxos * @param {number} amount The target amount of tokens required * @returns {Promise<{ utxos: IUtxo[], utxosAmount: number}> */ export async function bestUtxoSelection( storage: IStorage, token: string, amount: number, ): Promise<{ utxos: IUtxo[], amount: number}> { const utxos: IUtxo[] = []; let utxosAmount = 0; let selectedUtxo: IUtxo|null = null; const options: IUtxoFilterOptions = { token, authorities: 0, only_available_utxos: true, order_by_value: 'desc', }; for await (const utxo of storage.selectUtxos(options)) { // storage ensures the utxo can be used if (utxo.value === amount) { return { utxos: [utxo], amount: amount, }; } utxos.push(utxo); utxosAmount += utxo.value; if (utxo.value > amount) { // We want to select the smallest utxo that is bigger than the amount if (selectedUtxo === null || utxo.value < selectedUtxo.value) { selectedUtxo = utxo; } } if (utxo.value < amount) { if (selectedUtxo !== null) { // We already have an utxo that is bigger than the amount required // with the lowest possible value. // We don't need to iterate more break; } if (utxosAmount >= amount) { // We have enough funds to fill the amount required // We don't need to iterate more break; } } } if (selectedUtxo !== null) { return { utxos: [selectedUtxo], amount: selectedUtxo.value, }; } else if (utxosAmount < amount) { // We don't have enough funds return { utxos: [], amount: 0, }; } else { // We need to ensure we use the smallest number of utxos and avoid hitting the maximum number of inputs // This can be done by ordering the utxos by value and selecting the highest values first until the amount is fulfilled // But since the store ensures the utxos are ordered by value descending // (Which is ensured by options.order_by_value = 'desc' on the selectUtxos method) // And we stop selecting when the amount in the utxos array is greater than or equal to the requested amount // We can just return the utxos selected during the loop above return { utxos, amount: utxosAmount, }; } }
7f1f105965c8ba59714d9cebfb01a5aaf341de7e
TypeScript
immyidubor/qa_playground
/src/practice/creatingFunctions.ts
3.40625
3
function fancyPrint(firstString: string, secondString: string): string { //code goes here var stringA = firstString; var stringB = secondString; var result = stringA + "\n" + stringB; return result; } console.log(fancyPrint("*****Hello*****", "*****World*****"));
02a87f188b6b53d032b5ee57f2739f6af3e1b8e5
TypeScript
damianpokorski/adventofcode
/2021/day2.ts
3.359375
3
import { data } from "./data/day2.data"; interface Vector2 { depth: number; horizontal: number; }; const Vector2Zero = { depth: 0, horizontal: 0 } as Vector2; const addVector2 = (a: Vector2, b: Vector2) => ({ depth: a.depth + b.depth, horizontal: a.horizontal + b.horizontal, }) as Vector2; const multiplyVectorValues = (vector: Vector2) => vector.depth * vector.horizontal; const stringToVector = (input: string): Vector2 => { const direction = input.split(" ").shift() || ""; const value = parseInt(input.split(" ").pop() || "") || 0; switch(direction) { case "forward": return { horizontal: value, depth: 0 } as Vector2; case "down": return { horizontal: 0, depth: value } as Vector2; case "up": return { horizontal: 0, depth: value * -1 } as Vector2; } return {...Vector2Zero}; } // Part 1 console.log({ ["Part 1"]: multiplyVectorValues( data .map(stringToVector) .reduce(addVector2, Vector2Zero) ) }); // Part 2 interface Vector3 extends Vector2{ aim: number }; const result = data .map(stringToVector) .map(vector => ({...vector, aim: 0}) as Vector3) .reduce((previousVector: Vector3, currentVector: Vector3): Vector3 => { return { depth: previousVector.depth + (currentVector.horizontal * previousVector.aim), horizontal: previousVector.horizontal + currentVector.horizontal, aim: previousVector.aim + currentVector.depth } }, {aim: 0, horizontal: 0, depth: 0} as Vector3); console.log({["Part 2"] : result.horizontal * result.depth});
dd364fd5f7a5fb51003ca4eb76c56fac2d374e03
TypeScript
Juexro/react-components
/components/utils/index.ts
3.140625
3
export function className(name: any): string { if (Array.isArray(name)) { return name.reduce((total, current) => { const result = className(current); if (result) { total += `${total ? ' ' : ''}${result}`; } return total; }, '') } if (Object.prototype.toString.call(name) === '[object Object]') { return Object.entries(name).reduce((total, [k, v]) => { if (!!v) { total += `${total ? ' ' : ''}${k}`; } return total; }, '') } return !!name ? name : ''; } export function classNames(...names: any[]) { return className(names); }
2b5c131f11aa9a3be3346ab5684b0759cb8aa14b
TypeScript
luckyxts/leetcodeTs
/medium/61_70/63_Unique_Paths_II.ts
3.171875
3
/** * Created by Administrator on 2020/6/11. */ function uniquePathsWithObstacles(obstacleGrid: number[][]): number { for(let i: number = 0; i < obstacleGrid.length; i++){ for(let j: number = 0; j < obstacleGrid[i].length; j++){ if( obstacleGrid[i][j] === 1){ obstacleGrid[i][j] = -1; }else if( i === 0 ){ if(obstacleGrid[i][j - 1] !== -1){ obstacleGrid[i][j] = 1; }else{ obstacleGrid[i][j] = -1; } }else if( j === 0){ if(obstacleGrid[i - 1][j] !== -1){ obstacleGrid[i][j] = 1; }else{ obstacleGrid[i][j] = -1; } }else{ let leftStep: number = obstacleGrid[i - 1][ j] === -1 ? 0: obstacleGrid[i - 1][ j]; let rightStep: number = obstacleGrid[i][ j - 1] === -1 ? 0: obstacleGrid[i ][ j - 1]; obstacleGrid[i][j] = leftStep + rightStep; } } } let res: number = obstacleGrid[obstacleGrid.length - 1][obstacleGrid[obstacleGrid.length - 1].length - 1]; return res === -1 ? 0 : res; }
3e80dd54d4ae909b7353863c8c4628772a4232f1
TypeScript
eazey-e/WagerrCom
/src/app/utils/addressValidator.service.ts
2.53125
3
import { Injectable } from '@angular/core'; import { AbstractControl } from '@angular/forms'; import * as baseX from 'base-x'; import sha from 'sha.js'; import { environment } from '../../environments/environment'; @Injectable() export class AddressValidatorService { private addressTypes = { 0x49: { type: 'p2pkh', network: 'mainnet' }, 0x41: { type: 'p2pkh', network: 'testnet' }, 0x3f: { type: 'p2sh', network: 'mainnet' }, 0x7d: { type: 'p2sh', network: 'testnet' } }; private base58 = baseX('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'); constructor() { this.validateWgrAddress = this.validateWgrAddress.bind(this); } private sha256(payload: Buffer): Buffer { return Buffer.from(sha('sha256').update(payload).digest()); } validateWgrAddress(control: AbstractControl): {[key: string]: any} | null { const address = control.value; if (!address) { return { wgr: true }; } let decoded: Buffer; try { decoded = this.base58.decode(address); } catch (error) { return { wgr: true }; } const { length } = decoded; if (length !== 25) { return { wgr: true }; } const version = decoded.readUInt8(0); const checksum = decoded.slice(length - 4, length); const body = decoded.slice(0, length - 4); const expectedChecksum = this.sha256(this.sha256(body)).slice(0, 4); if (!checksum.equals(expectedChecksum)) { return { wgr: true }; } const addressType = this.addressTypes[version]; if (!addressType) { return { wgr: true }; } if (environment[environment.access].testnet && addressType.network !== 'testnet') { return { wgr: true }; } else if (!environment[environment.access].testnet &&addressType.network !== 'mainnet') { return { wgr: true }; } return null; } }
cae3aaf1a9246af75b122955c7a37b46bdaaddcf
TypeScript
untoldwind/t-rust-less-ui
/attic/action-creator.ts
3.65625
4
/** * @type EmptyAction - Empty Action Type * @template T - Generic Type */ export type EmptyAction<T> = { readonly type: T; }; /** * @type PayloadAction - Flux Standard Action Type * @template T - Generic Type * @template P - Generic Type */ export type PayloadAction<T, P> = { readonly type: T; readonly payload: P; readonly error?: boolean; }; /** * @export Action Creator helper factory function * @class ActionCreator * @template T - Generic Type * @template P - Generic Type */ export class ActionCreator<T, P> { readonly type: T; readonly payload: P; constructor(type: T) { this.type = type; } create = (payload: P) => ({ type: this.type, payload }); } /** * @export createEmptyAction - empty action creator function * @template T - Generic Type * @param type: T * @returns () => EmptyAction<T> */ export function createEmptyAction<T>(type: T): () => EmptyAction<T> { return () => ({ type }); } /** * @export createPayloadAction - FSA action creator function * @template T - Generic Type * @template P - Generic Type * @param type: T * @returns (payload: P) => PayloadAction<T, P> */ export function createPayloadAction<T, P>(type: T): (payload: P) => PayloadAction<T, P> { return (payload) => ({ type, payload }); }
77f5d496089b462416f53acb6e23e3b88dcdfea1
TypeScript
kelseyyoung/office-ui-fabric-react
/scripts/tasks/api-extractor.ts
2.609375
3
import fs from 'fs'; import * as glob from 'glob'; import * as path from 'path'; import jju from 'jju'; import { apiExtractorVerifyTask, task, series, resolveCwd, logger, TaskFunction, TscTaskOptions } from 'just-scripts'; const apiExtractorConfigs: Array< [ configPath: string, /** * config name is created from <configName> suffix `api-extractor.<configName>.json`. * @example * `api-extractor.fast.json -> configName === fast` * * default behavior: * `api-extractor.json -> configName === default` */ configName: string, ] > = glob .sync(path.join(process.cwd(), 'config/api-extractor*.json')) .map(configPath => [configPath, configPath.replace(/.*\bapi-extractor(?:\.(.*))?\.json$/, '$1') || 'default']); const apiExtractorConfigsForExecution = apiExtractorConfigs.filter(([, configName]) => configName !== 'local'); // Whether to update automatically on build const localBuild = !process.env.TF_BUILD; export function apiExtractor() { return apiExtractorConfigsForExecution.length ? (series( ...apiExtractorConfigsForExecution.map(([configPath, configName]) => { const taskName = `api-extractor:${configName}`; task( taskName, apiExtractorVerifyTask({ configJsonFilePath: configPath, localBuild, onConfigLoaded: config => { const tsConfig: TsConfig = jju.parse(fs.readFileSync(resolveCwd('./tsconfig.json'), 'utf-8')); const isUsingTsSolutionConfigs = fs.existsSync(resolveCwd('./tsconfig.lib.json')); if (isUsingTsSolutionConfigs) { logger.info(`api-extractor: package is using TS path aliases. Overriding TS compiler settings.`); // baseUrl is the only override needed, but if any overrides are specified, API Extractor // no longer reads the default tsconfig.json. So we have to include the whole tsconfig here. tsConfig.compilerOptions.baseUrl = '.'; config.compiler = { overrideTsconfig: tsConfig, }; } }, }), ); return taskName; }), ) as TaskFunction) : () => { if (apiExtractorConfigs.length) { logger.info( `skipping api-extractor execution - no configs to execute present besides: '${apiExtractorConfigs}'`, ); return; } logger.info(`skipping api-extractor execution - no configs present`); }; } interface TsConfig { extends?: string; /** * typescript doesn't provide a correct type for the compiler options file * (`typescript.CompilerOptions` has enum values instead of raw options in some cases) */ compilerOptions: Omit<TscTaskOptions, 'nodeArgs'>; include?: string[]; exclude?: string[]; }
118a79c6eccb120f6809a86d31ad08b2e8f51274
TypeScript
Lorick23/breizhcamp-2018-console
/ihm.ts
2.796875
3
import readline from 'readline'; import {Service} from './service'; export class Ihm{ public rl:readline.Interface; public service:Service; constructor(){ this.rl = readline.createInterface({ input: process.stdin, output: process.stdout }); this.service = new Service(); } start(){ console.log(` ************************* 1. Rafraichir les données 2. Lister les sessions 3. Lister les présentateurs 4. Rechercher une session 99. Quitter`); this.rl.question('Quel est votre choix ? ', (saisie: any) => { if (saisie == 1) { this.refreshData(); } else if (saisie == 2) { this.getConferences(); } else if (saisie == 3) { this.getSpeakers(); } else if (saisie == 4) { this.searchForConference(); } else if (saisie == 99) { this.rl.close(); } else { this.start(); } }); } refreshData() { this.service.init() .then(nbSessions => console.log('[maj] Données mis-à-jour,', nbSessions, 'sessions trouvées.')) .catch(err => console.log('Oops', err)) } getConferences() { this.service.listerSessions() .then(talks => { talks.forEach(e => { console.log(e.name + " (" + e.speakers + ")"); }) }) .catch(err => console.log('Oops', err)); } getSpeakers() { this.service.listerSpeakers() .then(langs => langs.forEach(e => { console.log(e.innerHTML); })) .catch(err => console.log('Oops', err)); } searchForConference() { this.rl.question('Quel mot voulez vous rechercher ? ', word => { if (word === "") { this.searchForConference(); } else { this.service.findByWord() .then(talks => { let count = 0; let find = false; //let conferencesFound: Array<any> = new Array<any>(); let conferencesFound = new Map(); talks.forEach(e => { if (e.name.toLowerCase().indexOf(word) >= 0) { find = true; count++; console.log(count + ". " + e.name); conferencesFound.set(count, e); } }); if (find) { this.conferenceFound(conferencesFound); } else { console.log("Aucune session trouvée"); this.newSearch(); } }) .catch(err => console.log('Oops', err)); } }); } conferenceFound(conferencesFound: any) { console.log(` 98. Refaire une nouvelle recherche 99. Retour au menu principal `); this.rl.question('Quel est votre choix ? ', (choice: any) => { for (let [id, conf] of conferencesFound) { if (id == choice) { console.log(` *Titre* : `+ conf.name + ` ** *Présentateurs* : `+ conf.speakers + ` *Description* `+ conf.description); this.newSearch(); } } if (choice === 98) { this.searchForConference(); } else if (choice === 99) { this.start(); } else { this.newSearch(); } }) } newSearch() { console.log(` 98. Refaire une nouvelle recherche 99. Retour au menu principal `); this.rl.question('Quel est votre choix ? ', choice => { if (choice === '98') { this.searchForConference(); } else if (choice === '99') { this.start(); } else { this.newSearch(); } }) } } // let rl = readline.createInterface({ // input: process.stdin, // output: process.stdout // }); // const service = new Service(); // export const start = () => { // console.log(` // ************************* // 1. Rafraichir les données // 2. Lister les sessions // 3. Lister les présentateurs // 4. Rechercher une session // 99. Quitter`); // rl.question('Quel est votre choix ? ', (saisie: any) => { // if (saisie == 1) { // refreshData(); // } else if (saisie == 2) { // getConferences(); // } else if (saisie == 3) { // getSpeakers(); // } else if (saisie == 4) { // searchForConference(); // } else if (saisie == 99) { // rl.close(); // } else { // start(); // } // }); // } // function refreshData() { // service.init() // .then(nbSessions => console.log('[maj] Données mis-à-jour,', nbSessions, 'sessions trouvées.')) // .catch(err => console.log('Oops', err)) // } // function getConferences() { // service.listerSessions() // .then(talks => { // talks.forEach(e => { // console.log(e.name + " (" + e.speakers + ")"); // }) // }) // .catch(err => console.log('Oops', err)); // } // function getSpeakers() { // service.listerSpeakers() // .then(langs => langs.forEach(e => { // console.log(e.innerHTML); // })) // .catch(err => console.log('Oops', err)); // } // function searchForConference() { // rl.question('Quel mot voulez vous rechercher ? ', word => { // if (word === "") { // searchForConference(); // } else { // service.findByWord() // .then(talks => { // let count = 0; // let find = false; // //let conferencesFound: Array<any> = new Array<any>(); // let conferencesFound = new Map(); // talks.forEach(e => { // if (e.name.toLowerCase().indexOf(word) >= 0) { // find = true; // count++; // console.log(count + ". " + e.name); // conferencesFound.set(count, e); // } // }); // if (find) { // conferenceFound(conferencesFound); // } else { // console.log("Aucune session trouvée"); // newSearch(); // } // }) // .catch(err => console.log('Oops', err)); // } // }); // } // function conferenceFound(conferencesFound: any) { // console.log(` // 98. Refaire une nouvelle recherche // 99. Retour au menu principal // `); // rl.question('Quel est votre choix ? ', (choice: any) => { // for (let [id, conf] of conferencesFound) { // if (id == choice) { // console.log(` // *Titre* : `+ conf.name + ` ** // *Présentateurs* : `+ conf.speakers + ` // *Description* // `+ conf.description); // newSearch(); // } // } // if (choice === 98) { // searchForConference(); // } else if (choice === 99) { // start(); // } else { // console.log("test"); // newSearch(); // } // }) // } // function newSearch() { // console.log(` // 98. Refaire une nouvelle recherche // 99. Retour au menu principal // `); // rl.question('Quel est votre choix ? ', choice => { // if (choice === '98') { // searchForConference(); // } else if (choice === '99') { // start(); // } else { // newSearch(); // } // }) // }
7d8261fd6329b36a59548b9e608e2c3d3632be52
TypeScript
ACRoark/wismoui
/app/components/Stepper/getActiveProduct.ts
2.5625
3
import { IProduct } from 'types'; const getActiveProduct = (productType: string, products: IProduct[]): IProduct | undefined => { const activeProduct = products.find( (product: IProduct): boolean | undefined => product.productType === productType && product.isCanceled === false, ); return activeProduct; }; export default getActiveProduct;
98fb2ca162adfc62c5302162150001bfe41a961d
TypeScript
gnoesiboe/personal-goal-based-todos
/context/todos/stateModifiers/filterModifiers.ts
2.59375
3
import { countAppliedFilters } from './../utility/todoFilterUtilities'; import { AppliedFilters, State } from '../reducers/todoReducer'; import { applyFilters } from '../utility/todoFilterUtilities'; import produce from 'immer'; export const applyFilterToggleModifier = ( currentState: State, filter: keyof AppliedFilters, ): State => { return produce<State>(currentState, (nextState) => { nextState.appliedFilters[filter] = !nextState.appliedFilters[filter]; // reset current index, as it might now be hidden nextState.currentTodoIndex = null; // apply new filters on items nextState.filteredItems = nextState.items ? applyFilters(nextState.items, nextState.appliedFilters) : null; // reset counts nextState.filterCounts = countAppliedFilters(nextState.items); }); };
e0706b1f9404564d5607f71f67ec3d073b918270
TypeScript
gitter-badger/CarbonLDP-JS-SDK
/src/Agents.ts
2.65625
3
import Context from "./Context"; import * as Agent from "./Agent"; import * as Pointer from "./Pointer"; import * as Response from "./HTTP/Response"; import * as Utils from "./Utils"; import * as Errors from "./Errors"; export class Class { private context:Context; constructor( context:Context ) { this.context = context; } create( agentDocument:Agent.Class ):Promise<[ Pointer.Class, Response.Class]>; create( slug:string, agentDocument:Agent.Class ):Promise<[ Pointer.Class, Response.Class]>; create( slugOrAgent:any, agentDocument?:Agent.Class ):Promise<[ Pointer.Class, Response.Class]> { let containerURI:string = this.context.resolve( this.getContainerURI() ); let slug:string = Utils.isString( slugOrAgent ) ? slugOrAgent : null; agentDocument = agentDocument || slugOrAgent; if ( ! Agent.Factory.is( agentDocument ) ) return Promise.reject<any>( new Errors.IllegalArgumentError( "The Document is not a `Carbon.Agents.Agent.Class` object." ) ); if( slug ) { return this.context.documents.createChild( containerURI, slug, agentDocument ); } else { return this.context.documents.createChild( containerURI, agentDocument ); } } private getContainerURI():string { if ( ! this.context.hasSetting( "platform.agents.container" ) ) throw new Errors.IllegalStateError( "The agents container URI hasn't been set." ); return this.context.getSetting( "platform.agents.container" ); } } export default Class;
cf409cc719b33fa0a71157cea9ef0801b9cdabab
TypeScript
joonhocho/ts-jutil
/src/string/formatName.ts
2.890625
3
const formatNamePart = (s: string): string => { if (s) { return s[0].toUpperCase() + s.substring(1).toLowerCase(); } return ''; }; const allWS = /\s+/g; export const formatName = (s: string): string => { if (s) { return s.trim().split(allWS).map(formatNamePart).join(' '); } return ''; };
991e5598381d4e1f2fea8f097a07cde9af1ec0cf
TypeScript
codebysandip/nralcm
/src/exceptions/handler-not-found.exception.ts
2.625
3
import { HttpResponseMessage } from "../lifecycle"; import { Exception } from "../core"; import { StatusCode } from "../common/enums"; /** * Expection class to throw handler not found 400 */ export class HandlerNotFoundException<T> extends Exception<T> { httpResponseMessage: HttpResponseMessage<T>; constructor() { super(); this.httpResponseMessage = new HttpResponseMessage(); this.httpResponseMessage.errorMessages = ["There is no handler supported for the request"]; this.httpResponseMessage.statusCode = StatusCode.BadRequest; } }
5f256dfd122403fa4b6e49ee950d3c2972314141
TypeScript
Timba82/heroes
/src/app/helpers/pipes/filter.pipe.ts
2.78125
3
import { Pipe, PipeTransform } from '@angular/core'; import { Hero } from 'src/app/interfaces/heroe/hero'; @Pipe({ name: 'filter', pure: false }) export class FilterPipe implements PipeTransform { transform(value: Hero[], filteringString: string, ...arg: string[]): Hero[] { if (value.length === 0 || !filteringString) { return value; } const resultArray = []; for (const spreadArgument of arg) { resultArray.push( value.filter((item) => item[spreadArgument].toString().includes(filteringString) ) ); } return [].concat(...resultArray); } }
6ad875c153b3e52c0e8cf768e2d1ff41db1beade
TypeScript
yetsen/surveychartapp
/src/main/webapp/app/shared/model/answer.model.ts
2.84375
3
export interface IAnswer { userId?: string; questionName?: string; choiceValue?: string | number; } export class Answer implements IAnswer { constructor(public userId?: string, public questionName?: string, public choiceValue?: string | number) {} }
bf2600bc4d90b6d09adbb7222e9093750164eec9
TypeScript
karolis-arbaciauskas/node-ibus-mediacenter
/src/ibus/IbusProtocol.ts
2.5625
3
import { Transform, TransformCallback, TransformOptions } from 'stream'; import autoBind from 'auto-bind'; import { Encoding } from '../constants'; import loggerSystem from '../logger'; import { IncommingMessage } from './types'; const logger = loggerSystem.child({ service: 'IbusProtocol' }); class IbusProtocol extends Transform { private buffer: Buffer; private isProcessing: boolean; private processId: number; constructor(options: TransformOptions = {}) { super(options); this.buffer = Buffer.alloc(0); this.processId = 0; this.isProcessing = false; autoBind(this); } _transform(chunk: Buffer, _encoding: BufferEncoding, cb: TransformCallback) { if (this.isProcessing === true) logger.error('Error. This _transform function should NOT be running..'); this.isProcessing = true; logger.debug(`Processing: ${this.processId}`); logger.debug(`Current buffer: ${this.buffer.toString(Encoding.Hex)}`); logger.debug(`Current chunk: ${chunk.toString(Encoding.Hex)}`); this.processId++; this.buffer = Buffer.concat([this.buffer, chunk]); logger.debug(`Buffer concatinated with chunk: ${this.buffer.toString(Encoding.Hex)}`); const copyChunk = this.buffer; if (copyChunk.length >= 5) { const messages: IncommingMessage[] = []; let endOfLastMessage = -1; for (let i = 0; i < copyChunk.length - 5; i++) { const packetSource = copyChunk[i]; const packetLength = copyChunk[i + 1]; const packetDestination = copyChunk[i + 2]; const packetMessage = copyChunk.slice(i + 3, i + 3 + packetLength - 2); const lastChunkItem = i + 2 + packetLength; const packetChecksum = copyChunk[lastChunkItem - 1]; let crc = 0x00; if (copyChunk.length >= lastChunkItem) { crc = crc ^ packetSource; crc = crc ^ packetLength; crc = crc ^ packetDestination; for (let j = 0; j < packetMessage.length; j++) { crc = crc ^ packetMessage[j]; } if (crc === packetChecksum) { messages.push({ id: Date.now(), src: packetSource.toString(16), len: packetLength.toString(16), dst: packetDestination.toString(16), msg: packetMessage, crc: packetChecksum.toString(16), }); endOfLastMessage = lastChunkItem; i = endOfLastMessage - 1; } } } if (messages.length) { messages.forEach((message) => { this.emit('message', message); }); } if (endOfLastMessage !== -1) { this.buffer = copyChunk.slice(endOfLastMessage); logger.debug(`Sliced data: ${endOfLastMessage} ${this.buffer}`); } else { if (this.buffer.length > 500) { logger.warning('Dropping some data..'); this.buffer = copyChunk.slice(chunk.length - 300); } } } logger.debug(`Buffered messages size: ${this.buffer.length}`); this.isProcessing = false; cb(); } } export default IbusProtocol;
050a6a149fab959810ae2ce173ce9fda2ec0e2de
TypeScript
lijugeorge/reach4
/src/app/shared/list-errors.component.ts
2.546875
3
import { Component, Input } from '@angular/core'; import { Errors } from './models'; @Component({ selector: 'list-errors', templateUrl: './list-errors.component.html' }) export class ListErrorsComponent { formattedErrors: Array<string> = []; @Input() set errors(errorList: any) { this.formattedErrors = []; const parent = this; if (typeof errorList === 'object') { Object.keys(errorList).map(function(objectKey, index) { const value = errorList[objectKey]; if (typeof errorList[objectKey] === 'string') { parent.formattedErrors.push(value); } else { if (value.length > 0) { parent.formattedErrors.push(value[0]); } } }); } else { this.formattedErrors.push(errorList); } // console.log(errorList) // if (errorList.errors) { // // tslint:disable-next-line:forin // for (const field in errorList.errors) { // this.formattedErrors.push(`${errorList.errors[field]}`); // } // } else { // console.log(typeof errorList) // } }; get errorList() { return this.formattedErrors; } }
03b053a6e3ad13ba80693e79eaffc7c1f342e464
TypeScript
bandyg/politicodds
/server/src/services/OddsService.ts
2.796875
3
import BettingClient from '../domain/BettingClient' import { RunnerOdds, Runner } from '../domain/types' import Odds from '../domain/Odds' class OddsService { constructor ( private bettingClient: BettingClient ) {} async getByMarket (marketId: string, limit?: number): Promise<RunnerOdds[]> { const runners = await this.bettingClient.getRunnersByMarket(marketId) const prices = await this.bettingClient.getPricesByMarket(marketId) // @Todo: encapsulate all logic in a RunnerOdds class incl. sort/slice (?) let runnerOdds: RunnerOdds[] = prices.map(price => { const runner = runners.find(r => r.id === price.runnerId) as Runner const odds = new Odds(price.value) return { runnerName: runner.name, odds: odds.toFractional(), probability: odds.toImpliedProbability() } }) // Sort by descending probability runnerOdds.sort((r1, r2) => (r1.probability < r2.probability) ? 1 : -1) if (limit) { runnerOdds = runnerOdds.slice(0, limit) } return runnerOdds } } export default OddsService
191a909702b0b4b0e1b1e89dd818cf7259857c38
TypeScript
forCrowd/GlobalGoalsFund
/ng2Client/app/modules/logger/logger.service.ts
2.53125
3
import { Injectable } from "@angular/core"; import { BodyOutputType, ToasterConfig, ToasterService } from "angular2-toaster"; import { pad } from "../../utils"; //export { ToasterConfig, ToasterModule } @Injectable() export class Logger { toasterConfigured = false; constructor(private toasterService: ToasterService) { } getToasterConfig(): ToasterConfig { this.toasterConfigured = true; return new ToasterConfig({ bodyOutputType: BodyOutputType.TrustedHtml, positionClass: "toast-bottom-right" }); } log(message: string, data?: Object, showToast?: boolean) { return this.logIt(message, data, showToast, "debug"); } logError(message: string, data?: Object, showToast?: boolean) { return this.logIt(message, data, showToast, "error"); } logInfo(message: string, data?: Object, showToast?: boolean) { return this.logIt(message, data, showToast, "info"); } logSuccess(message: string, data?: Object, showToast?: boolean) { return this.logIt(message, data, showToast, "success"); } logWarning(message: string, data?: Object, showToast?: boolean) { return this.logIt(message, data, showToast, "warning"); } logIt(message: string, data?: Object, showToast?: boolean, toastType?: string): void { showToast = typeof showToast === "undefined" ? false : showToast; const newDate = new Date(); const hour = pad(newDate.getHours().toString()); const minute = pad(newDate.getMinutes().toString()); const second = pad(newDate.getSeconds().toString()); let currentDateTime = hour + ":" + minute + ":" + second; let write: Function; switch (toastType) { case "debug": write = console.debug; break; case "error": write = console.error; break; case "info": write = console.info; break; case "success": write = console.log; break; case "warning": write = console.warn; break; default: write = console.log; break; } if (typeof data === "undefined") { write("ng2", currentDateTime, message); } else { write("ng2", currentDateTime, message, { data }); } if (showToast && this.toasterConfigured) { switch (toastType) { case "debug": this.toasterService.pop("info", "", message); break; case "error": this.toasterService.pop("error", "", message); break; case "info": this.toasterService.pop("info", "", message); break; case "success": this.toasterService.pop("success", "", message); break; case "warning": this.toasterService.pop("warning", "", message); break; default: this.toasterService.pop("success", "", message); break; } } } }
5e7ba707286e9bfb2f1e008d0f060089b3a8c942
TypeScript
jsxc/jsxc
/src/Avatar.ts
2.921875
3
import Hash from '@util/Hash'; import { IAvatar } from './Avatar.interface'; import Client from './Client'; import PersistentMap from './util/PersistentMap'; export default class implements IAvatar { private properties: PersistentMap; constructor(private sha1Hash: string, type?: string, data?: string) { let storage = Client.getStorage(); this.properties = new PersistentMap(storage, sha1Hash); if (!this.properties.get('data')) { if (data && type) { let expectedHash = Hash.SHA1FromBase64(data.replace(/^.+;base64,/, '')); if (expectedHash !== sha1Hash) { throw new Error('SHA-1 hash doesnt match'); } this.properties.set('data', data); this.properties.set('type', type); } else { throw new Error('Avatar not found'); } } } public getData(): string { return this.properties.get('data'); } public getType(): string { return this.properties.get('type'); } public getHash(): string { return this.sha1Hash; } }
d080189ecee7a3bc4ccfb7ee307e46d0cd5e0488
TypeScript
S4elkyn4eGGG/project
/src/store/main/index.ts
2.703125
3
import { BehaviorSubject } from 'rxjs'; import { useEffect, useState } from 'react'; import { IMainState } from './model'; export const initialState: IMainState = { isLoading: false, userName: null, }; export let _state: IMainState = initialState; const store$ = new BehaviorSubject<IMainState>(_state); export const updateState = (state: IMainState): void => { store$.next((_state = state)); }; export default (): IMainState => { const [state, setState] = useState(_state); useEffect(() => { const sub = store$.subscribe(setState); return (): void => sub.unsubscribe(); }, []); return state; };
142f6e9b6d45dbbd7c252deccf9f210101844454
TypeScript
sshubhamk1/social_site
/src/RoleUser/Controllers/authController.ts
2.546875
3
import { Request, Response, RequestHandler } from "express"; import bcrpyt from "bcryptjs"; import { Users } from "../../Engine/Models/users"; import { User_auth } from "../../Engine/Models/user_auth"; export const postChangePassword: RequestHandler = async ( req: Request, res: Response ) => { try { const { password, new_password } = req.body; let user = await Users.findOne({ where: { id: req.user.id } }); if (!user) throw "No user found with this credential!"; const isMatch: Boolean = await bcrpyt.compare(password, user.password); if (!isMatch) throw "Wrong password please try with correct old password!"; user.password = await bcrpyt.hash(new_password, 10); await user.save(); return res.status(200).json({ error: false, msg: "Password changed!" }); } catch (e) { return res.status(400).json({ error: true, msg: String(e) }); } }; export const postLogout: RequestHandler = async ( req: Request, res: Response ) => { try { await User_auth.destroy({ where: { user_id: req.user.id } }); return res.status(200).json({ error: false, msg: "successfully logout!" }); } catch (e) { return res.status(400).json({ error: false, msg: String(e) }); } };
9a5607766800aeeebc95d4cf2f3c7b7a154b0b81
TypeScript
Luobata/L3
/src/UI/layout/position.ts
3.25
3
/** * @desc 计算位置 */ import Chart from 'UI/chart/chart'; type verticalType = 'top' | 'bottom' | 'middle'; type horizonType = 'left' | 'center' | 'right'; /** * default class */ export default class Position { private chart: Chart; private vType: verticalType; constructor(chart: Chart) { this.chart = chart; } // 输入height 垂直方向布局规则 返回起始点坐标 public getVertical(dir: verticalType, height: number): number { const middle: number = this.chart.config.height / 2; const end: number = this.chart.config.height - this.chart.config.padding; const start: number = this.chart.config.padding; if (dir === 'top') { return this.chart.pixelRatio * start; } else if (dir === 'middle') { return this.chart.pixelRatio * (middle - height / 2); } else { return this.chart.pixelRatio * (end - height); } } public getHorizon(dir: horizonType, width: number): number { const middle: number = this.chart.config.width / 2; const end: number = this.chart.config.width - this.chart.config.padding; const start: number = this.chart.config.padding; if (dir === 'left') { return this.chart.pixelRatio * start; } else if (dir === 'center') { return this.chart.pixelRatio * (middle - width / 2); } else { return this.chart.pixelRatio * (end - width); } } }
40612965f6505efb6e7fcedc07ca12feb813d667
TypeScript
bagbag/tstdl
/base/source/utils/periodic-reporter.ts
2.625
3
import type { Observable } from 'rxjs'; import { Subject } from 'rxjs'; import { DeferredPromise } from '../promise/deferred-promise.js'; import { CancellationToken } from './cancellation-token.js'; import { cancelableTimeout } from './timing.js'; export class PeriodicReporter { private readonly reportSubject: Subject<number>; private readonly interval: number; private readonly ignoreZero: boolean; private readonly resetAfterReport: boolean; private readonly stopToken: CancellationToken; private readonly stopped: DeferredPromise; private running: boolean; private counter: number; private stopRequested: boolean; get report(): Observable<number> { return this.reportSubject.asObservable(); } constructor(interval: number, ignoreZero: boolean, resetAfterReport: boolean) { this.interval = interval; this.ignoreZero = ignoreZero; this.resetAfterReport = resetAfterReport; this.running = false; this.stopToken = new CancellationToken(); this.stopped = new DeferredPromise(); this.reportSubject = new Subject(); } increase(count: number): void { this.counter += count; } run(): void { if (this.running) { throw new Error('already started'); } this.running = true; // eslint-disable-next-line @typescript-eslint/no-floating-promises (async () => { this.counter = 0; this.stopRequested = false; this.stopToken.unset(); this.stopped.reset(); while (!this.stopRequested) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition await cancelableTimeout(this.interval, this.stopToken); if (!this.stopRequested && (!this.ignoreZero || (this.counter > 0))) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition this.emitReport(this.resetAfterReport); } } this.running = false; this.stopped.resolve(); })(); } async stop(): Promise<void> { if (!this.running) { return; } this.stopRequested = true; this.stopToken.set(); await this.stopped; } private emitReport(resetAfterReport: boolean): void { this.reportSubject.next(this.counter); if (resetAfterReport) { this.counter = 0; } } }
220fc8ddbef7ccd583e9c81bc3ef232a894f1116
TypeScript
ctmm/biotope-resource-loader
/src/fp/difference.ts
2.9375
3
import curry from './curry'; import _Set from './Set'; const difference = (first: ReadonlyArray<any>, second: ReadonlyArray<any>) => { const out = []; let idx = 0; const firstLen = first.length; const secondLen = second.length; const toFilterOut = new _Set(); for (let i = 0; i < secondLen; i++) { toFilterOut.add(second[i]); } while (idx < firstLen) { if (toFilterOut.add(first[idx])) { out[out.length] = first[idx]; } idx += 1; } return out; } export default curry(difference);
2222296a163da82f1a37a4ff292595e9cccd0e12
TypeScript
green-fox-academy/Eszkis
/JavaScript/Week-03/Day-2/Double.ts
3.015625
3
'use strict'; // Create a method that decrypts duplicated-chars.txt let fs = require('fs'); function double(fileName: string) { let content: string[] = fs.readFileSync(fileName, 'utf-8').split('\r'); let array: string[][] = []; let sentences: string = ''; content.forEach(function (value) { array.push(value.split('')) }) console.log(array) console.log(array.length); for (let outerArray: number = 0; outerArray < array.length; outerArray++) { for (let innerArray: number = 0; innerArray < array[outerArray].length; innerArray += 2) { sentences += array[outerArray][innerArray] } } console.log(sentences); } double('Double.txt');
cd285932100c504ef760a5030990ed52fd1d350a
TypeScript
KhushalGoyal/ExpressGatewayMicroservicePattern
/employee-gateway/identity-service/src/controllers/auth.controller.ts
2.515625
3
import { Router, Request, Response, NextFunction } from 'express'; import { body } from 'express-validator'; import { ErrorResponse, SuccessResponse } from '../helper/reponse'; import { validate } from '../middleware/validateUserRequest'; import { AuthService } from '../service/employee.service'; const AuthController = Router() AuthController.post('/login', validate([body('username').isString(), body('password').isString()]) ,async(req: Request, res: Response, next: NextFunction) => { try { console.log(req.body) if(AuthService.validatePassword(req.body)){ const token = AuthService.generateToken(req.body); const data = { token : token, redirectUri : 'http://localhost:8080' } res.status(200).send(new SuccessResponse(200, "Success", data)) return; } res.status(401).send(new ErrorResponse(401, "User not fount")) return; } catch (error) { res.status(500).send(new ErrorResponse(500, error.message)) return; } }) export default AuthController;
872d4847834f66cd90dff8620a289dc6e6a5fd06
TypeScript
HUANGRuirui1/ng-counter-group-2020-11-30-1-19-19-990
/src/app/service/counter-group.service.spec.ts
2.671875
3
import { TestBed } from '@angular/core/testing'; import { CounterGroupService } from './counter-group.service'; describe('CounterGroupService', () => { let service: CounterGroupService; beforeEach(() => { TestBed.configureTestingModule({}); service = TestBed.inject(CounterGroupService); }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should change count of counters when reset size', () => { // given // when service.setSize(10); // then expect(service.counters.length).toBe(10); }); it('should set size when create instance', () => { expect(service.size).toBe(5); }); it('should contain counters when create instance', () => { expect(service.counters.length).toBe(service.size); }); it('should return sum of all counters when call sum', () => { // given let expectedSum = 0; service.counters.forEach(item => { expectedSum += item.account; }); // when const sum = service.sum(); // then expect(sum).toBe(expectedSum); }); it('should all count be reset as 0 and sum change when click reset button', () => { // given let value = 1; service.counters.forEach(item => { item.account = value; value++; }); // when service.resetCounters(); const sum = service.sum(); // then expect(sum).toBe(0); service.counters.forEach(item => { expect(item.account).toBe(0); }); }); });
b43e4a38d4a52073ef1a63841a023c89ba09ab66
TypeScript
paloukari/shine
/app/dynamic/control/dynamic-dropdown-model.ts
2.546875
3
import { DynamicControlModel } from './dynamic-control-model'; import { NodeWrapper } from '../../parser/transaction/node-wrapper'; export class DynamicDropdownModel extends DynamicControlModel<any[]> { controlType = 'dropdown'; isListBox = false; private _children: { key: string, value: string }[]; constructor(node: NodeWrapper, options: {} = {}) { super(node, options); if (this.children) { this.value = this.children; } else { this.value = []; } if (options['isListBox']) { this.isListBox = options['isListBox'] as boolean; } } public get children(): { key: string, value: string }[] { return this._children || (this.getChildren()); } private getChildren(): { key: string, value: string }[] { this._children = []; this.node.children.forEach(option => { if (option.type === 'keyvalue') { let value = option.children[0].node.nodeValue; let nv = value.split('='); this._children.push({ key: nv[0], value: nv[1] }); } }); return this._children; } }
f87d364d6e25f05d3f7a094b22ca1188bcef824a
TypeScript
kuoluo1995/lineupjs
/src/model/CompositeNumberColumn.ts
2.671875
3
import { format } from 'd3-format'; import CompositeColumn from './CompositeColumn'; import type { IDataRow, IGroup, IColumnDesc } from './interfaces'; import { isMissingValue } from './missing'; import NumberColumn from './NumberColumn'; import { SortByDefault, toolbar } from './annotations'; import type { ISequence } from '../internal'; import type { INumberColumn } from './INumberColumn'; export interface ICompositeNumberDesc extends IColumnDesc { /** * d3 format number Format * @default 0.3n */ numberFormat?: string; } export declare type ICompositeNumberColumnDesc = ICompositeNumberDesc & IColumnDesc; /** * implementation of a combine column, standard operations how to select */ @toolbar('rename', 'clone', 'sort', 'sortBy', 'group', 'groupBy') @SortByDefault('descending') export default class CompositeNumberColumn extends CompositeColumn implements INumberColumn { private readonly numberFormat: (n: number) => string = format('.3n'); constructor(id: string, desc: Readonly<ICompositeNumberColumnDesc>) { super(id, desc); if (desc.numberFormat) { this.numberFormat = format(desc.numberFormat); } } getNumberFormat() { return this.numberFormat; } getLabel(row: IDataRow) { if (!this.isLoaded()) { return ''; } const v = this.getValue(row); //keep non number if it is not a number else convert using formatter return String(typeof v === 'number' && !Number.isNaN(v) && isFinite(v) ? this.numberFormat(v) : v); } getValue(row: IDataRow) { if (!this.isLoaded()) { return null; } //weighted sum const v = this.compute(row); if (isMissingValue(v)) { return null; } return v; } protected compute(_row: IDataRow) { return NaN; } getNumber(row: IDataRow) { const r = this.getValue(row); return r == null ? NaN : r; } getRawNumber(row: IDataRow) { return this.getNumber(row); } iterNumber(row: IDataRow) { return [this.getNumber(row)]; } iterRawNumber(row: IDataRow) { return [this.getRawNumber(row)]; } getExportValue(row: IDataRow, format: 'text' | 'json'): any { if (format === 'json') { return { value: this.getRawNumber(row), children: this.children.map((d) => d.getExportValue(row, format)), }; } return super.getExportValue(row, format); } toCompareValue(row: IDataRow) { return NumberColumn.prototype.toCompareValue.call(this, row); } toCompareValueType() { return NumberColumn.prototype.toCompareValueType.call(this); } toCompareGroupValue(rows: ISequence<IDataRow>, group: IGroup) { return NumberColumn.prototype.toCompareGroupValue.call(this, rows, group); } toCompareGroupValueType() { return NumberColumn.prototype.toCompareGroupValueType.call(this); } getRenderer(): string { return NumberColumn.prototype.getRenderer.call(this); } }
fe2f34c9e495a5d7bfcaf048658542d87ccbfe30
TypeScript
huaweicloud/huaweicloud-sdk-nodejs-v3
/services/sms/v3/model/UpdateTemplateRequest.ts
2.515625
3
import { UpdateTemplateReq } from './UpdateTemplateReq'; export class UpdateTemplateRequest { public id?: string; public body?: UpdateTemplateReq; public constructor(id?: string) { this['id'] = id; } public withId(id: string): UpdateTemplateRequest { this['id'] = id; return this; } public withBody(body: UpdateTemplateReq): UpdateTemplateRequest { this['body'] = body; return this; } }
a6302b2c064b94f977b649be3f9faacb552bbddf
TypeScript
Laisheung/codewars
/primorialofanumber/primorialofanumber.spec.ts
2.71875
3
import { numPrimorial } from "./primorialofanumber"; describe("Basic tests", () => { it("Testing for 3", () => expect(numPrimorial(3)).toStrictEqual(30)); it("Testing for 4", () => expect(numPrimorial(4)).toStrictEqual(210)); it("Testing for 5", () => expect(numPrimorial(5)).toStrictEqual(2310)); it("Testing for 8", () => expect(numPrimorial(8)).toStrictEqual(9699690)); it("Testing for 9", () => expect(numPrimorial(9)).toStrictEqual(223092870)); });
745dba1c457918afae6741b5c9592e215bb22ea2
TypeScript
Erik3003/myCalendar24
/src/app/components/login/login.component.ts
2.65625
3
/* * This component displays the login form. It consists functions for validating * the users input and sends valid input to the authentification service. */ import { Component, OnInit } from '@angular/core'; import { FormGroup, FormBuilder, Validators } from '@angular/forms'; import { AuthService } from '../../services/auth.service'; import { Router } from '@angular/router'; import { HttpErrorResponse } from '@angular/common/http'; import { UserModel } from 'src/models/user.model'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { //variable for inputting user values user: UserModel = new UserModel(); //form with username and password loginForm: FormGroup; //boolean to display error message isLogginError: boolean; constructor( private formBuilder: FormBuilder, private authService: AuthService, private router: Router ) { } //creating login form with username, password and validators ngOnInit() { this.loginForm = this.formBuilder.group({ name: ['', [ Validators.required, Validators.minLength(3), Validators.maxLength(30) ]], password: ['', [ Validators.required, Validators.minLength(8), Validators.maxLength(30) ]] }); } /*getting the inputs of the form and call the service for authentification. route to the main calendar if the login is successful.*/ submitLogin() { this.user.username = this.loginForm.get('name').value; this.user.password = this.loginForm.get('password').value; this.authService.loginUser(this.user).subscribe((data: any) => { this.authService.setUser(data.User); this.authService.setToken(data.token); this.router.navigate(['/calendar']); }, (err: HttpErrorResponse) => { this.isLogginError = true; }); } //getter for validating inputs in form get name() { return this.loginForm.get('name'); } get password() { return this.loginForm.get('password'); } }
8c6a6270f8ec24a26558e0eb7d6a3ae4693be311
TypeScript
Gretten/gba
/src/api/GoogleApiHandler.ts
2.921875
3
const MAIN_LINK = 'https://www.googleapis.com/books/v1/volumes' const API_KEY = 'AIzaSyCBVroRsJ0yUbiLU8r2pT4dzRdt6oFbUOw'; // перенести interface GoogleApiInt { retrieve: (params: any) => Promise<any> } class GoogleApiHandler implements GoogleApiInt { private mainLink: string; private apiKey: string; constructor(mainLink: string, apiKey: string) { this.mainLink = mainLink; this.apiKey = apiKey; } private buildParamString(parameters: any): string { let params = ''; for(let key in parameters) { const param = `&${key}=${parameters[key]}`; params += param; } return params; } private getMainLinkWithApiCode(): string { return `${this.mainLink}?key=${this.apiKey}` } public retrieve(parameters: any): Promise<any> { return fetch(this.getMainLinkWithApiCode() + this.buildParamString(parameters)) } } const googleApiHandler = new GoogleApiHandler(MAIN_LINK, API_KEY); export default googleApiHandler;