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
b4a6050a11877ce990a9b1537777ed9d23597849
TypeScript
InvenireAude/IAW-ESB-ServiceDirectory
/src/app/filters/general-filter.pipe.ts
2.765625
3
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'generalfilter', pure: false }) export class GeneralFilterPipe implements PipeTransform { transform(items: any[], filter: any, pagination: any): any[] { if (!items || !filter) { return items; } const r = items.filter((item: any) => this.applyFilter(item, filter)); if (pagination) { pagination.length = r.length; } return r; } applyFilter(item: any, filter: any): boolean { for (const field in filter) { if (filter[field] && item[field]) { const value = this.getValue(item[field]); if (typeof filter[field] === 'string') { if (value.toLowerCase().indexOf(filter[field].toLowerCase()) === -1) { return false; } } else if (typeof filter[field] === 'number') { if (value !== filter[field]) { return false; } } } } return true; } private getValue(item) { if (item instanceof Array) { let value = ''; item.forEach(i => { value += i; }); return value; } else { return item; } } }
a20d31e93d49fafce4da47d763ad92ff69ba2900
TypeScript
nemyagky/requests-interceptor
/renderer/src/app/app.component.ts
2.65625
3
import {Component, ElementRef, ViewChild} from '@angular/core'; import {ElectronService} from "./core/services/electron.service"; import {HTMLLinksArray} from "./core/interfaces/links-window-data.interface"; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) // Angular part is really small, so, only AppComponent was created // And it's dirty a little bit :) export class AppComponent { @ViewChild('container') container: ElementRef; private textLinks: HTMLLinksArray = []; private imageLinks: HTMLLinksArray = []; constructor( private electronService: ElectronService, ) { this.subscribeOnLinksUpdate(); } private subscribeOnLinksUpdate(): void { this.electronService.ipcRenderer.on('links-update', (event, outerLinks: string[]) => { this.clearLinks(); this.parseOuterLinks(outerLinks); this.sortTextLinks(); this.updateLinksInView(); }); } private parseOuterLinks(outerLinks: string[]): void { outerLinks.forEach((link) => { let htmlElement: ChildNode | HTMLElement = new DOMParser().parseFromString(link, 'text/html').body.firstChild; if (htmlElement.firstChild.nodeName === '#text' || (htmlElement.firstChild as HTMLElement).tagName === 'SPAN') { this.textLinks.push(htmlElement); } else { this.imageLinks.push(htmlElement); } }); } private sortTextLinks(): void { this.textLinks = this.textLinks.sort((first, second) => { return first.textContent.trim() > second.textContent.trim() ? 1 : -1; }) } // updating by nativeElement.appendChild due to performance && i'm lazy :D private updateLinksInView(): void { const linksContainer = document.createDocumentFragment(); this.imageLinks.forEach(el => linksContainer.appendChild(el)); this.textLinks.forEach(el => linksContainer.appendChild(el)); this.container.nativeElement.appendChild(linksContainer); } private clearLinks(): void { this.container.nativeElement.innerHTML = ''; this.textLinks = []; this.imageLinks = []; } }
ca6da41d1c6373bc0658be304cf1db1a8e018674
TypeScript
DanielleVictoria/Exercise2
/src/shoppingcart/components/filterview.component.ts
2.609375
3
import { Component, OnInit, Output, EventEmitter } from '@angular/core'; export interface FilterModel { category : string; pricerange : string; sort : string; } @Component({ selector: 'filterview', templateUrl: 'filterview.component.html' }) export class FilterViewComponent implements OnInit { @Output() filter: EventEmitter<{ category: string, pricerange: string, sort: string }> = new EventEmitter(); categories: string[] = ["None", "Healthcare", "Fashion", "Makeup", "Entertainment", "Lifestyle", "Fitness", "Others"]; pricerange: string[] = ["None", "0-1000", "1000-5000", "5000-10000"]; sort: string[] = ["Ascending", "Descending"]; filterModel : FilterModel = { category: this.categories[0], pricerange: this.pricerange[0], sort: this.sort[0] } constructor() { } ngOnInit() { } onSubmit() { this.filter.emit (this.filterModel); } }
634cc0a089f4abaefb149ccb7f0421e3efaefd8f
TypeScript
swerfel/retromote-angular-client
/src/app/bounds/bounds.ts
2.84375
3
import { PositionChange } from '../transformation/position-change'; export class Bounds { static EMPTY: Bounds = new Bounds(0, 0, 0, 0); constructor( public x: number, public y: number, public width: number, public height: number) {} public movedBy(change: PositionChange): Bounds { return new Bounds(this.x + change.dx, this.y + change.dy, this.width, this.height); } }
d16a79a0cb237a17fffc8348b3c7e5522d91dc75
TypeScript
VitaliyKulikov/StudHub
/Frontend/src/services/route-helper.service.ts
2.515625
3
import {Injectable} from '@angular/core'; import {NavigationEnd, Router} from '@angular/router'; import {Observable} from 'rxjs'; import {filter, map, shareReplay} from 'rxjs/internal/operators'; const blackRoutes = [ ]; const blackHeaderRoute = [ ]; @Injectable() export class RouteHelperService { constructor(private router: Router) { } getRouteColor(): Observable<IColorThemeDefinition> { const stream = this.router.events .pipe( filter(e => e instanceof NavigationEnd), shareReplay(1), map((e: NavigationEnd) => { if (blackRoutes.indexOf(e.urlAfterRedirects) !== -1) { return { color: ColorTheme.Black, isHeaderOnly: false }; } else { if (blackHeaderRoute.indexOf(e.urlAfterRedirects) !== -1) { return { color: ColorTheme.Black, isHeaderOnly: true }; } return { color: ColorTheme.White, isHeaderOnly: true }; } })); stream.subscribe(s => { /*ref count use instead is preferable*/ }); return stream; } } export interface IColorThemeDefinition { color: ColorTheme; isHeaderOnly: boolean; } export enum ColorTheme { White, Black }
25400cd5b266f8bef76f04ea1e145cf4bc499bec
TypeScript
marcobiedermann/codewars
/kata/8 kyu/return-two-highest-values-in-list/index.ts
2.84375
3
function twoHighest(arr: number[]): number[] { const sorted = [...new Set(arr)].sort((a, b) => b - a); return sorted.slice(0, 2); } export default twoHighest;
848ae26b7a72c443d8c236ee0300c7532bce5b01
TypeScript
SonTrungTo/Fullstack-2020-Helsinki
/part9/calculator/bmiCalculator.ts
3.4375
3
interface bmiInputs { height: number; weight: number; } export const calculateBmi = (height: number, weight: number): string => { const bmi = Number((weight / Math.pow(height * 0.01, 2)).toFixed(2)); switch (true) { case ( bmi < 18.5): return `Underweight (very unhealthy weight)`; case ( bmi >= 18.5 && bmi < 25): return `Normal (healthy weight)`; case ( bmi >= 25 && bmi <= 30 ): return `Overweight (unhealthy weight)`; case ( bmi > 30): return `Obese (very unhealthy weight)`; default: throw new Error('Invalid bmi!'); } }; const parseArguments = (args: Array<string>): bmiInputs => { if (args.length < 4) throw new Error('Not enough arguments'); if (args.length > 4) throw new Error('Too many arguments'); if (!isNaN(Number(process.argv[2])) && !isNaN(Number(process.argv[3]))) { return { height: Number(process.argv[2]), weight: Number(process.argv[3]) }; } else { throw new Error('Invalid height/weight input'); } }; try { console.log('Run: yarn calculateBmi <height(cm)> <weight(kg)>'); const { height, weight } = parseArguments(process.argv); console.log(calculateBmi(height, weight)); } catch (error) { console.log('There was a problem with your program:', error.message); // eslint-disable-line }
070fa79b7706bdfe480eed66855e45ab78efd88b
TypeScript
willneedit/mixed-reality-extension-sdk
/packages/common/src/math/path2.ts
3.65625
4
/*! * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import { Arc2, Orientation, Vector2 } from '.'; /** * Represents a 2D path made up of multiple 2D points */ export class Path2 { private _points = new Array<Vector2>(); private _length = 0.0; /** * If the path start and end point are the same */ public closed = false; /** * Creates a Path2 object from the starting 2D coordinates x and y. * @param x the starting points x value * @param y the starting points y value */ constructor(x: number, y: number) { this._points.push(new Vector2(x, y)); } /** * Adds a new segment until the given coordinates (x, y) to the current Path2. * @param x the added points x value * @param y the added points y value * @returns the updated Path2. */ public addLineTo(x: number, y: number): Path2 { if (this.closed) { return this; } const newPoint = new Vector2(x, y); const previousPoint = this._points[this._points.length - 1]; this._points.push(newPoint); this._length += newPoint.subtract(previousPoint).length(); return this; } /** * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, * end point coordinates, the arc start point being the current Path2 last point) to the current Path2. * @param midX middle point x value * @param midY middle point y value * @param endX end point x value * @param endY end point y value * @param numberOfSegments (default: 36) * @returns the updated Path2. */ public addArcTo(midX: number, midY: number, endX: number, endY: number, numberOfSegments = 36): Path2 { if (this.closed) { return this; } const startPoint = this._points[this._points.length - 1]; const midPoint = new Vector2(midX, midY); const endPoint = new Vector2(endX, endY); const arc = new Arc2(startPoint, midPoint, endPoint); let increment = arc.angle.radians() / numberOfSegments; if (arc.orientation === Orientation.CW) { increment *= -1; } let currentAngle = arc.startAngle.radians() + increment; for (let i = 0; i < numberOfSegments; i++) { const x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x; const y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y; this.addLineTo(x, y); currentAngle += increment; } return this; } /** * Closes the Path2. * @returns the Path2. */ public close(): Path2 { this.closed = true; return this; } /** * Gets the sum of the distance between each sequential point in the path * @returns the Path2 total length (float). */ public length(): number { let result = this._length; if (!this.closed) { const lastPoint = this._points[this._points.length - 1]; const firstPoint = this._points[0]; result += (firstPoint.subtract(lastPoint).length()); } return result; } /** * Gets the points which construct the path * @returns the Path2 internal array of points. */ public getPoints(): Vector2[] { return this._points; } /** * Retreives the point at the distance aways from the starting point * @param normalizedLengthPosition the length along the path to retreive the point from * @returns a new Vector2 located at a percentage of the Path2 total length on this path. */ public getPointAtLengthPosition(normalizedLengthPosition: number): Vector2 { if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) { return Vector2.Zero(); } const lengthPosition = normalizedLengthPosition * this.length(); let previousOffset = 0; for (let i = 0; i < this._points.length; i++) { const j = (i + 1) % this._points.length; const a = this._points[i]; const b = this._points[j]; const bToA = b.subtract(a); const nextOffset = (bToA.length() + previousOffset); if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) { const dir = bToA.normalize(); const localOffset = lengthPosition - previousOffset; return new Vector2( a.x + (dir.x * localOffset), a.y + (dir.y * localOffset) ); } previousOffset = nextOffset; } return Vector2.Zero(); } /** * Creates a new path starting from an x and y position * @param x starting x value * @param y starting y value * @returns a new Path2 starting at the coordinates (x, y). */ public static StartingAt(x: number, y: number): Path2 { return new Path2(x, y); } }
664739c83650fe5ee367ad8b96ff8b726c1a23a5
TypeScript
puncleV/ts-graphql
/src/entities/author.ts
2.65625
3
import { Field, ID, ObjectType } from "type-graphql"; import { Column, Entity, ManyToMany, PrimaryGeneratedColumn } from "typeorm"; import { Lazy } from "../types"; import { Book } from "./book"; @ObjectType() @Entity() export class Author { @Field((type) => ID) @PrimaryGeneratedColumn() readonly id!: number; @Field() @Column() name!: string; @ManyToMany((type) => Book, (book) => book.authors, { lazy: true }) @Field((type) => [Book]) books!: Lazy<Book[]>; }
4592854ef3e32b7bb05d3c80e0b51fcb4eee216b
TypeScript
mecoepcoo/react-redux-ts-demo
/src/redux/store/initState.ts
2.828125
3
export interface GoodsItem { id: number; name: string; price: number; stock: number; } export interface CartItem extends GoodsItem { num: number; } export interface InitState { goodsList: GoodsItem[]; cartList: CartItem[]; } const initState: InitState = { /* 商品列表 */ goodsList: [ // { // id: 123, // name: 'name', // price: 100, // stock: 996 // } ], /* 购物车列表 */ cartList: [ // { // id: 123, // name: 'name', // price: 100, // stock: 996, // num: 2 // } ] }; export default initState;
8e38d0dc82127e345df68e85c2d611d2996ebcd7
TypeScript
Trendyol/dynamic-render
/__tests__/hook.spec.ts
2.65625
3
import * as sinon from "sinon"; import * as faker from "faker"; import {expect} from "chai"; import {Hook, HookConfiguration} from "../src/hook"; const sandbox = sinon.createSandbox(); let hook: Hook; describe('[hook.ts]', () => { beforeEach(() => { hook = new Hook({ name: faker.random.word(), handler: sandbox.stub() }) }); afterEach(() => { sandbox.verifyAndRestore(); }); it('should create new Hook', () => { // Arrange const options: HookConfiguration = { name: faker.random.word(), handler: sandbox.stub() }; const hook = new Hook(options); // Assert expect(hook).to.be.instanceOf(Hook); }); it('should call handler on handle method', async () => { // Arrange const options = { name: faker.random.word(), handler:sandbox.stub() }; const hook = new Hook(options); const page = {} as any; // Act await hook.handle(page); // Assert expect(options.handler.calledWithExactly(page)).to.eq(true); }); });
73a278471e8a4e1465e5db9a57d9fd4cf4196e51
TypeScript
sneha-sharma-uiux/Angular-training
/src/app/shared/directives/highlight.directive.ts
2.75
3
import { Directive, OnInit, OnDestroy, ElementRef , HostListener, Renderer2, Input} from '@angular/core'; //h2, div , any tag that contains directive is called host element //Renderer2 DOM manipulation Library @Directive({ //[] - must, represent a property // used at ant tag/component selector: '[appHighlight]', exportAs:'appHighlight' // for #myDir="appHighlight" }) export class HighlightDirective implements OnInit, OnDestroy { @Input('appHighlight') color:string='lightgreen'; // is injected with host element ElementRef constructor(private hostElement:ElementRef, private renderer:Renderer2) { console.log('HighlightDirective Created'); } ngOnInit(){ console.log('HighlightDirective ngOnInit'); if(!this.color){ this.color='lightgreen'; } console.log('host Tag', this.hostElement.nativeElement.tagName) } ngOnDestroy(){ console.log('HighlightDirective ngOnDestroy'); } @HostListener('click') // for directive listen event coz paranthesis not used in directive clicked(){ console.log('click event'); } @HostListener('mouseenter') mouseEnter(){ this.renderer.setStyle(this.hostElement.nativeElement,'background',this.color) } @HostListener('mouseleave') mouseLeave(){ this.renderer.removeStyle(this.hostElement.nativeElement,'background') } }
7e5559af1c67d4258b6fbd03f7771b369961862f
TypeScript
Dans-labs/electron-experiments
/redux-form-tutorial/src/main/typescript/reducers/submitReducer.ts
2.703125
3
import {Reducer} from "redux" import {Users} from "../model/AppState" import * as uuid from 'uuid/v4' export const usersReducer: Reducer<Users> = (state = [], action) => { switch (action.type) { case "ADD_USER": const name = action.payload const user = {id: uuid(), name} return [...state, user] case "REMOVE_USER": const id = action.payload return state.filter(value => value.id !== id) } return state }
5378169ace9e7bfbd7732b9f1ae251b24b20d98e
TypeScript
domhanak/tomato-chat
/src/reducers/channel/editedChannelID.ts
2.515625
3
import { TOMATO_APP_CHANNEL_EDITING_STARTED, TOMATO_APP_CHANNEL_EDITING_CANCELLED, TOMATO_APP_CHANNEL_EDITING_SUCCESS } from '../../constants/actionTypes'; export const editedChannelId = (prevState: Uuid | null = null, action: Action): Uuid | null => { switch (action.type) { case TOMATO_APP_CHANNEL_EDITING_STARTED: return action.payload.id; case TOMATO_APP_CHANNEL_EDITING_SUCCESS: return action.payload.channel.id; case TOMATO_APP_CHANNEL_EDITING_CANCELLED: return null; default: return prevState; } };
cb557c2074f945f7cb08d7290b61bab696a18631
TypeScript
RMo-Sloth/Sudoku
/utility/CellPosition/SudokuCellPosition.spec.ts
2.875
3
import { SudokuCellPosition } from "./SudokuCellPosition"; describe( 'SudokuCellPosition', () => { describe( '.row', () => { it( 'returns 0 for too low out of range values', () => { let cellPosition = new SudokuCellPosition( 0 ); expect( cellPosition.row ).toBe( 0 ); }); it( 'returns 0 for too high out of range values', () => { let cellPosition = new SudokuCellPosition( 82 ); expect( cellPosition.row ).toBe( 0 ); }); it( 'returns 1 for cellIndex 1', () => { let cellPosition = new SudokuCellPosition( 1 ); expect( cellPosition.row ).toBe( 1 ); }); it( 'returns 2 for cellIndex 10', () => { let cellPosition = new SudokuCellPosition( 10 ); expect( cellPosition.row ).toBe( 2 ); }); it( 'returns 2 for cellIndex 18', () => { let cellPosition = new SudokuCellPosition( 18 ); expect( cellPosition.row ).toBe( 2 ); }); }); describe( '.column', () => { it( 'returns 0 for too low out of range values', () => { let cellPosition = new SudokuCellPosition( 0 ); expect( cellPosition.column ).toBe( 0 ); }); it( 'returns 0 for too high out of range values', () => { let cellPosition = new SudokuCellPosition( 82 ); expect( cellPosition.column ).toBe( 0 ); }); it( 'returns 1 for cellIndex 1', () => { let cellPosition = new SudokuCellPosition( 1 ); expect( cellPosition.column ).toBe( 1 ); }); it( 'returns 2 for cellIndex 11', () => { let cellPosition = new SudokuCellPosition( 11 ); expect( cellPosition.column ).toBe( 2 ); }); it( 'returns 1 for cellIndex 9', () => { let cellPosition = new SudokuCellPosition( 9 ); expect( cellPosition.column ).toBe( 9 ); }); }); describe( '.square', () => { it( 'returns 0 for too low out of range values', () => { let cellPosition = new SudokuCellPosition( 0 ); expect( cellPosition.square ).toBe( 0 ); }); it( 'returns 0 for too high out of range values', () => { let cellPosition = new SudokuCellPosition( 82 ); expect( cellPosition.square ).toBe( 0 ); }); it( 'returns 1 for cellIndex 1' , () => { let cellPosition = new SudokuCellPosition( 1 ); expect( cellPosition.square ).toBe( 1 ); }); it( 'returns 2 for cellIndex 4' , () => { let cellPosition = new SudokuCellPosition( 4 ); expect( cellPosition.square ).toBe( 2 ); }); it( 'returns 1 for cellIndex 19' , () => { let cellPosition = new SudokuCellPosition( 28 ); expect( cellPosition.square ).toBe( 4 ); }); }); });
97912efaf73c85c4e1e8f979c8e8e2eb46bf4c2a
TypeScript
farism/love2dtest
/packages/client/src/game/components/Platform.ts
2.515625
3
import { ComponentFlag } from '../flags' import { Timer } from '../utils/timer' export class Platform { static _id = 'Platform' _id = Platform._id static _flag = ComponentFlag.Platform _flag = ComponentFlag.Platform initialX: number initialY: number resetDuration: number stableDuration: number timer?: Timer constructor( stableDuration: number = 0, resetDuration: number = 0, initialX: number = 0, initialY: number = 0 ) { this.stableDuration = stableDuration this.resetDuration = resetDuration this.initialX = initialX this.initialY = initialY } }
03e7abfdb1bfeccb616cc487afd11cfbfee69080
TypeScript
SutRog/vscode-amphtml-validator
/server/src/utils.ts
2.65625
3
/** * Copyright 2018 The AMPHTML-Validator Authors. All Rights Reserved. * * 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. */ 'use strict'; import { TextDocument, Diagnostic, DiagnosticSeverity, Range } from 'vscode-languageserver/lib/main'; import * as AmpValidatorTypes from './amp-validator-types'; interface AmpDoc { isAmpDoc: boolean; ampDocType: string; ampDocTypeParsed: AmpValidatorTypes.AmpValidatorValidationHtmlFormat; } /** * Checks if the current document passed the regExp so as to validate as an * AMP HTML document. The validation checks the <html> tag for any of the * (⚡4ads|amp4ads|⚡4email|amp4email|amp|⚡) attributes in the order and passes * the regex as soon as found first occurance (non-greedy). * Also, each attribute can have empty value, i.e. amp="". * @param textDocument */ export function isAmpHtmlDocument(textDocument: TextDocument): AmpDoc { const ampPattern = /.*?<html\s*.*?\s+(⚡4ads|amp4ads|⚡4email|amp4email|amp|⚡){1}(\s+|>|=)/gi; // Remove all comments, which might include <html> tag. // Non-greedy pattern to capture nested comments. const commentsPattern = /<!--([\s\S]*?)-->/gi; const text = textDocument.getText().replace(commentsPattern, ''); const ampPatternResponse = ampPattern.exec(text); const ampDocType = ampPatternResponse === null ? '' : ampPatternResponse.length >= 1 && ampPatternResponse[1]; const ampDocTypParsed = ampDocType.toUpperCase().replace(/⚡/, 'AMP'); const ampDoc: AmpDoc = { isAmpDoc: ampDocType !== '', ampDocType: ampDocType, ampDocTypeParsed: <AmpValidatorTypes.AmpValidatorValidationHtmlFormat>( ampDocTypParsed ) }; return ampDoc; } /** * Gets the range of given error from the AMP validator. * @param error */ export function getRange( error: AmpValidatorTypes.AmpValidatorValidationResultError ): Range { return { start: { line: error.line - 1, character: error.col }, end: { line: error.line - 1, character: error.col + 5 } }; } /** * Builds the Diagnostic object from AMP Validator error object. * The `errorUrl` should be clickable link, VS Code does not support yet. * Ref: https://github.com/Microsoft/vscode/issues/11847 * @param error * @param docType */ export function makeDiagnostic( error: AmpValidatorTypes.AmpValidatorValidationResultError, docType: string ): Diagnostic { const errorUrl = error.specUrl ? ` : ${error.specUrl}` : ''; return { severity: error.severity == AmpValidatorTypes.AmpValidatorValidationResultErrorSeverity.ERROR ? DiagnosticSeverity.Error : DiagnosticSeverity.Warning, message: `${docType} : ${error.message}${errorUrl}`, range: getRange(error) }; }
863036c07a3f6fb717f707b9724a44a1ed82c441
TypeScript
jianfaw/node-blueprint
/src/model/Define/BlockDef.ts
2.75
3
import { BlockPortDirection, BlockPort } from "./Port"; import { OnUserAddPortCallback, BlockType, OnPortEventCallback, OnBlockEventCallback, OnBlockEditorEventCallback, OnAddBlockCheckCallback, OnPortUpdateCallback, OnPortRequestCallback, OnPortConnectCallback, OnPortEditorEventCallback, OnPortConnectCheckCallback, BlockSupportPlatform } from "./Block"; import { BlockEditor } from "../Editor/BlockEditor"; import { MenuItem } from "../Menu"; import { BlockParameterBaseType, BlockParameterSetType, BlockParameterType } from "./BlockParameterType"; import { BlockPortEditor } from "../Editor/BlockPortEditor"; import { PackageDef } from "./PackageDef"; //单元注册 //======================== /** * 单元信息结构 */ export class BlockRegData { /** * 创建单元信息结构 * @param guid 单元唯一GUID * @param name 单元名称 * @param description 说明字符串 * @param author 作者名字 * @param category 分类名称 */ public constructor(guid : string, name : string, description?:string, author?:string, category?:string) { this.guid = guid; this.baseInfo.name = name; if(description) this.baseInfo.description = description; if(author) this.baseInfo.author = author; if(category) this.baseInfo.category = category; } /** * 单元 唯一 GUID ,不能重复 */ public guid = ""; /** * 单元类型 */ public type : BlockType = 'normal'; /** * 该单元支持运行的平台类型 */ public supportPlatform : BlockSupportPlatform[] = [ 'all' ]; /** * 基础信息 */ public baseInfo = { /** * 单元名称 */ name: "Single", /** * 单元简单说明 */ description : "This is a single block. Useage: unknow.", /** * 单元图标 20x20 */ logo : require('../../assets/images/BlockIcon/function.svg'), /** * 单元所属类别。可以用 / 来归到子类里面 */ category : "", /** * 作者 */ author : "", /** * 版本 */ version : "" } /** * 单元所属的包 */ public pack : PackageDef = null; /** * 单元的端口 */ public ports : Array<BlockPortRegData> = []; /** * 根据方向、类型、键类型等参数在当前定义文件中查找一个端口 * @param direction 端口方向 * @param type 数据类型 * @param keyType 集合键的类型 * @param setType 数据集合的类型 * @param includeAny 是否包含 any 类型 */ public hasOnePortByDirectionAndType(direction : BlockPortDirection, type : BlockParameterType, keyType : BlockParameterType, setType : BlockParameterSetType = 'variable', includeAny = false) { if(type.isExecute()) { for(let i = 0, c = this.ports.length; i < c;i++) if(this.ports[i].direction == direction){ if(typeof this.ports[i].paramType == 'string' && this.ports[i].paramType == 'execute') return true; else if(typeof this.ports[i].paramType != 'string' && (<BlockParameterType>this.ports[i].paramType).isExecute()) return true; } }else { for(let i = 0, c = this.ports.length; i < c;i++) if(this.ports[i].direction == direction) { if(setType == 'dictionary' && this.ports[i].paramSetType == 'dictionary') { if( (this.ports[i].paramType == type.getType() || (type.isAny() && includeAny) || (this.ports[i].paramType == 'any' && includeAny)) && (this.ports[i].paramDictionaryKeyType == type.getType() || (keyType.isAny() && includeAny) || (this.ports[i].paramDictionaryKeyType == 'any' && includeAny)) ) return true; }else if(type.isAny() && includeAny && this.ports[i].paramSetType == setType) return true; else if( this.ports[i].paramType == type.getType() && this.ports[i].paramSetType == setType) return true; if(includeAny && this.ports[i].paramType == 'any' && this.ports[i].paramSetType == setType) return true; } } return false; } /** * 单元的配置 */ public settings : { /** * 端口动态配置 */ portsChangeSettings : { /** * 指示用户能不能添加输入端口 */ userCanAddInputPort: boolean, /** * 指示用户能不能添加输出端口 */ userCanAddOutputPort: boolean, }, /** * 参数动态配置 */ parametersChangeSettings : BlockParametersChangeSettings, /** * 获取或者设置当前单元是否只能在一个图表中出现一次 */ oneBlockOnly: boolean, /** * 自定义静态数据,会传输至每一个派生自此定义的 Block.data 上 */ data: any, /** * 是否在添加单元菜单中隐藏 */ hideInAddPanel: boolean, } = { portsChangeSettings : { userCanAddInputPort: false, userCanAddOutputPort: false, }, parametersChangeSettings : { userCanAddInputParameter: false, userCanAddOutputParameter: false, }, oneBlockOnly: false, data: {}, hideInAddPanel: false, } /** * 单元定义回调 */ public callbacks : { /** * 单元初始化时的回调。 * 通常在这个回调里面进行单元初始化的一些工作,请不要在这里调用行为节点(因为节点未初始化完成)。 * * (block : Block) => void */ onCreate : OnBlockEventCallback, /** * 单元在编辑器模式中初始化时的回调。 * (block : BlockEditor) => void */ onEditorCreate : OnBlockEditorEventCallback, /** * 单元释放时的回调。 * * (block : Block) => void */ onDestroy : OnBlockEventCallback, /** * 编辑器保存时的回调。(仅编辑器模式调用) * * (block : BlockEditor) => void */ onSave : OnBlockEditorEventCallback, /** * 当图表开始运行 * * (block : Block) => void */ onStartRun : OnBlockEventCallback, /** * 单元工作处理函数。入方向的执行端口激活时的回调。 * 通常在这个回调里面进行本单元的运算,然后调用下一个单元。 * * (block : Block, port : BlockPort) => void */ onPortExecuteIn : OnPortEventCallback, /** * 单元端口更新处理函数。 * 下一级单元请求本单元输出参数时发生的回调。 * 返回: * 在此回调中直接返回参数。如果本单元存在运行上下文,可直接设置出端口参数。 * * (block : Block, port : BlockPort, context : BlockRunContextData) => any */ onPortParamRequest : OnPortRequestCallback, /** * 用户添加了一个端口时的回调。 * * (block : Block, port : BlockPort) => void */ onPortAdd : OnPortEventCallback, /** * 用户删除了一个端口时的回调。 * * (block : Block, port : BlockPort) => void */ onPortRemove : OnPortEventCallback, /** * 创建单元自定义编辑器的回调(仅编辑器模式调用) * * (parentEle : HTMLElement, block : BlockEditor, regData : BlockRegData) => void */ onCreateCustomEditor : BlockEditorComponentCreateFn, /** * 创建单元自定义编辑器的回调(仅编辑器模式调用) * * (parentEle : HTMLElement, block : BlockEditor, port : BlockPort) => HTMLElement */ onCreatePortCustomEditor : BlockPortEditorComponentCreateFn, /** * 单元鼠标事件(仅编辑器模式调用) * * (blocak : BlockEditor, event : 'move'|'down'|'up', e : MouseEvent) => boolean * //返回true则终止默认事件 */ onBlockMouseEvent : BlockMouseEventFn, /** * 用户创建端口时的回调(仅编辑器模式调用) * * (block : BlockEditor, direction : BlockPortDirection, type : 'execute'|'param') => BlockPortRegData|BlockPortRegData[] */ onUserAddPort: OnUserAddPortCallback, /** * 添加单元时的回调,在这个回调中检查能否添加单元, * 返回null可以添加,返回一个字符串表示不能添加,字符串会显示给用户。(仅编辑器模式调用) * * (block : BlockRegData, graph : BlockGraphDocunment) => string|null */ onAddCheck: OnAddBlockCheckCallback, /** * 当的端口连接检查时的回调,在这个回调中检查能否连接端口, * 返回null可以添加,返回一个字符串表示不能连接,字符串会显示给用户。(仅编辑器模式调用) * * (block : BlockEditor, port : BlockPort, portSource : BlockPort) => string */ onPortConnectCheck: OnPortConnectCheckCallback, /** * 当端口连接时的回调。(仅编辑器模式调用) * * (block : BlockEditor, port : BlockPort, portSource : BlockPort) => void */ onPortConnect: OnPortConnectCallback, /** * 当端口断开连接时的回调。(仅编辑器模式调用) * * (block : BlockEditor, port : BlockPort) => void */ onPortUnConnect: OnPortEditorEventCallback, } = { onCreate: null, onDestroy: null, onEditorCreate: null, onStartRun : null, onPortExecuteIn : null, onPortParamRequest : null, onPortAdd : null, onPortRemove : null, onCreateCustomEditor : null, onCreatePortCustomEditor: null, onUserAddPort: null, onAddCheck: null, onPortConnectCheck: null, onPortConnect: null, onPortUnConnect: null, onSave: null, onBlockMouseEvent: null, } /** * 单元的自定义样式 */ public blockStyle = new BlockStyleSettings(); /** * 单元的自定义菜单 */ public blockMenu = new BlockMenuSettings(); /** * 参见 BlockPortRegData.portAnyFlexable , 该字段用于定义单元整体的key使用。 */ public portAnyFlexables : BlockPortAnyFlexablesData = {}; //以下字段用于编辑器内部使用 show = true; filterShow = true; grouped = false; } export interface BlockPortAnyFlexablesData { [index: string]: { setResultToOptions?: string, setResultToData?: string } } export interface PortAnyFlexableData { [ index: string ] : boolean|{ get: string, set: string } } export type BlockParametersChangeSettings = { /** * 指定用户是否可以添加进入参数 */ userCanAddInputParameter: boolean, /** * 指定用户是否可以添加输出参数 */ userCanAddOutputParameter: boolean } export class BlockMenuSettings { /** * 自定义菜单 */ public items : Array<MenuItem> = []; } /** * 单元样式设置 */ export class BlockStyleSettings { /** * 单元右上角的大图标 32x32 */ public logoRight = ""; /** * 单元左下角的小图标 16x16 */ public logoBottom = ""; /** * 单元左下角的小图标 16x16 * 如果设置为 “title:xxxxx” 那么将会显示为文字 xxxxx */ public logoBackground = ""; /** * 单元标题背景颜色 */ public titleBakgroundColor = 'rgba(255,255,255,0.3)'; /** * 单元标题颜色 */ public titleColor = ''; /** * 是否使用短标题栏 */ public smallTitle = false; /** * 是否隐藏题栏 */ public noTitle = false; /** * 是否不显示鼠标悬停提示 */ public noTooltip = false; /** * 是否不显示注释菜单 */ public noComment = false; /** * 单元最小宽度 */ public minWidth = ''; /** * 单元最小高度 */ public minHeight = ''; /** * 是否隐logo */ public hideLogo = false; /** * 指示用户是否可以调整该单元大小 */ public userCanResize = false; /** * 指定单元渲染所在层 */ public layer : 'normal'|'background' = 'normal'; } //端口注册 //======================== /** * 行为节点信息结构 */ export interface BlockPortRegData { /** * 节点 的唯一ID (不能为空,数字或字符串,可以随便写,在16个字符之内),只要保证一个单元内不能重复即可 */ guid: string, /** * 名称 */ name?: string, /** * 说明 */ description?: string, /** * 节点的方向 */ direction : BlockPortDirection, /** * 设置是否默认连接至此节点。最好只有一个设置为true,如果有多个,先添加的为默认连接。 */ defaultConnectPort?: boolean, /** * 对于这个执行端口,是否在新上下文执行端口。 * 只有新上下文执行才能延迟执行或在回调中执行。 * 默认为 false。 */ executeInNewContext?: boolean, /** * 端口的类型 */ paramType : BlockParameterType|string|BlockParameterBaseType; /** * 端口的集合类型 */ paramSetType ?: BlockParameterSetType; /** * 参数的默认值 */ paramDefaultValue ?: any; /** * 当端口为Dictionary时的键类型 */ paramDictionaryKeyType ?: BlockParameterType|string; /** * 是否引用传递参数值,默认为 false */ paramRefPassing ?: boolean; /** * 参数值是否为全局变量,默认为 false */ paramStatic ?: boolean; /** * 指定参数是否必须提供,默认为 false */ paramRequired ?: boolean; /** * 该字段用于指示类型为 any 的弹性端口的行为。 * * 该字段是一个Object,格式为: * { * key: boolean, * key2: boolean, * ... * } * 或: * { * key3: { get: 'paramDictionaryKeyType'|'paramType', set: 'paramDictionaryKeyType'|'paramType' }, * ... * } * (注意:字段中出现的key必须也在BlockDef的portAnyFlexables字段中定义并为true,如下: * portAnyFlexables: { * key: true * } * 不然的话数据不会保存) * * 说明: * 当key后面的值不是false或undefined时,表示这个flexable key可用, * 当两个端口都定义了相同名称的两个flexable key并且都可用时,表示两个端口弹性绑定, * 这是,如果其中一个端口连接上了一个有类型的端口,那么它将会转换自身类型至连接上的端口, * 并且把弹性绑定的另一个端口的类型也改过来,这就是弹性端口的功能。 * * 如果key后面的定义如key3所示,是一个get和set,这表示自定义弹性端口要参考和改变的字段 * get表示当接上了端口时要参考的字段,会将自己的类型改为对应的参考的字段值。 * set表示当弹性端口要更改自己的值时,他要更改哪个字段。 * 这通常用于集合类型的弹性端口。 * * paramType 表示端口类型 * paramDictionaryKeyType 表示端口的集合键的类型 * */ portAnyFlexable ? : PortAnyFlexableData; /** * 是否强制不显示编辑参数控件 */ forceNoEditorControl ?: boolean; /** * 是否强制不检查循环调用 */ forceNoCycleDetection ?: boolean; /** * 是否强制在输出端口显示编辑参数控件 */ forceEditorControlOutput ?: boolean; /** * 自定义静态数据,将会拷贝至每一个改单元的端口实例的 data 上。 */ data ?: any; } /** * 参数的编辑器注册数据 */ export class BlockParameterEditorRegData { /** * 一个函数回调,在这里创建数据类型的对应编辑器,用来编辑此种类型的数据。 */ public editorCreate : BlockParameterEditorComponentCreateFn = null; /** * 当需要强制更新这个编辑器内部显示的数据时发生的回调,更新编辑器显示的数据。 */ public forceUpdateValue : BlockParameterEditorValueChangedFn = null; /** * 指示这个类型编辑器可用的变量集合类型 */ public useInSetType : BlockParameterSetType[] = [ 'variable' ]; } //类型注册 //======================== /** * 数据类型信息结构。 * 此信息用来定义自己的参数类型 */ export class BlockParameterTypeRegData { public constructor(name : string, prototypeName : string, color?: string, editor ?: BlockParameterEditorRegData) { this.name = name; this.prototypeName = prototypeName; if(typeof editor != 'undefined') this.editor = editor; if(typeof color != 'undefined') this.color = color; } /** * 类型名称 */ public name = ""; /** * 自定义 object 的 prototype 名称 */ public prototypeName = ""; /** * 自动创建Enum的转换器 */ public autoCreateEnumConverter = true; /** * 编辑器创建 */ public editor : BlockParameterEditorRegData = null; /** * 类型的颜色 */ public color : string = 'rgb(253,253,253)'; /** * 显示给用户的名称 */ public nameForUser = ""; /** * getHashCode 获取哈希码函数. */ public getHashCode : (v : any) => string = null; /** * createDefaultValue 创建默认值函数. */ public createDefaultValue : () => any = null; } /** * 枚举的项结构 */ export type BlockParameterEnumValueData = { /** * 项的值 */ value: string, /** * 项的说明文字 */ description: string } /** * 枚举类型信息结构。 * 此信息用来定义自己的枚举类型 */ export class BlockParameterEnumRegData extends BlockParameterTypeRegData { /** * 创建枚举类型信息结构 * @param name 枚举名称 * @param allowTypes 枚举允许的项 * @param color 颜色 * @param editor 编辑器数据,若不定义,则使用默认枚举编辑器 */ public constructor(name : string, allowTypes ?: Array<BlockParameterEnumValueData> | Array<string>, color?: string, editor ?: BlockParameterEditorRegData) { super(name, 'enum', color, editor); if(typeof allowTypes != 'undefined' && allowTypes.length > 0) { if(typeof allowTypes[0] == 'string'){ allowTypes.forEach((element : any) => { this.allowTypes.push({ value: element, description: '' }) }); } else this.allowTypes = this.allowTypes.concat(<Array<BlockParameterEnumValueData>>allowTypes); } } /** * 枚举允许的项 */ public allowTypes : Array<BlockParameterEnumValueData> = []; } /** * 类型转换器的注册类型 */ export class BlockParameterTypeConverterData { /** * 源类型 */ public fromType : BlockParameterType = BlockParameterType.Any(); /** * 目标类型 */ public toType : BlockParameterType = BlockParameterType.Any(); /** * 转换所支持的集合类型 */ public allowSetType : BlockParameterSetType = 'variable' ; /** * 转换器 */ public converter : (source : any) => any; } //回调函数定义 //======================== export type BlockParameterEditorComponentCreateFn = (block : BlockEditor, port : BlockPortEditor, rparentEle : HTMLElement, changeCallback : (newVal : any) => any, nowVal : any, defaultVal : any, customType : BlockParameterTypeRegData) => HTMLElement; export type BlockParameterEditorValueChangedFn = (newVal : any, editorEle : HTMLElement) => void; export type BlockEditorComponentCreateFn = (parentEle : HTMLElement, block : BlockEditor, regData : BlockRegData) => void; export type BlockPortEditorComponentCreateFn = (parentEle : HTMLElement, block : BlockEditor, port : BlockPortEditor) => HTMLElement; export type BlockMouseEventFn = (block : BlockEditor, event : 'move'|'down'|'up', e : MouseEvent) => boolean;
d67e3a1b42b1bcf38e965926c3e7ad257e867895
TypeScript
gviligvili/atn4seed
/src/app/store/articles/articles.reducer.ts
2.84375
3
/** * Created by talgvili on 22/12/2016. */ import {ArticlesActions} from '../../actions/articlesActions/articles.actions' import {IPayloadAction} from "../../actions"; import {ARTICLES_INITIAL_STATE} from "./articles.initial-state"; export function articlesReducer(state = ARTICLES_INITIAL_STATE, action:IPayloadAction):any { switch (action.type) { case ArticlesActions.FETCH_ARTICLES_REQUEST: return Object.assign( {}, state, { pending: true, error: false }) case ArticlesActions.FETCH_ARTICLES_SUCCESS: return Object.assign( {}, /** IMPORTANT ! , Because like that, Object.assign will use fresh new object. **/ state, { articles: Object.assign({}, state.articles, action.payload.articles), /** Combine the previous articles, with the new articles, like that outdated articles will be overidden and others wont get deleted. **/ pending: false, error: false }); case ArticlesActions.FETCH_ARTICLES_FAILURE: return Object.assign({}, state, {error: action.payload.error, pending: false}) case ArticlesActions.SET_ARTICLE: return Object.assign( {}, state, { articles: Object.assign({}, state.articles, action.payload.article) }); case ArticlesActions.REMOVE_ARTICLE: /** * Creating a new articles object , * and from him, deleting the id of the article. */ let newArticles = Object.assign({}, state.articles) delete newArticles[action.payload.id]; return Object.assign( {}, state, { articles: newArticles }) default: return state; } }
8fcbb9af17bb4804ddc5d50234ea772082073181
TypeScript
rlong/browser.app.McRemote
/Project/src/lib/json_broker.ts
2.765625
3
import 'rxjs/add/operator/take'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/toPromise'; import {Http} from "@angular/http"; export class BrokerMessage { messageType:string = "request"; // 'fault'/'oneway'/'request'/'response'/'event' metaData:any = {}; serviceName:string = "__SERVICE_NAME__"; majorVersion:number = 1; minorVersion:number = 0; methodName:string = "__METHOD_NAME__"; associativeParameters:any = {}; orderedParameters:any[]; constructor(poja?:any[]) { // poja: plain old javascript array if (poja) { this.messageType = poja[0]; this.metaData = poja[1]; this.serviceName = poja[2]; this.majorVersion = poja[3]; this.minorVersion = poja[4]; this.methodName = poja[5]; this.associativeParameters = poja[6]; if( 8 == poja.length ) { this.orderedParameters = poja[7]; } } } public static buildRequest( serviceName: string, methodName: string ): BrokerMessage { let answer: BrokerMessage = new BrokerMessage(); answer.serviceName = serviceName; answer.methodName = methodName; return answer; } public static buildRequestWithOrderedParameters( serviceName: string, methodName: string, orderedParameters:any[] = [] ): BrokerMessage { let answer: BrokerMessage = new BrokerMessage(); answer.serviceName = serviceName; answer.methodName = methodName; answer.orderedParameters = orderedParameters; return answer; } toArray():any[] { var answer = new Array(6); answer[0] = this.messageType; answer[1] = this.metaData; answer[2] = this.serviceName; answer[3] = this.majorVersion; answer[4] = this.minorVersion; answer[5] = this.methodName; answer[6] = this.associativeParameters; if (this.orderedParameters) { answer[7] = this.orderedParameters; } return answer; } toData():any { return JSON.stringify(this.toArray()); } } export class RequestBuilder { public metaData = {}; constructor( private serviceName: string ) {} build( methodName: string ): BrokerMessage { let answer: BrokerMessage = new BrokerMessage(); answer.metaData = this.metaData; answer.serviceName = this.serviceName; answer.methodName = methodName; return answer; } } export class RequestDispatcher { url: string; constructor(private http:Http) { // localhost development if( '10000' === window.location.port ) { this.url = 'http://localhost:10000/services'; } else { this.url = '/services'; } console.log( [this], "constructor", this.url ); } dispatch(request: BrokerMessage): Promise<BrokerMessage> { return this.http.post( this.url, request.toData() ).take(1).map( ( result )=>{ return new BrokerMessage( result.json() ) } ).toPromise(); } }
090eda0737cf0e63f5e3158ce738eac6d75e0653
TypeScript
gsanta/silhouette-people
/src/model/objects/route/routing/ReversingRouter.ts
2.671875
3
import { RouteItem } from "../RouteItem"; import { RouteController } from "../../game_object/controller_route/RouteController"; import { IRouter } from "./IRouter"; export class ReversingRouter implements IRouter { private readonly routeWalker: RouteController; private readonly referenceRoute: RouteItem; constructor(routeWalker: RouteController) { this.routeWalker = routeWalker; this.referenceRoute = routeWalker.getRoute(); } edgeChanged(): void { const route = this.routeWalker.getRoute(); if (this.routeWalker.getEdge() === undefined) { let newRoute: RouteItem = route.lastVertex !== this.referenceRoute.lastVertex ? this.referenceRoute : this.referenceRoute.reverse(); this.routeWalker.setRoute(newRoute); if (newRoute.getEdges().length > 0) { this.routeWalker.setEdge(newRoute.getEdges()[0]); } } } }
8e464f357f88ef490e8ddf257c77c32d89b69ded
TypeScript
inqui05/english-for-kids-with-api
/client/src/components/button-component.ts
2.546875
3
import { Button } from '../shared/types'; export class ButtonComponent { readonly element: HTMLButtonElement; constructor(styles: string[] = [], params: Button) { this.element = document.createElement('button'); this.element.classList.add(...styles); if (params.name) this.element.innerHTML = params.name; if (params.disabled) this.element.disabled = params.disabled; } }
c07f4fa005f23d44096b92c4aa7a24523fd0665b
TypeScript
IuriiZhuk/angular_gmp_2019_q3
/src/app/courses/services/courses.service.spec.ts
2.578125
3
import { TestBed } from '@angular/core/testing'; import { CoursesService } from './courses.service'; import { ICourse } from '../models/course'; let service: CoursesService; const mockCourseList = [ { id: 'id1', title: 'title1', creationDate: '12-12-21', duration: 10, description: 'description1', topRated: true, }, { id: 'id2', title: 'title2', creationDate: '10-10-20', duration: 20, description: 'description2', topRated: false, }, ]; let newCourse: ICourse; let result: ICourse; describe('CoursesService', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [CoursesService] }); service = TestBed.get(CoursesService); service.coursesList = [ { id: 'id1', title: 'title1', creationDate: '12-12-21', duration: 10, description: 'description1', topRated: true, }, { id: 'id2', title: 'title2', creationDate: '10-10-20', duration: 20, description: 'description2', topRated: false, }, ]; }); it('should be created', () => { expect(service).toBeTruthy(); }); it('should return course by Id', () => { result = { id: 'id1', title: 'title1', creationDate: '12-12-21', duration: 10, description: 'description1', topRated: true, }, expect(service.getCourseById('id1')).toEqual(result); }); it('should add course', () => { newCourse = { id: 'id3', title: 'title3', creationDate: '12-12-21', duration: 10, description: 'description1', topRated: true, }; const resultCourses = mockCourseList.concat(newCourse); expect(service.addCourse(newCourse)).toEqual(resultCourses); }); it('should delete course by Id', () => { const res = [{ id: 'id1', title: 'title1', creationDate: '12-12-21', duration: 10, description: 'description1', topRated: true, }]; expect(service.deleteCourseById('id2')).toEqual(res); }); it('should update course by Id', () => { const res = [ { id: 'id1-update', title: 'title1-update', creationDate: '12-12-21', duration: 10, description: 'description1', topRated: true, }, { id: 'id2', title: 'title2', creationDate: '10-10-20', duration: 20, description: 'description2', topRated: false, }, ]; const updateCourse = { id: 'id1-update', title: 'title1-update', creationDate: '12-12-21', duration: 10, description: 'description1', topRated: true, }; expect(service.updateCourseById('id1', updateCourse)).toEqual(res); }); });
c5523e8319bd03b5d19aa540daee21e2fced3e48
TypeScript
corefunc/corefunc
/json/stringify/with.ts
2.90625
3
import { jsonStringifySafe } from "./safe"; /** * @param {*} object * @param {Function=} replacer * @param {String=} spaces * @param {Function=} cycleReplacer * @return {String} */ export function jsonStringifyWith( object: any, replacer?: (this: any, key: string, value: any) => any, spaces?: string | number, cycleReplacer?: (key: string, value: any) => any, ): string { return jsonStringifySafe(object, replacer, spaces, cycleReplacer); }
e258e95e7144ae5258051c160b6421a1c29aaafc
TypeScript
Saad-Malik/gamauml
/express/examples/attribute-configuration.ts
2.578125
3
import { DomainConfiguration, Runtime } from 'graph-on-rails'; import _ from 'lodash'; // ENUM const winnerYear = { Toyota: [2020, 2019, 2018], Porsche: [2017,2016,2015,2014,2013,2012,2011,2010], Peugeot: [2009], Audi: [2008,2007,2006,2005,2004], Bentley:[2003] } const repaint = async (rt:Runtime, id:string, color:string) => { const car = rt.entity('Car'); const c = await car.findById( id ); c.item.color = color; return (await c.save()).item; } const domainConfiguration:DomainConfiguration = { query: { leMansWinner: (rt:Runtime) => ({ type: '[Int!]', args: { brand: { type: 'CarBrand' } }, resolve: ( root:any, args:any ) => _.get( winnerYear, args.brand as string ) }) }, mutation: { repaint: (rt:Runtime) => ({ type: 'Car', args: { id: { type: 'ID' }, color: { type: 'String!' } }, resolve: async (root:any, args:any) => repaint( rt, args.id, args.color ) }) } } // export const example1 = new DomainDefinition( './config-types/car-config-1'); // example1.add( domainConfiguration ); export const example4:DomainConfiguration = { entity: { Car: { attributes: { brand: { type: 'String', unique: true } }, seeds: { mercedes: { brand: 'Mercedes' }, vw: { brand: 'Volkswagen' }, } } } } export const example5:DomainConfiguration = { entity: { Organisation: { attributes: { name: 'Key' }, seeds: { ms: { name: 'Microsoft' }, fb: { name: 'Facebook' } }, assocFrom: 'Department' }, Department: { attributes: { name: { type: 'String!', unique: 'Organisation' } }, assocTo: 'Organisation!', seeds: { hrms: { name: 'HR', Organisation: 'ms' } } } } } export const unique1:DomainConfiguration = { entity: { Car: { attributes: { brand: 'String', licence: 'Key' }, seeds: { red_mercedes: { brand: 'Mercedes', licence: 'HH-BO 2020' } } } } } export const unique2:DomainConfiguration = { entity: { Car: { attributes: { brand: 'String', color: { type: 'String', unique: 'brand' } }, seeds: { red_mercedes: { brand: 'Mercedes', color: 'red' } } } } } export const file1:DomainConfiguration = { entity: { Car: { attributes: { brand: 'String!', image: 'File' } } } } export const list1:DomainConfiguration = { entity: { Car: { attributes: { licence: 'Key', repairsAtKm: '[Int!]', tags: { type: 'String', required: true, list: true } }, seeds: { 1: { licence: 'HH TR 2929', repairsAtKm: [30000, 20000, 40000], tags: ['foo', 'bar', 'foobar'] }, 2: { licence: 'MA HH 4324', repairsAtKm: [10000, 55000, 44000, 5000], tags: [] }, 3: { licence: 'BO ZU 7365', repairsAtKm: [5500, 100], tags: ['foo', 'bar', 'baz'] }, 4: { licence: 'LG ZT 6578', repairsAtKm: [], tags: ['foobar'] } } } } }
62db589dd59845a2e920222d227174ddc823422c
TypeScript
dragonxu/imodeljs
/ui/appui-abstract/src/appui-abstract/UiAbstract.ts
2.53125
3
/*--------------------------------------------------------------------------------------------- * Copyright (c) Bentley Systems, Incorporated. All rights reserved. * See LICENSE.md in the project root for license terms and full copyright notice. *--------------------------------------------------------------------------------------------*/ /** @packageDocumentation * @module Utilities */ import { Logger } from "@itwin/core-bentley"; import { Localization } from "@itwin/core-common"; import { MessagePresenter } from "./notification/MessagePresenter"; import { getClassName } from "./utils/getClassName"; import { UiError } from "./utils/UiError"; /** * Entry point for static initialization required by various components used in the package. * @public */ export class UiAbstract { private static _initialized = false; private static _localization?: Localization; private static _messagePresenter?: MessagePresenter; /** * Registers the Localization service namespace for UiAbstract * @param localization The internationalization service created by the application. */ public static async initialize(localization: Localization): Promise<void> { if (UiAbstract._initialized) { Logger.logInfo(UiAbstract.loggerCategory(UiAbstract), `UiAbstract.initialize already called`); return; } UiAbstract._localization = localization; await UiAbstract._localization.registerNamespace(UiAbstract.localizationNamespace); UiAbstract._initialized = true; } /** Unregisters the UiAbstract internationalization service namespace */ public static terminate() { if (UiAbstract._localization) UiAbstract._localization.unregisterNamespace(UiAbstract.localizationNamespace); UiAbstract._localization = undefined; UiAbstract._initialized = false; } /** Determines if UiAbstract has been initialized */ public static get initialized(): boolean { return UiAbstract._initialized; } /** The internationalization service created by the application. */ public static get localization(): Localization { if (!UiAbstract._localization) throw new UiError(UiAbstract.loggerCategory(this), "UiAbstract not initialized"); return UiAbstract._localization; } /** The internationalization service namespace. */ public static get localizationNamespace(): string { return "UiAbstract"; } /** Calls localization.getLocalizedStringWithNamespace with the "UiAbstract" namespace. Do NOT include the namespace in the key. * @internal */ public static translate(key: string | string[]): string { return UiAbstract.localization.getLocalizedStringWithNamespace(UiAbstract.localizationNamespace, key); } /** @internal */ public static get packageName(): string { return "appui-abstract"; } /** @internal */ public static loggerCategory(obj: any): string { const className = getClassName(obj); const category = UiAbstract.packageName + (className ? `.${className}` : ""); return category; } /** The MessagePresenter used to display messages. */ public static get messagePresenter(): MessagePresenter { if (!UiAbstract._messagePresenter) throw new UiError(UiAbstract.loggerCategory(this), "UiAbstract.MessagePresenter not set"); return UiAbstract._messagePresenter; } public static set messagePresenter(mp: MessagePresenter) { UiAbstract._messagePresenter = mp; } }
57b6ba3cf506e82a460fcb8a8c2d062dcf4b5ef1
TypeScript
houssemDevs/koa-ioc-utils
/src/utils.ts
2.65625
3
import { Context } from 'koa'; import mime from 'mime'; import { METADATA_KEYS } from './constants'; import { ControllerMetadata, ControllersMetadata, ErrorMapper, IReponseObject, MethodMetadata, MethodsMetadata, ParamsMetadata, } from './types'; /** * get all the decorated controllers metadata, or an empty Array. */ export const getControllersFromMetadata = (): ControllersMetadata => Reflect.getMetadata(METADATA_KEYS.controller, Reflect) || new Map<string, ControllerMetadata>(); /** * get all the methods metadata of a controller * @param controller controller constructor function from which methods metadata will be extracted. * @throw throw error if no method is defined on the controller, an empty controller has no reason to be. */ export const getMethodsMetadataFromController = (controller: Function): MethodsMetadata => { const methodsMetadataMap: Map<string, MethodMetadata> = Reflect.getMetadata(METADATA_KEYS.method, controller); if (methodsMetadataMap) { return methodsMetadataMap; } throw new Error(`no methods defined on controller ${controller.name}`); }; export const getMethodParamsMetadata = (method: any): ParamsMetadata => { const metadata: ParamsMetadata = Reflect.getMetadata(METADATA_KEYS.params, method); return metadata; }; /** * return the contructor name of an object instance. * @param o object instance to get constructor name from . */ export const getObjectName = (o: any): string => { return o.constructor.name; }; /** * get the controller metadata by name. * @param name name of the controller * @throw throw if no controller is found. */ export const getControllerMetadataByName = (name: string): ControllerMetadata => { const controllersMetadataMap: Map<string, ControllerMetadata> = Reflect.getMetadata(METADATA_KEYS.controller, Reflect) || new Map(); const metadata = controllersMetadataMap.get(name); if (metadata) { return metadata; } else { throw new Error(`No controller metadata for name ${name}`); } }; export const responseObjectToKoaResponse = (ro: IReponseObject, ctx: Context) => { ctx.type = ro.type; ctx.status = ro.status; ro.headers.forEach(h => { ctx.set(h.header, h.value); }); ctx.body = ro.body; }; export const defaultErrorMapper: ErrorMapper = (err: Error) => { return { type: mime.getType('json') || 'application/json', status: 500, headers: [], body: { error: 'internal server error, contact site admin' }, }; };
8815ac02d290e03a48765781a8910bcecf51d217
TypeScript
jacquesikot/AstanahServer
/src/validation/user.ts
2.765625
3
import Joi from 'joi'; import { IGoogleAuth, IUser } from '../types'; const validateUser = (user: IUser) => { const schema = Joi.object({ first_name: Joi.string().min(2).max(45).required(), last_name: Joi.string().min(2).max(45), email: Joi.string().email().min(3).max(45).required(), password: Joi.string().min(3).max(25).required(), googleId: Joi.string().min(3).max(45), facebookId: Joi.string().min(3).max(45), }); return schema.validate(user); }; interface ILogin { email_address: string; password: string; } export const validateAuth = (credential: ILogin) => { const schema = Joi.object({ email: Joi.string().min(5).max(255).required().email(), password: Joi.string().min(3).max(255).required(), }); return schema.validate(credential); }; export const validateGoogleAuth = (credentials: IGoogleAuth) => { const schema = Joi.object({ id: Joi.string().required(), firstName: Joi.string(), lastName: Joi.string(), email: Joi.string().email(), provider: Joi.string(), }); return schema.validate(credentials); }; export default validateUser;
6eb43da98741ebf5660a25a72cf6d37dce69a4c8
TypeScript
b3h3m0th/hellsio_vinyl_shop
/src/Hooks/useScript.ts
2.59375
3
import { useState, useEffect } from "react"; const useScript = (url: string, name: any) => { const [lib, setLib] = useState<any>({}); useEffect(() => { const script = document.createElement("script"); script.src = url; script.async = true; script.onload = () => setLib({ [name]: window[name] }); document.body.appendChild(script); return () => { document.body.removeChild(script); }; //eslint-disable-next-line react-hooks/exhaustive-deps }, [url]); return lib; }; export default useScript;
62b94a6436fb8720c3f527aeae0d53930034a25e
TypeScript
lpreiss-wsei/paw
/lab5/index.ts
3.5
4
function StandardAccess(constructorFn: Function): void { constructorFn.prototype.role = Role.Standard; } function ModeratorAccess(constructorFn: Function): void { constructorFn.prototype.role = Role.Moderator; } function AdminAccess(constructorFn: Function): void { constructorFn.prototype.role = Role.Admin; } function watch(target: object, propKey: string, descriptor: PropertyDescriptor) { const originalFn = target[propKey]; descriptor.value = function(param) { console.log(`User: ${param} wants ${propKey}`); return originalFn.call(this, param); }; } enum Role { Standard = 'Standard', Moderator = 'Moderator', Admin = 'Admin' } class User { name: string; surname: string; role: Role; toString(): string { return `${this.name} ${this.surname} ${this.role}`; } } @StandardAccess class StandardUser extends User { constructor(name: string, surname: string) { super(); this.name = name; this.surname = surname; } } @ModeratorAccess class ModeratorUser extends User { constructor(name: string, surname: string) { super(); this.name = name; this.surname = surname; } } @AdminAccess class AdminUser extends User { constructor(name: string, surname: string) { super(); this.name = name; this.surname = surname; } } class Resource { private resourceValue: string; constructor() { this.resourceValue = "resource value"; } @watch public read(user: User): void { if (user.role === Role.Moderator || user.role === Role.Admin) { console.log(this.resourceValue); } } @watch public change(user: User): void { if (user.role === Role.Admin) { this.resourceValue = "changed resource value"; } } } const user1 = new StandardUser("Luke", "Skywalker"); const user2 = new ModeratorUser("Han", "Solo"); const user3 = new AdminUser("Obi-Wan", "Kenobi"); const res = new Resource(); console.log(user1.toString()); console.log(user2.toString()); console.log(user3.toString()); console.log('User 1:'); res.read(user1); res.change(user1); console.log('User 2:'); res.read(user2); res.change(user2); res.read(user3); console.log('User 3:'); res.change(user3); res.read(user3);
2920043af001d280afedeb1969d67f2f5117742f
TypeScript
jiweiyuan/bytebase
/frontend/src/types/error.ts
2.609375
3
export enum GeneralErrorCode { OK = 0, INTERNAL = 1, NOT_AUTHORIZED = 2, INVALID = 3, NOT_FOUND = 4, CONFLICT = 5, NOT_IMPLEMENTED = 6, } export enum DBErrorCode { CONNECTION_ERROR = 101, SYNTAX_ERROR = 102, EXECUTION_ERROR = 103, } export enum MigrationErrorCode { MIGRATION_SCHEMA_MISSING = 201, MIGRAITON_ALREADY_APPLIED = 202, MGIRATION_OUT_OF_ORDER = 203, MIGRATION_BASELINE_MISSING = 204, } export enum CompatibilityErrorCode { COMPATIBILITY_DROP_DATABASE = 10001, COMPATIBILITY_RENAME_TABLE = 10002, COMPATIBILITY_DROP_TABLE = 10003, COMPATIBILITY_RENAME_COLUMN = 10004, COMPATIBILITY_DROP_COLUMN = 10005, COMPATIBILITY_ADD_PRIMARY_KEY = 10006, COMPATIBILITY_ADD_UNIQUE_KEY = 10007, COMPATIBILITY_ADD_FOREIGN_KEY = 10008, COMPATIBILITY_ADD_CHECK = 10009, COMPATIBILITY_ALTER_CHECK = 10010, COMPATIBILITY_ALTER_COLUMN = 10011, } export type ErrorCode = | GeneralErrorCode | DBErrorCode | MigrationErrorCode | CompatibilityErrorCode; export type ErrorTag = "General" | "Compatibility"; export type ErrorMeta = { code: ErrorCode; hash: string; };
fe26ea4fd9852d82f624c6e872c2870728980376
TypeScript
okolomiets/stocksTrader
/src/app/store/reducers/markets.reducers.ts
2.8125
3
import * as fromMarkets from '../actions/markets.actions'; import { Market } from '../../models/market.model'; export interface MarketsState { markets: Market[]; loaded: boolean; loading: boolean; } export const initialState: MarketsState = { markets: [], loaded: false, loading: false }; export function reducer( state = initialState, action: fromMarkets.MarketsActions ): MarketsState { switch (action.type) { case fromMarkets.LOAD_MARKETS: { return { ...state, loading: true, }; } case fromMarkets.LOAD_MARKETS_SUCCESS: { const markets = action.payload; return { ...state, loading: false, loaded: true, markets, }; } case fromMarkets.LOAD_MARKETS_FAIL: { return { ...state, loading: false, loaded: false, }; } } return state; } export const getMarkets = (state: MarketsState) => state.markets; export const getMarketsLoading = (state: MarketsState) => state.loading; export const getMarketsLoaded = (state: MarketsState) => state.loaded;
1b4ee2e0b5c5d504dd66ec140e5c34f3fe07a862
TypeScript
ClaudePlos/webNaprzodSA
/app/http-test.component.ts
2.671875
3
import {Component, OnInit} from 'angular2/core'; import {HTTPTestService} from './http-test.service'; class User { name: string; email: string; rating: number; } @Component({ selector: 'http-test', template: ` <button (click)="onTestGet()">Test get</button><br> <p>Output: {{getData}}</p> <button (click)="onTestPost()">Test post</button><br> <p>Output: {{postData}}</p> <button (click)="onGetUsers()">Test users</button><br> <p>Output: {{contacts}}</p> Pass, when you click on name user: <input type="text" [(ngModel)]="selectedItem"> <button (click)="onDeleteItem()">Delete Item</button> <br> <input type="text" #userNew> <button (click)="onAddItem(userNew)">Add new name user</button> <h1>Angular2 HTTP Demo App</h1> <h2>Users</h2> <ul> <li *ngFor="#user of users" (click)="onItemClicked(user.uzHasloZakodowane)"> {{user.prcId}}, {{user.uzNazwa}} </li> </ul> `, providers: [HTTPTestService] }) export class HTTPTestComponent implements OnInit { getData: string; postData: string; contacts: string; public users = [{}]; public selectedItem: {uzHasloZakodowane: ''}; constructor (private _httpService: HTTPTestService) {} ngOnInit() { this.onGetUsers(); } onTestGet() { this._httpService.getCurrentTime() .subscribe( data => this.getData = JSON.stringify(data), error => alert(error), () => console.log('Finished') ); } onTestPost() { this._httpService.postJSON() .subscribe( data => this.postData = JSON.stringify(data), error => alert(error), () => console.log('Finished') ); } onGetUsers() { this._httpService.getUsers() .subscribe( data => this.users = data, error => alert(error), () => console.log('Finished') ); } onItemClicked(item: {uzHasloZakodowane: ''}) { this.selectedItem = item; } onAddItem(userNew) { this.users.push({uzNazwa: userNew.value}); } onDeleteItem() { this.users.splice( this.users.indexOf(this.selectedItem), 1); } }
83aecb04e6f5984f77dec901a0782ccb9a1266db
TypeScript
sonnguyen112/database-gateway
/src/v2/schemas/common.ts
2.625
3
import { JSONSchemaType } from 'ajv'; export type WhereClause = Record<string, unknown> | Array<string | [any, any, any]>; export type OrderByClause = Array<string | { column: string; order: 'asc' | 'desc' }>; const whereClauseSchema: JSONSchemaType<WhereClause> = { anyOf: [ { type: 'object', required: [], }, { type: 'array', items: { anyOf: [ { type: 'string', minLength: 1, }, { type: 'array', items: [{}, {}, {}], minItems: 3, maxItems: 3, }, ], }, }, ], } as any; const orderByClauseSchema: JSONSchemaType<OrderByClause> = { type: 'array', items: { anyOf: [ { type: 'string', minLength: 1, }, { type: 'object', required: ['column', 'order'], properties: { column: { type: 'string', minLength: 1 }, order: { type: 'string', enum: ['asc', 'desc'] }, }, additionalProperties: false, }, ], }, }; export { whereClauseSchema, orderByClauseSchema };
c8c55a47f0cc6b81858a8c15290e6cf8b5e81b6b
TypeScript
amandabeiner/garden-app
/src/Application/actions.ts
2.515625
3
import { PersonalInfo, HistoryInfo, GardenPreferences } from './reducer'; export const savePersonalInfo = (payload: PersonalInfo): ApplicationAction => { return { type: ActionType.SAVE_PERSONAL_INFO, payload }; }; export const saveHistoryInfo = (payload: HistoryInfo): ApplicationAction => { return { type: ActionType.SAVE_HISTORY_INFO, payload }; }; export const saveGardenPreferences = ( payload: GardenPreferences, ): ApplicationAction => { return { type: ActionType.SAVE_GARDEN_PREFERENCES, payload }; }; export const toggleAgreeToTermsAccepted = (): ApplicationAction => { return { type: ActionType.TOS_TOGGLE }; }; export const toggleSignAgreement = (): ApplicationAction => { return { type: ActionType.SIGN_AGREEMENT_TOGGLE }; }; export enum ActionType { SAVE_PERSONAL_INFO, SAVE_HISTORY_INFO, SAVE_GARDEN_PREFERENCES, TOS_TOGGLE, SIGN_AGREEMENT_TOGGLE, } export type ApplicationAction = | { type: ActionType.SAVE_PERSONAL_INFO; payload: PersonalInfo } | { type: ActionType.SAVE_HISTORY_INFO; payload: HistoryInfo } | { type: ActionType.SAVE_GARDEN_PREFERENCES; payload: GardenPreferences } | { type: ActionType.TOS_TOGGLE } | { type: ActionType.SIGN_AGREEMENT_TOGGLE };
2fdaa8a48d18dbe4d7494c7ac66f571f2bff690f
TypeScript
milehighfd/confluence-mhfd-frontend
/src/store/reducers/notesReducer.ts
2.8125
3
import * as types from '../types/notesTypes'; const initState = { notes: [], groups: [], open: false, availableColors: [], isnewnote: false }; const notesReducer = (state = initState, action : any) => { switch(action.type) { case types.SET_IS_NEW_NOTE: return { ...state, isnewnote: action.payload } case types.CREATE_NOTE: return { ...state, notes: [...state.notes, action.note], isnewnote: true } case types.CREATE_GROUP: return { ...state, groups: [...state.groups, action.group] } case types.DELETE_GROUP: return { ...state, notes: state.notes.filter((note: any) => note.groupnotes_id !== action.id), groups: state.groups.filter(group => { return group['groupnotes_id'] !== action.id; }) } case types.GET_GROUPS: return { ...state, groups: action.groups } case types.EDIT_GROUP: return { ...state, groups: state.groups.map(group => { if (group['groupnotes_id'] === action.group['groupnotes_id']) { return action.group; } return group; }) } case types.DELETE_NOTE: return { ...state, notes: state.notes.filter(note => { return note['newnotes_id'] !== action.id }) } case types.LIST_NOTES: return { ...state, notes: action.notes } case types.EDIT_NOTES: return { ...state, notes: state.notes.map(note => { if (note['newnotes_id'] === action.note['newnotes_id']) { return action.note; } return note; }) } case types.GET_AVAILABLE_COLORS: return { ...state, availableColors: action.availableColors } case types.SIDEBAR_STATUS: return { ...state, open: action.open } default: return state; } } export default notesReducer;
4986cf5b7cbaeadfb3d78529ed42be36b69b8471
TypeScript
sandeshdanwale/umber
/src/main/resources/public/scripts/src/app/actions/property.action.ts
2.578125
3
import { Action } from '@ngrx/store'; import { Property } from '../models/aggregate/property.model'; import { type } from '../util'; export const ActionTypes = { LOAD_SUCCESS: type('[Property] Load Success'), LOAD: type('[Property] Load'), UPDATE_PROPERTY_DETAIL: type('[Property] Update Property Detail') }; export class LoadSuccessAction implements Action { type = ActionTypes.LOAD_SUCCESS; constructor(public payload: Property[]) { } } export class LoadAction implements Action { type = ActionTypes.LOAD; constructor(public payload: Property[]) { } } export class UpdatePropertyDetail implements Action { type = ActionTypes.UPDATE_PROPERTY_DETAIL; constructor(public payload: Property) { } } export type Actions = LoadSuccessAction | LoadAction | UpdatePropertyDetail;
34bd4654ec74b75c67266b72041a88dfe0e038c0
TypeScript
hwhang0917/busiman
/backend/src/projects/entities/project.entity.ts
2.53125
3
import { Client } from 'src/clients/entities/client.entity'; import { Employee } from 'src/employees/entities/employee.entity'; import { CoreEntity } from 'src/common/entities/core.entity'; import { Document } from './document.entity'; import { Column, Entity, JoinTable, ManyToMany, ManyToOne, OneToMany, } from 'typeorm'; import { IsEnum, IsNumber, IsString } from 'class-validator'; export enum Status { Pending = 'Pending', Ongoing = 'Ongoing', Completed = 'Completed', } @Entity() export class Project extends CoreEntity { @Column() @IsString() title: string; @Column() @IsNumber() revenue: number; @Column({ type: 'enum', enum: Status }) @IsEnum(Status) status: Status; @OneToMany(() => Document, (document) => document.project) documents: Document[]; @ManyToOne(() => Employee, (employee) => employee.leadingProjects, { onDelete: 'SET NULL', nullable: true, }) projectManager: Employee; @ManyToMany(() => Employee, (employee) => employee.assignedProjects) @JoinTable() assignedMembers: Employee[]; @ManyToOne(() => Client, (client) => client.projects, { onDelete: 'SET NULL', nullable: true, }) client?: Client; }
650245e60ffda6a0eb8dd2436c1ebc018a1e4840
TypeScript
WdsFomenko/schematics-react
/src/functional-component/index_spec.ts
2.53125
3
import { Tree } from '@angular-devkit/schematics'; import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; import * as path from 'path'; import { Schema as FnComponentOptions } from './schema'; const collectionPath = path.join(__dirname, '../collection.json'); const defaultOptions: FnComponentOptions = { name: 'test', path: '/bar', styleext: 'css', noSpec: false, subfolder: false, propTypes: false, ts: false }; describe('functional-component', () => { it('requires required name option', () => { const runner = new SchematicTestRunner('schematics', collectionPath); expect(() => runner.runSchematic('functional-component', {}, Tree.empty())).toThrow(); }); it('works', () => { const runner = new SchematicTestRunner('schematics', collectionPath); const tree = runner.runSchematic('functional-component', {...defaultOptions}, Tree.empty()); expect(tree.files.length).toEqual(3); expect(tree.files.sort()).toEqual(['/bar/Test.css', '/bar/Test.js', '/bar/Test.test.js']); const componentContent = tree.readContent('/bar/Test.js'); expect(componentContent).toMatch(/const Test = \({ myProp, children }\)/); expect(componentContent).toMatch(/export default Test/); }); it('creates scss file', () => { const runner = new SchematicTestRunner('schematics', collectionPath); const tree = runner.runSchematic('functional-component', {...defaultOptions, styleext: 'scss'}, Tree.empty()); expect(tree.files.find(path => path.includes('css'))).toEqual('/bar/Test.scss'); }); it('omits test file creation', () => { const runner = new SchematicTestRunner('schematics', collectionPath); const tree = runner.runSchematic('functional-component', {...defaultOptions, noSpec: true}, Tree.empty()); expect(tree.files.length).toEqual(2); expect(tree.files.sort()).toEqual(['/bar/Test.css', '/bar/Test.js']); }); it('creates subfoler', () => { const runner = new SchematicTestRunner('schematics', collectionPath); const tree = runner.runSchematic('functional-component', {...defaultOptions, subfolder: true}, Tree.empty()); expect(tree.files.length).toEqual(3); expect(tree.files.sort()).toEqual(['/bar/Test/Test.css', '/bar/Test/Test.js', '/bar/Test/Test.test.js']); }); it('creates propTypes', () => { const runner = new SchematicTestRunner('schematics', collectionPath); const tree = runner.runSchematic('functional-component', {...defaultOptions, propTypes: true}, Tree.empty()); const componentContent = tree.readContent('/bar/Test.js'); expect(componentContent).toMatch(/import PropTypes from \'prop-types\'/); expect(componentContent).toMatch(/Test\.propTypes/); }); it('uses TypeScript', () => { const runner = new SchematicTestRunner('schematics', collectionPath); const tree = runner.runSchematic('functional-component', {...defaultOptions, ts: true}, Tree.empty()); expect(tree.files.length).toEqual(3); expect(tree.files.sort()).toEqual(['/bar/Test.css', '/bar/Test.test.ts', '/bar/Test.tsx']); const componentContent = tree.readContent('/bar/Test.tsx'); expect(componentContent).toMatch(/type Props/); expect(componentContent).toMatch(/import React, { SFC } from \'react\'/); expect(componentContent).toMatch(/const Test: SFC<Props> = \({ myProp, children }\)/); }); });
55df8783b541f0cd5af08831f10b0d77810bff8f
TypeScript
sanity-io/sanity
/packages/sanity/src/core/studio/workspaces/__tests__/validateWorkspaces.test.ts
2.890625
3
import {validateBasePaths, validateNames} from '../validateWorkspaces' describe('validateBasePaths', () => { it('allows empty basePaths', () => { validateBasePaths([{name: 'foo', basePath: '/'}]) validateBasePaths([{name: 'foo', basePath: ''}]) validateBasePaths([{name: 'foo', basePath: undefined}]) }) it('throws if more than one workspace is defined, but one or more workspace does not have a basepath', () => { expect(() => { validateBasePaths([{name: 'first'}, {name: 'second', basePath: '/2nd'}]) }).toThrowErrorMatchingInlineSnapshot( `"If more than one workspace is defined, every workspace must have a \`basePath\` defined. Workspace \`first\` is missing a \`basePath\`"`, ) expect(() => { validateBasePaths([{name: 'first', basePath: '/1st'}, {name: 'second'}]) }).toThrowErrorMatchingInlineSnapshot( `"If more than one workspace is defined, every workspace must have a \`basePath\` defined. Workspace \`second\` is missing a \`basePath\`"`, ) expect(() => { validateBasePaths([ {name: 'first', basePath: '/1st'}, {name: 'second', basePath: ''}, ]) }).toThrowErrorMatchingInlineSnapshot( `"If more than one workspace is defined, every workspace must have a \`basePath\` defined. Workspace \`second\` has an invalid \`basePath\` (must be a non-empty string)"`, ) }) it('throws if a workspace has invalid characters', () => { expect(() => { validateBasePaths([{name: 'foo', basePath: '\tinvalid.characters%everywhere '}]) }).toThrowErrorMatchingInlineSnapshot( `"All workspace \`basePath\`s must start with a leading \`/\`, consist of only URL safe characters, and cannot end with a trailing \`/\`. Workspace \`foo\`'s basePath is \` invalid.characters%everywhere \`"`, ) }) it("throws if a workspace doesn't start with a leading `/`", () => { expect(() => { validateBasePaths([{name: 'foo', basePath: 'no-leading-slash'}]) }).toThrowErrorMatchingInlineSnapshot( `"All workspace \`basePath\`s must start with a leading \`/\`, consist of only URL safe characters, and cannot end with a trailing \`/\`. Workspace \`foo\`'s basePath is \`no-leading-slash\`"`, ) }) it('throws if a workspace has a trailing `/`', () => { expect(() => { validateBasePaths([{name: 'foo', basePath: '/has-trailing-slash/'}]) }).toThrowErrorMatchingInlineSnapshot( `"All workspace \`basePath\`s must start with a leading \`/\`, consist of only URL safe characters, and cannot end with a trailing \`/\`. Workspace \`foo\`'s basePath is \`/has-trailing-slash/\`"`, ) }) it('allows base paths with a leading `/`, URL safe characters, and no trailing slash', () => { validateBasePaths([{name: 'foo', basePath: '/valid'}]) validateBasePaths([{name: 'foo', basePath: '/also/valid'}]) validateBasePaths([{name: 'foo', basePath: '/still-valid'}]) }) it('throws if workspace base paths have differing segment counts', () => { expect(() => { validateBasePaths([ {name: 'twoSegments', basePath: '/one/two'}, {name: 'threeSegments', basePath: '/one/two/three'}, ]) }).toThrowErrorMatchingInlineSnapshot( `"All workspace \`basePath\`s must have the same amount of segments. Workspace \`twoSegments\` had 2 segments \`/one/two\` but workspace \`threeSegments\` had 3 segments \`/one/two/three\`"`, ) expect(() => { validateBasePaths([ {name: 'noSegments', basePath: '/'}, {name: 'oneSegment', basePath: '/one'}, ]) }).toThrowErrorMatchingInlineSnapshot( `"All workspace \`basePath\`s must have the same amount of segments. Workspace \`noSegments\` had 0 segments \`/\` but workspace \`oneSegment\` had 1 segment \`/one\`"`, ) }) it('throws if workspaces have identical base paths', () => { expect(() => { validateBasePaths([ {name: 'foo', basePath: '/one/two'}, {name: 'bar', basePath: '/foo/bar'}, {name: 'fooAgain', basePath: '/OnE/TwO'}, ]) }).toThrowErrorMatchingInlineSnapshot( `"\`basePath\`s must be unique. Workspaces \`foo\` and \`fooAgain\` both have the \`basePath\` \`/one/two\`"`, ) }) }) describe('validateNames', () => { it('allows missing name on single workspace', () => { validateNames([{basePath: '/'}]) validateNames([{name: undefined, basePath: '/'}]) }) it('throws if more than one workspace is defined, but one or more workspace does not have a name', () => { expect(() => { validateNames([{basePath: '/first'}, {name: 'second', basePath: '/2nd'}]) }).toThrowErrorMatchingInlineSnapshot( `"All workspaces must have a \`name\`, unless only a single workspace is defined. Workspace at index 0 did not define a \`name\`."`, ) expect(() => { validateNames([ {basePath: '/first', title: 'First'}, {name: 'second', basePath: '/2nd'}, ]) }).toThrowErrorMatchingInlineSnapshot( `"All workspaces must have a \`name\`, unless only a single workspace is defined. Workspace at index 0 (titled \\"First\\") did not define a \`name\`."`, ) expect(() => { validateNames([{name: 'first', basePath: '/1st'}, {basePath: '/second'}]) }).toThrowErrorMatchingInlineSnapshot( `"All workspaces must have a \`name\`, unless only a single workspace is defined. Workspace at index 1 did not define a \`name\`."`, ) expect(() => { validateNames([ {name: 'first', basePath: '/1st'}, {basePath: '/second', title: 'Second'}, ]) }).toThrowErrorMatchingInlineSnapshot( `"All workspaces must have a \`name\`, unless only a single workspace is defined. Workspace at index 1 (titled \\"Second\\") did not define a \`name\`."`, ) expect(() => { validateNames([ {name: 'first', basePath: '/1st'}, {name: '', basePath: '/2nd'}, ]) }).toThrowErrorMatchingInlineSnapshot( `"All workspaces must have a \`name\`, unless only a single workspace is defined. Workspace at index 1 did not define a \`name\`."`, ) }) it('throws if a workspace name has invalid characters', () => { expect(() => { validateNames([{name: '/nope', basePath: '/niet'}]) }).toThrowErrorMatchingInlineSnapshot( `"All workspace \`name\`s must consist of only a-z, 0-9, underscore and dashes, and cannot begin with an underscore or dash. Workspace at index 0 has the invalid name \`/nope\`"`, ) expect(() => { validateNames([{name: '/nope', basePath: '/niet', title: 'Nei'}]) }).toThrowErrorMatchingInlineSnapshot( `"All workspace \`name\`s must consist of only a-z, 0-9, underscore and dashes, and cannot begin with an underscore or dash. Workspace at index 0 (titled \\"Nei\\") has the invalid name \`/nope\`"`, ) }) it('throws if a workspace name leads with a dash/underscore', () => { expect(() => { validateNames([{name: '-no-leading-dash', basePath: '/okay'}]) }).toThrowErrorMatchingInlineSnapshot( `"All workspace \`name\`s must consist of only a-z, 0-9, underscore and dashes, and cannot begin with an underscore or dash. Workspace at index 0 has the invalid name \`-no-leading-dash\`"`, ) expect(() => { validateNames([{name: '_no_leading_underscore', basePath: '/okay'}]) }).toThrowErrorMatchingInlineSnapshot( `"All workspace \`name\`s must consist of only a-z, 0-9, underscore and dashes, and cannot begin with an underscore or dash. Workspace at index 0 has the invalid name \`_no_leading_underscore\`"`, ) expect(() => { validateNames([ {name: '_no_leading_underscore', basePath: '/okay', title: 'The Leading Underscore'}, ]) }).toThrowErrorMatchingInlineSnapshot( `"All workspace \`name\`s must consist of only a-z, 0-9, underscore and dashes, and cannot begin with an underscore or dash. Workspace at index 0 (titled \\"The Leading Underscore\\") has the invalid name \`_no_leading_underscore\`"`, ) }) it('allows base paths with a leading [a-z0-9], underscores and dashes', () => { validateNames([{name: 'valid', basePath: '/one'}]) validateNames([{name: 'also-valid', basePath: '/two'}]) validateNames([{name: 'even_this_is_valid', basePath: '/three'}]) validateNames([{name: '2009-was-okay', basePath: '/four'}]) validateNames([{name: 'however_2020_was_not', basePath: '/five'}]) validateNames([{name: 'even_m1x3d-but_dont-do_it', basePath: '/six'}]) }) it('throws if workspaces have identical names paths', () => { expect(() => { validateNames([ {name: 'Foo', basePath: '/1st'}, {name: 'bar', basePath: '/2nd'}, {name: 'foO', basePath: '/3rd'}, ]) }).toThrowErrorMatchingInlineSnapshot( `"\`name\`s must be unique. Workspace at index 0 and workspace at index 2 both have the \`name\` \`foO\`"`, ) expect(() => { validateNames([ {name: 'bAr', basePath: '/1st', title: 'First'}, {name: 'bar', basePath: '/2nd', title: 'Second'}, {name: 'foO', basePath: '/3rd', title: 'Third'}, ]) }).toThrowErrorMatchingInlineSnapshot( `"\`name\`s must be unique. Workspace at index 0 (titled \\"First\\") and workspace at index 1 (titled \\"Second\\") both have the \`name\` \`bar\`"`, ) }) })
abf297160a646cdb818dba198a932e3fd36ff5e4
TypeScript
Oneirocom/Magick
/packages/plugins/avatar/client/src/hooks/useOMIPersonality.ts
2.53125
3
import { useEffect, useState } from 'react' export const useOMIPersonality = (oldVRM) => { const [newVRM, setNewVRM] = useState([]) useEffect(() => { if(oldVRM) { oldVRM.scene.userData = { "$schema": "http://json-schema.org/draft-07/schema#", "title": "OMI_personality", "description": "An extension for the glTF format that defines a personality for a node and an endpoint where additional information can be queried.", "type": "object", "properties": { "agent": { "type": "string", "description": oldVRM.scene.uuid, "maxLength": 128 }, "personality": { "type": "string", "description": "#agent has a cheerful personality." }, "defaultMessage": { "type": "string", "description": "nya nya!" } }, "required": ["agent", "personality"] } setNewVRM(oldVRM); } }, [oldVRM]) return newVRM }
37ee4c562fc87acb314d000112cb311163d13824
TypeScript
danielfb88/challenge-accepted
/backend/src/models/Weather.ts
2.5625
3
import { Column, Entity, PrimaryGeneratedColumn } from "typeorm"; @Entity({ name: "weathers" }) export class Weather { @PrimaryGeneratedColumn("uuid") id!: string; @Column({ name: "locale_id" }) localeId!: string; @Column() date!: Date; @Column() text!: string; @Column({ name: "temperature_min" }) temperatureMin!: number; @Column({ name: "temperature_max" }) temperatureMax!: number; @Column({ name: "rain_probability" }) rainProbability!: number; @Column({ name: "rain_precipitation" }) rainPrecipitation!: number; }
17f5cf077d186347b69e1412a51a3616ac7900dd
TypeScript
diegomgerminiani/blog-api
/src/controllers/InfoController.ts
2.578125
3
import db from "../database/connection"; import http from 'http-status'; import { Request, Response} from 'express'; export default class InfoController{ async index(request: Request, response: Response) { try { const infos = await db('informations').select(); return response.status(http.OK).send(infos); } catch (error) { console.log(`error: ${error}`); return response.status(http.BAD_REQUEST).send({error: 'Unexpected error while finding informations'}) } } async create(request: Request, response: Response) { const { name, street, complement, number, neighborhood, cep, city_uf, phone, email, embedlink } = request.body; try { const insertedInfos = await db('informations').insert({ name, street, complement, number, neighborhood, cep, city_uf, phone, email, embedlink }); const info_id = insertedInfos[0]; return response.status(http.CREATED).send({id: info_id}) } catch (error) { console.log(`error: ${error}`); return response.status(http.BAD_REQUEST).send({error: 'Unexpected error while creating new informations'}) } } async newAccess(request: Request, response: Response) { try { await db('metrics').insert({}); return response.status(http.CREATED).send({}) } catch (error) { console.log(`error: ${error}`); return response.status(http.BAD_REQUEST).send({error: 'Unexpected error while creating new informations'}) } } async alter(request: Request, response: Response) { const { name, street, complement, number, neighborhood, cep, city_uf, phone, email, embedlink } = request.body; const id = request.params.id; try { const info = await db('informations').where('id', '=', id).update({ name, street, complement, number, neighborhood, cep, city_uf, phone, email, embedlink }); return response.status(http.OK).send() } catch (error) { console.log(`error: ${error}`); return response.status(http.BAD_REQUEST).send({error: 'Unexpected error while updating informations'}) } } async delete(request: Request, response: Response) { const id = request.params.id; try { const posts = await db('informations').where('id', '=', id).delete(); return response.status(http.OK).send() } catch (error) { console.log(`error: ${error}`); return response.status(http.BAD_REQUEST).send({error: 'Unexpected error while deleting informations'}) } } }
83359b055167670ce41351ea0ced4b76f52cd315
TypeScript
tbone1020/Auto-Complete
/src/app/models/letter.spec.ts
3.15625
3
import { Letter } from './letter'; describe('Letter Data Structure', () => { let letter: Letter; beforeEach(() => { letter = new Letter("a"); }); it ('Assigns Letter Correctly', () => { expect(letter.letter === 'a').toBe(true); }); it ('Has isEndOfWOrd', () => { expect(letter.isEndOfWord).toBe(false); }); it ('Checks if nextLetters Is An Array', () => { expect(Array.isArray(letter.nextLetters)).toBe(true) }); });
15d72cd2cd4e032b9262d0ed411a60f95dd1f0e2
TypeScript
PJMPR/BIU_library_2
/src/view-models/TableOfContents.ts
2.78125
3
export class TableOfContents { public name: string; public listOfSubContents: TableOfContents[]; constructor(name: string, listOfSubContents: TableOfContents[]) { this.name = name; this.listOfSubContents = listOfSubContents; } }
124e3fe32788b84ffddb904600f5f54811ce6d78
TypeScript
palldalma/Bootcamp_curriculum
/I.FOUNDATION/OOP/post-it.ts
3
3
export {}; class PostIt { backgroundColor: string; text: string; textColor: string; constructor(text: string, background: string, textcolor: string) { this.text = text; this.backgroundColor = background; this.textColor = textcolor; } write(): void { console.log( 'textColor: ' + this.textColor + ' ' + 'backgroundColor: ' + this.backgroundColor + ' ' + 'text: ' + this.text ); } } let postIt1 = new PostIt('Idea1', 'orange', 'blue'); postIt1.write();
943502f206a7db5161c05476c05a4805315abc09
TypeScript
bigdig/uCMS
/client/src/services/OperatorService/OperatorService.service.ts
2.609375
3
import environment from "@/environment"; import qs from "querystring"; import { OperatorResponse } from "@/models/Operators.model"; import { AxiosService } from "../AxiosService/AxiosService.service"; export default class OperatorService { public static async create({ email }: { email: string }): Promise<OperatorResponse> { const url = `${environment.apiUrl}operator/register`; const resParam = qs.stringify({ login: email, }); const { status, data } = await AxiosService.post(url, resParam); if (!status) throw Error("Cannot get data from api"); return data; } public static changeCodeToMessage(code: string) { let msg = ""; if (code === "operator.register.wrong.email") { msg = "Wrong e-mail!"; } return msg; } public static async changePassword(token: string | null, password: string, remindPassword: string) { const url = `${environment.apiUrl}operator/reset-password`; const resParam = qs.stringify({ token, password, remindPassword, }); const { status, data } = await AxiosService.patch(url, resParam); if (!status) throw Error("Cannot get data from api"); return data; } }
aee217d5ff8ce8568e1c5dc93cc227c85aadd69e
TypeScript
alejandrozeb/Angular2021
/presupuesto-app/src/app/egreso.model.ts
2.75
3
export class Egreso{ nombre:string; cantidad:number; constructor(nombre:string, cantidad:number){ this.nombre = nombre; this.cantidad = cantidad; } }
199250373c63bba587df8953a91335f50ad7eb28
TypeScript
16Yongjin/ctrl-cv-resume-write-automation
/wanted/education.ts
2.65625
3
import { Page } from "puppeteer"; import { IResumeData } from "../IResume"; import { clickText, clickHasText, clickXPath, click$x } from "../utils"; const fillEducation = (page: Page) => async ({ educations }: IResumeData) => { for (let index = 0; index < educations.length; index++) { const education = educations[index]; const parentPath = `.educations .list-group-item:nth-of-type(1)`; const parentXPath = `//div[contains(@class, "educations")]//li[contains(@class, "list-group-item")][1]`; console.log("학력 추가", index + 1); await page.waitForXPath( '//*[contains(@class, "educations")]//button[text()="+ 추가"][not(@disabled)]' ); await clickText(page)(".educations", "button")("+ 추가"); await page.waitFor( `.educations .list-group-item:nth-of-type(${index + 1})` ); console.log("재학 기간 입력"); const startYear = education.schoolEntrance.substring(0, 4); const startMonth = education.schoolEntrance.substring(4, 6); await page.type(`${parentPath} .start-time .year`, startYear); await page.type(`${parentPath} .start-time .month`, startMonth); const endYear = education.schoolGraduation.substring(0, 4); const endMonth = education.schoolGraduation.substring(4, 6); await page.type(`${parentPath} .end-time .year`, endYear); await page.type(`${parentPath} .end-time .month`, endMonth); if (education.educationState === "재학중") { await page.click(`${parentPath} input[label="현재 재학중"]`); } console.log("학교명 입력"); await page.type(`${parentPath} .school_name`, education.schoolName); console.log("전공 입력"); await page.type( `${parentPath} .major`, [education.majorName, education.minorName].filter(i => i).join(", ") ); } }; export default fillEducation;
4440567a9c50f6546765abd90b3a1ddad1d5423e
TypeScript
denkstrap/denkstrap-core
/src/utils/helper/data.test.ts
2.828125
3
import { data } from './data'; const testObject = { bestanden: true }; const testAttributes = { t1: 't1', json: JSON.stringify( testObject ) }; const testAttributesWithPrefix = { 'prefix-t1': 't1', 'prefix-json': JSON.stringify( testObject ) }; const testResultObject = { t1: testAttributes.t1, json: testObject }; const testResultObjectWithPrefix = { 'prefix-t1': testAttributesWithPrefix[ 'prefix-t1' ], 'prefix-json': testObject }; const testResultObjectComplete = { ...testResultObject, ...testResultObjectWithPrefix }; const testNode = `<div id="TestNode" data-t1="${testAttributes.t1}" data-json='${testAttributes.json}' data-prefix-t1="${testAttributes.t1}" data-prefix-json='${testAttributes.json}' ></div>`; document.body.innerHTML = testNode; const TestNode = document.querySelector( '#TestNode' ); describe( 'data', () => { test( 'to get a single data attribute from a node', () => { let result = data( TestNode, testAttributes.t1 ); expect( result[ testAttributes.t1 ] ).toBe( testAttributes.t1 ); } ); test( 'to get all data attributes from a node', () => { let result = data( TestNode, '*' ); expect( result ).toMatchObject( testResultObjectComplete ); } ); test( 'to get all data attributes from a node if no name is specified', () => { let result = data( TestNode ); expect( result ).toMatchObject( testResultObjectComplete ); } ); test( 'to get all to a regex matching data attributes from a node', () => { let result = data( TestNode, '*js*' ); expect( result ).toMatchObject( { json: testObject, 'prefix-json': testObject } ); } ); test( 'to get all prefixed data attributes from a node', () => { let result = data( TestNode, '*', 'prefix' ); expect( result ).toMatchObject( testResultObject ); } ); test( 'to get all prefixed to a regex matching data attributes from a node', () => { let result = data( TestNode, '*js*', 'prefix' ); expect( result ).toMatchObject( { json: testObject } ); } ); test( 'to get a single prefixed data attribute from a node', () => { let result = data( TestNode, testAttributes.t1, 'prefix' ); expect( result[ testAttributes.t1 ] ).toBe( testAttributes.t1 ); } ); test( 'to provide all scraped data attributes as a single object', () => { let result = data( TestNode, testAttributes.t1, 'prefix' ); expect( result[ testAttributes.t1 ] ).toBe( testAttributes.t1 ); } ); test( 'to remove the prefix from the object property names', () => { let result = data( TestNode, '*', 'prefix' ); expect( result ).toMatchObject( testResultObject ); } ); test( 'to parse JSON values', () => { let result = data( TestNode, 'json', 'prefix' ); expect( result ).toMatchObject( { json: testObject } ); } ); test( 'to return an empty object when element not exists', () => { jest.spyOn( console, 'error' ).mockImplementation( jest.fn() ); let result = data( null, '*' ); expect( result ).toMatchObject( {} ); } ); test( 'to log an error when element not exists', () => { const spy = jest.spyOn( console, 'error' ).mockImplementation( jest.fn() ); data( null, '*' ); expect( spy ).toHaveBeenCalled(); } ); test( 'to return an empty object when attribute not exists', () => { let result = data( TestNode, 'does-not-exist' ); expect( result ).toMatchObject( {} ); } ); } );
e6f72b0838e17b2f5731506f0004d909e954b4fa
TypeScript
tiborbotos/ts-collection
/src/utils.ts
3.515625
4
type stringOrNumber = string | number; export interface Map<V> { [key: string]: V; } export function isArray(arr: any): boolean { return arr && typeof arr === 'object' && typeof arr.length === 'number'; } export function isUndefined(value: any): boolean { return value === undefined; } export function isDefined(value: any): boolean { return !isUndefined(value); } export function isFunction(value: any): boolean { return typeof value === 'function'; } export function isString(value: any): boolean { return typeof value === 'string'; } /** * Returns the value of an object path * @param item {Object} Object with optional objects in it * @param fields {Array<String>} path of the required fields * @param value * @returns {*} Value of the field path (could be undefined) */ export function getNestedFieldValue(item: any, fields: Array<string>, value?: any): any { if (item !== undefined && item !== null) { if (fields.length > 1) { let innerObject: Array<any> | never = item[fields[0]]; if (isArray(innerObject)) { let ind = 0; do { let result = getNestedFieldValue(innerObject[ind], fields.slice(1), value); if (result) { return result; } ind++; } while (ind < innerObject.length); return undefined; } else { return getNestedFieldValue(innerObject, fields.slice(1), value); } } else { return (item[fields[0]]) === value ? item : undefined; } } else { return undefined; } } export function isMapFalsyOrMapsValueFalsy<T>(model: Map<T>, field: string) { return !model || !model[field]; } export function sortCompareFn(left: Map<any>, right: Map<any>, sortByField: string, defaultField?: string): number { if (isMapFalsyOrMapsValueFalsy(left, sortByField) && isMapFalsyOrMapsValueFalsy(right, sortByField)) { return 0; } else if (isMapFalsyOrMapsValueFalsy(right, sortByField)) { return left[sortByField] ? 1 : 0; } else if (isMapFalsyOrMapsValueFalsy(left, sortByField)) { return right[sortByField] ? -1 : 0; } else if (left[sortByField] === right[sortByField]) { if (defaultField) { return sortCompareFn(left, right, defaultField); } else { return 0; } } return (left[sortByField] > right[sortByField]) ? 1 : -1; } // // obj[key] has an issue? // // export function getFieldValueByObjectPath(obj: any, // fields: Array<string>) { // if (obj[fields[0]] && fields[1]) { // const key = fields.splice(0, 1); // return getFieldValueByObjectPath(obj[key], fields); // } else if (isUndefined(fields[1])) { // return obj[fields[0]]; // } else { // return undefined; // } // }
a8ca1a18678081fc1b23fd2b1c83903f1e7c3145
TypeScript
shantu/mui-treasury-next
/packages/layout/src/utils/combineBreakpoints.ts
2.515625
3
import { Breakpoint } from "@material-ui/core/styles/createBreakpoints"; import { BREAKPOINT_KEYS } from "./muiBreakpoints"; import { Responsive } from "./types"; export const sortBreakpoints = (breakpoints: Breakpoint[]): Breakpoint[] => breakpoints.sort( (a, b) => BREAKPOINT_KEYS.indexOf(a) - BREAKPOINT_KEYS.indexOf(b) ); export const combineBreakpoints = ( ...args: (Responsive<any> | Breakpoint[])[] ): Breakpoint[] => { let result: Breakpoint[] = []; args.forEach((item) => { const breakpoints = Array.isArray(item) ? item : (Object.keys(item) as Breakpoint[]); breakpoints.forEach((k) => { if (!result.includes(k)) { result.push(k); } }); }); return sortBreakpoints(result); };
b86ae369719e262cd63be197d6c5612b68b6b8c6
TypeScript
vercel/vercel
/packages/build-utils/test/unit.glob.test.ts
2.71875
3
import fs from 'fs-extra'; import { join } from 'path'; import { tmpdir } from 'os'; import { glob, isDirectory, isSymbolicLink } from '../src'; describe('glob()', () => { it('should not return entries for empty directories by default', async () => { const dir = await fs.mkdtemp(join(tmpdir(), 'build-utils-test')); try { await Promise.all([ fs.writeFile(join(dir, 'root.txt'), 'file at the root'), fs.mkdirp(join(dir, 'empty-dir')), fs .mkdirp(join(dir, 'dir-with-file')) .then(() => fs.writeFile(join(dir, 'dir-with-file/data.json'), '{"a":"b"}') ), fs.mkdirp(join(dir, 'another/subdir')), ]); const files = await glob('**', dir); const fileNames = Object.keys(files).sort(); expect(fileNames).toHaveLength(2); expect(fileNames).toEqual(['dir-with-file/data.json', 'root.txt']); expect(isDirectory(files['dir-with-file/data.json'].mode)).toEqual(false); expect(isDirectory(files['root.txt'].mode)).toEqual(false); expect(files['dir-with-file']).toBeUndefined(); expect(files['another/subdir']).toBeUndefined(); expect(files['empty-dir']).toBeUndefined(); } finally { await fs.remove(dir); } }); it('should return entries for empty directories with `includeDirectories: true`', async () => { const dir = await fs.mkdtemp(join(tmpdir(), 'build-utils-test')); try { await Promise.all([ fs.writeFile(join(dir, 'root.txt'), 'file at the root'), fs.mkdirp(join(dir, 'empty-dir')), fs .mkdirp(join(dir, 'dir-with-file')) .then(() => fs.writeFile(join(dir, 'dir-with-file/data.json'), '{"a":"b"}') ), fs.mkdirp(join(dir, 'another/subdir')), ]); const files = await glob('**', { cwd: dir, includeDirectories: true }); const fileNames = Object.keys(files).sort(); expect(fileNames).toHaveLength(4); expect(fileNames).toEqual([ 'another/subdir', 'dir-with-file/data.json', 'empty-dir', 'root.txt', ]); expect(isDirectory(files['another/subdir'].mode)).toEqual(true); expect(isDirectory(files['empty-dir'].mode)).toEqual(true); expect(isDirectory(files['dir-with-file/data.json'].mode)).toEqual(false); expect(isDirectory(files['root.txt'].mode)).toEqual(false); expect(files['dir-with-file']).toBeUndefined(); } finally { await fs.remove(dir); } }); it('should allow for following symlinks', async () => { const rootDir = await fs.mkdtemp(join(tmpdir(), 'build-utils-test')); const dir = await fs.mkdtemp(join(rootDir, 'build-utils-test')); try { await Promise.all([ fs.writeFile(join(rootDir, 'root.txt'), 'file outside of "dir"'), fs.writeFile(join(dir, 'root.txt'), 'file at the root'), fs.mkdirp(join(dir, 'empty-dir')), fs .mkdirp(join(dir, 'dir-with-file')) .then(() => fs.writeFile(join(dir, 'dir-with-file/data.json'), '{"a":"b"}') ), fs.mkdirp(join(dir, 'another/subdir')), fs.symlink('root.txt', join(dir, 'root-link')), fs.symlink(join(dir, 'root.txt'), join(dir, 'abs-root-link')), fs.symlink('dir-with-file', join(dir, 'dir-link')), fs.symlink('empty-dir', join(dir, 'empty-dir-link')), fs.symlink('../root.txt', join(dir, 'outside-cwd-link')), fs.symlink(join(dir, '../root.txt'), join(dir, 'abs-outside-cwd-link')), ]); const files = await glob('**', { cwd: dir, follow: true }); const fileNames = Object.keys(files).sort(); expect(fileNames).toHaveLength(5); expect(fileNames).toEqual([ 'abs-root-link', 'dir-link/data.json', 'dir-with-file/data.json', 'root-link', 'root.txt', ]); for (const file of Object.values(files)) { expect(isSymbolicLink(file.mode)).toEqual(false); } } finally { await fs.remove(dir); } }); });
82ccae065657fd80810ad251da7275c7152fd8cf
TypeScript
alex-vladut/online-shop-typescript
/src/guards/authorization.guard.ts
2.65625
3
import { CanActivate, ExecutionContext, Injectable } from '@nestjs/common'; import { Reflector } from '@nestjs/core'; import { Role } from '../auth/role'; import { RequestWithUserInfo } from './request-with-user-info.interface'; @Injectable() export class AuthorizationGuard implements CanActivate { constructor(private readonly reflector: Reflector) {} canActivate(context: ExecutionContext): boolean { if (this.isPublic(context)) { return true; } const { user } = context.switchToHttp().getRequest<RequestWithUserInfo>(); const authorizedRoles = this.getAuthorizedRoles(context); return ( authorizedRoles && authorizedRoles.length && user.roles && user.roles.length && authorizedRoles.some((role) => user.roles.includes(role)) ); } private isPublic(context: ExecutionContext) { return this.reflector.get<boolean>('isPublic', context.getHandler()); } /** * Extract authorized roles either from the method or the class decorated with Authorize */ private getAuthorizedRoles(context: ExecutionContext) { return ( this.reflector.get<Role[]>('roles', context.getHandler()) || this.reflector.get<Role[]>('roles', context.getClass()) ); } }
c38530ef3bb79a12045bfa89e015b142af13bc42
TypeScript
ksaldana1/ts-compiler-fun
/src/http/generation/createClass.ts
2.703125
3
import * as ts from 'typescript'; export function createClassDeclaration( name: string, uri: string, heritage: ts.HeritageClause, methods: ts.PropertyDeclaration[] ): ts.ClassDeclaration { return ts.createClassDeclaration( [], [ts.createToken(ts.SyntaxKind.ExportKeyword)], name, [], [heritage], [apiProperty(uri), ...methods] ); } function apiProperty(uri: string): ts.ConstructorDeclaration { return ts.createConstructor( [], [], [ ts.createParameter( [], [ ts.createToken(ts.SyntaxKind.PrivateKeyword), ts.createToken(ts.SyntaxKind.ReadonlyKeyword), ], undefined, 'API', undefined, ts.createKeywordTypeNode(ts.SyntaxKind.StringKeyword), undefined ), ], ts.createBlock([]) ); }
eacb642eb474492ea9788b51cece8f70ff7b253b
TypeScript
piotrek-k/TaskManager
/frontend-app/src/app/DTOs/ColumnDTO.ts
2.71875
3
import { BaseDTO } from './BaseDTO'; export class ColumnDTO extends BaseDTO { id: number; name?: string | undefined; orderIndex: number; longTermGoalId: number; init(data?: any) { data = this.prepareDataIndexes(data); if (data) { this.id = data["Id".toLowerCase()]; this.name = data["Name".toLowerCase()]; this.orderIndex = data["OrderIndex".toLowerCase()]; this.longTermGoalId = data["LongTermGoalId".toLowerCase()]; } } static fromJS(data: any): ColumnDTO { data = typeof data === 'object' ? data : {}; let result = new ColumnDTO(); result.init(data); return result; } toJSON(data?: any) { data = typeof data === 'object' ? data : {}; data["Id"] = this.id; data["Name"] = this.name; data["OrderIndex"] = this.orderIndex; data["LongTermGoalId"] = this.longTermGoalId; return data; } }
139cae51462989fad96abcca6554cfb39ec13c9a
TypeScript
kiminozo/bangumi-explorer
/src/service/bgmdb.ts
2.53125
3
import Path from "path"; import low from 'lowdb'; import FileAsync from 'lowdb/adapters/FileAsync' import { WatchInfo, UserWatchInfo } from '../common/watch'; import { watchFile } from "../common/defines"; export interface WatchDB { users: UserWatchInfo[]; } export default class BangumiDB { db: low.LowdbAsync<WatchDB> | null = null; constructor() { } async prepare() { const adapter = new FileAsync<WatchDB>(watchFile) this.db = await low(adapter); this.db.defaults({ users: [] }).write(); } private update(infos: WatchInfo[]) { } async save(userWatchInfo: UserWatchInfo) { // await fs.promises.writeFile(Path.join("output", "down-watch-data.json"), JSON.stringify(userWatchInfo, null, 1)); if (this.db === null) { console.log("db === null"); return null; } let query = { id: userWatchInfo.id } // const userCount = this.db.get('users').size().value(); const index = this.db.get('users').findIndex(query).value(); console.log("user-index:" + index); if (index < 0) { console.log("new-user:" + userWatchInfo.id); await this.db.get('users').push(userWatchInfo).write(); } else { console.log("update-user:" + userWatchInfo.id); //await this.db.get('users').find(query).assign(userWatchInfo).write(); const watchDB = this.db.get('users').find(query).get('watches'); for (const watch of userWatchInfo.watches) { const item = watchDB.find({ id: watch.id }); if (item.value()) { console.log("assign:" + watch.title); await item.assign(watch).write(); } else { console.log("push:" + watch.title); await watchDB.push(watch).write(); } } await watchDB.write() } // this.db.set('info', infoList).write(); } get(user: number, id: number): WatchInfo | null { if (this.db === null) { return null; } const item = this.db.get("users").find({ id: user }) .get('watches').find({ id }).value(); return item; } getAll(user: number): WatchInfo[] { if (this.db === null) { return []; } const items = this.db.get("users").find({ id: user }) .get('watches').value(); return items; } } // const info2 = db.get('info') // .filter(p => p.type === 'collect') // .get('dataList') // .value() // const db = new BangumiDB("kiminozo"); // console.log(db.get(183957)); //test(); // async function test() { // const db = new BangumiDB(); // await db.prepare(); // const info: UserWatchInfo = { id: 10747, name: "", watches: [] }; // info.watches.push({ // id: 262899, // title: "电影 摇曳露营△", // type: "wish" // }); // await db.save(info) // } // test();
b0ca5f0d70419d0a3e71895a915a65763cf84c84
TypeScript
senolkeskin/newSucu
/src/redux/reducers/productForCustomerReducers.ts
2.75
3
import { ProductForCustomer, Action } from "../states"; import { PRODUCT_FOR_CUSTOMER_GET, PRODUCT_FOR_CUSTOMER_LOADING } from "../types"; import {IProductForCustomerItem} from "../models/productForCustomerModel" const initialProduct:IProductForCustomerItem={ productId:0, productName:"", unitPrice:0, productCode:"", } const intialState = { product:initialProduct, isLoading: false }; export default (state: ProductForCustomer = intialState, action: Action) => { switch (action.type) { case PRODUCT_FOR_CUSTOMER_GET: return { ...state, product: action.payload, isLoading:false }; case PRODUCT_FOR_CUSTOMER_LOADING: return { ...state, isLoading: action.payload }; default: return state; } };
1b785b984a5b4c50ea14bd7453e3b2af2e5e87ff
TypeScript
fuath/vectorious
/src/Matrix.spec.ts
2.953125
3
import { deepStrictEqual, throws, } from 'assert'; import { Matrix } from './'; describe('Matrix', () => { describe('Matrix.binOp(a, b, (a, b) => a + b)', () => { it('should work as the static equivalent of a.binOp(b, (a, b) => a + b)', () => { const x: Matrix = new Matrix([[1, 1, 1]]); const y: Matrix = new Matrix([[1, 2, 3]]); const f: (a: number, b: number) => number = (a: number, b: number): number => a + b; deepStrictEqual(x.copy().binOp(y, f), Matrix.binOp(x, y, f)); }); }); describe('Matrix.add(a, b)', () => { it('should work as the static equivalent of a.add(b)', () => { const x: Matrix = new Matrix([[1, 1, 1]]); const y: Matrix = new Matrix([[1, 2, 3]]); deepStrictEqual(x.copy().add(y), Matrix.add(x, y)); }); }); describe('Matrix.subtract(a, b)', () => { it('should work as the static equivalent of a.subtract(b)', () => { const x: Matrix = new Matrix([[1, 1, 1]]); const y: Matrix = new Matrix([[1, 2, 3]]); deepStrictEqual(x.copy().subtract(y), Matrix.subtract(x, y)); }); }); describe('Matrix.scale(a, scalar)', () => { it('should work as the static equivalent of a.scale(scalar)', () => { const x: Matrix = new Matrix([[1, 1, 1]]); deepStrictEqual(x.copy().scale(5), Matrix.scale(x, 5)); }); }); describe('Matrix.product(a, b)', () => { it('should work as the static equivalent of a.product(b)', () => { const x: Matrix = new Matrix([[3, 2, 1]]); const y: Matrix = new Matrix([[1, 2, 3]]); deepStrictEqual(x.copy().product(y), Matrix.product(x, y)); }); }); describe('Matrix.multiply(a, b)', () => { it('should work as the static equivalent of a.multiply(b)', () => { const x: Matrix = new Matrix([[1], [2], [3]]); const y: Matrix = new Matrix([[1, 1, 1]]); deepStrictEqual(x.copy().multiply(y), Matrix.multiply(x, y)); }); }); describe('Matrix.plu(a)', () => { it('should work as the static equivalent of a.plu()', () => { const x: Matrix = new Matrix([[1, 3, 5], [2, 4, 7], [1, 1, 0]]); deepStrictEqual(x.copy().plu(), Matrix.plu(x)); }); }); describe('Matrix.augment(a, b)', () => { it('should work as the static equivalent of a.augment(b)', () => { const x: Matrix = new Matrix([[1, 1, 1]]); const y: Matrix = new Matrix([[1, 2, 3]]); deepStrictEqual(x.copy().augment(y), Matrix.augment(x, y)); }); }); describe('Matrix.equals(a, b)', () => { it('should work as the static equivalent of a.equals(b)', () => { const x: Matrix = new Matrix([[1, 1, 1]]); const y: Matrix = new Matrix([[1, 1, 1]]); deepStrictEqual(x.copy().equals(y), Matrix.equals(x, y)); }); }); describe('Matrix.identity()', () => { it('should throw error if invalid size', () => { throws(() => { Matrix.identity(-1); }, Error); throws(() => { Matrix.identity(0); }, Error); }); it('should work as expected', () => { deepStrictEqual(new Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]]), Matrix.identity(3)); }); }); describe('Matrix.magic()', () => { it('should throw error if invalid size', () => { throws(() => { Matrix.magic(-1); }, Error); throws(() => { Matrix.identity(0); }, Error); }); it('should work as expected', () => { deepStrictEqual(new Matrix([[8, 1, 6], [3, 5, 7], [4, 9, 2]]), Matrix.magic(3)); }); }); describe('Matrix.zeros()', () => { it('should throw error if invalid size', () => { throws(() => { Matrix.zeros(0, 0); }, Error); throws(() => { Matrix.zeros(-1, 1); }, Error); throws(() => { Matrix.zeros(1, -1); }, Error); }); it('should work as expected', () => { deepStrictEqual(new Matrix([[0, 0, 0]]), Matrix.zeros(1, 3)); deepStrictEqual(new Matrix([[0], [0], [0]]), Matrix.zeros(3, 1)); deepStrictEqual(new Matrix([[0, 0], [0, 0]]), Matrix.zeros(2, 2)); }); }); describe('Matrix.ones()', () => { it('should throw error if invalid size', () => { throws(() => { Matrix.ones(0, 0); }, Error); throws(() => { Matrix.ones(-1, 1); }, Error); throws(() => { Matrix.ones(1, -1); }, Error); }); it('should work as expected', () => { deepStrictEqual(new Matrix([[1, 1, 1]]), Matrix.ones(1, 3)); deepStrictEqual(new Matrix([[1], [1], [1]]), Matrix.ones(3, 1)); deepStrictEqual(new Matrix([[1, 1], [1, 1]]), Matrix.ones(2, 2)); }); }); });
bcac8048625507a85c6e4ec90fa39a760e69ec25
TypeScript
newcat/baklavajs
/packages/baklavajs-playground/src/MathNode.ts
2.734375
3
import { NodeBuilder } from "../../baklavajs-core/src"; export default new NodeBuilder("MathNode") .addInputInterface("Number 1", "NumberOption", 1, { displayName: "Number" }) .addInputInterface("Number 2", "NumberOption", 10, { displayName: "Number" }) .addOption("Operation", "SelectOption", "Add", undefined, { items: [ "Add", "Subtract" ] }) .addOutputInterface("Output") .onCalculate((n, d) => { const n1 = n.getInterface("Number 1").value; const n2 = n.getInterface("Number 2").value; const operation = n.getOptionValue("Operation").selected; let result; if (operation === "Add") { result = n1 + n2; } else if (operation === "Subtract") { result = n1 - n2; } n.getInterface("Output").value = result; }) .build();
c7dbf6516346b3cf6fd4dff821d5b36f55d0122d
TypeScript
Warrenate/ProjectTiny
/Assets/TinySamples/GalaxyRaiders/Scripts/GameService.ts
2.859375
3
namespace game { export class GameService { /** * @desc invoked once when the game is launched */ static initialize(world: ut.World, context: game.GameContext) { this.reset(world, context); ut.EntityGroup.instantiate(world, 'game.GameMenu'); context.State = game.GameState.Menu; }; /** * @desc clears entities and resets the game */ static reset(world: ut.World, context: game.GameContext) { ut.EntityGroup.destroyAll(world, 'game.GameScene'); ut.EntityGroup.destroyAll(world, 'game.GameOver'); ut.EntityGroup.destroyAll(world, 'game.GameWin'); context.Life = 2; context.Score = 0; }; /** * @desc starts the game */ static start(world: ut.World, context: game.GameContext) { ut.EntityGroup.destroyAll(world, 'game.GameMenu'); ut.EntityGroup.instantiate(world, 'game.GameScene'); context.State = game.GameState.Play; context.TimeElapsedSinceStart = 0; }; /** * @desc Increase player's score */ static increaseScore(world: ut.World, context: game.GameContext, points : number) { context.Score += points; }; /** * @desc Decrease player's life */ static decreaseLife(world: ut.World, context: game.GameContext) { context.Life -= 1; // "Respawn" the spaceship world.forEach([ut.Entity, game.Spaceship, ut.Core2D.Sprite2DSequencePlayer],(entity, spaceship, sprite2DSequencePlayer)=>{ sprite2DSequencePlayer.paused = true; sprite2DSequencePlayer.paused = false; }); }; /** * @desc Stops the spaceship from shooting and moving */ static stopSpaceship(world: ut.World) { world.forEach([ut.Entity, game.Spaceship], (entity, spaceship) => { world.removeComponent(entity, game.Spaceship); }); }; /** * @desc Stops the hit process for the damage system */ static stopHits(world: ut.World){ world.forEach([ut.Entity, game.Hit], (entity, hit) => { world.removeComponent(entity, game.Hit); }); } /** * @desc Stops all the lasers */ static stopLasers(world: ut.World){ world.forEach([ut.Entity, game.Laser], (entity, laser) => { world.destroyEntity(laser.reference); }); } /** * @desc Stops the raiders from shooting and moving */ static stopRaiders(world: ut.World) { world.forEach([ut.Entity, game.Raiders], (entity, raiders) => { world.removeComponent(entity, game.Raiders); }); world.forEach([ut.Entity, game.Raider], (entity, raider) => { world.removeComponent(entity, game.Raider); }); }; /** * @desc Stops the movement of the ship */ static stopMovement(world: ut.World) { world.forEach([ut.Entity, game.Move], (entity, move) => { world.removeComponent(entity, game.Move); }); }; /** * @desc Ends the current game, player has lost */ static gameOver(world: ut.World, context: game.GameContext) { ut.EntityGroup.instantiate(world, 'game.GameOver'); // Play the spaceship destroy animation world.forEach([ut.Entity, game.Spaceship, ut.Core2D.Sprite2DSequencePlayer],(entity, spaceship, sprite2DSequencePlayer)=>{ sprite2DSequencePlayer.loop = ut.Core2D.LoopMode.ClampForever; sprite2DSequencePlayer.paused = false; }); this.stopGame(world); context.State = game.GameState.GameOver; }; /** * @desc Ends the current game, player has won */ static gameWin(world: ut.World, context: game.GameContext) { ut.EntityGroup.instantiate(world, 'game.GameWin'); this.stopGame(world); context.State = game.GameState.GameOver; }; /** * @desc Remove components related to an active playing session */ static stopGame(world: ut.World) { this.stopLasers(world); this.stopHits(world); this.stopSpaceship(world); this.stopRaiders(world); this.stopMovement(world); }; } }
80e369076bd785a688e1f8c5592c27936fb9c669
TypeScript
neerolyte/vscode-gitblame
/src/textdecorator.ts
2.703125
3
import {workspace} from 'vscode'; import * as moment from 'moment'; import * as ObjectPath from 'object-path'; import {IGitBlameInfo, IGitCommitInfo} from './gitinterfaces'; export class TextDecorator { static toTextView(commit: IGitCommitInfo): string { const config = workspace.getConfiguration('gitblame'); if (commit['hash'] === '0000000000000000000000000000000000000000') { return <string>config.get('statusBarMessageNoCommit'); } else { const normalizedCommitInfo = TextDecorator.normalizeCommitInfoTokens(commit); const messageFormat = <string>config.get('statusBarMessageFormat'); return TextDecorator.parseTokens(messageFormat, normalizedCommitInfo); } } static toDateText(dateNow: Date, dateThen: Date): string { const momentNow = moment(dateNow); const momentThen = moment(dateThen); const months = momentNow.diff(momentThen, 'months'); const days = momentNow.diff(momentThen, 'days'); const hours = momentNow.diff(momentThen, 'hours'); const minutes = momentNow.diff(momentThen, 'minutes'); if (minutes <= 4) { return 'right now'; } else if (minutes <= 70) { return minutes + ' ' + (minutes === 1 ? 'minute' : 'minutes') + ' ago'; } else if (hours <= 47) { return hours + ' ' + (hours === 1 ? 'hour' : 'hours') + ' ago'; } else if (days <= 40) { return days + ' ' + (days === 1 ? 'day' : 'days') + ' ago'; } else { return months + ' ' + (months === 1 ? 'month' : 'months') + ' ago'; } } static parseTokens(target: string, tokens: object = {}): string { const tokenRegex = /\$\{([a-z\.\-\_]{1,})[,]*(|.{1,}?)(?=\})}/gi; return target.replace(tokenRegex, (string: string, key: string, inValue: string): string => { const currentToken = ObjectPath.get(tokens, key) const value = inValue.length > 0 ? inValue : undefined; if (typeof currentToken === 'string') { return currentToken; } else if (typeof currentToken === 'number') { return currentToken.toString(); } else if (typeof currentToken === 'function') { let newString = currentToken.call(this, value, key); if (typeof newString === 'string') { return newString; } else if (typeof newString === 'number') { return newString.toString(); } } return key; }); } static normalizeCommitInfoTokens(commitInfo: IGitCommitInfo): Object { const now = new Date(); const authorTime = moment.unix(commitInfo.author.timestamp); const committerTime = moment.unix(commitInfo.committer.timestamp); return { 'commit': { 'hash': commitInfo.hash, 'hash_short': (length = 7) => commitInfo.hash.substr(0, length), 'summary': commitInfo.summary, 'filename': commitInfo.filename }, 'author': commitInfo.author, 'committer': commitInfo.committer, 'time': { 'ago': () => TextDecorator.toDateText(now, authorTime.toDate()), 'from': () => authorTime.fromNow(), 'custom': (momentFormat) => authorTime.format(momentFormat), 'c_ago': () => TextDecorator.toDateText(now, committerTime.toDate()), 'c_from': () => committerTime.fromNow(), 'c_custom': (momentFormat) => committerTime.format(momentFormat) } } } }
69126905518c8755deccd65362989845d9b5a183
TypeScript
VitorLuizC/vue-loadable
/types/callWithHooks.d.ts
2.984375
3
/** * Call function and execute its hooks. Executes `onDone` when its done and * `onError` when it throws an error. * @param call * @param onDone * @param onError */ declare const callWithHooks: <T>(call: () => T | Promise<T>, onDone: () => void, onError?: () => void) => Promise<T>; export default callWithHooks;
efb1c94a873be71f162dd5847ce68d93bdca3fde
TypeScript
isomerpages/isomercms-frontend
/src/utils/pages.ts
2.546875
3
import _ from "lodash" export const SPECIAL_PAGES = ["homepage", "navbar", "contact-us"] export const isEditPageUrl = (url: string): boolean => { // NOTE: Lowercase here because `/editpage` also works return url.toLowerCase().includes("/editpage/") && url.endsWith(".md") } export const isSpecialPagesUrl = (url: string): boolean => { return _.some(SPECIAL_PAGES, (page) => url.toLowerCase().includes(page)) }
d27f0a45d67b965c680de55d7a74df6cece27a0d
TypeScript
briwa/vue-flowter
/src/components/flowter-editor/index.ts
2.65625
3
// Libraries import { Component, Vue } from 'vue-property-decorator' // Components import FlowterFlowchart from '@/components/flowter-flowchart/index.vue' // Fixtures // It won't be used for production... import allGraph from '../../../__fixtures__/simple.json' // Types import { GraphNode, GraphEdge, EditingEdgeDetails, EventEditingEdge, Mode, EdgeType, Editing } from '@/shared/types' /** * The Flowter editor's Vue class component. */ @Component({ components: { FlowterFlowchart } }) export default class FlowterEditor extends Vue { /* * ------------------------------- * Public data * ------------------------------- */ /** * The nodes to be rendered in this editor. * Right now it is seeded from the fixtures. */ public nodes: Record<string, GraphNode> = allGraph.nodes /** * The edges to be rendered in this editor. * Right now it is seeded from the fixtures. */ public edges: GraphEdge[] = allGraph.edges /** * The flowchart mode for the editor. */ public mode: Mode = Mode.VERTICAL /** * The currently edited node id. */ public editingNodeId: string = this.defaultElems.nodeId /** * Whenever the mouse is over a node, the id is saved here. */ public mouseOverNodeId: string | null = null /** * The information needed when editing an edge. */ public editingEdge: EditingEdgeDetails = { draggingType: 'from', from: this.defaultElems.edgeFrom, to: this.defaultElems.edgeTo } /** * Whether it's editing an edge or a node. */ public editing: Editing = Editing.NONE /** * The type of the edge being rendered in the editor. */ public edgeType: EdgeType = EdgeType.BENT /** * The font size for nodes and edges in the editor. */ public fontSize: number = 12 /* * ------------------------------- * Public computed properties * ------------------------------- */ /** * The default values for the flowchart elements. * * This is basically the first node and the first edge. */ public get defaultElems (): Record<string, string> { return { nodeId: this.nodeIds[0], edgeFrom: this.edges[0].from, edgeTo: this.edges[0].to } } /** * The currently edited edge's node id from. */ public get editingEdgeFromId () { return this.isEditingEdge && this.editingEdge.draggingType === 'from' && this.mouseOverNodeId ? this.mouseOverNodeId : this.editingEdge.from } /** * The currently edited edge's node id to. */ public get editingEdgeToId () { return this.isEditingEdge && this.editingEdge.draggingType === 'to' && this.mouseOverNodeId ? this.mouseOverNodeId : this.editingEdge.to } /** * Disable the user select when editing. */ public get flowchartStyle () { return { userSelect: this.isNotEditing ? 'auto' : 'none' } } /** * Whether it's currently editing a node. */ public get isEditingNode () { return this.editing === Editing.NODE } /** * Whether it's currently editing an edge. */ public get isEditingEdge () { return this.editing === Editing.EDGE } /** * Whether it's currently not editing anything. */ public get isNotEditing () { return this.editing === Editing.NONE } /* * ------------------------------- * Private computed properties * ------------------------------- */ /** * All the node ids in the flowchart. */ private get nodeIds (): string[] { return Object.keys(this.nodes) } /* * ------------------------------- * Public methods * ------------------------------- */ /** * When an edge is edited, it is handled depending on the type. */ public onEditEdge (event: EventEditingEdge) { switch (event.type) { case 'drag-start': { if (this.editing === Editing.NONE) { const payload = event.payload as EventEditingEdge<'from-to'>['payload'] this.editingEdge.from = payload.from this.editingEdge.to = payload.to this.editingEdge.draggingType = payload.draggingType switch (payload.draggingType) { case 'from': { this.editingNodeId = payload.from break } case 'to': { this.editingNodeId = payload.to break } default: { throw new Error(`Unknown dragging type: ${payload.draggingType}`) break } } this.editing = Editing.EDGE // Attach global mouse events to detect dragging this.attachMouseEvents() } break } case 'drag-end': { this.detachMouseEvents() const newFromId = this.editingEdgeFromId const newToId = this.editingEdgeToId if (this.getEdge(newFromId, newToId)) { // @todo Use a proper notification system // tslint:disable-next-line console.warn('There is already an edge for that') this.editing = Editing.NONE break } const edge = this.getEdge(this.editingEdge.from, this.editingEdge.to) if (!edge) { throw new Error(`Unable to find edge from list of edges with ` + `from id: ${this.editingEdge.from} and ` + `to id: ${this.editingEdge.to}.`) } this.$set(edge, 'from', newFromId) this.$set(edge, 'to', newToId) this.editing = Editing.NONE break } default: { throw new Error(`Unknown type: ${event.type}`) } } } /** * Get the edge given the from and to id. */ private getEdge (from: string, to: string) { return this.edges.find((edge) => { return edge.from === from && edge.to === to }) } /** * Attaching mouseup events to the document. * * This is because the interactions when dragging is * beyond this component's scope, hence attaching to `document` instead. */ private attachMouseEvents () { document.addEventListener('mouseup', this.onMouseUp) } /** * Detaching mouseup events to the document. */ private detachMouseEvents () { document.removeEventListener('mouseup', this.onMouseUp) } /** * When it is no longer dragging, this should do * the callback depending on whether it is editing node or edge. */ private onMouseUp () { switch (this.editing) { case Editing.NODE: { break } case Editing.EDGE: { const event = { type: 'drag-end', payload: null } as EventEditingEdge this.onEditEdge(event) break } default: { throw new Error('Mouseup is executed while not editing anything.') } } } }
c70a8c205681000712c4a24699d0b5ad87ceda5c
TypeScript
Bojackxiang/map-project
/client/src/Components/CustomizedHooks/useCheckiSessionToken.ts
2.796875
3
import { useEffect, useState } from "react"; import { useHistory } from "react-router-dom"; interface ICheckAuthInput { successJumpTo?: string; failJumpTo?: string; } // check if the user is logged in or not const useCheckSessionToken = (checkAuthInput?: ICheckAuthInput) => { const [isAuth, setIsAuth] = useState<boolean | null>(null); const history = useHistory(); useEffect(() => { const isFindSessionToken = localStorage.getItem( process.env.REACT_APP_SESSION_NAME as string ); // preventing incorrectly redirecting if (!isFindSessionToken) { if (checkAuthInput && checkAuthInput.failJumpTo ) { history.push(checkAuthInput.failJumpTo); } else { setIsAuth(false); } } else { if (checkAuthInput && checkAuthInput.successJumpTo) { history.push(checkAuthInput.successJumpTo); } else { setIsAuth(true); } } }, [history, checkAuthInput]); return { isAuth, }; }; export default useCheckSessionToken;
cc37f54e019eb45366a4b3d49ee6b613620ecf82
TypeScript
fleshascs/WebRTC-DamageEvaluation
/frontend/helpers/fetchWrapper.ts
2.609375
3
import getConfig from 'next/config'; import { accountService } from '../services'; const { publicRuntimeConfig } = getConfig(); export const fetchWrapper = { get, post, put, delete: _delete, authHeader, handleResponse }; function get(url) { const requestOptions = { method: 'GET', headers: authHeader(url) }; return handleResponse(fetch(url, requestOptions)); } function post(url, body) { const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json', ...authHeader(url) }, credentials: 'include' as RequestCredentials, body: JSON.stringify(body) }; return handleResponse(fetch(url, requestOptions)); } function put(url, body) { const requestOptions = { method: 'PUT', headers: { 'Content-Type': 'application/json', ...authHeader(url) }, body: JSON.stringify(body) }; return handleResponse(fetch(url, requestOptions)); } // prefixed with underscored because delete is a reserved word in javascript function _delete(url) { const requestOptions = { method: 'DELETE', headers: authHeader(url) }; return handleResponse(fetch(url, requestOptions)); } // helper functions function authHeader(url) { // return auth header with jwt if user is logged in and request is to the api url const user = accountService.userValue; const isLoggedIn = user && user.jwtToken; const isApiUrl = url.startsWith(publicRuntimeConfig.apiUrl); if (isLoggedIn && isApiUrl) { return { Authorization: `Bearer ${user.jwtToken}` }; } else { return {}; } } function handleResponse(fetchPromise) { return fetchPromise.then((response) => response.text().then((text) => { const data = text && JSON.parse(text); if (!response.ok) { // if ([401, 403].includes(response.status)) { if ([401, 403].includes(response.status) && accountService.userValue) { // auto logout if 401 Unauthorized or 403 Forbidden response returned from api accountService.logout(); } const error = (data && data.message) || response.statusText; return Promise.reject(error); } return data; }) ); }
4599cfb31b74f20e776eea503241e746ef3a8902
TypeScript
hnu-digihealth/sensorframework-media-recorder
/src/web.ts
2.546875
3
import {WebPlugin} from '@capacitor/core'; import {MediaRecorderOptions, MediaRecorderPlugin} from './definitions'; interface MediaRecording { id: string; stream: MediaStream; recorder: any; chunks: Blob[]; finished: Promise<void>; name: string; } const uuidv4 = (): string => { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); }; const Recorder = (window as any).MediaRecorder; export class MediaRecorderWeb extends WebPlugin implements MediaRecorderPlugin { private recordings: Map<string, MediaRecording> = new Map<string, MediaRecording>(); constructor() { super({ name: 'MediaRecorder', platforms: ['web', 'android'] }); } async startRecording(options: MediaRecorderOptions): Promise<{ id: string }> { const stream = await navigator.mediaDevices.getUserMedia(options); const recorder = new Recorder(stream); const id = uuidv4(); const chunks: Blob[] = []; const name = options.name || Date.now().toString(); const finished = new Promise<void>((resolve) => { recorder.ondataavailable = (event: any) => { if (event.data.size > 0) { chunks.push(event.data); } }; recorder.onstop = () => { resolve(); }; recorder.start(); }); const recording = { id, stream, recorder, chunks, finished, name, }; this.recordings.set(id, recording); return {id}; } async stopRecording(options: { id: string }): Promise<File> { const {id} = options; const recording = this.recordings.get(id); if(!recording){ return Promise.reject(`Recording with id ${id} does not exist`); } recording.recorder.stop(); await recording.finished; const blob = new Blob(recording.chunks); const file = new File([blob], recording.name, {type: blob.type}); recording.stream.getTracks().forEach((track: MediaStreamTrack) => track.stop()); this.recordings.delete(id); return file; } async getPreview(options: { id: string }): Promise<MediaStream> { const {id} = options; const recording = this.recordings.get(id); return recording != null ? recording.stream : null; } } const MediaRecorder = new MediaRecorderWeb(); export {MediaRecorder}; import {registerWebPlugin} from '@capacitor/core'; registerWebPlugin(MediaRecorder);
3bda8664c6b884f8eac847f5adea48ccfacf7337
TypeScript
kunalx86/reddit-clone-server
/src/controllers/commentsController.ts
2.546875
3
import { Comment } from "@entities/Comment"; import { CommentVote } from "@entities/CommentVote"; import { Post } from "@entities/Post"; import { User } from "@entities/User"; import { LoadStrategy } from "@mikro-orm/core"; import { ICommentPostRequest, IVoteCommentRequest } from "@shared/types"; import { Response, Request } from "express"; export const createComment = async (req: ICommentPostRequest, res: Response) => { const { em } = req; const postId = parseInt(req.params.postId); if (!req.body.comment.length || req.body.comment.length > 150) { return res.status(400).send({ errors: { comment: "Comment cannot exceed 150 characters/It is also required field" } }) } const post = await em.findOneOrFail(Post, { id: postId }); const user = await User.getUser(req.session.userId || -1); const comment = new Comment(req.body.comment); comment.user = user; comment.post = post; if (req.body.parent) { const parent = await em.findOneOrFail(Comment, { id: req.body.parent }); comment.parent = parent; } await em.persistAndFlush(comment); res.status(201).send({ data: { ...comment, } }); } export const getComments = async (req: Request, res: Response) => { const { em } = req; const postId = parseInt(req.params.postId); const comments = await em.find(Comment, { post: postId, parent: null }, { populate: ['replies', 'votes', 'user.profile', 'replies.user', 'replies.user.profile', 'replies.votes'], orderBy: { createdAt:'asc' }, strategy: LoadStrategy.JOINED }); // Has to be inside because of req object const mapCommentVotes = (comment: Comment) => { const replies = comment.replies.getItems().map(reply => ({ ...reply, parent: undefined, votes: undefined, voted: reply.getHasVoted(req.session.userId || -1) })) return { ...comment, replies: replies, votes: undefined, voted: comment.getHasVoted(req.session.userId || -1), } } const data = comments.map(mapCommentVotes); res.status(200).send({ data }) } export const voteComment = async (req: IVoteCommentRequest, res: Response) => { const { em } = req; const commentId = parseInt(req.params.commentId); const vote = req.body.vote >= 1 && ! (req.body.vote < -1) ? 1 : -1; const comment = await em.findOneOrFail(Comment, { id: commentId, }, { populate: ['votes'], strategy: LoadStrategy.JOINED }); const commentVote = await em.findOne(CommentVote, { comment, user: req.session.userId }); if (commentVote) { if (vote === commentVote.vote) { comment.votes.remove(commentVote); vote === 1 ? comment.votesCount-- : comment.votesCount++; await em.removeAndFlush(commentVote); } else { commentVote.vote = vote; vote === 1 ? comment.votesCount++ : comment.votesCount--; await em.persistAndFlush(commentVote); } await em.persistAndFlush(comment) } else { const user = await User.getUser(req.session.userId || -1); const newCommentVote = new CommentVote(vote); newCommentVote.user = user; newCommentVote.comment = comment; comment.votes.add(newCommentVote); comment.votesCount += vote; await em.persistAndFlush([comment, newCommentVote]); } const data = { ...comment, voted: comment.getHasVoted(req.session.userId || -1) } res.status(201).send({ data }); }
1dd6582ebb16837fffbaee76e8193af3da426b9a
TypeScript
ethereum/js-ethereum-cryptography
/test/test-vectors/assert.ts
3.3125
3
// Minimal assert version to avoid dependecies on node internals // Allows to verify that none of brwoserify version of node internals is included in resulting build function deepStrictEqual(actual: unknown, expected: unknown, message?: string) { const [actualType, expectedType] = [typeof actual, typeof expected]; const err = new Error( `Non-equal values: actual=${actual} (type=${actualType}) expected=${expected} (type=${expectedType})${ message ? `. Message: ${message}` : "" }` ); if (actualType !== expectedType) { throw err; } // Primitive types if ( ["string", "number", "bigint", "undefined", "boolean"].includes(actualType) ) { if (actual !== expected) { throw err; } return; } if (actual instanceof Uint8Array && expected instanceof Uint8Array) { if (actual.length !== expected.length) { throw err; } for (let i = 0; i < actual.length; i++) { if (actual[i] !== expected[i]) { throw err; } } return; } if (Array.isArray(actual) && Array.isArray(expected)) { if (actual.length !== expected.length) { throw err; } for (let i = 0; i < actual.length; i++) { deepStrictEqual(actual[i], expected[i], message); } return; } if (actual === null && expected === null) { return; } if (actualType === "object") { const [actualKeys, expectedKeys] = [ Object.keys(actual as object), Object.keys(expected as object), ]; deepStrictEqual(actualKeys, expectedKeys, message); for (const key of actualKeys) { deepStrictEqual((actual as any)[key], (expected as any)[key], message); } return; } throw err; } function throws(cb: () => any) { try { cb(); } catch (e) { return; } throw new Error("Missing expected exception."); } async function rejects(cb: () => Promise<any>): Promise<void> { try { await cb(); } catch (e) { return; } throw new Error("Missing expected rejection."); } // Run tests with node assert: // import { deepStrictEqual, throws } from "assert"; export { deepStrictEqual, throws, rejects };
915732a47c53b72ad03fd8dfbab480fa11530306
TypeScript
kamibababa/SplitTime
/src/engine/player/ability/jump.ts
3.015625
3
namespace splitTime.player.ability { export class Jump implements IAbility { body: splitTime.Body zVelocity: number /** * @param {splitTime.Body} body * @param {number} zVelocity initial z velocity (560 is a good value) * @implements {G.Ability} */ private constructor(body: splitTime.Body, zVelocity: number) { this.body = body this.zVelocity = zVelocity } static fromMaxHeight(body: splitTime.Body, approxMaxHeight: number): Jump { // Solving x = 1/2 * a * t^2 + v0 * t + x0 const timeToReachMax = Math.sqrt(approxMaxHeight / (0.5 * Math.abs(body.GRAVITY))) const initialVelocity = Math.abs(body.GRAVITY) * timeToReachMax return new Jump(body, initialVelocity) } use(): boolean { var fallCollisionInfo = this.body.mover.vertical.calculateZCollision( this.body.level, this.body.x, this.body.y, this.body.z, -1 ) if (fallCollisionInfo.dzAllowed === 0) { this.body.zVelocity = this.zVelocity return true } return false } } }
d8c3db1bb62bdb6f1aa444a78bd5d5a4bbfe0871
TypeScript
doug-martin/nestjs-query
/packages/query-graphql/__tests__/types/find-one-args.type.spec.ts
2.65625
3
// eslint-disable-next-line max-classes-per-file import { plainToClass } from 'class-transformer'; import { validateSync } from 'class-validator'; import { Resolver, Query, Args, Int, ArgsType, ObjectType } from '@nestjs/graphql'; import { FilterableField, FindOneArgsType, IDField } from '../../src'; import { generateSchema } from '../__fixtures__'; describe('FindOneArgsType', (): void => { @ObjectType() class FindOneDTO { @FilterableField() field!: string; } @ArgsType() class FindOne extends FindOneArgsType(FindOneDTO) {} it('should create an args type with id field as the type', async () => { @Resolver() class FindOneArgsTypeSpec { @Query(() => Int) // eslint-disable-next-line @typescript-eslint/no-unused-vars test(@Args() input: FindOne): number { return 1; } } const schema = await generateSchema([FindOneArgsTypeSpec]); expect(schema).toMatchSnapshot(); }); it('should create an args type with a custom ID type', async () => { @ObjectType() class FindOneCustomIDDTO { @IDField(() => String) field!: string; } @ArgsType() class FindOneCustomId extends FindOneArgsType(FindOneCustomIDDTO) {} @Resolver() class FindOneArgsTypeSpec { @Query(() => Int) // eslint-disable-next-line @typescript-eslint/no-unused-vars test(@Args() input: FindOneCustomId): number { return 1; } } const schema = await generateSchema([FindOneArgsTypeSpec]); expect(schema).toMatchSnapshot(); }); describe('validation', () => { it('should validate the id is defined', () => { const input = {}; const it = plainToClass(FindOne, input); const errors = validateSync(it); expect(errors).toEqual([ { children: [], constraints: { isNotEmpty: 'id should not be empty', }, property: 'id', target: input, }, ]); }); it('should validate the id is not empty', () => { const input = { id: '' }; const it = plainToClass(FindOne, input); const errors = validateSync(it); expect(errors).toEqual([ { children: [], constraints: { isNotEmpty: 'id should not be empty', }, property: 'id', target: input, value: '', }, ]); }); }); });
476123159441ca4fe0941f707951add3ecbd629c
TypeScript
limengke123/sg2ts
/src/util.ts
2.59375
3
export const getSpaces = (num: number = 0): string => { const space: string = ' ' return space.repeat(num) }
b1171df2b214f747699fcb0b0bc870432cc0fd59
TypeScript
future4code/Adryane-Fernandes
/Semana 18 - Autorização de Usuários/Projeto - Cookenu/src/endpoints/deleteUser.ts
2.65625
3
import { Request, Response } from "express"; import connection from "../connection"; import { userExist } from "../function/userExist"; import { getTokenData } from "../services/authenticator"; import { authenticatorData, USER_ROLES } from "../types"; async function deleteUser(req: Request, res: Response): Promise<void> { try { const idUser: string = req.params.id; const token = req.headers.authorization as string; if (!idUser) { res.statusCode = 400; throw new Error("parameter is missing"); } if (!token) { res.statusCode = 403; throw new Error("not authorized"); } const tokenData: authenticatorData = getTokenData(token); userExist(tokenData.id) if(tokenData.role === USER_ROLES.NORMAL){ res.statusCode = 403 throw new Error("Not authorized. Only administrators can delete users."); } await connection.raw(` DELETE FROM followers_cookenu WHERE follower_id = "${idUser}" `) await connection.raw(` DELETE FROM recipe_cookenu WHERE user_id = "${idUser}" `) await connection.raw(` DELETE FROM user_cookenu WHERE id = "${idUser}" `) res.end() } catch (error) { if (error.message.includes("jwt expired")) { res.status(403).send({ message: "Token expired" }); } res.send({ message: error.message || error.sqlMessage }); } } export default deleteUser;
5d61f44c747323af6075add3ded09bc62a38f4ef
TypeScript
ZEISS/react-view-pdf
/src/utils/hacks.ts
3.6875
4
/** * Produces an array with N items, the value of each item is n * * @param i: Length of the array to be generated */ export function range(i: number): Array<number> { return i ? range(i - 1).concat(i) : []; } /** * Checks whether a string provided is a data URI. * * @param {String} str String to check */ export const isDataURI = (str: string) => /^data:/.test(str); export const dataURItoUint8Array = (dataURI: string) => { if (!isDataURI(dataURI)) { throw new Error('dataURItoUint8Array was provided with an argument which is not a valid data URI.'); } let byteString; if (dataURI.split(',')[0].indexOf('base64') >= 0) { byteString = atob(dataURI.split(',')[1]); } else { byteString = unescape(dataURI.split(',')[1]); } const ia = new Uint8Array(byteString.length); for (let i = 0; i < byteString.length; i += 1) { ia[i] = byteString.charCodeAt(i); } return ia; }; /** * Throttles a function call * * @param func * @param limit */ export function throttle(func: (...arg: Array<any>) => void, limit = 1000) { let inThrottle = false; return function(...args: Array<any>) { // eslint-disable-next-line @typescript-eslint/no-this-alias const context = this; if (!inThrottle) { func.apply(context, args); inThrottle = true; setTimeout(() => (inThrottle = false), limit); } }; } /** * Converts SnakeCase to Camelcase * @param s */ export function toCamel(s: string) { const camel = s.toLowerCase().replace(/([-_][a-z])/gi, $1 => { return $1 .toUpperCase() .replace('-', '') .replace('_', ''); }); return camel.charAt(0).toUpperCase() + camel.slice(1); }
124f691504820a88631ba3304e9fe49b4ae081a4
TypeScript
Ntub-Class/homework-if-pippentu6708
/src/index.ts
4.28125
4
// 請介紹兩個字串方法跟數字方法 //字串1.substring的用法,將變數定義的字串值,透過參數搭配取出字串中的第幾個字元到字串第幾個位置的字元後回傳。(作業) let dd: string = 'pippentu6708'; console.log(dd.substring(6, 8)); //tu 要回傳tu,結束的值需要+1) console.log(dd.substring(6)); //tu6708,回傳第6個字串之後 //字串2. concat的用法,將變數定義的字串值,透過參數搭配一前一後的,回傳成為一個字串值顯示。(作業) let ee: string = 'Good'; let ff: string = 'Morning'; console.log(ee.concat(ff)); //GoodMorning //字串3. toLowerCase的用法,將變數定義的字串值,將值變成小寫後,再回傳回來。(作業) let gg: string = 'Good Morning'; console.log(gg.toLowerCase()); //good morning console.log('*'.repeat(100)); //數字 1. toFixed的用法,將變數定義的數值,轉換成數字字串後,傳回指定的小數點位數,透過()內的進位數來指定位數和四捨五入。 let cost: number = 80.388; console.log(cost); //80.388 let cost1 = cost.toFixed(2); console.log(cost1); //80.39(小數點兩位,四捨五入) let cost2 = cost.toFixed(); console.log(cost2); //80()空白,四捨五入成整數 console.log(typeof (cost2)); //string輸出值為字串 //數字2. toExponential的用法, 將把數字字串轉換為指數型態表示回傳,參數為指定小數點後的位數,並且四捨五入。 //這部分,可否請老師您再教導與說明? let num: number = 99.3992158; console.log(num); //99.3992158 let num0 = num.toExponential(0); console.log(num0); //1e+2 let num1 = num.toExponential(1); //9.9e+1 console.log(num1); let num2 = num.toExponential(2); //9.94e+1 (有四捨五入) console.log(num2); let num3 = num.toExponential(3); //9.940e+1 (有四捨五入) console.log(num3); let num4 = num.toExponential(4); //9.9399e+1 console.log(num4); let num5 = num.toExponential(5); //9.93992e+1 console.log(num5); let num6 = num.toExponential(6); //9.939922e+1(有四捨五入) console.log(num6); console.log(typeof (num1)); //string //數字2. 不同數字換算: 123.4,則為e+2 10的2次方 let numA: number = 123.4; console.log(numA); //123.4 let numA0 = numA.toExponential(0); //1e+2 console.log(numA0); let numA1 = numA.toExponential(1); //1.2e+2 console.log(numA1); let numA2 = numA.toExponential(2); //1.23e+2 console.log(numA2); let numA3 = numA.toExponential(3); //1.234e+2 console.log(numA3); let numA4 = numA.toExponential(4); //1.2340e+2 console.log(numA4); let numA5 = numA.toExponential(5); //1.23400e+2 console.log(numA5); let numA6 = numA.toExponential(6); //1.234000e+2 console.log(numA6); console.log(typeof (numA1)); //string //數字3 toPrecision的用法,整數部分:將把要顯示數字指定為幾位數字,()參數為指定數後,並且四捨五入。若參數定義有超過數字的範圍則用0去補\替代,轉換為數字字串後的型態回傳。 //這部分,可否請老師您再教導與說明? let numP: number = 90.015; console.log(numP); //90.015 let numP0 = numP.toPrecision(); console.log(numP0); //90.015 let numP1 = numP.toPrecision(1); console.log(numP1); //9e+1 let numP2 = numP.toPrecision(2); console.log(numP2); //90 let numP3 = numP.toPrecision(3); console.log(numP3); //90.0 let numP4 = numP.toPrecision(4); console.log(numP4); //90.02 let numP5 = numP.toPrecision(5); console.log(numP5); //90.015 let numP6 = numP.toPrecision(6); console.log(numP6); //90.0150 console.log(typeof (numP1)); //string //數字3.toPrecision的用法,小數點的數字部分:則取小數點數字內非0的數字並且四捨五入。作為開始顯示數字,搭配()參數為指定數後,並且四捨五入。若參數定義有超過數字的範圍則用0去補\替代,轉換為數字字串後的型態回傳, let numB: number = 0.015; console.log(numB); //0.015 let numB0 = numB.toPrecision(); console.log(numB0); //0.015 let numB1 = numB.toPrecision(1); console.log(numB1); //0.01 let numB2 = numB.toPrecision(2); console.log(numB2); //0.015 let numB3 = numB.toPrecision(3); console.log(numB3); //0.0150 let numB4 = numB.toPrecision(4); console.log(numB4); //0.01500 let numB5 = numB.toPrecision(5); console.log(numB5); //0.015000 let numB6 = numB.toPrecision(6); console.log(numB6); //0.0150000 console.log(typeof (numB1)); //string console.log('*'.repeat(100)); // 錢錢大於一個值,叫乾爹 let money = 40000; let limit = 500000; // 限制值 if (money > limit) { console.log('您還不夠格'); } else { console.log('乾爹,您好'); }
1cfc7b26366289d45aa428a441fbd62137340bf5
TypeScript
mpm1900/loot
/src/types/character/character.status.ts
3.015625
3
import { Guage, sGuage } from '../guage' import { AppRecord } from '..' export type sCharacterStatus = { poison: sGuage, sleep: sGuage, paralysis: sGuage, burn: sGuage, } export type iCharacterStatus = { poison?: Guage, sleep?: Guage, paralysis?: Guage, burn?: Guage, } const defaultCharacterStatus: iCharacterStatus = { poison: new Guage(), sleep: new Guage(), paralysis: new Guage(), burn: new Guage(), } export class CharacterStatus extends AppRecord implements iCharacterStatus { public readonly poison: Guage public readonly sleep: Guage public readonly paralysis: Guage public readonly burn: Guage constructor(args?: iCharacterStatus) { args ? super({ ...defaultCharacterStatus, ...args } as iCharacterStatus) : super(defaultCharacterStatus) } with(values: iCharacterStatus): CharacterStatus { return super.with(values) as CharacterStatus } serialize(): sCharacterStatus { return { poison: this.poison.serialize(), sleep: this.sleep.serialize(), paralysis: this.paralysis.serialize(), burn: this.burn.serialize(), } } static deserialize(sCharacterStatus: sCharacterStatus): CharacterStatus { return new CharacterStatus({ poison: Guage.deserialize(sCharacterStatus.poison), sleep: Guage.deserialize(sCharacterStatus.sleep), paralysis: Guage.deserialize(sCharacterStatus.paralysis), burn: Guage.deserialize(sCharacterStatus.burn), }) } }
3ece1ed3e1ea2a354fd9a426c2c02faf8eda0378
TypeScript
Minious/CoolSlide
/src/app/pawnSprites/pawnSprite.ts
3.03125
3
import { LevelScene } from "../levels/levelScene"; import { Action } from "../actions/actionInterface"; export class PawnSprite extends Phaser.GameObjects.Container { private maxLife: number; private heartsContainer: Phaser.GameObjects.Container; public constructor( scene: Phaser.Scene, x: number, y: number, texture: string, maxLife: number ) { super(scene, x, y); this.maxLife = maxLife; const pawnSprite: Phaser.GameObjects.Image = this.scene.add.image( 0, 0, texture ); this.add(pawnSprite); const heartsSize: number = this.scene.textures.get("fullHeart").get(0) .width; const heartsXMargin: number = 1; const heartsYOffset: number = -13; const heartsTotalWidth: number = this.maxLife * heartsSize + (this.maxLife - 1) * heartsXMargin; const heartsX0: number = -heartsTotalWidth / 2 + heartsSize / 2; this.heartsContainer = this.scene.add.container(0, heartsYOffset); this.add(this.heartsContainer); for (let i: number = 0; i < this.maxLife; i += 1) { const heartSprite: Phaser.GameObjects.Image = this.scene.add.image( heartsX0 + i * (heartsSize + heartsXMargin), 0, "fullHeart" ); this.heartsContainer.add(heartSprite); } } public attack(action: Action, timeStep: number): void { const fromPos: Phaser.Math.Vector2 = (this .scene as LevelScene).gridPosToWorldPos(action.from); const destPos: Phaser.Math.Vector2 = (this .scene as LevelScene).gridPosToWorldPos(action.to); const midPos: Phaser.Math.Vector2 = destPos.clone().lerp(fromPos, 0.5); this.scene.tweens.add({ targets: this, x: midPos.x, y: midPos.y, yoyo: true, duration: timeStep / 2, ease: "Quad.easeIn", onYoyo: (): void => action.targetPawnSprite.updateLife(action.targetPawnNewLife), }); } public move(action: Action, timeStep: number): void { const destPos: Phaser.Math.Vector2 = (this .scene as LevelScene).gridPosToWorldPos(action.to); this.scene.tweens.add({ targets: action.fromPawnSprite, x: destPos.x, y: destPos.y, duration: timeStep, ease: "Quad.easeOut", }); } public updateLife(newLife: number): void { const heartSprites: Array<Phaser.GameObjects.Image> = this.heartsContainer.getAll() as Array< Phaser.GameObjects.Image >; heartSprites.forEach( (heartSprite: Phaser.GameObjects.Image, i: number): void => { if (i >= newLife) { heartSprite.setTexture("emptyHeart"); } } ); } }
efbb1ffe47d44bf5d66527f5694b0f8149f48d76
TypeScript
Girimallappa/FarmManager
/src/app/services/farm.service.ts
2.578125
3
import { PaddockService } from './paddock.service'; import { FarmTypeEnum } from './../models/FarmTypeEnum'; import { Farm } from './../models/farm'; import { Injectable } from '@angular/core'; import * as _ from 'lodash'; @Injectable({ providedIn: 'root', }) export class FarmService { private storeKey = 'Farms'; constructor(private _paddocksService: PaddockService) {} /** * Get all items from store */ getAll(): Farm[] { const localStrgItem = JSON.parse(localStorage.getItem(this.storeKey)); return localStrgItem == null ? [] : localStrgItem.Farms; } /** * Add a farm to the store */ addOrUpdate(farm: Farm, isSeed: boolean): void { let farms = this.getAll(); const farmToUpdate = this.getById(farm.Id); if (farmToUpdate) { farms = _.filter(farms, (f: Farm) => f.Id !== farmToUpdate.Id); } else { const max = _.maxBy(farms, (f: Farm) => f.Id); farm.Id = max ? max.Id + 1 : 1; } if (!isSeed) { // set the owner id for all paddocks to farm id for (const p of farm.Paddocks) { p.OwnerFarmId = farm.Id; p.isOpen = false; this._paddocksService.addOrUpdate(p); } const farmPaddocks = this._paddocksService.getByOwnerId(farm.Id); const paddockIds = _.chain(farmPaddocks) .map((p) => p.Id) .value(); farm.PaddockIds = paddockIds; } farm.FarmTypeName = FarmTypeEnum[farm.FarmType]; farms.push(farm); this.set(farms); } /** * Set farms in store */ set(farms: Farm[]): void { localStorage.removeItem(this.storeKey); localStorage.setItem(this.storeKey, JSON.stringify({ Farms: farms })); } /** * Get by id */ getById(id: number): Farm { const farms = this.getAll(); const farm: Farm = _.find(farms, (f) => f.Id === +id); return farm; } /** * delete the farm from store */ delete(id: number): void { let farms = this.getAll(); const farmToDelete = this.getById(+id); if (farmToDelete) { farms = _.filter(farms, (f: Farm) => f.Id !== farmToDelete.Id); this.set(farms); } } /** * saves the farm * @param farm */ saveFarm(farm: Farm): void { // remove the farm from store if (farm.Id > 0) { // remove all the paddocks for (const pId of farm.PaddockIds) { this._paddocksService.delete(pId); } // Remove the farm this.delete(farm.Id); } this.addOrUpdate(farm, false); } }
f4a914a5ca1c9a63a03e279a0d84b1a18f361fe3
TypeScript
krystaDev/typescript-design-patterns
/factory/pizzeria-2/pizzeria-types/americans-pizzeria.ts
2.65625
3
import {Pizzeria} from "../pizzeria"; import {Pizza} from "../pizza-abstract"; import {PizzaType} from "../pizza-type"; import {AmericanCheesePizza} from "../pizza-types/americans/american-cheese-pizza"; import {AmericanVegePizza} from "../pizza-types/americans/american-vege-pizza"; import {AmericanPepperoniPizza} from "../pizza-types/americans/american-pepperoni-pizza"; import {AmericanSeaFoodPizza} from "../pizza-types/americans/american-sea-food-pizza"; import {AmericansProductsFactory} from "../products-factories/americans-products-factory"; export class AmericansPizzeria extends Pizzeria { constructor() { super(new AmericansProductsFactory()); } protected createPizza(type: PizzaType): Pizza { switch (type) { case PizzaType.CHEESE: return new AmericanCheesePizza(this.productsFactory); case PizzaType.VEGE: return new AmericanVegePizza(this.productsFactory); case PizzaType.PEPPERONI: return new AmericanPepperoniPizza(this.productsFactory); case PizzaType.SEA_FOOD: return new AmericanSeaFoodPizza(this.productsFactory); } } }
fbb57ac6f790fc226b67405d91c6caff77dd07d4
TypeScript
twosevenkid/yearn-data
/tools/decoder.ts
2.65625
3
import decoder from "abi-decoder"; import path from "path"; import fs from "fs"; const abidir = path.join("abi", "full"); const [_, __, ...rest] = process.argv; if (rest.length !== 1) { console.error("[!] please provide data"); process.exit(1); } const data = rest[0]; function loadAbis(dir: string) { fs.readdirSync(dir).forEach((file) => { const fullpath = path.join(dir, file); const lstat = fs.lstatSync(fullpath); if (lstat.isFile() && !file.startsWith(".")) { try { const contents = fs.readFileSync(fullpath, "utf-8"); decoder.addABI(JSON.parse(contents)); } catch (error) { console.error(`Skipping ${fullpath}: ${error}`); } } else if (lstat.isDirectory()) { loadAbis(fullpath); } }); } loadAbis(abidir); console.log(decoder.decodeMethod(data));
1fba87980c909591b3490a743285de28d84f8f47
TypeScript
lockcp/scriptcat
/src/apps/msg-center/browser.ts
2.6875
3
// 前端用通信 import { randomString } from "@App/pkg/utils"; export type ListenMsg = (msg: any) => void; // 浏览器页面之间的通信,主要在content和injected页面之间 export class BrowserMsg { public id: string; public content: boolean; public listenMap = new Map<string, ListenMsg>(); constructor(id: string, content: boolean) { this.id = id; this.content = content; document.addEventListener(this.id + (content ? 'ct' : 'fd'), (event: any) => { let detail = event.detail; let topic = detail.topic; let listen = this.listenMap.get(topic); if (listen) { listen(detail.msg); } }); } public send(topic: string, msg: any) { let detail = { topic: topic, msg: msg, }; if ((<any>global).cloneInto) { detail = (<any>global).cloneInto(detail, document.defaultView); } let ev = new CustomEvent(this.id + (this.content ? 'fd' : 'ct'), { detail: detail, }); document.dispatchEvent(ev); } public listen(topic: string, callback: ListenMsg) { this.listenMap.set(topic, callback); } }
f09a9c08ed1c730fc64016ead0c501e3190359f5
TypeScript
Liam-So/bug_tracker
/frontend/src/interfaces/constants.ts
2.890625
3
export const API_URL = "http://localhost:8001"; // WE ALWAYS ASSUME THAT THESE ARE IN THIS ORDER export const status_codes = [ { value: 'pending', label: 'Pending 🤷' }, { value: 'in_progress', label: 'In Progress 🧑‍⚕️' }, { value: 'completed', label: 'Done ✅' } ]; export const getDefaultStatusCode = (status: string) => { if (status === 'pending') { return 0; } else if (status === 'in_progress') { return 1; } else { return 2; } } export const ticketTypeArray = [ { value: 'new_feature', label: 'New Feature ✔️' }, { value: 'bug', label: 'Bug 🐛' }, ]; export const getDefaultTicketType = (type: string) => { if (type === 'new_feature') { return 0; } else { return 1; } } export const ticketSeverityArray = [ { value: 'critical', label: 'Critical 🚑' }, { value: 'high', label: 'High 🙀' }, { value: 'md', label: 'Medium 😅' }, { value: 'low', label: 'Low ☕' } ]; export const getDefaultTicketSeverity = (type: string) => { if (type === 'critical') { return 0; } else if (type === 'high') { return 1; } else if (type === 'md') { return 2; } else { return 3; } }
ebabb9a46914129eeeef2832ccb0a317bfc00b09
TypeScript
bfutema/mentorando
/web/src/components/Link/styles.ts
2.515625
3
import styled from 'styled-components'; import { shade, lighten, darken } from 'polished'; interface ILinkProps { outline?: boolean; amount?: number; color: string; func?: 'lighten' | 'darken'; } export const Container = styled.div<ILinkProps>` a { min-width: 180px; background: ${props => (props.outline ? 'transparent' : props.color)}; color: ${props => (props.outline ? props.color : props.theme.colors.white)}; border: 1px solid ${props => props.color}; padding: 8px 16px; border-radius: 4px; font-size: 18px; font-weight: bold; letter-spacing: 1px; text-transform: uppercase; position: relative; display: flex; align-items: center; justify-content: center; transition: background-color 0.4s; &:hover { color: ${props => props.outline && lighten(0.2, props.color)}; background: ${props => props.outline && props.func ? props.func === 'lighten' ? lighten(props.amount || 0.2, props.color) : darken(props.amount || 0.2, props.color) : shade(0.2, props.color)}; } } `;
ab673844d81d812e7841981268f3be3b7d50035b
TypeScript
WarriorRocker/angular-xo-material
/src/app/directives/clipboard/clipboard.directive.ts
2.59375
3
// Modifed from: https://www.bennadel.com/blog/3235-creating-a-simple-copy-to-clipboard-directive-in-angular-2-4-9.htm import { Directive, Input } from '@angular/core'; import { EventEmitter } from '@angular/core'; import { ClipboardService } from './clipboard.service'; @Directive({ selector: '[clipboard]', host: { '(click)': 'copyToClipboard()' } }) export class ClipboardDirective { @Input() clipboard: string; @Input() copyEvent: EventEmitter<string> = null; @Input() errorEvent: EventEmitter<Error> = null; constructor(private _clipboard: ClipboardService) { } public copyToClipboard(): void { this._clipboard .copy(this.clipboard) .then((value: string): void => { if (this.copyEvent) this.copyEvent.emit(value); }) .catch((error: Error): void => { if (this.errorEvent) this.errorEvent.emit(error); }); } }
1b20ac8cd19a85608e259dd75cb56bc7af502b3c
TypeScript
joshmedeski/wheniwork-cli
/testing/using.ts
3.546875
4
/** * Allows you to provide data to iterate and use for a test. * * @param {object} values A key used as the description and an array of values. * @param {function} func The function. */ export const using = (values, func) => { for (const key in values) { if (values.hasOwnProperty(key)) { values[key].unshift(key); func.apply(null, values[key]); } } };
b473eece652df48ed56450fba71cd3f1313dd624
TypeScript
Gun-che/EloquentGame
/src/actors/Monster.ts
2.890625
3
import { Vec } from './../Vec'; import { State } from '../State'; import { monsterSpeed } from '../consts'; export class Monster { pos: Vec; size: Vec; constructor(pos: Vec) { this.pos = pos; this.size = new Vec(1.2, 2); } get type() { return 'monster'; } static create(pos: Vec): Monster { return new Monster(pos.plus(new Vec(0, -1))); } update(time: number, state: State): Monster { let player = state.player; let speed = (player.pos.x < this.pos.x ? -1 : 1) * time * monsterSpeed; let newPos = new Vec(this.pos.x + speed, this.pos.y); if (state.level.touches(newPos, this.size, 'wall')) { return this; } else { return new Monster(newPos) } } collide(state: State) { let player = state.player; if (player.pos.y + player.size.y < this.pos.y + 0.5) { let filtered = state.actors.filter(a => a != this); return new State(state.level, filtered, state.status); } else { return new State(state.level, state.actors, 'lost') } } }
81c3b05bd6f1b07a75aad7bafaccd619821815d2
TypeScript
xiefenga/algorithm-ts
/src/types/helper/TreeNode.ts
3.125
3
class TreeNode<T> { public val: T public right: TreeNode<T> | null = null public left: TreeNode<T> | null = null public parent: TreeNode<T> | null = null constructor(val: T) { this.val = val } public isLeave(): boolean { return !this.left && !this.right } } export default TreeNode
3ac13cc7c3848af3a67aca546bc30411772ef81a
TypeScript
Ben16005/EarthdawnWebApp
/src/app/models/character.ts
2.578125
3
import { Race } from './race'; import { Discipline } from './discipline'; import { Talent } from './talent'; import { Stat } from './stat'; export class Character { public name: string; public player: string; public age: number; public height: string; public weight: number; public gender: string; public stats: Stat[]; public race: Race; public disciplines: Discipline[]; public skills: Talent[]; constructor(name: string) { this.name = name; } }
fa2d6c1773652cb0059aa77fbb564b733f0807da
TypeScript
d-fischer/connection
/src/WebSocketConnection.ts
2.796875
3
import type { ClientOptions } from '@d-fischer/isomorphic-ws'; import { WebSocket } from '@d-fischer/isomorphic-ws'; import { AbstractConnection } from './AbstractConnection'; import type { ConnectionOptions, ConnectionTarget } from './Connection'; export interface WebSocketConnectionOptions { wsOptions?: ClientOptions; } export class WebSocketConnection extends AbstractConnection<WebSocketConnectionOptions> { private _socket: WebSocket | null = null; private readonly _url: string; private _closingOnDemand = false; constructor(target: ConnectionTarget, options?: ConnectionOptions<WebSocketConnectionOptions>) { super(options); if (target.hostName && target.port) { this._url = `ws${target.secure ? 's' : ''}://${target.hostName}:${target.port}`; } else if (target.url) { this._url = target.url; } else { throw new Error('WebSocketConnection requires either hostName & port or url to be set'); } } get hasSocket(): boolean { return !!this._socket; } sendRaw(line: string): void { this._socket?.send(line); } connect(): void { this._logger?.trace('WebSocketConnection connect'); this._connecting = true; this._socket = new WebSocket(this._url, this._additionalOptions?.wsOptions); this._socket.onopen = () => { this._logger?.trace('WebSocketConnection onOpen'); this._connected = true; this._connecting = false; this.emit(this.onConnect); }; this._socket.onmessage = ({ data }) => { this.receiveRaw((data as Buffer).toString()); }; // The following empty error callback needs to exist so connection errors are passed down to `onclose` down below - otherwise the process just crashes instead this._socket.onerror = e => { this._logger?.trace(`WebSocketConnection onError message:${e.message}`); }; this._socket.onclose = e => { const wasConnected = this._connected; const wasConnecting = this._connecting; this._logger?.trace( `WebSocketConnection onClose wasConnected:${wasConnected.toString()} wasConnecting:${wasConnecting.toString()} closingOnDemand:${this._closingOnDemand.toString()} wasClean:${e.wasClean.toString()}` ); this._connected = false; this._connecting = false; if (e.wasClean || this._closingOnDemand) { this._closingOnDemand = false; this.emit(this.onDisconnect, true); this.emit(this.onEnd, true); } else { const err = new Error(`[${e.code}] ${e.reason}`); this.emit(this.onDisconnect, false, err); this.emit(this.onEnd, false, err); } this.clearSocket(); }; } disconnect(): void { this._logger?.trace('WebSocketConnection disconnect'); this._closingOnDemand = true; this._socket?.close(); } protected clearSocket(): void { if (this._socket) { this._socket.onopen = null; this._socket.onmessage = null; this._socket.onerror = null; this._socket.onclose = null; this._socket = null; } } }
dd58969c76ad45ce9c998c185435151c1be81679
TypeScript
cnnor/design-patterns-ts
/src/creational/tests/Builder.test.ts
2.59375
3
import { PizzaBuilder } from '../Builder'; test('make a yummy pepperoni and cheese pizza', () => { const yummyPiza = new PizzaBuilder(12).addSauce().addCheese().addPepperoni().make(); const expected = { slices: 12, sauce: true, cheese: true, pepperoni: true, veggies: [] }; expect(yummyPiza).toMatchObject(expected); }); test('make a not-so-yumm pizza with onions', () => { const notSoYummyPizza = new PizzaBuilder(12).addSauce().addCheese().addVeggies(['onions']).make(); const expected = { slices: 12, sauce: true, cheese: true, pepperoni: false, veggies: ['onions'] }; expect(notSoYummyPizza).toMatchObject(expected); });
425d8be174dd17a3561e8d386404143159fe5910
TypeScript
jorgefortunatof/clients.backend
/src/services/UpdateClientService.ts
2.796875
3
import { getRepository } from "typeorm"; import AppError from "../errors/AppError"; import Client from "../models/Client"; interface Request { id: string; name: string; email: string; cpf: string; } class UpdateClienteService { async execute({ id, name, email, cpf }: Request): Promise<Client> { const clientRepository = getRepository(Client); const numberId = Number(id); if (!numberId || numberId < 1) { throw new AppError("Id do cliente não foi informado ou é inválido."); } const client = await clientRepository.save({ id: numberId, name, email, cpf, }); return client; } } export default UpdateClienteService;
84b958c2a2b1d336d989321f2637148a5b35e8c8
TypeScript
bollwyvl/jupyterlab-lsp
/packages/jupyterlab-lsp/src/magics/defaults.spec.ts
2.671875
3
import { expect } from 'chai'; import { language_specific_overrides } from './defaults'; import { CellMagicsMap, LineMagicsMap } from './maps'; let CELL_MAGIC_EXISTS = `%%MAGIC some text `; let NO_CELL_MAGIC = `%MAGIC some text %%MAGIC some text `; let LINE_MAGIC_WITH_SPACE = `%MAGIC line = dd`; describe('Default IPython overrides', () => { describe('IPython cell magics', () => { let cell_magics_map = new CellMagicsMap( language_specific_overrides['python'].cell_magics ); it('overrides cell magics', () => { let override = cell_magics_map.override_for(CELL_MAGIC_EXISTS); expect(override).to.equal('MAGIC()'); }); it('does not override cell-magic-like constructs', () => { let override = cell_magics_map.override_for(NO_CELL_MAGIC); expect(override).to.equal(null); override = cell_magics_map.override_for(LINE_MAGIC_WITH_SPACE); expect(override).to.equal(null); }); }); describe('IPython line magics', () => { let line_magics_map = new LineMagicsMap( language_specific_overrides['python'].line_magics ); it('overrides line magics', () => { let override = line_magics_map.override_for(LINE_MAGIC_WITH_SPACE); expect(override).to.equal('MAGIC()'); }); it('overrides shell commands', () => { let override = line_magics_map.override_for('!ls -o'); expect(override).to.equal('ls()'); }); }); });
1e9d60199578323f49a61ce2293535eba78302a7
TypeScript
jlno/gif-share-backend
/src/controllers/video-controller.ts
2.78125
3
import { FileController } from './file-controller'; import { Inject } from '../core/decorators'; /** * VideoController */ export class VideoController { /** * fileController */ @Inject private fileController: FileController; /** * videoToBase64Gif * * @param options * @param file */ async videoToBase64Gif(options: any, file: any): Promise<string> { this.validate(options, file); const opts = { start: options.start, duration: options.end - options.start }; return await this.fileController.createBase64Gif(file.video, opts); } /** * validate * * @param options * @param file */ private validate(options: any, file: any): void { if (!file || !file.video) { throw new Error('[video] is required.'); } if (isNaN(options.start)) { throw new Error('[start] is required.'); } else { options.start = Number(options.start); } if (isNaN(options.end)) { throw new Error('[end] is required.'); } else { options.end = Number(options.end); } if (options.end - options.start > 15) { throw new Error('[start]-[end] is invalid.'); } } }
7cad5c50ed46fadb0fe2b09300ea6c7ed5162188
TypeScript
GriffinLedingham/rog
/src/classes/components/camera.ts
2.828125
3
import Canvas from './canvas/canvas' class Camera { public x public y public canvas constructor(canvas: Canvas) { this.canvas = canvas } moveCamera(x,y) { this.x = x this.y = y } render() { let halfX = Math.round((this.canvas.width - 1)/2) let halfY = Math.round((this.canvas.height - 1)/2) this.canvas.drawCanvas( this.x - halfX, this.x + halfX, this.y - halfY, this.y + halfY ) } } export default Camera
90026a32e7055c29dea591b70b2d0c215976a3eb
TypeScript
ccorcos/datalog-prototype
/src/shared/database/memory.ts
3.1875
3
/* EAV Store. A set of utilities for maintaining 5 permutations of 3-tuples, known by various names which you can google about: - Entity-Attribute-Value Store - Datomic - Datalog - Prolog - RDL - SPARQ Knowledgebases and graph databases typically rely on something like this under the hood. */ import { addToIndex, removeFromIndex, DatabaseIndex, scanIndex, } from "./indexHelpers" import { Expression, Binding } from "./queryHelpers" import { MIN, MAX } from "./compare" import { Fact, Database } from "./types" interface EAVIndexes { eav: DatabaseIndex<Fact> ave: DatabaseIndex<Fact> vea: DatabaseIndex<Fact> } // Only need three index to query a 3-tuple expression. // e // ea // ev -> ve // a // av // v export function createInMemoryDatabase(): Database { const eav: DatabaseIndex<Fact> = { sort: [1, 1, 1], values: [], } const ave: DatabaseIndex<Fact> = { sort: [1, 1, 1], values: [], } const vea: DatabaseIndex<Fact> = { sort: [1, 1, 1], values: [], } const indexes: EAVIndexes = { eav, ave, vea } return { setFact(fact: Fact) { return setFact(indexes, fact) }, unsetFact(fact: Fact) { return unsetFact(indexes, fact) }, evaluateExpression(expression) { return evaluateExpression(indexes, expression) }, } } export function setFact(indexes: EAVIndexes, fact: Fact) { const [e, a, v] = fact for (const [name, index] of Object.entries(indexes)) { const chars = name.split("") as [ "e" | "a" | "v", "e" | "a" | "v", "e" | "a" | "v" ] // Reorder the fact for the corresponding index. const value = chars.map(char => ({ e, a, v }[char])) as Fact addToIndex(index, value) } } export function unsetFact(indexes: EAVIndexes, fact: Fact) { const [e, a, v] = fact for (const [name, index] of Object.entries(indexes)) { const chars = name.split("") as [ "e" | "a" | "v", "e" | "a" | "v", "e" | "a" | "v" ] // Reorder the fact for the corresponding index. const value = chars.map(char => ({ e, a, v }[char])) as Fact removeFromIndex(index, value) } } /** * This logic determines which EAV index to scan to evaluate for the unknowns * in an expression. It returns the bindings as well as the facts that were * necessary for computing the result. * * TODO: The facts are returned so that we can easily sync data to the client. * However, we could derive the facts by replacing the unknowns in the query * with each binding. */ function evaluateExpression( indexes: EAVIndexes, expression: Expression ): { bindings: Array<Binding>; facts: Array<Fact> } { const { entity, attribute, value } = expression if (entity.type === "known") { if (attribute.type === "known") { if (value.type === "known") { // EAV. const results = scanIndex(indexes.eav, { gte: [entity.value, attribute.value, value.value], lte: [entity.value, attribute.value, value.value], }) // Bind the unknowns. const facts = results const bindings = results.map(() => ({})) return { bindings, facts } } else { // EA_ const results = scanIndex(indexes.eav, { gte: [entity.value, attribute.value, MIN], lte: [entity.value, attribute.value, MAX], }) // Bind the unknowns. const facts = results const bindings = facts.map(([e, a, v]) => { return { [value.name]: v } }) return { bindings, facts } } } else { if (value.type === "known") { // E_V const results = scanIndex(indexes.vea, { gte: [value.value, entity.value, MIN], lte: [value.value, entity.value, MAX], }) const facts = results.map(([v, e, a]) => [e, a, v] as Fact) // Bind the unknowns. const bindings = facts.map(([e, a, v]) => { return { [attribute.name]: a } }) return { bindings, facts } } else { // E__ // Warning: this is expensive. const results = scanIndex(indexes.eav, { gte: [entity.value, MIN, MIN], lte: [entity.value, MAX, MAX], }) const facts = results // Bind the unknowns. const bindings = facts.map(([e, a, v]) => { return { [attribute.name]: a, [value.name]: v } }) return { bindings, facts } } } } else { if (attribute.type === "known") { if (value.type === "known") { // _AV const results = scanIndex(indexes.ave, { gte: [attribute.value, value.value, MIN], lte: [attribute.value, value.value, MAX], }) const facts = results.map(([a, v, e]) => [e, a, v] as Fact) // Bind the unknowns. const bindings = facts.map(([e, a, v]) => { return { [entity.name]: e } }) return { bindings, facts } } else { // _A_ // Warning: this is expensive. const results = scanIndex(indexes.ave, { gte: [attribute.value, MIN, MIN], lte: [attribute.value, MAX, MAX], }) const facts = results.map(([a, v, e]) => [e, a, v] as Fact) // Bind the unknowns. const bindings = facts.map(([e, a, v]) => { return { [value.name]: v, [entity.name]: e } }) return { bindings, facts } } } else { if (value.type === "known") { // __V // Warning: this is expensive. const results = scanIndex(indexes.vea, { gte: [value.value, MIN, MIN], lte: [value.value, MAX, MAX], }) const facts = results.map(([v, e, a]) => [e, a, v] as Fact) // Bind the unknowns. const bindings = facts.map(([e, a, v]) => { return { [attribute.name]: a, [entity.name]: e } }) return { bindings, facts } } else { // ___ // Warning: this is *very* expensive. const results = scanIndex(indexes.eav, { gte: [MIN, MIN, MIN], lte: [MAX, MAX, MAX], }) const facts = results // Bind the unknowns. const bindings = facts.map(([e, a, v]) => { return { [entity.name]: e, [attribute.name]: a, [value.name]: v } }) return { bindings, facts } } } } }
61ae992b3ce0dc283abdb3fac5d882b8f2a74d8d
TypeScript
vuepress-theme-hope/vuepress-theme-hope
/packages/shared/src/shared/utils/deepAssign.ts
3.28125
3
import { entries, isArray, isPlainObject } from "./helper.js"; // eslint-disable-next-line @typescript-eslint/no-explicit-any type IAnyObject = Record<string, any>; /** Deep merge objects to the first one */ export const deepAssign = < T extends IAnyObject, U extends IAnyObject = T, V extends Partial<T> & Partial<U> = T & U, >( originObject: T, ...overrideObjects: (U | null | undefined)[] ): V => { if (overrideObjects.length === 0) return originObject as unknown as V; /** Object being merged */ const assignObject = overrideObjects.shift() || null; if (assignObject) entries(assignObject).forEach(([property, value]) => { if (property === "__proto__" || property === "constructor") return; if (isPlainObject(originObject[property]) && isPlainObject(value)) deepAssign(originObject[property], value); else if (isArray(value)) (originObject as IAnyObject)[property] = [...(<unknown[]>value)]; else if (isPlainObject(value)) (originObject as IAnyObject)[property] = { ...value, }; else (originObject as IAnyObject)[property] = <unknown>( assignObject[property] ); }); return deepAssign(originObject, ...overrideObjects); };
654d30c4c702d5e2e89997eb634fbac728e3197b
TypeScript
bluelovers/node-jsdom-url
/lib/URLImpl.ts
2.5625
3
/** * Created by user on 2018/2/11/011. */ import createClassProxy, { IClassProxyHandler, ClassProxyStatic } from 'class-proxy'; import { implementation as WURLImpl } from 'whatwg-url/lib/URL-impl'; import { URLSearchParamsImpl, IURLSearchParams, URLSearchParamsImplCore } from './URLSearchParams'; import { isValidURLObject } from './valid/URL'; export { URLSearchParamsImpl, URLSearchParamsImplCore } export class URLImplCore extends WURLImpl { href: string; origin: string; protocol: string; username: string; password: string; host: string; hostname: string; port: string; pathname: string; search: string; hash: string; _query?: URLSearchParamsImplCore; _url?: URLImplCore.IImpl; constructor(href, base?) { if (Array.isArray(href)) { [href, base] = href; } //console.log(222, [href, base]); super([href && href.toString(), base ? base.toString() : undefined]); this._query = new URLSearchParamsImpl(this._query, { doNotStripQMark: true, }); //console.log(this._query); } static create(href, base?) { return new this(href, base); } get searchParams(): URLSearchParamsImplCore { return this._query; } get [Symbol.toStringTag]() { return 'URLImpl'; } inspect() { let name = this[Symbol.toStringTag]; return `${name}("${this.toString()}")`; } toJSON() { return this.href; } toString() { return this.href; } toObject() { const self = this; return Object.keys(self).reduce(function (ret, k) { ret[k] = self[k]; return ret; }, {} as URLImplCore.IURL); } static isValidURLObject(url) { return isValidURLObject(url); } } export import IURL = URLImplCore.IURL; export import IURL2 = URLImplCore.IURL2; export import IImpl = URLImplCore.IImpl; export import IStaticURL = URLImplCore.IStaticURL; export module URLImplCore { export interface IImpl { scheme: string, username: string, password: string, host: string, port, path: string[], query: string, fragment, cannotBeABaseURL: boolean, } export interface IURL { href: string; origin: string; protocol: string; username: string; password: string; host: string; hostname: string; port: string; pathname: string; search: string; hash: string; searchParams?: IURLSearchParams; } export interface IURL2 { _query?: IURLSearchParams; _url?: URLImplCore.IImpl; } export interface IStaticURL<T> extends ClassProxyStatic<T> { new (href: Array<T | string>): T; new (href: T | string, base?: T | string): T; new (href: any, base?: any): T; create(href: Array<T | string>): T; create(href: T | string, base?: T | string): T; create(href: any, base?: any): T; } } export function packProxyURL<T>(classURL: URLImplCore.IStaticURL<T>) { return createClassProxy(classURL, { get(target, name) { return target[name]; }, set(target, prop, value, receiver) { if (prop == '_query') { value._url = target; //console.log(value); } target[prop] = value; return true; }, ownKeys(target): string[] { return [ 'href', 'origin', 'protocol', 'username', 'password', 'host', 'hostname', 'port', 'pathname', 'search', 'hash', 'searchParams', ]; }, getOwnPropertyDescriptor(target, prop) { return { value: target[prop], enumerable: this.ownKeys(target).includes(prop), configurable: true, }; }, /* construct(target, args) { return new target(...args); }, */ } as IClassProxyHandler) as URLImplCore.IStaticURL<T>; } export const URLImpl = packProxyURL(URLImplCore); /* let url = new URLImpl(['https://www.npmjs.com/package/dgeni?l=1&l=2&k=kkk']); let url3 = new URLImplProxy([url]); console.log(url); console.log(url3, url3 instanceof WURLImpl); //console.log(Object.keys(url)); //console.log(Object.keys(url3)); console.dir(url); console.dir(url3); console.dir(url3._url); //console.dir(url); */ export default URLImpl;
a54fd7d6481b5c906b06da4b471e8705b57c0e4e
TypeScript
imjoshellis/ticketapp.dev
/tickets/src/routes/__test__/show.test.ts
2.671875
3
import req from 'supertest' import { app } from '../../app' import { generateUserCookie } from '../../test/setup' import mongoose from 'mongoose' it('returns 404 if the id is invalid format', async () => { await req(app) .get('/api/tickets/ieawfhtiaehrstawftieharst') .expect(404) }) it('returns 404 if the id is valid format but not found', async () => { const id = mongoose.Types.ObjectId().toHexString() await req(app) .get('/api/tickets/' + id) .expect(404) }) it('returns the ticket if the ticket is found', async () => { const title = 'title' const price = 10 const createRes = await req(app) .post('/api/tickets') .set('Cookie', generateUserCookie()) .send({ title, price }) .expect(201) const showRes = await req(app) .get('/api/tickets/' + createRes.body.id) .expect(200) expect(showRes.body.title).toEqual(title) expect(showRes.body.price).toEqual(price) })
2f0fed017145640a14da45838f35b1f291bb2393
TypeScript
HiroakiMikami/micro-versioning-systems
/src/graph.ts
3.484375
3
import { ConstrainedData } from "./common" /** Constraints of the directed graph */ type Predicate<V, L> = (self: DirectedGraph<V, L>) => string | null /** A labeled directed graph */ interface DirectedGraph<V, L> { /** The vertex set */ readonly vertices: ReadonlySet<V>; /** The edge set (there is a v1 -> v2 edge with label `l` if this.edges.get(v1) contains (v2, l)) */ readonly edges: ReadonlyMap<V, ReadonlyMap<V, L>>; /** * @param v * @returns The successors of `v` with labels of the edges */ successors(v: V): ReadonlyMap<V, L>; } /** * @param vertices The vertex set * @param edges The edge set (there is a v1 -> v2 edge with label `l` if this.edges.get(v1) contains (v2, l)) * @param pred The user defined constraint * @returns The error message */ function validate<V, L>(vertices: ReadonlySet<V>, edges: ReadonlyMap<V, ReadonlyMap<V, L>>, pred?: Predicate<V, L>): string | null { /* Invalid if an edge connects vertices that are not in this.vertices */ for (const edge of edges) { const [v1, vs] = edge if (!vertices.has(v1)) { return `the vertex (${v1}) is not in the vertices set` } for (const v of vs) { const v2 = v[0] if (!vertices.has(v2)) { return `the vertex (${v2}) is not in the vertices set` } } } if (pred) { return pred(new ImmutableDirectedGraph(vertices, edges)) // eslint-disable-line @typescript-eslint/no-use-before-define } return null } /** A immutable labeled directed graph */ class ImmutableDirectedGraph<V, L> extends ConstrainedData { /** * @param vertices The vertex set * @param edges The edge set (there is a v1 -> v2 edge with label `l` if this.edges.get(v1) contains (v2, l)) * @param pred The user defined constraint */ constructor(public readonly vertices: ReadonlySet<V>, public readonly edges: ReadonlyMap<V, ReadonlyMap<V, L>>, protected readonly pred?: Predicate<V, L>) { super(() => validate(vertices, edges, pred)) } public successors(v: V): ReadonlyMap<V, L> { return this.edges.has(v) ? this.edges.get(v) : new Map() } } /** A mutable labeled directed graph */ class MutableDirectedGraph<V, L> extends ConstrainedData { /** * @param vertices The vertex set * @param edges The edge set (there is a v1 -> v2 edge with label `l` if this.edges.get(v1) contains (v2, l)) * @param pred The user defined constraint */ constructor(public readonly vertices: Set<V>, public readonly edges: Map<V, Map<V, L>>, protected readonly pred?: Predicate<V, L>) { super(() => validate(vertices, edges, pred)) } public successors(v: V): ReadonlyMap<V, L> { return this.edges.has(v) ? this.edges.get(v) : new Map() } /** * @param v The vertex to be added */ public addVertex(v: V): void { this.vertices.add(v) } /** * @param v The vertex to be removed */ public removeVertex(v: V): void { this.vertices.delete(v) this.edges.delete(v) const tmp = [] for (const elem of this.edges) { if (elem[1].has(v)) { tmp.push([elem[0], v]) } } for (const [v1, v2] of tmp) { this.removeEdge(v1, v2) } } /** * @param v1 The endpoint vertex of the edge to be added (1) * @param v2 The endpoint vertex of the edge to be added (2) * @param label The label of the edge to be added */ public addEdge(v1: V, v2: V, label: L): void { if (!this.edges.has(v1)) { this.edges.set(v1, new Map([[v2, label]])) } else { this.edges.get(v1).set(v2, label) } } /** * @param v1 The endpoint vertex of the edge to be removed(1) * @param v2 The endpoint vertex of the edge to be removed (2) */ public removeEdge(v1: V, v2: V): void { if (!this.edges.has(v1)) return this.edges.get(v1).delete(v2) if (this.edges.get(v1).size == 0) { this.edges.delete(v1) } } } /** * @returns The immutable object of the graph */ function toImmutable<V, L>(graph: DirectedGraph<V, L>): ImmutableDirectedGraph<V, L> { const edges = new Map() for (const [v1, vs] of graph.edges) { edges.set(v1, new Map(Array.from(vs))) } return new ImmutableDirectedGraph<V, L>(new Set(Array.from(graph.vertices)), edges) } /** * @returns The mutable object of the graph */ function toMutable<V, L>(graph: DirectedGraph<V, L>): MutableDirectedGraph<V, L> { const edges = new Map() for (const [v1, vs] of graph.edges) { edges.set(v1, new Map(Array.from(vs))) } return new MutableDirectedGraph<V, L>(new Set(Array.from(graph.vertices)), edges) } export { Predicate, DirectedGraph, ImmutableDirectedGraph, MutableDirectedGraph, toImmutable, toMutable }