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
7407b094872b697d55601b9d0d0973ed11502ea1
TypeScript
si-saude/saude-app
/src/app/controller/equipe/equipe.builder.ts
2.609375
3
import { Equipe } from './../../model/equipe'; import { ProfissionalSaudeBuilder } from './../profissional-saude/profissional-saude.builder'; import { Profissional } from './../../model/profissional'; import { EmpregadoBuilder } from './../empregado/empregado.builder'; import { Empregado } from './../../model/empregado'; import { GenericBuilder } from './../../generics/generic.builder'; export class EquipeBuilder extends GenericBuilder { initialize( equipe: Equipe ) { equipe = new Equipe(); equipe.setCoordenador(new Profissional()); equipe.getCoordenador().setEmpregado(new EmpregadoBuilder().initialize(new Empregado())); return equipe; } initializeList( equipes: Array<Equipe> ) { let array: Array<Equipe> = new Array<Equipe>(); if ( equipes === null || equipes === undefined ) equipes = new Array<Equipe>(); for ( let equipe of equipes ) { array.push( this.initialize( equipe ) ); } return array; } clone( equipe: Equipe ): Equipe { if ( equipe === null || equipe === undefined ) equipe = new Equipe(); let cloneEquipe: Equipe = new Equipe(); cloneEquipe.setId( this.getValue( equipe, "getId" ) ); cloneEquipe.setNome( this.getValue( equipe, "getNome" ) ); cloneEquipe.setAbreviacao( this.getValue( equipe, "getAbreviacao" ) ); cloneEquipe.setPrioridadeSast( this.getValue( equipe, "getPrioridadeSast" ) ) cloneEquipe.setVersion( this.getValue( equipe, "getVersion" ) ); if ( this.getValue( equipe, "getCoordenador" ) !== undefined ) { if ( this.getValue(this.getValue( equipe, "getCoordenador" ), "getId") > 0 ) cloneEquipe.setCoordenador( new ProfissionalSaudeBuilder().clone( this.getValue( equipe, "getCoordenador" ) ) ); else cloneEquipe.setCoordenador( undefined ); } else { cloneEquipe.setCoordenador( new ProfissionalSaudeBuilder().initialize( null ) ); } return cloneEquipe; } cloneList( equipes: Array<Equipe> ): Array<Equipe> { let array: Array<Equipe> = new Array<Equipe>(); if ( equipes !== null && equipes !== undefined ) { for ( let equipe of equipes ) { array.push( this.clone( equipe ) ); } } return array; } }
0df632c1c35ef800211f3c3b65dac38e2e12bce1
TypeScript
AbdulMoiz8994/NinjaTSPRactice
/src/index.ts
3.890625
4
let names = "Abdul moiz"; let value=12; let isTure=true; names="Abdul Rafay" console.log(names); let arr=["Abdul moiz", "Abdul Rafay", "Abdul Malik" ,"Rizwan"] // we cna not assign the number and any type here arr.push("Abdu basit") arr[0]="Whadan" console.log(arr); let arr1=["Abdul moiz", 1, true]; let arr2: string[]=[]; arr2=["Abdul moiz", "Khanzada"] let nameFirst:string="Abdulllah" let NumberFirst:number; NumberFirst=1 let arr4: (string | boolean)[]=[]; arr4=["Abdul Moiz"] console.log(arr); let arr3: string | boolean; // arr3=true // arr3=1 let obj={ Name:" Abduo moiz", fatherNmae: "zafar ali", age: 20 } console.log(obj.age); let obj1:{ firstName?: string, lastName: number, isAge: number, isTure: boolean } // obj1.firstName="Names"; // obj1.isAge=12 obj1={ // firstName: "moiz", lastName: 10, isAge: 24, isTure: false } let ninija: object; ninija=[{Firts: "moiz"}] console.log(ninija); ninija={ from1: "Abdul moiz", from2: 12, form3: ["moiz"] }; console.log(ninija); let object3:{ firstName: string, lastName: string id: number, }; object3={ firstName: "Abdul moiz", lastName: "khanzada", id:12 }
40ddc16d1ef8921fef8d5bbaededbd58648b42b6
TypeScript
macastilhos/typescript-crud-api
/src/controllers/records.ts
2.6875
3
import { Repository } from 'typeorm'; import { Request, Response } from 'express'; import { validate } from 'class-validator'; export const recordsController = <T>(repository: Repository<T>) => { const wrap = (fn: Function) => { return (req: Request, res: Response) => { fn(req, res).catch((e: Error) => { res.status(400).send(e); }); }; }; const findAll = wrap(async (req: Request, res: Response) => { // return all records const results = await repository.find(req.query); return res.send(results); }); const findOne = wrap(async (req: Request, res: Response) => { // return one record by id const results = await repository.findOne(req.params.id, req.query); return res.send(results); }); const create = wrap(async (req: Request, res: Response) => { // create a new record const record = repository.create(req.body); const validation = await validate(record); if (validation.length) { return res.status(422).send({ validation }); } const results = await repository.save(record); return res.send(results); }); const update = wrap(async (req: Request, res: Response) => { // update a record by a given id const record = await repository.findOne(req.params.id); repository.merge(record, req.body); const results = await repository.save(record); return res.send(results); }); const remove = wrap(async (req: Request, res: Response) => { // delete a record by a given id const results = await repository.delete(req.params.id); return res.send(results); }); return { findAll, findOne, create, update, remove }; };
75c84e6ba0546fa6a4672d65766afd91a9d11201
TypeScript
satyakranthi1/Foodie
/serverless/src/businessLogic/s3Helper.ts
2.515625
3
import * as AWS from 'aws-sdk' import * as AWSXRay from 'aws-xray-sdk' import { createLogger } from '../utils/logger' const bucketName = process.env.IMAGES_S3_BUCKET const urlExpiration = parseInt(process.env.SIGNED_URL_EXPIRATION, 10) const XAWS = AWSXRay.captureAWS(AWS) const logger = createLogger('S3Helper') const s3 = new XAWS.S3({ signatureVersion: 'v4' }) export class S3Helper { async GenerateUploadUrl(reviewId: string) { try { const uploadUrl = s3.getSignedUrl('putObject', { Bucket: bucketName, Key: reviewId, Expires: urlExpiration }) logger.info(`uploadUrl is ${uploadUrl}`) return uploadUrl } catch(err) { logger.error(`get signed url failed: ${JSON.stringify(err)}`) throw new Error('get signed url failed') } } async getImage(reviewId: string) { try { const s3Object = await s3.getObject({ Bucket: bucketName, Key: reviewId }).promise() return s3Object.Body } catch(err) { logger.error(`get image failed: ${JSON.stringify(err)}`) throw new Error('get image failed') } } async putImage(imageBuffer: Buffer, reviewId: string) { try { const key = `thumbnails/${reviewId}` await s3.putObject({ Bucket: bucketName, Key: key, Body: imageBuffer }).promise() logger.info(`putImage successful Key: ${key}`) } catch(err) { logger.error(`put image failed: ${JSON.stringify(err)}`) throw new Error('put image failed') } } }
8c7892621de8601785d953b1c99f72ab9bf519c7
TypeScript
Rawan-Eltobgy/react-redux-saga-typescript-boilerplate
/src/types/action.ts
2.859375
3
import { ActionTypes } from "literals"; import { Action } from 'redux' export interface UserLoginPayload { username: string; password: string; } export interface UserLoginSuccessPayload { loginToken: string; } export interface UserLoginFailurePayload { error: Error; } export interface UserLoginRequest extends Action { type: ActionTypes.USER_LOGIN_REQUEST; // !! here we assign the string literal type of the constant payload: UserLoginPayload } export interface UserLoginSuccess extends Action { type: ActionTypes.USER_LOGIN_SUCCESS; // !! here we assign the string literal type of the constant payload: UserLoginSuccessPayload } export function loginSuccess(loginToken: string): UserLoginSuccess { return { type: ActionTypes.USER_LOGIN_SUCCESS, payload: { loginToken }, }; } export interface UserLoginFailure extends Action { type: ActionTypes.USER_LOGIN_FAILURE; // !! here we assign the string literal type of the constant payload: UserLoginFailurePayload } export interface User { username: string; password: string; loginToken: string; loginError?: Error; status?: number; } export type UsersActions = | UserLoginSuccess | UserLoginFailure | UserLoginRequest;
d801f78e9d4a240b202b713799413e5d37689611
TypeScript
shiqingsong715/solana-program-demo
/src/client/main.ts
2.515625
3
import { LAMPORTS_PER_SOL } from '@solana/web3.js'; import { establishConnection, calculatePayfees, establishPayer, loadProgram, storeNumber, getNumber, } from './demo'; const solPath = 'dist/program/demo.so'; function randNumber(): number { let num = Math.random() * 100; return parseInt(num + ''); } async function main() { try { console.log("Establish connection..."); const res = await establishConnection('http://localhost:8899'); console.log("Connection to cluster established: ", res.version); const { connection } = res; console.log("Caculate pay for fees..."); const fees = await calculatePayfees(solPath, connection); console.log("Fees:", fees / LAMPORTS_PER_SOL); console.log("Establish payer..."); const payer = await establishPayer(fees, connection); console.log("Using account ", payer.publicKey.toBase58(), " to load the program."); const program = await loadProgram(solPath, payer, connection); const { programId, pubkey } = program; console.log('Program loaded to account:', programId.toBase58()); console.log('And created account: ', pubkey.toBase58(), 'to demonstrate the demo.'); let num = randNumber(); console.log("Prepare to store the number: ", num); await storeNumber(num + '', pubkey, programId, payer, connection); console.log("Stored number success!"); let storedNum = await getNumber(pubkey, connection); console.log("Get stored number from the chain: ", storedNum); } catch(err) { console.log(err); } } main();
b4155f5e6a16d270b90be2d181d25b6b079249a8
TypeScript
estruyf/vscode-front-matter
/src/utils/fieldWhenClause.ts
3.171875
3
import { WhenClause } from './../models/PanelSettings'; import { Field, WhenOperator } from '../models'; import { IMetadata } from '../panelWebView/components/Metadata'; /** * Validate the field its "when" clause * @param field * @param parent * @returns */ export const fieldWhenClause = (field: Field, parent: IMetadata): boolean => { const when = field.when; if (!when) { return true; } let whenValue = parent[when.fieldRef]; if (when.caseSensitive || typeof when.caseSensitive === 'undefined') { return caseSensitive(when, field, whenValue); } else { return caseInsensitive(when, field, whenValue); } }; /** * Case sensitive checks * @param when * @param field * @param whenValue * @returns */ const caseInsensitive = ( when: WhenClause, field: Field, whenValue: string | IMetadata | string[] | null ) => { whenValue = lowerValue(whenValue); const whenClone = Object.assign({}, when); whenClone.value = lowerValue(whenClone.value); return caseSensitive(whenClone, field, whenValue); }; /** * Case insensitive checks * @param when * @param field * @param whenValue * @returns */ const caseSensitive = ( when: WhenClause, field: Field, whenValue: string | IMetadata | string[] | null ) => { switch (when.operator) { case WhenOperator.equals: if (whenValue !== when.value) { return false; } break; case WhenOperator.notEquals: if (whenValue === when.value) { return false; } break; case WhenOperator.contains: if ( (typeof whenValue === 'string' || whenValue instanceof Array) && !whenValue.includes(when.value) ) { return false; } break; case WhenOperator.notContains: if ( (typeof whenValue === 'string' || whenValue instanceof Array) && whenValue.includes(when.value) ) { return false; } break; case WhenOperator.startsWith: if (typeof whenValue === 'string' && !whenValue.startsWith(when.value)) { return false; } break; case WhenOperator.endsWith: if (typeof whenValue === 'string' && !whenValue.endsWith(when.value)) { return false; } break; case WhenOperator.greaterThan: if (typeof whenValue === 'number' && whenValue <= when.value) { return false; } break; case WhenOperator.greaterThanOrEqual: if (typeof whenValue === 'number' && whenValue < when.value) { return false; } break; case WhenOperator.lessThan: if (typeof whenValue === 'number' && whenValue >= when.value) { return false; } break; case WhenOperator.lessThanOrEqual: if (typeof whenValue === 'number' && whenValue > when.value) { return false; } break; default: break; } return true; }; /** * Lower the value(s) * @param value * @returns */ const lowerValue = (value: string | string[] | any) => { if (typeof value === 'string') { value = value.toLowerCase(); } else if (value instanceof Array) { value = value.map((crntValue) => { if (typeof crntValue === 'string') { return crntValue.toLowerCase(); } return crntValue; }); } return value; };
75ab80dcd389e3db7e77a2d3ab53a098b668d3da
TypeScript
bgoonz/UsefulResourceRepo2.0
/_GENERAL/FIREBASE/notes/firebase-tools/src/test/extensions/askUserForConsent.spec.ts
2.53125
3
"use strict"; import * as _ from "lodash"; import * as clc from "cli-color"; import * as chai from "chai"; chai.use(require("chai-as-promised")); import * as sinon from "sinon"; import * as askUserForConsent from "../../extensions/askUserForConsent"; import * as iam from "../../gcp/iam"; import * as resolveSource from "../../extensions/resolveSource"; import * as extensionHelper from "../../extensions/extensionsHelper"; const expect = chai.expect; describe("askUserForConsent", () => { describe("formatDescription", () => { let getRoleStub: sinon.SinonStub; beforeEach(() => { getRoleStub = sinon.stub(iam, "getRole"); getRoleStub.rejects("UNDEFINED TEST BEHAVIOR"); }); afterEach(() => { getRoleStub.restore(); }); const roles = ["storage.objectAdmin", "datastore.viewer"]; it("format description correctly", () => { const extensionName = "extension-for-test"; const projectId = "project-for-test"; const question = `${clc.bold( extensionName )} will be granted the following access to project ${clc.bold(projectId)}`; const storageRole = { title: "Storage Object Admin", description: "Full control of GCS objects.", }; const datastoreRole = { title: "Cloud Datastore Viewer", description: "Read access to all Cloud Datastore resources.", }; const storageDescription = "- Storage Object Admin (Full control of GCS objects.)"; const datastoreDescription = "- Cloud Datastore Viewer (Read access to all Cloud Datastore resources.)"; const expected = _.join([question, storageDescription, datastoreDescription], "\n"); getRoleStub.onFirstCall().resolves(storageRole); getRoleStub.onSecondCall().resolves(datastoreRole); const actual = askUserForConsent.formatDescription(extensionName, projectId, roles); return expect(actual).to.eventually.deep.equal(expected); }); }); });
ca09680c79fe39291bd59567f8d8c748b4cd57a2
TypeScript
destiaarti/inventoryCI
/assets/tinymce/src/core/main/ts/fmt/Preview.ts
2.515625
3
/** * Preview.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ import DOMUtils from '../api/dom/DOMUtils'; import Tools from '../api/util/Tools'; import Schema from '../api/html/Schema'; /** * Internal class for generating previews styles for formats. * * Example: * Preview.getCssText(editor, 'bold'); * * @private * @class tinymce.fmt.Preview */ const each = Tools.each; const dom = DOMUtils.DOM; const parsedSelectorToHtml = function (ancestry, editor) { let elm, item, fragment; const schema = editor && editor.schema || Schema({}); const decorate = function (elm, item) { if (item.classes.length) { dom.addClass(elm, item.classes.join(' ')); } dom.setAttribs(elm, item.attrs); }; const createElement = function (sItem) { let elm; item = typeof sItem === 'string' ? { name: sItem, classes: [], attrs: {} } : sItem; elm = dom.create(item.name); decorate(elm, item); return elm; }; const getRequiredParent = function (elm, candidate) { const name = typeof elm !== 'string' ? elm.nodeName.toLowerCase() : elm; const elmRule = schema.getElementRule(name); const parentsRequired = elmRule && elmRule.parentsRequired; if (parentsRequired && parentsRequired.length) { return candidate && Tools.inArray(parentsRequired, candidate) !== -1 ? candidate : parentsRequired[0]; } else { return false; } }; const wrapInHtml = function (elm, ancestry, siblings) { let parent, parentCandidate, parentRequired; const ancestor = ancestry.length > 0 && ancestry[0]; const ancestorName = ancestor && ancestor.name; parentRequired = getRequiredParent(elm, ancestorName); if (parentRequired) { if (ancestorName === parentRequired) { parentCandidate = ancestry[0]; ancestry = ancestry.slice(1); } else { parentCandidate = parentRequired; } } else if (ancestor) { parentCandidate = ancestry[0]; ancestry = ancestry.slice(1); } else if (!siblings) { return elm; } if (parentCandidate) { parent = createElement(parentCandidate); parent.appendChild(elm); } if (siblings) { if (!parent) { // if no more ancestry, wrap in generic div parent = dom.create('div'); parent.appendChild(elm); } Tools.each(siblings, function (sibling) { const siblingElm = createElement(sibling); parent.insertBefore(siblingElm, elm); }); } return wrapInHtml(parent, ancestry, parentCandidate && parentCandidate.siblings); }; if (ancestry && ancestry.length) { item = ancestry[0]; elm = createElement(item); fragment = dom.create('div'); fragment.appendChild(wrapInHtml(elm, ancestry.slice(1), item.siblings)); return fragment; } else { return ''; } }; const selectorToHtml = function (selector, editor?) { return parsedSelectorToHtml(parseSelector(selector), editor); }; const parseSelectorItem = function (item) { let tagName; const obj: any = { classes: [], attrs: {} }; item = obj.selector = Tools.trim(item); if (item !== '*') { // matching IDs, CLASSes, ATTRIBUTES and PSEUDOs tagName = item.replace(/(?:([#\.]|::?)([\w\-]+)|(\[)([^\]]+)\]?)/g, function ($0, $1, $2, $3, $4) { switch ($1) { case '#': obj.attrs.id = $2; break; case '.': obj.classes.push($2); break; case ':': if (Tools.inArray('checked disabled enabled read-only required'.split(' '), $2) !== -1) { obj.attrs[$2] = $2; } break; } // atribute matched if ($3 === '[') { const m = $4.match(/([\w\-]+)(?:\=\"([^\"]+))?/); if (m) { obj.attrs[m[1]] = m[2]; } } return ''; }); } obj.name = tagName || 'div'; return obj; }; const parseSelector = function (selector) { if (!selector || typeof selector !== 'string') { return []; } // take into account only first one selector = selector.split(/\s*,\s*/)[0]; // tighten selector = selector.replace(/\s*(~\+|~|\+|>)\s*/g, '$1'); // split either on > or on space, but not the one inside brackets return Tools.map(selector.split(/(?:>|\s+(?![^\[\]]+\]))/), function (item) { // process each sibling selector separately const siblings = Tools.map(item.split(/(?:~\+|~|\+)/), parseSelectorItem); const obj = siblings.pop(); // the last one is our real target if (siblings.length) { obj.siblings = siblings; } return obj; }).reverse(); }; const getCssText = function (editor, format) { let name, previewFrag, previewElm, items; let previewCss = '', parentFontSize, previewStyles; previewStyles = editor.settings.preview_styles; // No preview forced if (previewStyles === false) { return ''; } // Default preview if (typeof previewStyles !== 'string') { previewStyles = 'font-family font-size font-weight font-style text-decoration ' + 'text-transform color background-color border border-radius outline text-shadow'; } // Removes any variables since these can't be previewed const removeVars = function (val) { return val.replace(/%(\w+)/g, ''); }; // Create block/inline element to use for preview if (typeof format === 'string') { format = editor.formatter.get(format); if (!format) { return; } format = format[0]; } // Format specific preview override // TODO: This should probably be further reduced by the previewStyles option if ('preview' in format) { previewStyles = format.preview; if (previewStyles === false) { return ''; } } name = format.block || format.inline || 'span'; items = parseSelector(format.selector); if (items.length) { if (!items[0].name) { // e.g. something like ul > .someClass was provided items[0].name = name; } name = format.selector; previewFrag = parsedSelectorToHtml(items, editor); } else { previewFrag = parsedSelectorToHtml([name], editor); } previewElm = dom.select(name, previewFrag)[0] || previewFrag.firstChild; // Add format styles to preview element each(format.styles, function (value, name) { value = removeVars(value); if (value) { dom.setStyle(previewElm, name, value); } }); // Add attributes to preview element each(format.attributes, function (value, name) { value = removeVars(value); if (value) { dom.setAttrib(previewElm, name, value); } }); // Add classes to preview element each(format.classes, function (value) { value = removeVars(value); if (!dom.hasClass(previewElm, value)) { dom.addClass(previewElm, value); } }); editor.fire('PreviewFormats'); // Add the previewElm outside the visual area dom.setStyles(previewFrag, { position: 'absolute', left: -0xFFFF }); editor.getBody().appendChild(previewFrag); // Get parent container font size so we can compute px values out of em/% for older IE:s parentFontSize = dom.getStyle(editor.getBody(), 'fontSize', true); parentFontSize = /px$/.test(parentFontSize) ? parseInt(parentFontSize, 10) : 0; each(previewStyles.split(' '), function (name) { let value = dom.getStyle(previewElm, name, true); // If background is transparent then check if the body has a background color we can use if (name === 'background-color' && /transparent|rgba\s*\([^)]+,\s*0\)/.test(value)) { value = dom.getStyle(editor.getBody(), name, true); // Ignore white since it's the default color, not the nicest fix // TODO: Fix this by detecting runtime style if (dom.toHex(value).toLowerCase() === '#ffffff') { return; } } if (name === 'color') { // Ignore black since it's the default color, not the nicest fix // TODO: Fix this by detecting runtime style if (dom.toHex(value).toLowerCase() === '#000000') { return; } } // Old IE won't calculate the font size so we need to do that manually if (name === 'font-size') { if (/em|%$/.test(value)) { if (parentFontSize === 0) { return; } // Convert font size from em/% to px const numValue = parseFloat(value) / (/%$/.test(value) ? 100 : 1); value = (numValue * parentFontSize) + 'px'; } } if (name === 'border' && value) { previewCss += 'padding:0 2px;'; } previewCss += name + ':' + value + ';'; }); editor.fire('AfterPreviewFormats'); // previewCss += 'line-height:normal'; dom.remove(previewFrag); return previewCss; }; export default { getCssText, parseSelector, selectorToHtml };
337adb0062749fff5c6019309c7806c472b95abe
TypeScript
satriowinarendro/haloarlo.id
/src/lib/image.ts
2.609375
3
export function createSliderImageUrl(images: string[]){ return images.map((image) => { return { source: image } }) }
f2529998d353ec85cbbaf5fcd5a392b1449eb437
TypeScript
Dimi-Dun-Morogh/school-TS
/src/utils.ts
3.046875
3
const logger = { getTimeStamp: (): string => new Date().toISOString(), info(namespace: string, message: string, object?: any) { if (object) { console.log( `[${this.getTimeStamp()}] [INFO] [${namespace}] [${message}]`, object, ); } else { console.log( `[${this.getTimeStamp()}] [INFO] [${namespace}] [${message}]`, ); } }, }; /* '("55", "female", "33", "{"somecrap":["rrr","xxx"]}", "Red lady")' -- replace " before { with ' */ const fixBracketsJSON = (query: string): string => { let fixed = ''; for (let i = 0; i < query.length; i += 1) { if (query[i + 1] === '[' || query[i - 1] === ']') { fixed += "'"; } else { fixed += query[i]; } } return fixed; }; export { logger, fixBracketsJSON };
994f146076aef6a6da17e5b39c0c22449b7500a1
TypeScript
dolanmiu/docx
/src/file/table/table-width.ts
2.875
3
// http://officeopenxml.com/WPtableWidth.php import { NextAttributeComponent, XmlComponent } from "@file/xml-components"; import { measurementOrPercentValue, Percentage, UniversalMeasure } from "@util/values"; // <xsd:simpleType name="ST_TblWidth"> // <xsd:restriction base="xsd:string"> // <xsd:enumeration value="nil"/> // <xsd:enumeration value="pct"/> // <xsd:enumeration value="dxa"/> // <xsd:enumeration value="auto"/> // </xsd:restriction> // </xsd:simpleType> export enum WidthType { /** Auto. */ AUTO = "auto", /** Value is in twentieths of a point */ DXA = "dxa", /** No (empty) value. */ NIL = "nil", /** Value is in percentage. */ PERCENTAGE = "pct", } // <xsd:complexType name="CT_TblWidth"> // <xsd:attribute name="w" type="ST_MeasurementOrPercent"/> // <xsd:attribute name="type" type="ST_TblWidth"/> // </xsd:complexType> export type ITableWidthProperties = { readonly size: number | Percentage | UniversalMeasure; readonly type?: WidthType; }; export class TableWidthElement extends XmlComponent { public constructor(name: string, { type = WidthType.AUTO, size }: ITableWidthProperties) { super(name); // super("w:tblW"); let tableWidthValue = size; if (type === WidthType.PERCENTAGE && typeof size === "number") { tableWidthValue = `${size}%`; } this.root.push( new NextAttributeComponent<ITableWidthProperties>({ type: { key: "w:type", value: type }, size: { key: "w:w", value: measurementOrPercentValue(tableWidthValue) }, }), ); } }
7962d2e7b6f12f5e4de87c94d9eb07b200b084f3
TypeScript
JulianNymark/jcoin
/Block.ts
3.03125
3
import { Sha256 } from './sha256'; interface BlockContent { serial: number; previousHash: string; data: string; // ledger goes here guess: string; } export class Block { private content: BlockContent; constructor(content: BlockContent) { this.content = content; } public getRawHashee(guess: string): string { this.content.guess = guess; return JSON.stringify(this.content); } public hash = (guess: string): string => { const toHash = this.getRawHashee(guess); const hashed = Sha256.hash(toHash); return hashed; } public verify = (difficulty: number, nextSerial: number, guess: string): boolean => { if (this.content.serial !== nextSerial) { return false; } const hashed = this.hash(guess); if (hashed.startsWith(`0`.repeat(difficulty))) { return true; } return false; } }
baa17b91b04e1b38714e6b0254958d2e8cd66683
TypeScript
mimittqq/playground
/sort.ts
3.984375
4
/** * `冒泡排序法` * 原理是比较相邻的数, 前一个比后一个大就调换位置, 第一趟比较完后最后一个必定是最大的数 */ export function bubbleSort(arr) { const len = arr.length; for (let i = 1; i < len - 1; i++) { for (let j = 0; j < len - i; j++) { let prev = arr[j]; let next = arr[j+1]; if (prev > next) { [arr[j], arr[j+1]] = [arr[j+1], arr[j]]; } } } return arr; } /** * `选择排序法` * 原理是先用第一个元素与其他做比较, 然后选出最小的放在第一位, */ export function selectSort(arr) { for (let i = 0; i < arr.length; i++) { for (let j = i; j < arr.length; j++) { const v1 = arr[i]; const v2 = arr[j]; if (v2 < v1) { [arr[i], arr[j]] = [arr[j], arr[i]]; } } } return arr; } /** * `插入排序法` * 原理是先选择一个数(一般是第一个数), 然后把数组剩下的数字按照大小排列插入到已经排好的这个序列中 */ export function insertSort(arr) { for (let i = 1; i < arr.length; i++) { for (let j = i + 1; j--;) { if (arr[j - 1] > arr[j]) { [arr[j - 1], arr[j]] = [arr[j], arr[j - 1]]; } else { break; } } } return arr; } /** * `快速排序法` * 原理是选择数组中的某个数进行比较, 递归依次把比这个数小的数放在它之前, 比它大的放在之后 */ export function quickSort(nums:number[]) : number[] { if (nums.length <= 1) { return nums; // 递归出口 } const left = []; const right = []; const target = nums.shift(); // 取出数组中第一位作为比较对象, 并去掉数组第一位 for (let i = nums.length; i--;) { const item = nums[i] if (item > target) { right.push(item) } else { left.push(item) } } return [...quickSort(left), target, ...quickSort(right)]; } /** * 堆排序 * 思想: 利用堆结构来进行排序, 此算法实现的是大顶堆 * 大顶堆规则: 每一个根节点都比其左右节点大, 因此大顶堆最大的元素就是根节点 */ export class HeapSort { private arr = []; constructor(arr) { this.arr = arr; } /** * 调整大顶堆的结构, 使其可以合乎大顶堆规则 * @param index 检查的起始下标 * @param heapSize 堆大小 */ maxHeapify(arr, index, heapSize) { let iMax, iLeft, iRight; do { iMax = index; iLeft = this._getLeftNodeIndex(iMax); iRight = this._getRightNodeIndex(iMax); if (arr[iMax] < arr[iLeft] && iLeft < heapSize) { iMax = iLeft; } if (arr[iMax] < arr[iRight] && iRight < heapSize) { iMax = iRight; } // 如果最大数被交换了, 继续调整 if (iMax !== index) { [arr[index], arr[iMax]] = [arr[iMax], arr[index]]; index = iMax; iMax = undefined; } } while (iMax !== index) } /** * 将一个普通数组通过调整转化成大顶堆结构 * @param arr 传入数组 */ buildMaxHeapify(arr) { const heapSize = arr.length; // 注意, 此 iParent 不是指根节点的 index, 而是指创建大顶堆需要开始的下标 // 即倒数第二层最后一个前面是完全排列节点的节点 const iParent = Math.floor((heapSize - 1) / 2); for (let i = iParent; i >= 0; i--) { // 只有比下标小的节点才拥有叶子节点, 才需要调整比较 this.maxHeapify(arr, i, heapSize); } } heapifySort() { const { arr } = this; let size = arr.length; this.buildMaxHeapify(arr); for (let i = size - 1; i > 0; i--) { [arr[i], arr[0]] = [arr[0], arr[i]]; // 把最大数移到数组尾后, 把末尾数移到堆的根节点, 然后末尾数下沉找到自己的位置后又形成堆 this.maxHeapify(arr, 0, --size); } return arr; } _getLeftNodeIndex(index) { return 2 * index + 1; } _getRightNodeIndex(index) { return 2 * (index + 1); } }
9098397932aa88ed1e1571c30be97b8a94efefb4
TypeScript
Ellesent/react-native-queue
/dist/Models/Worker.d.ts
3.25
3
/** * * Worker Model * */ export default class Worker { /** * * Singleton map of all worker functions assigned to queue. * */ static workers: {}; /** * * Assign a worker function to the queue. * * Worker will be called to execute jobs associated with jobName. * * Worker function will receive job id and job payload as parameters. * * Example: * * function exampleJobWorker(id, payload) { * console.log(id); // UUID of job. * console.log(payload); // Payload of data related to job. * } * * @param jobName {string} - Name associated with jobs assigned to this worker. * @param worker {function} - The worker function that will execute jobs. * @param options {object} - Worker options. See README.md for worker options info. */ addWorker(jobName: string, worker: Function, options?: object): void; /** * * Un-assign worker function from queue. * * @param jobName {string} - Name associated with jobs assigned to this worker. */ removeWorker(jobName: string): void; /** * * Get the concurrency setting for a worker. * * Worker concurrency defaults to 1. * * @param jobName {string} - Name associated with jobs assigned to this worker. * @throws Throws error if no worker is currently assigned to passed in job name. * @return {number} */ getConcurrency(jobName: string): number; /** * * Execute the worker function assigned to the passed in job name. * * If job has a timeout setting, job will fail with a timeout exception upon reaching timeout. * * @throws Throws error if no worker is currently assigned to passed in job name. * @param job {object} - Job realm model object */ executeJob(job: object): Promise<void>; /** * * Execute an asynchronous job lifecycle callback associated with related worker. * * @param callbackName {string} - Job lifecycle callback name. * @param jobName {string} - Name associated with jobs assigned to related worker. * @param jobId {string} - Unique id associated with job. * @param jobPayload {object} - Data payload associated with job. */ executeJobLifecycleCallback(callbackName: string, jobName: string, jobId: string, jobPayload: object): Promise<void>; }
67c3ae92aabd107c3a1484e8bac4a7be5b2134d0
TypeScript
KcirePunk/angular-templated
/src/app/services/productos.service.ts
2.53125
3
import { Injectable, ɵConsole } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Producto } from '../interfaces/product.interfaces'; @Injectable({ providedIn: 'root' }) export class ProductosService { loading = true; producto: Producto[] = []; productoFiltrado: Producto[] = []; constructor(private http: HttpClient) { this.cargarProducto(); } private cargarProducto(){ return new Promise((resolve, reject) => { this.http.get('https://angular-templated.firebaseio.com/productos_idx.json') .subscribe( (res:Producto[]) => { this.loading = false; this.producto = res; resolve(); }); }); } getProducto(id: string){ return this.http.get(`https://angular-templated.firebaseio.com/productos/${id}.json`); } buscarProducto(termino: string){ if(this.producto.length == 0){ // cargar productos this.cargarProducto().then(()=> { // ejecutar despues de tener los productos // aplicar fultro this.filtrarProducto(termino); }); }else { this.filtrarProducto(termino); } } private filtrarProducto(termino: string){ console.log(this.producto); this.productoFiltrado = []; termino = termino.toLocaleLowerCase(); this.producto.forEach(prod => { const tituloLo = prod.titulo.toLowerCase(); if(prod.categoria.indexOf(termino) >= 0 || tituloLo.indexOf(termino) >= 0){ this.productoFiltrado.push(prod); } }); } }
e4ee4c7bbde97e78a49c2d383e3cc0b285460b39
TypeScript
keystonejs/keystone
/tests/api-tests/fields/types/fixtures/select/test-fixtures.ts
2.59375
3
import { select } from '@keystone-6/core/fields'; type MatrixValue = typeof testMatrix[number]; export const name = 'Select'; export const typeFunction = select; export const exampleValue = (matrixValue: MatrixValue) => matrixValue === 'enum' ? 'thinkmill' : matrixValue === 'string' ? 'a string' : 1; export const exampleValue2 = (matrixValue: MatrixValue) => matrixValue === 'enum' ? 'atlassian' : matrixValue === 'string' ? '1number' : 2; export const supportsNullInput = true; export const supportsUnique = true; export const supportsDbMap = true; export const fieldConfig = (matrixValue: MatrixValue) => { if (matrixValue === 'enum' || matrixValue === 'string') { return { type: matrixValue, options: matrixValue === 'enum' ? [ { label: 'Thinkmill', value: 'thinkmill' }, { label: 'Atlassian', value: 'atlassian' }, { label: 'Thomas Walker Gelato', value: 'gelato' }, { label: 'Cete, or Seat, or Attend ¯\\_(ツ)_/¯', value: 'cete' }, { label: 'React', value: 'react' }, ] : matrixValue === 'string' ? [ { label: 'A string', value: 'a string' }, { label: 'Another string', value: 'another string' }, { label: '1number', value: '1number' }, { label: '@¯\\_(ツ)_/¯', value: '@¯\\_(ツ)_/¯' }, { label: 'something else', value: 'something else' }, ] : [], }; } return { type: matrixValue, options: [ { label: 'One', value: 1 }, { label: 'Two', value: 2 }, { label: 'Three', value: 3 }, { label: 'Four', value: 4 }, { label: 'Five', value: 5 }, ], }; }; export const fieldName = 'company'; export const testMatrix = ['enum', 'string', 'integer'] as const; export const getTestFields = (matrixValue: MatrixValue) => ({ company: select(fieldConfig(matrixValue)), }); export const initItems = (matrixValue: MatrixValue) => { if (matrixValue === 'enum') { return [ { name: 'a', company: 'thinkmill' }, { name: 'b', company: 'atlassian' }, { name: 'c', company: 'gelato' }, { name: 'd', company: 'cete' }, { name: 'e', company: 'react' }, { name: 'f', company: null }, { name: 'g' }, ]; } else if (matrixValue === 'string') { return [ { name: 'a', company: 'a string' }, { name: 'b', company: '@¯\\_(ツ)_/¯' }, { name: 'c', company: 'another string' }, { name: 'd', company: '1number' }, { name: 'e', company: 'something else' }, { name: 'f', company: null }, { name: 'g' }, ]; } else if (matrixValue === 'integer') { return [ { name: 'a', company: 1 }, { name: 'b', company: 2 }, { name: 'c', company: 3 }, { name: 'd', company: 4 }, { name: 'e', company: 5 }, { name: 'f', company: null }, { name: 'g' }, ]; } return []; }; export const storedValues = (matrixValue: MatrixValue) => { if (matrixValue === 'enum') { return [ { name: 'a', company: 'thinkmill' }, { name: 'b', company: 'atlassian' }, { name: 'c', company: 'gelato' }, { name: 'd', company: 'cete' }, { name: 'e', company: 'react' }, { name: 'f', company: null }, { name: 'g', company: null }, ]; } else if (matrixValue === 'string') { return [ { name: 'a', company: 'a string' }, { name: 'b', company: '@¯\\_(ツ)_/¯' }, { name: 'c', company: 'another string' }, { name: 'd', company: '1number' }, { name: 'e', company: 'something else' }, { name: 'f', company: null }, { name: 'g', company: null }, ]; } else if (matrixValue === 'integer') { return [ { name: 'a', company: 1 }, { name: 'b', company: 2 }, { name: 'c', company: 3 }, { name: 'd', company: 4 }, { name: 'e', company: 5 }, { name: 'f', company: null }, { name: 'g', company: null }, ]; } };
f67fd7887eff077f3104030026ab90a95d629fa8
TypeScript
aohanhe/swallow3-web-admin
/src/views/components/data-dialog/data-dialog-mix.ts
2.703125
3
/** * 数据对话框 共用属性与操作 */ import { Prop, Vue, Component } from 'vue-property-decorator' import { objectCopy } from '@/libs/common-tools.js' import { DataDialogOperts, DataDialogMode } from '@/views/components/data-dialog/data-dialog-def' @Component({ components:{} }) export default class DataDialogMix extends Vue implements DataDialogOperts { /** * 显示新增对话框 */ showAddNewDlg () { let dlg=this.$refs.dlg as any let that=this as any that.dlgData={} // 清空初始数据 dlg.showDlg(DataDialogMode.AddNew) } /** * 显示指定模式的对话框 * @param mode * @param data */ showDlg (mode:DataDialogMode, data:any) { let dlg=this.$refs.dlg as any let that=this as any that.dlgData=objectCopy(data) dlg.showDlg(mode) } // 刷新打开对应的数据列表的数据 freshDataList () { console.log('dofresh') this.$emit('onFreshDataList') } }
a01bd4ccf5c44a467e600060cbec05918a74eb59
TypeScript
hallh/ngx-segment-analytics
/dist/ngx-segment-analytics.service.d.ts
2.8125
3
import { WindowWrapper } from './ngx-segment-analytics.module'; import { SegmentConfig } from './ngx-segment-analytics.config'; /** @dynamic */ export declare class SegmentService { private w; private doc; private config; /** * @param w Browser window * @param doc Browser DOM * @param config Segment configuration */ constructor(w: WindowWrapper, doc: Document, config: SegmentConfig); /** * The identify method is how you associate your users and their actions to a recognizable userId and traits. * * @param userId The database ID for the user. * @param traits A dictionary of traits you know about the user, like their email or name * @param options A dictionary of options. * * @returns */ identify(userId?: string, traits?: any, options?: any): Promise<SegmentService>; /** * The track method lets you record any actions your users perform. * * @param event The name of the event you’re tracking. * @param properties A dictionary of properties for the event. * @param options A dictionary of options. * * @returns */ track(event: string, properties?: any, options?: any): Promise<SegmentService>; /** * The page method lets you record page views on your website, along with optional extra information about the page being viewed. * * @param name The name of the page. * @param properties A dictionary of properties of the page. * @param options A dictionary of options. * * @returns */ page(name?: string, properties?: any, options?: any): Promise<SegmentService>; /** * The page method lets you record page views on your website, along with optional extra information about the page being viewed. * * @param category The category of the page. * @param name The name of the page. * @param properties A dictionary of properties of the page. * @param options A dictionary of options. * * @returns */ page(category: string, name: string, properties?: any, options?: any): Promise<SegmentService>; /** * The group method associates an identified user with a company, organization, project, workspace, team, tribe, platoon, * assemblage, cluster, troop, gang, party, society or any other name you came up with for the same concept. * * @param groupId The Group ID to associate with the current user. * @param traits A dictionary of traits for the group. * * @returns */ group(groupId: string, traits?: any): Promise<SegmentService>; /** * The alias method combines two previously unassociated user identities. * * @param userId The new user ID you want to associate with the user. * @param previousId The previous ID that the user was recognized by. This defaults to the currently identified user’s ID. * @param options A dictionary of options. * * @returns */ alias(userId: string, previousId?: string, options?: any): Promise<SegmentService>; /** * The ready method allows you execute a promise that will be called as soon as all of your enabled destinations have loaded * and analytics.js has completed initialization. * * @returns */ ready(): Promise<SegmentService>; /** * Return informations about the currently identified user * * @returns Informations about the currently identified user */ user(): any; /** * Return identifier about the currently identified user * * @returns Identifier about the currently identified user */ id(): string | null; /** * Return traits about the currently identified user * * @returns Traits about the currently identified user */ traits(): any; /** * Reset the id, including anonymousId, and clear traits for the currently identified user and group. */ reset(): void; /** * Turn on/off debug mode, logging helpful messages to the console. * * @param enabled Enable or not the debug mode */ debug(enabled?: boolean): void; /** * Set listeners for these events and run your own custom code. * * @param method Name of the method to listen for * @param callback A function to execute after each the emitted method */ on(method: string, callback: (event?: string, properties?: any, options?: any) => any): void; /** * Attaches the `track` call as a handler to a link * * @param elements DOM element or an array of DOM elements to be bound with track method. * @param event The name of the event, passed to the `track` method or a function that returns a string to be used * as the name of the track event. * @param properties A dictionary of properties to pass with the `track` method. */ trackLink(elements: HTMLElement | HTMLElement[], event: string | Function, properties?: any | Function): void; /** * Binds a `track` call to a form submission. * * @param forms The form element to track or an array of form * @param event The name of the event, passed to the `track` method. * @param properties A dictionary of properties to pass with the `track` method. */ trackForm(forms: HTMLElement | HTMLElement[], event: string | Function, properties?: any | Function): void; /** * Set the length (in milliseconds) of the callbacks and helper functions * * @param timeout Number of milliseconds */ timeout(timeout: number): void; /** * Add a source middleware called on events * * @param middleware Custom function */ addSourceMiddleware(middleware: ({integrations, payload, next}) => void): void; }
79132cf183be7fbb0e8b96c8f1ef27b408e98543
TypeScript
ghnz/react
/src/redux/reducers/layout.slice.reducer.ts
2.515625
3
import { createSlice, PayloadAction } from '@reduxjs/toolkit'; import LayoutMode from '../../enums/LayoutMode'; type IState = { mode: LayoutMode }; const initialState: IState = { mode: LayoutMode.admin }; const layoutSlice = createSlice({ name: 'layout', initialState: initialState, reducers: { setLayoutMode: (state, action: PayloadAction<LayoutMode>) => { return { ...state, mode: action.payload } } } }); export const { setLayoutMode } = layoutSlice.actions; export default layoutSlice.reducer;
9e4d81f67a78955f0dc2050da17bb01ddeef3f54
TypeScript
valpr/adventofcode-2020
/src/day03/part02.ts
3.109375
3
import { readFileSync } from 'fs'; const input = readFileSync('./input.txt', 'utf-8').split('\n').map(line => line.trim()); const slopes = [[1, 1], [1, 3], [1, 5], [1, 7], [2, 1]];//index 0 is y, index 1 is x var treesMultiplied =1; for (var i = 0; i < slopes.length; i++){ var y = 0; var x = 0; var trees = 0; while (y < input.length-1){ x+=slopes[i][1]; y+=slopes[i][0]; if (input[y][x % input[0].length] && input[y][x % input[0].length] === '#'){ trees++; } } treesMultiplied *= trees; } console.log(treesMultiplied);
bda2d8ee97f5472316ffae30a494f5d696ee17a7
TypeScript
rlugojr/phosphor-di
/src/index.ts
3.078125
3
/*----------------------------------------------------------------------------- | Copyright (c) 2014-2015, PhosphorJS Contributors | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ 'use strict'; /** * An enum which defines the registration lifetime policies. */ export enum Lifetime { /** * A single instance is created and shared among all consumers. */ Singleton, /** * A new instance is created each time one is requested. */ Transient, } /** * A run-time token object which holds compile-time type information. */ export class Token<T> { /** * Construct a new token object. * * @param name - A human readable name for the token. */ constructor(name: string) { this._name = name; } /** * Get the human readable name for the token. * * #### Note * This is a read-only property. */ get name(): string { return this._name; } private _name: string; private _tokenStructuralPropertyT: T; } /** * A factory which declares its dependencies. */ export interface IFactory<T> { /** * The lifetime policy for the registration. * * The default value is `Lifetime.Singleton`. */ lifetime?: Lifetime; /** * The dependencies required to create the instance. */ requires: Token<any>[]; /** * Create a new instance of the type. * * @param args - The resolved dependencies specified by `requires`. * * @returns A new instance of the type, or a Promise to an instance. */ create(...args: any[]): T | Promise<T>; } /** * A lightweight dependency injection container. */ export class Container { /** * Test whether a token is registered with the container. * * @param token - The run-time type token of interest. * * @returns `true` if the token is registered, `false` otherwise. */ isRegistered(token: Token<any>): boolean { return this._registry.has(token); } /** * Register a type mapping for the specified token. * * @param token - The run-time type token of interest. * * @param factory - The factory which will create the instance. * * #### Notes * If the token is already registered, or if registering the factory * would cause a circular dependency, an error will be logged to the * console and the registration will be ignored. */ register<T>(token: Token<T>, factory: IFactory<T>): void { if (this._registry.has(token)) { logRegisterError(token); return; } let cycle = findCycle(this._registry, token, factory); if (cycle.length > 0) { logCycleError(token, cycle); return; } this._registry.set(token, createResolver(factory)); } /** * Resolve an instance for the given token or factory. * * @param value - The token or factory object to resolve. * * @returns A promise which resolves to an instance of the requested * type, or rejects with an error if an instance fails to resolve. */ resolve<T>(value: Token<T> | IFactory<T>): Promise<T> { let result: T | Promise<T>; if (value instanceof Token) { result = resolveToken(this._registry, value as Token<T>); } else { result = resolveFactory(this._registry, value as IFactory<T>); } return Promise.resolve(result); } private _registry = createRegistry(); } /** * An object which manages the resolution of a factory. */ interface IResolver<T> { /** * The factory managed by the resolver. */ factory: IFactory<T>; /** * Resolve an instance of the type from the factory. */ resolve(registry: Registry): T | Promise<T>; } /** * A type alias for a resolver registry map. */ type Registry = Map<Token<any>, IResolver<any>>; /** * Create a new registry instance. */ function createRegistry(): Registry { return new Map<Token<any>, IResolver<any>>(); } /** * Log an error which indicates a token is already registered. */ function logRegisterError(token: Token<any>): void { console.error(`Token '${token.name}' is already registered.`); } /** * Log an error which indicates a cycle was detected. */ function logCycleError(token: Token<any>, cycle: Token<any>[]): void { let path = cycle.map(token => `'${token.name}'`).join(' -> '); console.error(`Cycle detected: '${token.name}' -> ${path}.`); } /** * Create a rejected promise which indicates the token is unregistered. */ function rejectUnregistered(token: Token<any>): Promise<any> { return Promise.reject(new Error(`Unregistered token: '${token.name}'.`)); } /** * Find a potential cycle in the registry from the given token. * * This returns an array of tokens which traces the path of the cycle. * The given token is the implicit start of the cycle. If no cycle is * present, the array will be empty. */ function findCycle<T>(registry: Registry, token: Token<T>, factory: IFactory<T>): Token<any>[] { let trace: Token<any>[] = []; visit(factory); return trace; function visit(factory: IFactory<any>): boolean { for (let other of factory.requires) { trace.push(other); if (other === token) { return true; } let resolver = registry.get(other); if (resolver && visit(resolver.factory)) { return true; } trace.pop(); } return false; } } /** * Resolve a token using the specified registry. */ function resolveToken<T>(registry: Registry, token: Token<T>): T | Promise<T> { let result: T | Promise<T>; let resolver = registry.get(token) as IResolver<T>; if (resolver) { result = resolver.resolve(registry); } else { result = rejectUnregistered(token); } return result; } /** * Resolve a factory using the specified registry. */ function resolveFactory<T>(registry: Registry, factory: IFactory<T>): Promise<T> { let promises = factory.requires.map(token => resolveToken(registry, token)); return Promise.all(promises).then(dependencies => { return factory.create.apply(factory, dependencies); }); } /** * Create a resolver for the given factory. */ function createResolver<T>(factory: IFactory<T>): IResolver<T> { let result: IResolver<T>; if (factory.lifetime === Lifetime.Transient) { result = new TransientResolver(factory); } else { result = new SingletonResolver(factory); } return result; } /** * A resolver which implements the transient lifetime behavior. */ class TransientResolver<T> implements IResolver<T> { /** * Construct a new transient resolver. */ constructor(factory: IFactory<T>) { this._factory = factory; } /** * The factory managed by the resolver. */ get factory(): IFactory<T> { return this._factory; } /** * Resolve an instance of the type from the factory. */ resolve(registry: Registry): T | Promise<T> { return resolveFactory(registry, this._factory); } private _factory: IFactory<T>; } /** * A resolver which implements the singleton lifetime behavior. */ class SingletonResolver<T> implements IResolver<T> { /** * Construct a new transient resolver. */ constructor(factory: IFactory<T>) { this._factory = factory; } /** * The factory managed by the resolver. */ get factory(): IFactory<T> { return this._factory; } /** * Resolve an instance of the type from the factory. */ resolve(registry: Registry): T | Promise<T> { if (this._resolved) { return this._value; } if (this._promise) { return this._promise; } this._promise = resolveFactory(registry, this._factory).then(value => { this._value = value; this._promise = null; this._resolved = true; return value; }, error => { this._promise = null; throw error; }); return this._promise; } private _value: T = null; private _resolved = false; private _factory: IFactory<T>; private _promise: Promise<T> = null; }
47baae1a7e3d54aebe3e809a0d1226fbe59c5710
TypeScript
stockint/client
/src/Depth.ts
2.703125
3
import * as service from "./service" import { Level } from "./Level" export class Depth { constructor( readonly tick: number, readonly bids: ReadonlyArray<Level>, readonly asks: ReadonlyArray<Level>) { } static load(url: string): Promise<Depth> { return fetch(url).then(async response => await response.json() as service.Depth).then(data => new Depth(data.tick, data.bids.map(l => new Level(l.price, l.volume, l.count)), data.asks.map(l => new Level(l.price, l.volume, l.count)))) } }
333c4405b6f554307969497867fa0265a0d79163
TypeScript
calebjmatthews/NewSummer
/client/models/seed/adjective.ts
2.921875
3
export default class Adjective implements AdjectiveInterface { word: string; extent: number; constructor(adjective: AdjectiveInterface) { Object.assign(this, adjective); } } interface AdjectiveInterface { word: string; extent: number; }
7f3408c5e0383e3c83a4801801ac392babadead7
TypeScript
lemonmade/quilt
/packages/react-html/source/hooks/viewport.ts
2.9375
3
import {useDomEffect} from './dom-effect.ts'; interface Options { /** * Whether the viewport should cover any physical “notches” of the * user’s device. * * @default true */ cover?: boolean; } /** * Adds a `viewport` `<meta>` tag to the `<head>` of the document. * The viewport directive sets a good baseline for response HTML * documents, and prevents disabling zoom, a common accessibility * mistake. * * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Viewport_meta_tag */ export function useViewport({cover = true}: Options) { useDomEffect( (manager) => { const parts = [ 'width=device-width, initial-scale=1.0, height=device-height', ]; if (cover) parts.push('viewport-fit=cover'); return manager.addMeta({ name: 'viewport', content: parts.join(', '), }); }, [cover], ); }
47774d641d67c29b685b0ba935ec3e36fdf42e6e
TypeScript
jclee/winter_ts
/src/winter/obstacle.ts
2.921875
3
import { Caption } from "./caption.js" import { Entity } from "./entity.js" import { PyEngine, Sprite } from "./winter.js" class Obstacle extends Entity { public flagName: string constructor( engineRef: PyEngine, sprite: Sprite, anim: {[key: string]: [[number, number][][], boolean]} = {}, ) { super(engineRef, sprite, anim) this.flagName = this.sprite.name this.invincible = true if (engineRef.getSaveFlag(this.flagName) !== '') { this.remove() } } remove() { this.sprite.x = -100 this.sprite.y = -100 this.engineRef.destroyEntity(this) } update() {} } export class IceWall extends Obstacle { // Not very exciting. The entity's type is all the information // we need. isKind(kind: string) { return kind == 'IceWall' || super.isKind(kind) } } export class Gap extends Obstacle { // A big empty hole. :P isKind(kind: string) { return kind == 'Gap' || super.isKind(kind) } } const _iceChunksAnim: {[key: string]: [[number, number][][], boolean]} = { default: [[ [[0, 50], [1, 50]], [[0, 50], [1, 50]], [[0, 50], [1, 50]], [[0, 50], [1, 50]], [[0, 50], [1, 50]], [[0, 50], [1, 50]], [[0, 50], [1, 50]], [[0, 50], [1, 50]], ], true], } const _frozenTiles = [ [145, 149, 144], [142, 113, 143], [139, 148, 138], ] export class IceChunks extends Obstacle { constructor( engineRef: PyEngine, sprite: Sprite, ) { super(engineRef, sprite, _iceChunksAnim) this.startAnimation('default') } isKind(kind: string) { return kind == 'IceChunks' || super.isKind(kind) } remove() { this.freeze() super.remove() } freeze() { const lay = this.sprite.layer const tx = Math.floor(this.sprite.x / 16) const ty = Math.floor(this.sprite.y / 16) for (let y = 0; y < 3; ++y) { for (let x = 0; x < 3; ++x) { this.engine.map.setTile(x + tx, y + ty, lay, _frozenTiles[y][x]) this.engine.map.setObs(x + tx, y + ty, lay, 0) } } this.engineRef.setSaveFlag(this.flagName, 'True') } } export class Boulder extends Obstacle { update() { if (this.touches(this.engineRef.getPlayerEntity())) { // find a stick of TNT for (let key of ['dynamite0', 'dynamite1', 'dynamite2', 'dynamite3']) { if (this.engineRef.getSaveFlag(key) !== 'True') { continue; } // TODO: explode animation here this.engineRef.setSaveFlag(key, 'False') this.engineRef.setSaveFlag(this.flagName, 'Broken') this.engineRef.destroyEntity(this) this.engineRef.addThing(new Caption(this.engineRef, this.engineRef.font, 'Blew the rock apart!')) } } } }
9a02f2d5dc7999f77cdf628ed1c832ee5ae36799
TypeScript
mayanktechno/angularkudvenkat
/src/app/employee/employee.component.ts
2.515625
3
import { Component, OnInit } from '@angular/core'; import { Employee } from '../model/employeeinterface' // import {EmployeeData} from '../employeedata' import { EmployeeService } from './employee.service'; @Component({ selector: 'app-employee', templateUrl: './employee.component.html', styleUrls: ['./employee.component.css'] }) export class EmployeeComponent implements OnInit { // data : Employee [] = EmployeeData; data : Employee [] name :string = "mayank"; age : number =24; technology : string ="angular"; company :string = 'appinventriv'; showDetail = false; employeeCountRadioButtonValue = 'All'; constructor(private _employeeService : EmployeeService) { } ngOnInit() { this.data = this._employeeService.getEmployee(); console.log(this.data ,"data by service") } togggleDetail(){ this.showDetail = !this.showDetail; } employeeCountShow(selectedValue){ console.log(selectedValue,"selected value"); this.employeeCountRadioButtonValue = selectedValue; } getAllEmployee(){ return this.data.length; } getAllMaleEmployee(){ return this.data.filter(e=>e.gender.toLowerCase()==="male").length; } getAllFemaleEmployee(){ return this.data.filter(e=>e.gender.toLowerCase()==="female").length; } }
1c2c7c82cfca49dc6721d6700d2b52dcebf02293
TypeScript
MostlyArmless/advent-of-code-2020
/src/problem4.ts
3.0625
3
import { inRange } from "./tools"; const validEyeColors: Set<string> = new Set( [ 'amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth' ] ); class Passport { birthYear: string; issueYear: string; expirationYear: string; height: string; hairColor: string; eyeColor: string; passportId: string; // countryId: string; private heightIsValid(): boolean { const match = /^(\d+)(cm|in)$/.exec( this.height ); if ( !match ) return false; const value = match[1] const units = match[2]; if ( units === 'cm' ) return inRange( parseInt( value ), 150, 193 ); if ( units === 'in' ) return inRange( parseInt( value ), 59, 76 ) return false; } isKindaValid(): boolean { return this.birthYear !== undefined && this.issueYear !== undefined && this.expirationYear !== undefined && this.height !== undefined && this.hairColor !== undefined && this.eyeColor !== undefined && this.passportId !== undefined; } isStrictlyValid(): boolean { return this.isKindaValid() && inRange( parseInt( this.birthYear ), 1920, 2002 ) && inRange( parseInt( this.issueYear ), 2010, 2020 ) && inRange( parseInt( this.expirationYear ), 2020, 2030 ) && this.heightIsValid() && /^#(([0-9])|([a-f])){6}$/.test( this.hairColor ) && validEyeColors.has( this.eyeColor ) && /^\d{9}$/.test( this.passportId ); } } function countValidPassports( input: string, strict: boolean ): number { const lines = input.split( '\n' ); let passport = new Passport(); let numValidPassports = 0; lines.forEach( ( line, iLine, lines ) => { iLine === lines.length - 1 if ( line === '' ) { numValidPassports += ( strict ? passport.isStrictlyValid() : passport.isKindaValid() ) ? 1 : 0; passport = new Passport(); return; } if ( passport.birthYear === undefined ) { const match = /byr:([^\s]+)/.exec( line ); passport.birthYear = match ? match[1] : undefined; } if ( passport.issueYear === undefined ) { const match = /iyr:([^\s]+)/.exec( line ); passport.issueYear = match ? match[1] : undefined; } if ( passport.expirationYear === undefined ) { const match = /eyr:([^\s]+)/.exec( line ); passport.expirationYear = match ? match[1] : undefined; } if ( passport.height === undefined ) { const match = /hgt:([^\s]+)/.exec( line ); passport.height = match ? match[1] : undefined; } if ( passport.hairColor === undefined ) { const match = /hcl:([^\s]+)/.exec( line ); passport.hairColor = match ? match[1] : undefined; } if ( passport.eyeColor === undefined ) { const match = /ecl:([^\s]+)/.exec( line ); passport.eyeColor = match ? match[1] : undefined; } if ( passport.passportId === undefined ) { const match = /pid:([^\s]+)/.exec( line ); passport.passportId = match ? match[1] : undefined; } // if ( passport.countryId === undefined ) // { // const match = /cid:([^\s]+)/.exec( line ); // passport.countryId = match ? match[1] : undefined; // } if ( iLine === lines.length - 1 ) { numValidPassports += ( strict ? passport.isStrictlyValid() : passport.isKindaValid() ) ? 1 : 0; return; } } ); return numValidPassports; } export function problem4_part1( input: string ): number { return countValidPassports( input, false ); } export function problem4_part2( input: string ): number { return countValidPassports( input, true ); }
ff27ba72ac25ea77b3ba14c15f5df3f1a9a712db
TypeScript
linningmii/react-dag-editor
/packages/ReactDagEditor/src/controllers/TwoFingerHandler.ts
2.703125
3
import * as React from "react"; import { GraphCanvasEvent } from "../models/event"; import { IContainerRect } from "../models/geometry"; import { distance, getContainerCenter } from "../utils"; import { EventChannel } from "../utils/eventChannel"; import { ITouchHandler } from "./TouchController"; /** * debug helpers, just leave them here */ // const canvas = document.createElement("canvas"); // canvas.height = window.innerHeight; // canvas.width = window.innerWidth; // Object.assign(canvas.style, { // pointerEvents: "none", // position: "fixed", // top: "0", // left: "0" // }); // document.body.append(canvas); // // const ctx = canvas.getContext("2d")!; // // function draw({ x, y }: ITouch, style: string): void { // ctx.fillStyle = style; // ctx.fillRect(x - 2.5, y - 2.5, 5, 5); // } export class TwoFingerHandler implements ITouchHandler { private readonly rectRef: React.RefObject<IContainerRect | undefined>; private readonly eventChannel: EventChannel; private prevEvents: [PointerEvent, PointerEvent] | undefined; private prevDistance = 0; public constructor( rectRef: React.RefObject<IContainerRect | undefined>, eventChannel: EventChannel ) { this.rectRef = rectRef; this.eventChannel = eventChannel; } public onEnd(): void { // noop } public onMove(pointers: Map<number, PointerEvent>, e: PointerEvent): void { const events = Array.from(pointers.values()) as [PointerEvent, PointerEvent]; const currentDistance = distance(events[0].clientX, events[0].clientY, events[1].clientX, events[1].clientY); const { prevEvents, prevDistance } = this; this.prevDistance = currentDistance; this.prevEvents = events; if (!prevEvents) { return; } const dx1 = events[0].clientX - prevEvents[0].clientX; const dx2 = events[1].clientX - prevEvents[1].clientX; const dy1 = events[0].clientY - prevEvents[0].clientY; const dy2 = events[1].clientY - prevEvents[1].clientY; const dx = (dx1 + dx2) / 2; const dy = (dy1 + dy2) / 2; const scale = (currentDistance - prevDistance) / prevDistance + 1; const anchor = getContainerCenter(this.rectRef); if (!anchor) { return; } this.eventChannel.trigger({ type: GraphCanvasEvent.Pinch, rawEvent: e, dx, dy, scale, anchor }); } public onStart(pointers: Map<number, PointerEvent>): void { if (pointers.size !== 2) { throw new Error(`Unexpected touch event with ${pointers.size} touches`); } this.prevEvents = Array.from(pointers.values()) as [PointerEvent, PointerEvent]; this.prevDistance = distance( this.prevEvents[0].clientX, this.prevEvents[0].clientY, this.prevEvents[1].clientX, this.prevEvents[1].clientY ); } }
b38d54d1eb8817351c33724b15777acd672c1064
TypeScript
rikshot/testbed
/src/ts/Fractal/Config.ts
2.75
3
import { IRectangle, Rectangle } from 'Sandbox/Rectangle.js'; export interface IConfig { iterations: number; red: number; green: number; blue: number; rectangle: IRectangle; } export class Config { public readonly iterations: number; public readonly red: number; public readonly green: number; public readonly blue: number; public readonly rectangle: Rectangle; constructor(iterations: number, red: number, green: number, blue: number, rectangle: Rectangle) { this.iterations = iterations; this.red = red; this.green = green; this.blue = blue; this.rectangle = rectangle; } public getDTO(): IConfig { return { iterations: this.iterations, red: this.red, green: this.green, blue: this.blue, rectangle: this.rectangle.getDTO(), }; } }
c35d941b1093865882fbe70c7b6b52777f317dd8
TypeScript
shahedbd/TypeScriptBasic
/04Function/ArrowFunctions.ts
3.6875
4
// Arrow functions are always anonymous and turn: // (parameters) => {expression} // Named function function add(x, y) { return x + y; } // Call named function console.log(add(5, 10)); var add2 = (x, y) => x + y; console.log(add2(5, 10));
df8f28f2d40417536fd1c8ce1973bd3e9510260e
TypeScript
kenrick95/luxord
/src/timer/switchTimer.test.ts
2.78125
3
import SwitchTimer, { TIMER_ID } from './switchTimer'; const alertSpy = jest .spyOn(window, 'alert') .mockImplementation((...args) => console.info.apply(null, args)); let switchTimer: SwitchTimer; const timerAmount = 1000; const now = performance.now(); const _realPerformanceNow = performance.now; function advanceTo(time: number) { performance.now = jest.fn(() => time); } function clear() { performance.now = _realPerformanceNow; } beforeEach(() => { jest.useFakeTimers(); advanceTo(now); }); afterEach(() => { jest.clearAllTimers(); alertSpy.mockClear(); clear(); }); test('switchTimer initial state', () => { const switchTimer = new SwitchTimer(timerAmount); expect(switchTimer.activeTimerId).toBe(TIMER_ID.NONE); }); describe('switchTimer Player 1 starts', () => { test('initial state', () => { switchTimer = new SwitchTimer(timerAmount); switchTimer.activeTimerId = TIMER_ID.ONE; switchTimer.start(); expect(switchTimer.timers[TIMER_ID.ONE].isActive).toBe(true); expect(switchTimer.timers[TIMER_ID.ONE].msLeft).toBe(1000); expect(switchTimer.timers[TIMER_ID.TWO].isActive).toBe(false); expect(switchTimer.timers[TIMER_ID.ONE].msLeft).toBe(1000); expect(alertSpy).not.toBeCalled(); }); test('after 400 ms', () => { switchTimer = new SwitchTimer(timerAmount); switchTimer.activeTimerId = TIMER_ID.ONE; switchTimer.start(); advanceTo(now + 400); jest.advanceTimersByTime(400); expect(switchTimer.timers[TIMER_ID.ONE].isActive).toBe(true); expect(switchTimer.timers[TIMER_ID.ONE].msLeft).toBe(600); expect(switchTimer.timers[TIMER_ID.TWO].isActive).toBe(false); expect(switchTimer.timers[TIMER_ID.TWO].msLeft).toBe(1000); expect(alertSpy).not.toBeCalled(); }); test('after 400 ms, switch', () => { switchTimer = new SwitchTimer(timerAmount); switchTimer.activeTimerId = TIMER_ID.ONE; switchTimer.start(); advanceTo(now + 400); jest.advanceTimersByTime(400); switchTimer.switch(); expect(switchTimer.timers[TIMER_ID.ONE].isActive).toBe(false); expect(switchTimer.timers[TIMER_ID.ONE].msLeft).toBe(600); expect(switchTimer.timers[TIMER_ID.TWO].isActive).toBe(true); expect(switchTimer.timers[TIMER_ID.TWO].msLeft).toBe(1000); expect(alertSpy).not.toBeCalled(); }); test('after 400 ms, switch, and wait for 200 ms', () => { switchTimer = new SwitchTimer(timerAmount); switchTimer.activeTimerId = TIMER_ID.ONE; switchTimer.start(); advanceTo(now + 400); jest.advanceTimersByTime(400); switchTimer.switch(); advanceTo(now + 600); jest.advanceTimersByTime(200); expect(switchTimer.timers[TIMER_ID.ONE].isActive).toBe(false); expect(switchTimer.timers[TIMER_ID.ONE].msLeft).toBe(600); expect(switchTimer.timers[TIMER_ID.TWO].isActive).toBe(true); expect(switchTimer.timers[TIMER_ID.TWO].msLeft).toBe(800); expect(alertSpy).not.toBeCalled(); }); test('after 400 ms, switch, wait for 200 ms, and switch', () => { switchTimer = new SwitchTimer(timerAmount); switchTimer.activeTimerId = TIMER_ID.ONE; switchTimer.start(); advanceTo(now + 400); jest.advanceTimersByTime(400); switchTimer.switch(); advanceTo(now + 600); jest.advanceTimersByTime(200); switchTimer.switch(); expect(switchTimer.timers[TIMER_ID.ONE].isActive).toBe(true); expect(switchTimer.timers[TIMER_ID.ONE].msLeft).toBe(600); expect(switchTimer.timers[TIMER_ID.TWO].isActive).toBe(false); expect(switchTimer.timers[TIMER_ID.TWO].msLeft).toBe(800); expect(alertSpy).not.toBeCalled(); }); test('after 400 ms, switch, wait for 200 ms, switch, and wait 600 ms', () => { switchTimer = new SwitchTimer(timerAmount); switchTimer.activeTimerId = TIMER_ID.ONE; switchTimer.start(); advanceTo(now + 400); jest.advanceTimersByTime(400); switchTimer.switch(); advanceTo(now + 600); jest.advanceTimersByTime(200); switchTimer.switch(); advanceTo(now + 1200); jest.advanceTimersByTime(600); expect(switchTimer.timers[TIMER_ID.ONE].isActive).toBe(false); expect(switchTimer.timers[TIMER_ID.ONE].msLeft).toBe(1000); expect(switchTimer.timers[TIMER_ID.TWO].isActive).toBe(false); expect(switchTimer.timers[TIMER_ID.TWO].msLeft).toBe(1000); expect(alertSpy).toBeCalled(); }); });
1d691f7f6c54977cb1669b59d4e09f0804b93d4b
TypeScript
daxingyou/H601_CrazyTapHero
/H6017_Code_Client/trunk/GuLongQunXiaZhuan_EUI/src/Model/DataLocal/ShopData.ts
2.53125
3
module Model{ /** * * @author cai_haotian * @Date 2016.2.26 * */ export class ShopData { public constructor(_dy:Model.ShopDyModel,_st:Model.ShopStModel) { this.dy = _dy; this.st = _st; } /** * @商城动态数据 */ public dy:Model.ShopDyModel; /** * @商城静态数据 */ public st: Model.ShopStModel; /** * @获得铜币数量(不带单位) */ public gold:number; /** * @获得铜币显示数量 */ public get goldAndUnit(){ return MainLocalService.toUnitConversion(this.gold); } /** * @获得商品类型 */ public get Type() { return <ShopType>ShopType[this.st.type]; } } }
483cb228e4fe956a095b33054c92a1eda33fbbc2
TypeScript
bzf/glimmer-todo
/src/ui/components/glimmer-todo/component.ts
3.125
3
import Component, { tracked } from "@glimmer/component"; interface TodoItem { title: string; checked: boolean; } enum Filter { Checked, Unchecked, }; type Order = "asc" | "desc"; export default class GlimmerBzf extends Component { @tracked order: Order = "asc"; @tracked showOnlyUnchecked: boolean = false; @tracked items: Array<TodoItem> = [ { title: "Learn TypeScript", checked: true }, { title: "Try out GlimmerJS", checked: true }, { title: "Figure out the next big thing", checked: false }, ]; @tracked('order') get sortAsc(): boolean { return this.order == "asc"; } @tracked('order') get sortDesc(): boolean { return this.order == "desc"; } @tracked('items', 'showOnlyUnchecked') get filteredItems(): Array<TodoItem> { if (this.showOnlyUnchecked) { return this.items.filter((a) => !a.checked); } else { return this.items; } } @tracked('items', 'order', 'showOnlyUnchecked') get todoItems(): Array<TodoItem> { if (this.order == "asc") { return this.filteredItems.sort((a, b) => a.title > b.title); } else { return this.filteredItems.sort((a, b) => a.title < b.title); } } toggleOrder(order: Event) { this.order = order.target.value; } toggleChecked(item: TodoItem) { const nextItem = { ...item, checked: !item.checked, }; const itemsWithoutItem = this.items.filter((a) => a.title != item.title); this.items = [ ...itemsWithoutItem, nextItem, ]; } toggleOnlyUnchecked() { this.showOnlyUnchecked = !this.showOnlyUnchecked; } };
6812d81fefdc1a118ba89202413baba543d2094c
TypeScript
ayuayue/ts-study
/interface/interface.ts
4.78125
5
// 接口 interface person { name: string, age: number, say: () => string } // 实现 person let lili: person = { name: "lili", age: 14, say: () => { return "i am lili"; } }; console.log(lili.name, lili.age, lili.say()); // 联合类型和接口 interface unionInterface { name: string; say: string[] | string | (() => string); } let uI: unionInterface = { name: "unionInterface", say: "string array" }; console.log(uI.say); uI = { name: "unionInterface array", say: ["string", "array"] }; console.log(uI.say[0], uI.say[1]); uI = { name: "unionInterface func", say: () => { return "func"; } }; console.log(uI.say); // 接口和数组 // 接口中我们可以将数组的索引值和元素设置为不同类型,索引值可以是数字或字符串。 // 接口继承 // 接口继承就是说接口可以通过其他接口来扩展自己。 // 单继承 interface litterPerson extends person { type: string; }; let lisa: litterPerson = { type: "child", name: "lisa", age: 18, say: () => { return "extends" } } console.log(lisa.name, lisa.type); // 多继承 interface action extends person,litterPerson { act: string, type: string, } let multiply: action = { act: "act", type: "act", name: "lisa", age: 18, say: () => { return "extends" } } console.log(multiply.act, multiply.type);
45c3b52d83e3cbbf150a6fe57dba493f09d76afc
TypeScript
yp2005/BWAnimationU5
/src/MulTouch/MulTouchMain.ts
2.59375
3
// 游戏主界面 class MulTouchMain extends ui.MulTouchUI { private configView: MTConfigView; // 配置页 public speed: number = 0; // 转速 public mustStop: boolean = false; constructor() { super(); this.configView = new MTConfigView(this.configBox); this.tip.visible = false; this.setting.on(Laya.Event.CLICK, this, this.showConfigView) if(MulTouch.gameConfig.gameModel) { this.setting.visible = false; } this.speak.on(Laya.Event.CLICK,this,this.speakWord); } public speakWord(){ if(!MulTouch.gameChecking){ let word = MulTouch.allWords[(MulTouch.soundRandom[MulTouch.wordContext]-1)]; console.log("sound:::"+"res/audio/multouch/"+word+".mp3"); Laya.SoundManager.playSound("res/audio/multouch/"+word+".mp3", 1); MulTouch.gameChecking = true; MulTouch.mulTouchMain.speak.skin = "MulTouch/sound-disabled.png"; MulTouch.wordContext++; MulTouch.leftimageOk = false; MulTouch.leftwordOk = false; MulTouch.rightwordOk = false; MulTouch.rightimageOk = false; // let addheight = 20 * picture.height / picture.width; // picture.width = picture.width+20; // picture.height = picture.height + addheight; // picture.x = picture.x - 10; // picture.y = picture.y - addheight/2; for(var i = 0;i<MulTouch.mulTouchMain.mainbox.numChildren;i++){ let img = MulTouch.mulTouchMain.mainbox.getChildAt(i) as Laya.Image; // if((img.x !== 50) || (img.x !== 280) ||(img.x != 562) ||(img.x != 792){ // } if(![50, 280, 562,792].includes(img.x)){ let addheight = 20 * img.height / img.width; img.width = img.width-20; img.height = img.height - addheight; img.x = img.x + 10; img.y = img.y + addheight/2; } } Laya.timer.once(1000,this,function(){ // 播放到最后一个单词音频的时候replay亮起,播放再也不能点了; if(MulTouch.soundRandom.length == MulTouch.wordContext){ MulTouch.gameChecking = true; MulTouch.mulTouchMain.replayBtn.skin = "common/replay-abled.png"; }else{ MulTouch.gameChecking = false; MulTouch.mulTouchMain.speak.skin = "MulTouch/sound.png"; } }); } } // 显示提示 public showTip(text: string) { this.tip.text = text; this.tip.visible = true; Laya.timer.once(2000, this, this.hideTip); } private hideTip() { this.tip.visible = false; } // 显示游戏配置页面 private showConfigView() { this.configView.show(); } // 设置设置按钮是否显示 public showSetting(state: boolean) { if(!MulTouch.gameConfig.gameModel) { this.setting.visible = state; } } }
857af084eb0348b83eaf9ae0c1eb7aa5158f52a2
TypeScript
DoTriDucBK/DATN_API
/giasu_api/app/utils/Validate.ts
2.53125
3
export const Utils = { checkLogin(params) { if (!params) return false; if (!(params.user_acc_emai && params.user_acc_pass)) return false return true }, checkKeysNotExists(obj: object, keys: string[]) { if (Array.isArray(keys)) { for (let i = 0; i < keys.length; i++) { if (!(keys[i] in obj)) { return i; } } } else if (!(keys in obj)) { return 0; } return -1; }, checkUsername(user_acc_name: string) { console.log(user_acc_name, "&&&&&") if (user_acc_name && user_acc_name.length > 0) return true return false; }, checkPassword(user_acc_pass: string) { if (user_acc_pass.length > 3) { return true; } return false; }, isPhoneNumber: (user_acc_phon) => { if (!user_acc_phon) return false; user_acc_phon = user_acc_phon.trim(); var flag = false; const gpcPattern = /^(84|0)(9(1|4)|12(3|4|5|7|9)|88)\d{7}$/; const vinaphone = /^(84|0)(9(1|4)|8(1|2|3|4|5))\d{7}$/; const vmsPattern = /^(84|0)(9(0|3)|12(0|1|2|6|8)|89)\d{7}$/; const mobiphone = /^(84|0)(9(0|3)|7(0|6|7|8|9))\d{7}$/; const viettelPattern = /^(84|0)(9(6|7|8)|16(8|9|6|7|3|4|5|2)|86)\d{7}$/; const viettel = /^(84|0)(9(6|7|8)|3(8|9|6|7|3|4|5|2)|86)\d{7}$/; const vnm = /^(84|0)(92|188|186)\d{7}$/; const vnmobile = /^(84|0)(92|58|56)\d{7}$/; const beeline = /^(84|0)((1|)99)\d{7}$/; const Gmobile = /^(84|0)(99|59)\d{7}$/; const telephone = /^(02|2)\d{9}$/; flag = user_acc_phon.match(gpcPattern) || user_acc_phon.match(vmsPattern) || user_acc_phon.match(viettelPattern) || user_acc_phon.match(vnm) || user_acc_phon.match(beeline) || user_acc_phon.match(telephone) || user_acc_phon.match(vinaphone) || user_acc_phon.match(mobiphone) || user_acc_phon.match(viettel) || user_acc_phon.match(vnmobile) || user_acc_phon.match(Gmobile); return flag; }, isEmailAddress: (user_acc_emai) => user_acc_emai && user_acc_emai.match(/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]{2,})+$/i), }
652624a512a8ee750ad89a7b9ad42f213dd8ec9f
TypeScript
r2moon/arCore
/test/general/BalanceExpireTracker.test.ts
2.5625
3
import { expect } from "chai"; import { ethers } from "hardhat"; import { Contract, Signer, BigNumber, constants } from "ethers"; import { getTimestamp, increase } from "../utils"; let step = BigNumber.from("259200"); function getBucket(expire: BigNumber) : BigNumber { return (expire.div(step)).mul(step); } describe("BalanceExpireTracker", function(){ let tracker: Contract; let now: BigNumber; beforeEach(async function(){ const Tracker = await ethers.getContractFactory("BalanceExpireTrackerMock"); tracker = await Tracker.deploy(); const realTime = await getTimestamp(); await increase(getBucket(realTime).add(step).sub(realTime).toNumber()); now = await getTimestamp(); }); describe("#push()", function(){ describe("when everything is empty", function(){ beforeEach(async function(){ await tracker.add(now); }); it("should store expire metadata", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); expect(metadata.next).to.be.equal(0); expect(metadata.prev).to.be.equal(0); expect(metadata.expiresAt).to.be.equal(now); }); it("should set head to new id", async function(){ const id = await tracker.lastId(); const head = await tracker.head(); expect(id).to.be.equal(head); }); it("should set tail to new id", async function(){ const id = await tracker.lastId(); const tail = await tracker.tail(); expect(id).to.be.equal(tail); }); it("should set bucket head and tail to new id", async function(){ const id = await tracker.lastId(); const bucket = await tracker.checkPoints(getBucket(now)); expect(bucket.head).to.be.equal(id); expect(bucket.tail).to.be.equal(id); }); }); describe("when there is something", function(){ describe("when new expire is prior to head", async function(){ describe("when bucket is empty", function(){ let head: any; let tail: any; let headId: BigNumber; let tailId: BigNumber; beforeEach(async function(){ // this will add to the front of the bucket await tracker.add(now); head = await tracker.infos(await tracker.head()); headId = await tracker.head(); tail = await tracker.infos(await tracker.tail()); tailId = await tracker.tail(); // this will add to the last of the empty bucket await tracker.add(head.expiresAt.sub(step)); }); it("should store expire metadata", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); expect(metadata.next).to.be.equal(headId); expect(metadata.prev).to.be.equal(0); expect(metadata.expiresAt).to.be.equal(head.expiresAt.sub(step)); }); it("should set head to new id", async function(){ const id = await tracker.lastId(); const head = await tracker.head(); expect(id).to.be.equal(head); }); it("should set bucket head and tail to new id", async function(){ const id = await tracker.lastId(); const bucket = await tracker.checkPoints(getBucket(head.expiresAt.sub(step))); expect(bucket.head).to.be.equal(id); expect(bucket.tail).to.be.equal(id); }); it("should be connected", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); const metadata_next = await tracker.infos(metadata.next); expect(metadata_next.prev).to.be.equal(id); }); }); describe("when bucket is not empty", function(){ let head: any; let tail: any; let headId: BigNumber; let tailId: BigNumber; beforeEach(async function(){ // this will add to the front of the bucket await tracker.add(now.add(1)); head = await tracker.infos(await tracker.head()); headId = await tracker.head(); tail = await tracker.infos(await tracker.tail()); tailId = await tracker.tail(); // this will add to the front of the bucket await tracker.add(head.expiresAt.sub(1)); }); it("should store expire metadata", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); expect(metadata.next).to.be.equal(headId); expect(metadata.prev).to.be.equal(0); expect(metadata.expiresAt).to.be.equal(head.expiresAt.sub(1)); }); it("should set head to new id", async function(){ const id = await tracker.lastId(); const head = await tracker.head(); expect(id).to.be.equal(head); }); it("should set bucket head and tail to new id", async function(){ const id = await tracker.lastId(); const bucket = await tracker.checkPoints(getBucket(now)); expect(bucket.head).to.be.equal(id); expect(bucket.tail).to.be.equal(id.sub(1)); }); it("should be connected", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); const metadata_next = await tracker.infos(metadata.next); expect(metadata_next.prev).to.be.equal(id); }); }); }); describe("when new expire is later than tail", async function(){ describe("when bucket is empty", function(){ let head: any; let tail: any; let headId: BigNumber; let tailId: BigNumber; beforeEach(async function(){ // this will add to the front of the bucket await tracker.add(now); head = await tracker.infos(await tracker.head()); headId = await tracker.head(); tail = await tracker.infos(await tracker.tail()); tailId = await tracker.tail(); // this will add to the last of the empty bucket await tracker.add(tail.expiresAt.add(step)); }); it("should store expire metadata", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); expect(metadata.next).to.be.equal(0); expect(metadata.prev).to.be.equal(tailId); expect(metadata.expiresAt).to.be.equal(tail.expiresAt.add(step)); }); it("should set tail to new id", async function(){ const id = await tracker.lastId(); const tail = await tracker.tail(); expect(id).to.be.equal(tail); }); it("should set bucket head and tail to new id", async function(){ const id = await tracker.lastId(); const bucket = await tracker.checkPoints(getBucket(tail.expiresAt.add(step))); expect(bucket.head).to.be.equal(id); expect(bucket.tail).to.be.equal(id); }); it("should be connected", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); const metadata_prev = await tracker.infos(metadata.prev); expect(metadata_prev.next).to.be.equal(id); }); }); describe("when bucket is not empty", function(){ let head: any; let tail: any; let headId: BigNumber; let tailId: BigNumber; beforeEach(async function(){ // this will add to the front of the bucket await tracker.add(now.add(1)); head = await tracker.infos(await tracker.head()); headId = await tracker.head(); tail = await tracker.infos(await tracker.tail()); tailId = await tracker.tail(); // this will add to the front of the bucket await tracker.add(tail.expiresAt.add(step.sub(100))); }); it("should store expire metadata", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); expect(metadata.next).to.be.equal(0); expect(metadata.prev).to.be.equal(tailId); expect(metadata.expiresAt).to.be.equal(tail.expiresAt.add(step.sub(100))); }); it("should set tail to new id", async function(){ const id = await tracker.lastId(); const tail = await tracker.tail(); expect(id).to.be.equal(tail); }); it("should set bucket tail to new id", async function(){ const id = await tracker.lastId(); const bucket = await tracker.checkPoints(getBucket(tail.expiresAt)); expect(bucket.head).to.be.equal(id.sub(1)); expect(bucket.tail).to.be.equal(id); }); it("should be connected", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); const metadata_prev = await tracker.infos(metadata.prev); expect(metadata_prev.next).to.be.equal(id); }); }); }); describe("when new expire is in between", async function(){ beforeEach(async function(){ await tracker.add(now); await tracker.add(now.add(100)); for(let i = 1;i<10; i++) { await tracker.add(now.add(step).add(100*i)); } await tracker.add(now.add(step).add(1000)); await tracker.add(now.add(step.mul(4)).add(1000)); }); describe("when bucket is empty", function(){ beforeEach(async function(){ await tracker.add(now.add(step.mul(3)).add(1)); }); it("should store expire metadata", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); expect(metadata.next).to.be.equal(id.sub(1)); expect(metadata.prev).to.be.equal(id.sub(2)); expect(metadata.expiresAt).to.be.equal(now.add(step.mul(3)).add(1)); }); it("should connect prev and next", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); const metadata_next = await tracker.infos(metadata.next); const metadata_prev = await tracker.infos(metadata.prev); expect(metadata_next.prev).to.be.equal(id); expect(metadata_prev.next).to.be.equal(id); }); it("should set bucket head and tail to new id", async function(){ const id = await tracker.lastId(); const bucket = await tracker.checkPoints(getBucket(now.add(step.mul(3)).add(1))); expect(bucket.head).to.be.equal(id); expect(bucket.tail).to.be.equal(id); }); it("should be connected", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); const metadata_next = await tracker.infos(metadata.next); const metadata_prev = await tracker.infos(metadata.prev); expect(metadata_next.prev).to.be.equal(id); expect(metadata_prev.next).to.be.equal(id); }); }); describe("when bucket is not empty", function(){ beforeEach(async function(){ await tracker.add(now.add(step.add(501))); }); it("should store expire metadata", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); const metadata_next = await tracker.infos(metadata.next); const metadata_prev = await tracker.infos(metadata.prev); expect(metadata_next.expiresAt).to.be.gte(metadata.expiresAt); expect(metadata_prev.expiresAt).to.be.lte(metadata.expiresAt); }); it("should be connected", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); const metadata_next = await tracker.infos(metadata.next); const metadata_prev = await tracker.infos(metadata.prev); expect(metadata_next.prev).to.be.equal(id); expect(metadata_prev.next).to.be.equal(id); }); describe("when new expire is head of bucket", async function(){ let bucket_metadata; beforeEach(async function(){ bucket_metadata = await tracker.checkPoints(getBucket(now.add(step))); await tracker.add(now.add(step)); }); it("should set bucket tail to new id", async function(){ const id = await tracker.lastId(); const bucket = await tracker.checkPoints(getBucket(now.add(step))); expect(bucket.head).to.be.equal(id); expect(bucket.tail).to.be.equal(bucket_metadata.tail); }); it("should be connected", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); const metadata_next = await tracker.infos(metadata.next); const metadata_prev = await tracker.infos(metadata.prev); expect(metadata_next.prev).to.be.equal(id); expect(metadata_prev.next).to.be.equal(id); }); }); describe("when new expire is tail of bucket", async function(){ let bucket_metadata; beforeEach(async function(){ bucket_metadata = await tracker.checkPoints(getBucket(now.add(step))); await tracker.add(now.add(step.mul(2).sub(1000))); }); it("should set bucket tail to new id", async function(){ const id = await tracker.lastId(); const bucket = await tracker.checkPoints(getBucket(now.add(step.mul(2).sub(1000)))); expect(bucket.head).to.be.equal(bucket_metadata.head); expect(bucket.tail).to.be.equal(id); }); it("should be connected", async function(){ const id = await tracker.lastId(); const metadata = await tracker.infos(id); const metadata_next = await tracker.infos(metadata.next); const metadata_prev = await tracker.infos(metadata.prev); expect(metadata_next.prev).to.be.equal(id); expect(metadata_prev.next).to.be.equal(id); }); }); }); }); }); }); describe("#pop()", function(){ describe("when there is only one element", function(){ beforeEach(async function(){ await tracker.add(now); const id = await tracker.lastId(); await tracker.remove(id); }); it("should delete head", async function(){ const head = await tracker.head(); expect(head).to.be.equal(0); }); it("should delete tail", async function(){ const tail = await tracker.tail(); expect(tail).to.be.equal(0); }); it("should delete bucket", async function(){ const bucket = await tracker.checkPoints(getBucket(now)); expect(bucket.head).to.be.equal(0); expect(bucket.tail).to.be.equal(0); }); }); describe("when there is two elements", function(){ beforeEach(async function(){ await tracker.add(now); await tracker.add(now.add(1000)); const id = await tracker.lastId(); await tracker.remove(id); }); it("should set left element's next == prev == 0", async function(){ const id = (await tracker.lastId()).sub(1); const metadata = await tracker.infos(id); expect(metadata.prev).to.be.equal(0); expect(metadata.next).to.be.equal(0); }); it("should set head == tail", async function(){ const id = (await tracker.lastId()).sub(1); const head = await tracker.head(); const tail = await tracker.tail(); expect(id).to.be.equal(head); expect(tail).to.be.equal(id); }); it("should set bucket.head == bucket.tail", async function(){ const id = (await tracker.lastId()).sub(1); const metadata = await tracker.infos(id); const bucket = await tracker.checkPoints(getBucket(metadata.expiresAt)); expect(bucket.head).to.be.equal(id); expect(bucket.tail).to.be.equal(id); }); }); describe("when there is more than 2 elements", function(){ beforeEach(async function(){ await tracker.add(now); await tracker.add(now.add(100)); for(let i = 1;i<10; i++) { await tracker.add(now.add(step).add(100*i)); } await tracker.add(now.add(step).add(1000)); await tracker.add(now.add(step.mul(2)).add(100)); await tracker.add(now.add(step.mul(2)).add(200)); await tracker.add(now.add(step.mul(3)).add(100)); await tracker.add(now.add(step.mul(4)).add(1000)); }); describe("when deleting element is head", function(){ let metadata_old; let bucket_old; beforeEach(async function(){ const id = await tracker.head(); metadata_old = await tracker.infos(id); bucket_old = await tracker.checkPoints(getBucket(metadata_old.expiresAt)); await tracker.remove(id); }); it("should move head to next", async function(){ const new_head = await tracker.head(); expect(new_head).to.be.equal(metadata_old.next); }); it("should delete prev of new head", async function(){ const new_head = await tracker.head(); const new_head_info = await tracker.infos(new_head); expect(new_head_info.prev).to.be.equal(0); }); }); describe("when deleting element is tail", function(){ let metadata_old; let bucket_old; beforeEach(async function(){ const id = await tracker.tail(); metadata_old = await tracker.infos(id); bucket_old = await tracker.checkPoints(getBucket(metadata_old.expiresAt)); await tracker.remove(id); }); it("should move tail to prev", async function(){ const new_tail = await tracker.tail(); expect(new_tail).to.be.equal(metadata_old.prev); }); it("should delete next of new tail", async function(){ const new_head = await tracker.head(); const new_head_info = await tracker.infos(new_head); expect(new_head_info.prev).to.be.equal(0); }); }); describe("when deleting element is in-between", function(){ describe("when bucket had only one element", function(){ let metadata_old; let bucket_old; beforeEach(async function(){ const id = (await tracker.tail()).sub(1); metadata_old = await tracker.infos(id); bucket_old = await tracker.checkPoints(getBucket(metadata_old.expiresAt)); await tracker.remove(id); }); it("should delete bucket", async function(){ const bucket = await tracker.checkPoints(getBucket(metadata_old.expiresAt)); expect(bucket.head).to.be.equal(0); expect(bucket.tail).to.be.equal(0); }); it("should be connected", async function(){ const prev_info = await tracker.infos(metadata_old.prev); const next_info = await tracker.infos(metadata_old.next); expect(prev_info.next).to.be.equal(metadata_old.next); expect(next_info.prev).to.be.equal(metadata_old.prev); }); }); describe("when bucket had two elements", function(){ let metadata_old; let bucket_old; beforeEach(async function(){ const id = (await tracker.tail()).sub(2); metadata_old = await tracker.infos(id); bucket_old = await tracker.checkPoints(getBucket(metadata_old.expiresAt)); await tracker.remove(id); }); it("should set bucket's head == tail", async function(){ const bucket = await tracker.checkPoints(getBucket(metadata_old.expiresAt)); expect(bucket.head).to.be.equal(bucket.tail); expect(bucket.tail).to.be.not.equal(0); }); it("should be connected", async function(){ const prev_info = await tracker.infos(metadata_old.prev); const next_info = await tracker.infos(metadata_old.next); expect(prev_info.next).to.be.equal(metadata_old.next); expect(next_info.prev).to.be.equal(metadata_old.prev); }); }); describe("when bucket had more than 3 elements and deleting is head", function(){ let metadata_old; let bucket_old; it("when head", async function(){ const id = (await tracker.tail()).sub(6); metadata_old = await tracker.infos(id); bucket_old = await tracker.checkPoints(getBucket(metadata_old.expiresAt)); metadata_old = await tracker.infos(bucket_old.head); await tracker.remove(bucket_old.head); const prev_info = await tracker.infos(metadata_old.prev); const next_info = await tracker.infos(metadata_old.next); expect(prev_info.next).to.be.equal(metadata_old.next); expect(next_info.prev).to.be.equal(metadata_old.prev); const bucket_new = await tracker.checkPoints(getBucket(metadata_old.expiresAt)); expect(bucket_new.head).to.be.equal(metadata_old.next); expect(bucket_new.tail).to.be.equal(bucket_old.tail); }); }); describe("when bucket had more than 3 elements", function(){ let metadata_old; let bucket_old; beforeEach(async function(){ const id = (await tracker.tail()).sub(6); metadata_old = await tracker.infos(id); bucket_old = await tracker.checkPoints(getBucket(metadata_old.expiresAt)); await tracker.remove(id); }); it("should be connected", async function(){ const prev_info = await tracker.infos(metadata_old.prev); const next_info = await tracker.infos(metadata_old.next); expect(prev_info.next).to.be.equal(metadata_old.next); expect(next_info.prev).to.be.equal(metadata_old.prev); }); }); }); }); }); });
411d4edd85bf82ceec06e1d4c0c7e5224c0d340c
TypeScript
manonet/typing
/src/reducers/focusUserInput.ts
2.84375
3
import { FocusUserInputAction } from '../actions/index'; export type FocusUserInputState = { isUserInputFocused: boolean; }; const initialState: FocusUserInputState = { isUserInputFocused: false, }; export default function focusUserInputReducer( state: FocusUserInputState = initialState, action: FocusUserInputAction ) { const { type, isUserInputFocused } = action; if (type === 'FOCUSUSERINPUT') { return Object.assign({}, state, { isUserInputFocused, }); } return state; }
262525cee98a9156d1b2be35726af5ac00384f6e
TypeScript
flocasts/flagpole
/src/flagpole.ts
2.90625
3
import { Suite } from "./suite/suite"; export class Flagpole { public static suites: Suite[] = []; /** * Create a new suite * * @param {string} title * @returns {Suite} * @constructor */ static suite = Flagpole.Suite; static Suite(title: string, callback?: (suite: Suite) => any): Suite { // Create suite const suite: Suite = new Suite(title); Flagpole.suites.push(suite); callback && callback(suite); return suite; } }
322280f213ac08987a676421a75841068117bbf9
TypeScript
dolthead/topzee
/src/app/services/scoring.service.spec.ts
2.90625
3
import { TestBed } from '@angular/core/testing'; import { ScoringService } from './scoring.service'; import { Die } from '../models/die.model'; const getDice = ([d1, d2, d3, d4, d5]: number[]): Die[] => { return [ { pips: d1, locked: false }, { pips: d2, locked: false }, { pips: d3, locked: false }, { pips: d4, locked: false }, { pips: d5, locked: false }, ]; }; describe('ScoringService', () => { beforeEach(() => TestBed.configureTestingModule({})); it('should be created', () => { const service: ScoringService = TestBed.get(ScoringService); expect(service).toBeTruthy(); }); describe('getScore (numbers)', () => { it('should return sum of ONES on dice', () => { const service: ScoringService = TestBed.get(ScoringService); expect(service.getScore(getDice([2,3,4,5,6]), 'Ones')).toEqual(0); expect(service.getScore(getDice([1,1,1,1,1]), 'Ones')).toEqual(5); expect(service.getScore(getDice([5,4,2,1,1]), 'Ones')).toEqual(2); }); it('should return sum of TWOS on dice', () => { const service: ScoringService = TestBed.get(ScoringService); expect(service.getScore(getDice([1,3,4,5,6]), 'Twos')).toEqual(0); expect(service.getScore(getDice([2,2,2,2,2]), 'Twos')).toEqual(10); expect(service.getScore(getDice([2,4,2,1,1]), 'Twos')).toEqual(4); }); it('should return sum of THREES on dice', () => { const service: ScoringService = TestBed.get(ScoringService); expect(service.getScore(getDice([1,2,4,5,6]), 'Threes')).toEqual(0); expect(service.getScore(getDice([3,3,3,3,3]), 'Threes')).toEqual(15); expect(service.getScore(getDice([2,3,2,3,1]), 'Threes')).toEqual(6); }); it('should return sum of FOURS on dice', () => { const service: ScoringService = TestBed.get(ScoringService); expect(service.getScore(getDice([1,2,3,5,6]), 'Fours')).toEqual(0); expect(service.getScore(getDice([4,4,4,4,4]), 'Fours')).toEqual(20); expect(service.getScore(getDice([4,3,2,3,4]), 'Fours')).toEqual(8); }); it('should return sum of FIVES on dice', () => { const service: ScoringService = TestBed.get(ScoringService); expect(service.getScore(getDice([1,2,3,4,6]), 'Fives')).toEqual(0); expect(service.getScore(getDice([5,5,5,5,5]), 'Fives')).toEqual(25); expect(service.getScore(getDice([4,5,5,3,4]), 'Fives')).toEqual(10); }); it('should return sum of SIXES on dice', () => { const service: ScoringService = TestBed.get(ScoringService); expect(service.getScore(getDice([1,2,3,4,5]), 'Sixes')).toEqual(0); expect(service.getScore(getDice([6,6,6,6,6]), 'Sixes')).toEqual(30); expect(service.getScore(getDice([4,6,5,3,6]), 'Sixes')).toEqual(12); }); }); describe('getScore (sets)', () => { it('should return sum of dice when 3 OAK', () => { const service: ScoringService = TestBed.get(ScoringService); expect(service.getScore(getDice([2,3,4,5,6]), '3 Oak')).toEqual(0); expect(service.getScore(getDice([1,1,1,1,1]), '3 Oak')).toEqual(5); expect(service.getScore(getDice([5,4,4,1,4]), '3 Oak')).toEqual(18); }); it('should return sum of dice when 4 OAK', () => { const service: ScoringService = TestBed.get(ScoringService); expect(service.getScore(getDice([2,3,4,5,6]), '4 Oak')).toEqual(0); expect(service.getScore(getDice([1,1,1,1,1]), '4 Oak')).toEqual(5); expect(service.getScore(getDice([4,4,4,1,4]), '4 Oak')).toEqual(17); }); it('should return 25 when Full House', () => { const service: ScoringService = TestBed.get(ScoringService); expect(service.getScore(getDice([2,3,4,5,6]), 'Full House')).toEqual(0); expect(service.getScore(getDice([1,1,1,1,1]), 'Full House')).toEqual(25); expect(service.getScore(getDice([4,4,1,1,4]), 'Full House')).toEqual(25); expect(service.getScore(getDice([6,5,6,5,6]), 'Full House')).toEqual(25); }); it('should return 30 when 4 Straight', () => { const service: ScoringService = TestBed.get(ScoringService); expect(service.getScore(getDice([2,3,5,5,5]), '4 Straight')).toEqual(0); expect(service.getScore(getDice([1,3,2,4,1]), '4 Straight')).toEqual(30); expect(service.getScore(getDice([4,3,1,1,2]), '4 Straight')).toEqual(30); expect(service.getScore(getDice([3,5,6,4,2]), '4 Straight')).toEqual(30); }); it('should return 40 when 5 Straight', () => { const service: ScoringService = TestBed.get(ScoringService); expect(service.getScore(getDice([1,1,1,1,1]), '5 Straight')).toEqual(0); expect(service.getScore(getDice([2,3,4,5,5]), '5 Straight')).toEqual(0); expect(service.getScore(getDice([1,3,2,4,5]), '5 Straight')).toEqual(40); expect(service.getScore(getDice([4,3,5,6,2]), '5 Straight')).toEqual(40); expect(service.getScore(getDice([3,5,6,4,2]), '5 Straight')).toEqual(40); }); it('should return 50 when 5 Oak', () => { const service: ScoringService = TestBed.get(ScoringService); expect(service.getScore(getDice([2,3,4,5,5]), '5 Oak')).toEqual(0); expect(service.getScore(getDice([5,3,5,5,5]), '5 Oak')).toEqual(0); expect(service.getScore(getDice([1,1,1,1,1]), '5 Oak')).toEqual(50); expect(service.getScore(getDice([3,3,3,3,3]), '5 Oak')).toEqual(50); expect(service.getScore(getDice([5,5,5,5,5]), '5 Oak')).toEqual(50); expect(service.getScore(getDice([6,6,6,6,6]), '5 Oak')).toEqual(50); }); it('should return sum of dice for Any', () => { const service: ScoringService = TestBed.get(ScoringService); expect(service.getScore(getDice([2,3,4,5,6]), 'Any')).toEqual(20); expect(service.getScore(getDice([1,1,1,1,1]), 'Any')).toEqual(5); expect(service.getScore(getDice([5,4,4,1,4]), 'Any')).toEqual(18); expect(service.getScore(getDice([6,6,6,5,6]), 'Any')).toEqual(29); expect(service.getScore(getDice([6,4,6,4,6]), 'Any')).toEqual(26); }); }); });
9e297c57f3e57c2854d04ff339069ca24e392e80
TypeScript
sushmitha007/angular-learning-unit2
/Lesson2.5.ts
3.15625
3
var a:number =1; var b:number= 2; if(a > b){ console.log("a is more than b") } else{ console.log("b is more than a") }
44d852d06a7ac0f668938ca0a893712369278b72
TypeScript
Holyoneqt/Revolution-Champion
/src/entities/player/Player.ts
3.03125
3
import { QuestDifficulty } from './../../quests/QuestDifficulty'; import * as ko from 'knockout'; import { Entity } from './../Entity'; import { Monster } from './../Monster'; import { Item } from './../../items/Item'; import { Backpack } from './features/Backpack'; import { Quest } from './../../quests/Quest'; import { Interval } from './../../util/Interval'; import { UiEventManager, UiEvent } from '../../core/UiEventManager'; export class Player extends Entity { exp: KnockoutComputed<String>; currentExp: KnockoutObservable<number>; requiredExp: KnockoutComputed<number>; gold: KnockoutObservable<number>; wood: KnockoutObservable<number>; stone: KnockoutObservable<number>; iron: KnockoutObservable<number>; backpack: Backpack; quests: KnockoutObservableArray<Quest>; statPoints: KnockoutObservable<number>; isFighting: KnockoutObservable<boolean>; constructor() { super(); this.stamina(10); this.strength(5); this.currentHealth(this.maxHealth()); this.currentExp = ko.observable(0); this.requiredExp = ko.computed(() => Math.floor(100 * Math.pow(this.level(), 0.75))); this.exp = ko.computed(() => this.checkExp()); this.gold = ko.observable(0); this.wood = ko.observable(0); this.stone = ko.observable(0); this.iron = ko.observable(0); this.backpack = new Backpack(); this.quests = ko.observableArray([ new Quest('Test Quest', 'Just for testing!', QuestDifficulty.EASY), new Quest('Collect Apples', 'We are hungry!', QuestDifficulty.EASY), new Quest('Help a Person', 'Someone is in need of help', QuestDifficulty.MEDIUM), new Quest('Killing Monster', 'Kill some Monsters', QuestDifficulty.HARD), new Quest('Dungeon!', 'Clear a Dungeon', QuestDifficulty.HEROIC) ]); this.quests()[0].test(2); this.statPoints = ko.observable(0); this.isFighting = ko.observable(false); this.level.subscribe(() => this.onLevelUp()); new Interval('HP-Reg', () => { this.regenerateHP(this); }, 500).start(); } /** * Call when Player kills a Monster. * @param {Monster} monster Monster that was killed. * @memberof Player */ public onMonsterKill(monster: Monster): void { this.rewardExp(monster.level()); this.backpack.addItems(monster.loot); } /** * Sells an Item and add the Gold-Value to the Player's gold. * @param {Item} item Item to sell. * @param {number} amount How many times to sell it. (Default is 1) * @memberof Player */ public sell(item: Item, amount: number = 1) { this.backpack.sell(item, amount); this.gold(this.gold() + (item.goldValue * amount)); } /** * Adds Experience Points to the Player * @param amount The Amount of Exp-Point to add. */ public addExp(amount: number): void { this.currentExp(this.currentExp() + Math.floor(amount)); } /** * Rewards Experience to the Player based on the Level of the Monster that was slain. * Formula: 150 / (10 - Monsterlevel-Difference) * Playerlevel * @param {number} monsterLvl Level of the Monster killed. * @memberof Player */ private rewardExp(monsterLvl: number): void { let monsterLevelDiff = monsterLvl - this.level(); let expReward = 150/(10 - monsterLevelDiff) * this.level(); this.currentExp(this.currentExp() + Math.floor(expReward)); } /** * Revives the Player * * @memberof Player */ public revive(): void { this.currentHealth(this.maxHealth()); } /** * Increases a Stat by a given amount. * * @param {KnockoutObservable<number>} stat The Observable Stat to increase * @param {number} amount By which amount to increase. * @memberof Player */ public increaseStat(stat: KnockoutObservable<number>, amount: number): void { stat(stat() + amount); this.statPoints(this.statPoints() - amount); } /** * This function is used to Calculate and Display the Level of the Player * * @private * @returns {String} Formatted Experience-Display * @memberof Player */ private checkExp(): String { if(this.currentExp() >= this.requiredExp()) { let expDiff = this.currentExp() - this.requiredExp(); this.level(this.level() + 1); this.statPoints(this.statPoints() + 1); this.currentExp(expDiff); } return this.currentExp() + '/' + this.requiredExp() } /** * This functions Subscribes to the Level of the Player * * @private * @memberof Player */ private onLevelUp(): void { UiEventManager.FireEvent(UiEvent.OnPlayerLevelUp, this.level()); this.stamina(this.stamina() + 1); this.strength(this.strength() + 1); } public isDead(): boolean { const isDead = super.isDead(); if(isDead) { UiEventManager.FireEvent(UiEvent.OnPlayerDeath, this); this.revive(); } return isDead; } /** * Used for Interval. Gets called every 3 seconds to regenerate 5HP * @private * @memberof Player */ private regenerateHP(_: Player) { if(!_.isDead()) { let regeneration = _.isFighting() ? 2 : 10; let curr = _.currentHealth(); if(curr + regeneration < _.maxHealth()) { _.currentHealth(curr + regeneration); } else { _.currentHealth(_.maxHealth()); } } } }
2105fa9e6edfff28335e2fec353978e9c577b407
TypeScript
luizaprata/QuizTime
/src/modules/quiz/types/Quiz.types.ts
2.640625
3
export type DifficultyScore = { hits: number; errors: number }; export interface IWorkspace { id: number; name: string; scores: Realm.Results<IScore>; } export interface IScore { id: number; difficulty: string; hits: number; errors: number; workspace: IWorkspace; }
10b740b86b9469792cdead0d18ffd988689c4b68
TypeScript
tuanzijiang/pizza
/pizza-consumer-web/src/utils/log.ts
2.765625
3
export const info = (tag: string, ...params: any) => { if (process.env.NODE_ENV === 'development') { console.info(`[${tag}]:`, ...params); } }; export const warn = (tag: string, extraInfo: string, ...params: any) => { console.warn(`[${tag}]:${extraInfo}`, ...params); }; export const error = (tag: string, extraInfo: string, ...params: any) => { console.error(`[${tag}]:${extraInfo}`, ...params); }; export enum LogTag { NET = 'NET', DB = 'DB', }
2414878197c9f83bf564c94b643ed342755a5fe6
TypeScript
chkt/xyzw-rgba
/source/lch.ts
2.65625
3
import { CSS4_ALPHA, CSS4_DELIM, CSS_MAX_DECIMALS, CssLchString, CssOptions, UINT8_TO_PCT, UINT8_TO_UNIT, UNIT_TO_PCT, createNumberOrPercentParser, cssDefaults, cssPrecision, parseCssAlpha, parseCssAngle, parseCssLabLightness } from './parse'; import { align, angle, angleUnit, clamp, interval, toFixed } from './real'; import * as labApi from './lab'; export interface Lch { lightness : number; chroma : number; hue : number; alpha : number; } const EXPR_CSS_LCH = /^lch\(\s*(\S+)\s*(\S+)\s*([^\s/]+)\s*(?:\/\s*(\S+)\s*)?\)$/; const TAU = 2.0 * Math.PI; const EPSILON = 1e-10; const { abs : absfn, max : maxfn, min : minfn, atan2 : atan2fn, sqrt : sqrtfn } = Math; const nanfn = Number.isNaN; const parseChroma = createNumberOrPercentParser({ percentScale : 1.5, clampMin : 0.0 }); export function equals(a:Lch, b:Lch, e:number = EPSILON) : boolean { return absfn(a.lightness - b.lightness) < e && absfn(a.chroma - b.chroma) < e && absfn(interval(a.hue, 0.0, TAU) - interval(b.hue, 0.0, TAU)) < e && absfn(a.alpha - b.alpha) < e; } export function isChromaHuePowerless(lch:Lch, e:number = EPSILON) : boolean { return nanfn(lch.lightness) || absfn(lch.lightness) < e; } export function isHuePowerless(lch:Lch, e:number = EPSILON) : boolean { return nanfn(lch.lightness + lch.chroma) || absfn(lch.lightness) < e || absfn(lch.chroma) < e; } export function Create(lightness:number = 100.0, chroma:number = 0.0, hue:number = 0.0, alpha:number = 1.0) : Lch { return { lightness, chroma, hue, alpha }; } export function assign<R extends Lch>( res:R, lightness:number = 100.0, chroma:number = 0.0, hue:number = 0.0, alpha:number = 1.0 ) : R { res.lightness = lightness; res.chroma = chroma; res.hue = hue; res.alpha = alpha; return res; } export function Lab(color:labApi.Lab) : Lch { return lab(Create(), color); } export function lab<R extends Lch>(res:R, color:labApi.Lab) : R { const { lightness, a, b, alpha } = color; res.lightness = lightness; res.chroma = sqrtfn(a ** 2 + b ** 2); res.hue = atan2fn(b, a); res.alpha = alpha; return res; } export function toLab(lch:Lch) : labApi.Lab { return assignLab(labApi.Create(), lch); } export function assignLab<R extends labApi.Lab>(res:R, lch:Lch) : R { const { lightness, chroma, hue, alpha } = lch; res.lightness = lightness; res.a = chroma * Math.cos(hue); res.b = chroma * Math.sin(hue); res.alpha = alpha; return res; } export function CssLch(expr:CssLchString) : Lch { return cssLch(Create(), expr); } export function cssLch<R extends Lch>(res:R, expr:CssLchString) : R { const match = EXPR_CSS_LCH.exec(expr) as [ string, string, string, string, string | undefined ] | null; if (match === null) throw new Error(`bad css color '${ expr }'`); const [ , l, c, h, a ] = match; try { res.lightness = parseCssLabLightness(l); res.chroma = parseChroma(c); res.hue = parseCssAngle(h); res.alpha = a !== undefined ? parseCssAlpha(a) : 1.0; } catch (err) { throw new Error(`bad css color '${ expr }'`); } return res; } export function toCss(lch:Lch, opts?:Partial<CssOptions>) : CssLchString { let { lightness, chroma, hue, alpha } = lch; if (Number.isNaN(lightness + chroma + hue + alpha)) throw new Error(`bad lch "${ lightness.toFixed(2) } ${ chroma.toFixed(2) } ${ hue.toFixed(2) } ${ alpha.toFixed(2) }"`); lightness = maxfn(lightness, 0.0); chroma = maxfn(chroma, 0.0); hue = interval(hue, 0.0, TAU); alpha = clamp(alpha, 0.0, 1.0); const settings = { ...cssDefaults, ...opts }; const lchDigits = clamp(settings.decimals, 0, CSS_MAX_DECIMALS); let alphaDigits = lchDigits; let unit = ''; if (settings.percent) { chroma *= 1.0 / 1.5; alpha *= UNIT_TO_PCT; unit = '%'; if (settings.precision === cssPrecision.uint8) { alpha = align(alpha, UINT8_TO_PCT, 0.5 - 1e10); alphaDigits = 1; } } else if (settings.precision === cssPrecision.uint8) { alpha = align(alpha, UINT8_TO_UNIT); alphaDigits = minfn(alphaDigits, 3); } let res = `${ toFixed(lightness, lchDigits) }${ unit }${ CSS4_DELIM }${ toFixed(chroma, lchDigits) }${ unit }${ CSS4_DELIM }${ toFixed(angle(hue, angleUnit.rad, settings.angleUnit), lchDigits) }${ settings.angleUnit !== angleUnit.deg ? settings.angleUnit : '' }`; if (alpha !== 1.0) res += `${ CSS4_ALPHA }${ toFixed(alpha, alphaDigits) }${ unit }`; return `lch(${ res })`; } export function Copy(lch:Lch) : Lch { return { ...lch }; } export function copy<R extends Lch>(res:R, lch:Lch) : R { res.lightness = lch.lightness; res.chroma = lch.chroma; res.hue = lch.hue; res.alpha = lch.alpha; return res; }
abb97df513dee1d0bcc0cd2f98b4ec695d310dce
TypeScript
amsdams/your-first-app
/src/app/in-memory-data.service.ts
2.875
3
import { InMemoryDbService } from 'angular-in-memory-web-api'; import { Injectable } from '@angular/core'; import { Product } from './models/models'; @Injectable({ providedIn: 'root', }) export class InMemoryDataService implements InMemoryDbService { createDb() { const products = [ { id: 0, name: 'Phone XL', price: 799, description: 'A large phone with one of the best screens' }, { id: 1, name: 'Phone Mini', price: 699, description: 'A great phone with one of the best cameras' }, { id: 2, name: 'Phone Standard', price: 299, description: '' } ]; const shippingCosts = [ { id: 0, type: 'Overnight', price: 25.99 }, { id: 1, type: '2-Day', price: 9.99 }, { id: 2, type: 'Postal', price: 2.99 } ]; return {products, shippingCosts}; } // Overrides the genId method to ensure that a hero always has an id. // If the heroes array is empty, // the method below returns the initial number (11). // if the heroes array is not empty, the method below returns the highest // hero id + 1. genId(products: Product[]): number { return products.length > 0 ? Math.max(...products.map(product => product.id)) + 1 : 11; } }
17a8abde329c0f6837b9e99b9ca379c732606cd0
TypeScript
gareththegeek/doom
/doom/src/collisions/lineCollisionResponse.ts
2.640625
3
import { ReadonlyVec2, vec2 } from 'gl-matrix' import { pointIsLeftOfLine } from '../maths/findLineSideForPoint' import { projectPositionOntoLine } from '../maths/projectVectorOntoVector' let v = vec2.create() const getLineNormal = (pout: vec2, start: ReadonlyVec2, end: ReadonlyVec2, side: ReadonlyVec2): void => { vec2.subtract(v, end, start) if (pointIsLeftOfLine(start, end, side)) { pout[0] = -v[1] pout[1] = v[0] } else { pout[0] = v[1] pout[1] = -v[0] } } let clipped = vec2.create() let normal = vec2.create() let offset = vec2.create() export const lineCollisionResponse = ( pout: vec2, start: ReadonlyVec2, end: ReadonlyVec2, radius: number, p0: ReadonlyVec2, p1: ReadonlyVec2 ): void => { projectPositionOntoLine(clipped, p1, start, end) getLineNormal(normal, start, end, p0) vec2.normalize(normal, normal) vec2.scale(offset, normal, radius + 1.0) vec2.add(pout, clipped, offset) }
e7204b697d48780ca2731a8308fcd547e0cd5803
TypeScript
sijujacobs/impetus_angular7
/src/app/reducers/product.reducer.ts
2.78125
3
import { Action } from "@ngrx/store"; import { IProduct } from "../models/product.model"; import * as ProductActions from "../actions/product.actions"; const initialState: IProduct = { name: "MyProduct", brand: "MyBrand", url: "https://www.google.com/" }; export function productReducer( state: IProduct[] = [initialState], action: ProductActions.Actions ) { switch (action.type) { case ProductActions.ADD_PRODUCT: return [...state, action.payload]; default: return state; } }
8384dd2dea4c2ce7385af0676b5ddebb6db6d52d
TypeScript
ClaudiaFeliciano/Arrow-6
/Scripts/objects/meteor.ts
2.765625
3
module objects { export class Meteor extends objects.AbstractGameObject { // private instance variables private _verticalSpeed: number; private _horizontalSpeed: number; // public properties // constructor constructor() { super("meteor"); this.Start(); } // private methods private _move(): void { this.x += this._verticalSpeed; //i want my meteor to move not ony vertical but also horizontal this.y += this._horizontalSpeed; } private _checkBounds(): void { if (this.x > 1024 + this.Width) { this.Reset(); } } // public methods public Reset(): void { this._verticalSpeed = Math.floor(Math.random() * 3 + 3); //randomizing my speed as well this._horizontalSpeed = Math.floor(Math.random() * 3 - 2); this.x = -this.Width; this.y = Math.floor( Math.random() * (1024 - this.Height) + this.HalfHeight ); this.alpha = 1; } public Start(): void { this.Reset(); } public Update(): void { this._move(); this._checkBounds(); } public Destroy(): void {} } }
6971dfbcb37eb92a8ea913f3c70429df1782ead0
TypeScript
32bitkid/sci.js
/libs/sci0/src/view.ts
2.65625
3
import { Cel } from '@4bitlabs/screen'; import { repeat } from './repeat'; import { parseCel } from './cel'; export interface ViewGroup { frames: Cel<4>[]; isMirrored: boolean; } export const parseFrom = (source: Uint8Array): ViewGroup[] => { const view = new DataView( source.buffer, source.byteOffset, source.byteLength, ); const groupCount = view.getUint16(0, true); const mirrored = view.getUint16(2, true); return repeat(groupCount, (groupIdx) => { const groupOffset = view.getUint16(8 + groupIdx * 2, true); const groupView = new DataView( source.buffer, source.byteOffset + groupOffset, ); const frameCount = groupView.getUint16(0, true); const isMirrored = (mirrored & (1 << groupIdx)) !== 0; const frames = repeat(frameCount, (frameIdx) => { const frameOffset = groupView.getUint16(frameIdx * 2 + 4, true); const frameView = new DataView( source.buffer, source.byteOffset + frameOffset, ); return parseCel(frameView); }); return { frames, isMirrored, }; }); };
7c43fd868e9e7c6561b68076c55ed4e49bbf3d61
TypeScript
bjabinn/HealthCheckWcf
/service-chart/src/app/app.component.ts
2.515625
3
import { Component } from '@angular/core'; import { DataService } from './services/data.service'; import { Services } from './models/services'; import { Observable } from 'rxjs'; import { Service } from './models/service'; import { element } from '@angular/core/src/render3'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { dataFromJson: any; services: Service[] = []; error: any; prefix:string = "TESCO"; constructor(private dataService:DataService){ // this.fillData(); // setInterval(()=>this.fillData(),5000); this.dataService.getJSON().subscribe( data => this.fillServices(data), error=> this.error = error.status===404 ? `Ups, algo ha ido mal intentando leer el json. ( File Not Found - ${error.status} )` : "Ups, algo ha ido mal intentando leer el json. Http error: " +error.status ); } fillServices(data: Services): void { this.services = []; data.services.forEach(element => { element = element; element.notifyTimeout = false; this.services.push(element); }); } // fillData(){ // let data = []; // let visits = 10; // for (let i = 1; i <= 4; i++) { // visits += Math.round((Math.random() < 0.5 ? 1 : -1) * Math.random() * 10); // data.push({ // data: 5+i, // // name: "name" + i, value: visits // }); // } // this.dataFromJson = data; // console.log(this.dataFromJson); // } }
2e381b71c042821630129c76a847d3ae97293e20
TypeScript
innogames/grpc-web
/test/ts/src/ChunkParser.spec.ts
2.5625
3
import {assert} from "chai"; import {decodeASCII} from "../../../ts/src/ChunkParser"; describe("ChunkParser", () => { describe("decodeASCII", () => { function asciiToBinary(src: string): Uint8Array { const ret = new Uint8Array(src.length); for (let i = 0; i !== src.length; ++i) { ret[i] = src.charCodeAt(i); } return ret; } function testDecode(testCase: string) { assert.equal(testCase, decodeASCII(asciiToBinary(testCase))); } it("should allow valid HTTP headers around", () => { testDecode("User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0\r\n"); }); it("should allow quoted headers", () => { testDecode(`alt-svc: hq=":443"; ma=2592000; quic=51303431; quic=51303339; quic=51303338; quic=51303337; quic=51303335,quic=":443"; ma=2592000; v="41,39,38,37,35"\r\n`); }); it("should reject non-encoded Unicode characters", () => { assert.throw(() => decodeASCII(Uint8Array.from([0xe3, 0x81, 0x82]))); // 'あ' }) }) });
1e34ac5ae2839456bc14f24fd7dfc27c0e43f404
TypeScript
krawaller/algol5
/modules/common/utils/possibilities.test.ts
3.171875
3
import { possibilities } from ".."; import { AlgolIfableExpressionAnon } from "../../types"; type PossTest<_T> = { expr: AlgolIfableExpressionAnon<_T>; poss: AlgolIfableExpressionAnon<_T>[]; player?: 0 | 1 | 2; action?: string; ruleset?: string; }; const possTests: PossTest< "FOO" | "BAR" | "BAZ" | "BIN" | { o: 1 } | { o: 2 } >[] = [ { expr: "FOO", poss: ["FOO"] }, { expr: { o: 1 }, poss: [{ o: 1 }] }, { expr: { ifelse: [["true"], "FOO", { ifelse: [["false"], "BAR", "BAZ"] }] }, poss: ["FOO", "BAR", "BAZ"], }, { expr: { ifactionelse: ["someaction", "BAR", "BIN"] }, poss: ["BAR", "BIN"], }, { expr: { ifactionelse: ["someaction", "BAR", "BIN"] }, action: "someaction", poss: ["BAR"], }, { expr: { ifactionelse: ["someaction", "BAR", "BIN"] }, action: "anotheraction", poss: ["BIN"], }, { expr: { playercase: ["FOO", "BAZ"] }, poss: ["FOO", "BAZ"], }, { expr: { playercase: ["FOO", "BAZ"] }, player: 1, poss: ["FOO"], }, { expr: { playercase: ["FOO", "BAZ"] }, player: 2, poss: ["BAZ"], }, { expr: { indexlist: [2, "BAR", "BAZ", { playercase: ["BAR", "BIN"] }] }, poss: ["BAR", "BAZ", "BIN"], }, { expr: { indexlist: [2, { o: 1 }, { playercase: [{ o: 1 }, { o: 2 }] }] }, poss: [{ o: 1 }, { o: 2 }], }, { expr: { if: [["false"], { ifelse: [["true"], "FOO", "BIN"] }] }, poss: ["FOO", "BIN"], }, { expr: { ifplayer: [1, "FOO"] }, player: 1, poss: ["FOO"], }, { expr: { ifplayer: [1, "FOO"] }, player: 2, poss: [], }, { expr: { ifaction: ["someaction", "FOO"] }, poss: ["FOO"], }, { expr: { ifaction: ["someaction", "FOO"] }, action: "someaction", poss: ["FOO"], }, { expr: { ifaction: ["someaction", "FOO"] }, action: "anotheraction", poss: [], }, { expr: { ifruleset: ["somerulez", "FOO"] }, ruleset: "somerulez", poss: ["FOO"], }, { expr: { ifruleset: ["somerulez", "FOO"] }, ruleset: "otherrulez", poss: [], }, { expr: { ifrulesetelse: ["somerulez", "FOO", "BAR"] }, ruleset: "somerulez", poss: ["FOO"], }, { expr: { ifrulesetelse: ["somerulez", "FOO", "BAR"] }, ruleset: "otherrulez", poss: ["BAR"], }, ]; test("possibilities", () => possTests.forEach( ({ expr, poss, player = 0, action = "any", ruleset = "basic" }) => expect(possibilities(expr, player as 0 | 1 | 2, action, ruleset)).toEqual( poss ) ));
232bfd27329a783817abb790fc2fd144122affa2
TypeScript
tomekkleszcz/redux-saga-promise-actions
/example/src/actions/auth.ts
2.5625
3
//Action creators import {createPromiseAction} from '../../../dist'; //Replace with redux-saga-promise-actions //Types import {Credentials, TokenPair} from '../types/auth'; /** * signIn promise action declaration * If you want payload to be empty in any stage declare it as undefined. * @type {PromiseActionSet<'SIGN_IN_REQUEST', 'SIGN_IN_SUCCESS', 'SIGN_IN_FAILURE', Credentials, TokenPair, undefined>} */ export const signIn = createPromiseAction( 'SIGN_IN_REQUEST', 'SIGN_IN_SUCCESS', 'SIGN_IN_FAILURE' )<Credentials, TokenPair, undefined>(); /** * signOut promise action declaration * @type {PromiseActionSet<'SIGN_OUT_REQUEST', 'SIGN_OUT_SUCCESS', 'SIGN_OUT_FAILURE', undefined, undefined, undefined>} */ export const signOut = createPromiseAction( 'SIGN_OUT_REQUEST', 'SIGN_OUT_SUCCESS', 'SIGN_OUT_FAILURE' )<undefined, undefined, undefined>();
265132678fae7180d772023f12ffa8abf1290d60
TypeScript
kyle-mccarthy/personal-v1
/src/api/auth/auth.service.ts
2.671875
3
import { Injectable } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { User } from '@src/api/user/user.entity'; import { UserService } from '@src/api/user/user.service'; import { DecodedPayload } from './dto/decoded-jwt'; import { JwtPayload } from './dto/jwt-payload'; @Injectable() export class AuthService { constructor( private readonly userService: UserService, private readonly jwtService: JwtService, ) {} public async validateUserCredentials(email: string, password: string) { let user = null; const errorText = 'The email and password combination do not match'; user = await this.userService.findByEmail(email); if (!user) { throw new Error(errorText); } const validPassword = await this.userService.comparePassword( password, user.password, ); if (!validPassword) { throw new Error(errorText); } return user; } public async validatePayload(payload: JwtPayload) { return await this.userService.findByEmail(payload.email); } public signUser(user: User) { const { name, email } = user; const payload: JwtPayload = { name, email }; return this.jwtService.sign(payload); } public verifyToken(token: string) { return this.jwtService.verify(token); } public decodeToken(token: string): null | DecodedPayload { return this.jwtService.decode(token, {}) as DecodedPayload; } }
a285413d62241cd51fdb219986217d96838e0ed2
TypeScript
samlbest/kitten.js
/src/sprites/imageSprite.ts
2.78125
3
import Sprite from "../graphics/sprite"; import SpriteOptions from "../graphics/spriteOptions"; export default class ImageSprite extends Sprite { constructor(private imagePath: string, spriteOptions: SpriteOptions) { super(spriteOptions); } render(): void { let img = new Image(); img.src = this.imagePath; this.canvasContext.drawImage(img, this.position.x, this.position.y, this.size.width, this.size.height); } }
32430d7ca38d6971959b0f16afd8eb118ba55232
TypeScript
staydecent/plugins
/packages/alias/src/index.ts
2.625
3
import { platform } from 'os'; import { PartialResolvedId, Plugin } from 'rollup'; import slash from 'slash'; import { Alias, ResolverFunction, RollupAliasOptions } from '../types'; const VOLUME = /^([A-Z]:)/i; const IS_WINDOWS = platform() === 'win32'; // Helper functions const noop = () => null; function matches(pattern: string | RegExp, importee: string) { if (pattern instanceof RegExp) { return pattern.test(importee); } if (importee.length < pattern.length) { return false; } if (importee === pattern) { return true; } const importeeStartsWithKey = importee.indexOf(pattern) === 0; const importeeHasSlashAfterKey = importee.substring(pattern.length)[0] === '/'; return importeeStartsWithKey && importeeHasSlashAfterKey; } function normalizeId(id: string): string; function normalizeId(id: string | undefined): string | undefined; function normalizeId(id: string | undefined) { if (typeof id === 'string' && (IS_WINDOWS || VOLUME.test(id))) { return slash(id.replace(VOLUME, '')); } return id; } function getEntries({ entries }: RollupAliasOptions): Alias[] { if (!entries) { return []; } if (Array.isArray(entries)) { return entries; } return Object.entries(entries).map(([key, value]) => { return { find: key, replacement: value }; }); } export default function alias(options: RollupAliasOptions = {}): Plugin { const entries = getEntries(options); // No aliases? if (entries.length === 0) { return { name: 'alias', resolveId: noop }; } return { name: 'alias', resolveId(importee, importer) { const importeeId = normalizeId(importee); const importerId = normalizeId(importer); // First match is supposed to be the correct one const matchedEntry = entries.find((entry) => matches(entry.find, importeeId)); if (!matchedEntry || !importerId) { return null; } const updatedId = normalizeId( importeeId.replace(matchedEntry.find, matchedEntry.replacement) ); let customResolver: ResolverFunction | null = null; if (typeof matchedEntry.customResolver === 'function') { ({ customResolver } = matchedEntry); } else if ( typeof matchedEntry.customResolver === 'object' && typeof matchedEntry.customResolver!.resolveId === 'function' ) { customResolver = matchedEntry.customResolver!.resolveId; } else if (typeof options.customResolver === 'function') { ({ customResolver } = options); } else if ( typeof options.customResolver === 'object' && typeof options.customResolver!.resolveId === 'function' ) { customResolver = options.customResolver!.resolveId; } if (customResolver) { return customResolver(updatedId, importerId); } return this.resolve(updatedId, importer, { skipSelf: true }).then((resolved) => { let finalResult: PartialResolvedId | null = resolved; if (!finalResult) { finalResult = { id: updatedId }; } return finalResult; }); } }; }
a0860681eef6fae5ddab78ba15e9ec216a486dec
TypeScript
muadjb/ReactPeopleFilter
/src/utils/utils.ts
2.890625
3
import { anyPass, isNil, isEmpty } from 'ramda' function unique<T>(xs: ReadonlyArray<T>): ReadonlyArray<T> { return [...new Set(xs)] } const prop = <T, P extends keyof T>(p: P) => (x: T): T[P] => x[p] export function uniqueProps<T, P extends keyof T>(p: P, xs: ReadonlyArray<T>): ReadonlyArray<T[P]> { return unique(xs.map(prop(p))) } export const isNilOrEmpty = anyPass([isNil, isEmpty])
5a78279aa164045dac4ab79568bb749020b6ab66
TypeScript
eordano/webb
/utils/scene/validation.ts
2.609375
3
import { isArray, isNumber } from 'util' import { AssetDefinition, AssetTagDefinition, ReferenceSystem, CoordinateDefinition, Coordinate, SpawnPointDefinition, Vector3Range, NumberOrRange, Range2, YRotation, UnsanitizedSceneManifest } from './SceneManifestTypes' import { Vector3 } from '../Vector' export function getInvalidReason(arg: any) { if (!hasValidVersion(arg)) { return 'version' } if (!hasValidAssets(arg)) { return 'assets' } if (!hasValidAssetTags(arg)) { return 'assetTags' } if (!hasValidRequiredTags(arg)) { return 'requiredTags' } if (!hasValidMain(arg)) { return 'main' } if (!hasValidReferenceSystem(arg)) { return 'referenceSystem' } if (!hasValidParcels(arg)) { return 'parcels' } if (!hasValidContact(arg)) { return 'contact' } if (!hasValidSpawnPoints(arg)) { return 'spawnPoint' } if (!hasValidDisplay(arg)) { return 'display' } } export function isValidSceneInput(arg: any): arg is UnsanitizedSceneManifest { return typeof arg === 'object' && getInvalidReason(arg) === undefined } export function hasValidVersion(arg: any) { return arg.version && typeof arg.version === 'number' && [1, 2].includes(arg.version) } export function isValidNumber(arg: any): arg is number { return isNumber(arg) } export function hasValidAssets(arg: any) { return arg.assets && isArray(arg.assets) && arg.assets.reduce((a: boolean, b: any) => a && isValidAsset(b), true) } export function isValidAsset(arg: any): arg is AssetDefinition { return ( arg && typeof arg === 'object' && typeof arg.name === 'string' && (typeof arg.uri === 'string' || typeof arg.hash === 'string') ) } export function hasValidAssetTags(arg: any): arg is { assetTags?: AssetTagDefinition[] } { return ( arg.assetTags === undefined || (isArray(arg.assetTags) && arg.assetTags.reduce((a: boolean, b: any) => a && isValidAssetTag(b), true)) ) } export function isValidAssetTag(arg: any): arg is AssetTagDefinition { return arg && typeof arg.name === 'string' && isArray(arg.assets) && isValidStringArray(arg.assets) } export function isValidStringArray(arg: any): arg is string[] { return isArray(arg) && arg.reduce((a: boolean, b: any) => a && typeof b === 'string', true) } export function hasValidRequiredTags(arg: any): arg is { requiredTags?: string[] } { return arg.requiredTags === undefined || isValidStringArray(arg.requiredTags) } export function hasValidMain(arg: any): arg is { main?: string } { return arg.main === undefined || isValidString(arg.main) } export function isValidString(arg: any): arg is string { return typeof arg === 'string' } export function hasValidReferenceSystem(arg: any): arg is { referenceSystem?: ReferenceSystem } { return ( arg.referenceSystem === undefined || ((typeof arg.referenceSystem.position === 'undefined' || isValidVector3(arg.referenceSystem.position)) && (typeof arg.referenceSystem.rotation === 'undefined' || isValidYRotation(arg.referenceSystem.rotation))) ) } export function isValidVector3(arg: any): arg is Vector3 { return typeof arg === 'object' && isValidNumber(arg.x) && isValidNumber(arg.y) && isValidNumber(arg.z) } export function hasValidParcels(arg: any): arg is { parcels: CoordinateDefinition[] } { return ( isArray(arg.parcels) && arg.parcels.length > 0 && arg.parcels.reduce((a: boolean, b: any) => a && isValidCoordinateDefinition(b), true) ) } export const CoordinateRegex = /^-?\d+,-?\d+$/ export function isValidCoordinateDefinition(arg: any): arg is CoordinateDefinition { return (typeof arg === 'string' && CoordinateRegex.test(arg)) || (typeof arg === 'object' && isValidCoordinate(arg)) } export function isValidCoordinate(arg: any): arg is Coordinate { return typeof arg === 'object' && isValidNumber(arg.x) && isValidNumber(arg.y) } export function hasValidContact(arg: any): arg is { contact?: Record<string, string> } { return arg.contact === undefined || isValidStringRecord(arg.contact) } export function isValidStringRecord(arg: any): arg is Record<string, string> { return Object.keys(arg).reduce((a: boolean, b: any) => a && typeof b === 'string' && typeof arg[b] === 'string', true) } export function hasValidSpawnPoints(arg: any): arg is { spawnPoints?: SpawnPointDefinition[] } { return ( arg.spawnPoints === undefined || (isArray(arg.spawnPoints) && arg.spawnPoints.reduce((a: boolean, b: any) => a && isValidSpawnPoint(b), true)) ) } export function isValidSpawnPoint(arg: any): arg is SpawnPointDefinition { return ( (arg.name === undefined || isValidString(arg.name)) && isValidVector3NumberOrRange(arg.position) && (isValidQuaternionRange(arg.camera) || isValidYRotation(arg.camera)) && (arg.default === undefined || typeof arg.default === 'boolean') ) } export function isValidVector3NumberOrRange(arg: any): arg is Vector3Range { return ( typeof arg === 'object' && isValidNumberOrRange(arg.x) && isValidNumberOrRange(arg.y) && isValidNumberOrRange(arg.z) ) } export function isValidQuaternionRange(arg: any): arg is Vector3Range { return ( typeof arg === 'object' && isValidNumberOrRange(arg.x) && isValidNumberOrRange(arg.y) && isValidNumberOrRange(arg.z) && isValidNumberOrRange(arg.w) ) } export function isValidNumberOrRange(arg: any): arg is NumberOrRange { return isValidNumber(arg) || isValidRange(arg) } export function isValidRange(arg: any): arg is Range2 { return isArray(arg) && arg.length === 2 && isValidNumber(arg[0]) && isValidNumber(arg[1]) } export function isValidYRotation(arg: any): arg is YRotation { return typeof arg === 'object' && isValidNumberOrRange(arg.y) } export function hasValidDisplay(arg: any): arg is { display?: Record<string, string> } { return arg.display === undefined || isValidStringRecord(arg.display) }
1ea9eeea80068e8a5047f6f2afca52ec04795824
TypeScript
bleshik/blinsky
/src/IdentifiedEntity.ts
2.78125
3
import { is } from 'immutable'; import { CloneWith } from './CloneWith'; import { EqualsHashCode } from './EqualsHashCode'; const hashIt = require('hash-it'); export abstract class IdentifiedEntity<K> extends CloneWith implements EqualsHashCode { readonly id: K; equals(other: any): boolean { return is(this.id, other['id']); } hashCode(): number { return hashIt(this.id); } }
07a8c169fb7b6151bb1145b8e873bcf3228cbda3
TypeScript
wilfoz/web-vpo
/src/app/store/budget-store.ts
2.515625
3
import { Injectable } from '@angular/core'; import { Budget } from '../models/budget'; import { Store } from './store'; import { Context } from '../models/context'; import { Category } from '../models/category'; export class BudgetState { currentBudget?: Budget; totalAvaliable: number; } @Injectable() export class BudgetStore extends Store<BudgetState> { constructor() { super(new BudgetState(), 'budget'); } get avaliable() { let total = 0; this.state.currentBudget.agrupamentos.forEach(a => { total += a.categorias.reduce( (previous, current) => previous + (current.valor_orcado - current.valor_atividades), 0 ) || 0; }); return total; } async setCurrentBudget(budget: Budget): Promise<any> { this.setState({ ...this.state, currentBudget: budget }); } avaliableByGroup(groupId: number): number { const categorias = this.state.currentBudget.agrupamentos.find(a => a.id_agrupamento === groupId).categorias; return categorias.reduce((previous, current) => previous + (current.valor_orcado - current.valor_atividades), 0) || 0; } avaliableByCategory(categoria: Category): number { return categoria.valor_orcado - categoria.valor_atividades; } }
57f19dc5bd8b3e00bd527800e39320516ed4db7e
TypeScript
Leila-karimi/moviehub
/movieHub/src/app/components/shared/groupby.pipe.ts
2.609375
3
import { Pipe, PipeTransform } from '@angular/core'; import { Actor } from '../../models/actor.model' @Pipe({name: 'groupBy'}) export class GroupByPipe implements PipeTransform { transform(value: Array<Actor>, field:string): Array<any> { console.log('field', field) if (value) { const groupedObj = value.reduce((prev, cur) =>{ if(!prev[cur[field]]) { prev[cur[field]] = cur } else{ prev[cur[field]].push(cur); } return prev; }, {}); return Object.keys(groupedObj).map(key => ({ key:key, value: groupedObj[key] })); } else { return null; } } }
e6c220ede4043aeeebb65112c0220e0a5ab6c16c
TypeScript
zbicin/mindbreaker-phonegap
/src/states/State.ts
2.703125
3
import { StateContext } from './StateContext'; import { UILabel, UIButton, UIElement, UIBitmapLabel, UIBitmapButton } from '../ui'; export abstract class State { public bitmaps: Array<UIBitmapLabel>; public bitmapButtons: Array<UIBitmapButton>; public buttons: Array<UIButton>; public labels: Array<UILabel>; public stateContext: StateContext; private backgroundImage: HTMLImageElement; private isBackgroundImageLoaded: boolean; private startTime: number; constructor(sc: StateContext) { this.stateContext = sc; this.startTime = new Date().getTime(); this.buttons = new Array<UIButton>(); this.labels = new Array<UILabel>(); this.bitmaps = new Array<UIBitmapLabel>(); this.bitmapButtons = new Array<UIBitmapButton>(); this.backgroundImage = new Image(); this.isBackgroundImageLoaded = false; this.backgroundImage.onload = () => { this.isBackgroundImageLoaded = true; }; // TODO set url } public abstract tick(): void; public draw(canvas: HTMLCanvasElement): void { const context = canvas.getContext('2d'); if (this.isBackgroundImageLoaded) { for (let x = 0; x < canvas.width; x += this.backgroundImage.width) { for (let y = 0; y < canvas.height; y += this.backgroundImage.height) { context.drawImage(this.backgroundImage, x, y, this.backgroundImage.width, this.backgroundImage.height); } } } this.labels.forEach((l) => l.draw(canvas)); this.buttons.forEach((b) => b.draw(canvas)); this.bitmaps.forEach((b) => b.draw(canvas)); this.bitmapButtons.forEach((bb) => bb.draw(canvas)); } public getTimeInCurrentState(): number { const result = new Date().getTime() - this.startTime; return result; } public onDown(x: number, y: number): void { console.log(`Unhandled tap x: ${x} y: ${y}`); } public onUp(x: number, y: number): void { } protected determineTapTarget(x: number, y: number): UIElement { let tappedButton: UIElement = null; tappedButton = this.buttons.filter((b) => b.isAtPoint(x, y))[0]; tappedButton = this.bitmapButtons.filter((b) => b.isAtPoint(x, y))[0]; return tappedButton ? tappedButton : null; } }
91154f4f4b624a21b0203786f1e0613fad804f9b
TypeScript
VaIcorn/Sequelize-Typescript-Example
/controller/util/log.controller.ts
3.265625
3
import * as log4js from 'log4js'; import * as path from 'path'; enum Severity { info, warn, error, debug } export class LogController { private static log: log4js.Logger; /** * Logs an Info-Message to Console * Disabled in Productionmode * @param message The Message that is always displayed * @param additionalObjects Additional Objects for Debugging - not displayed in Productionmode */ public static info(message: string, ...additionalObjects: any[]): void { this.logToConsole(Severity.info, message, additionalObjects); } /** * Logs an Warning to Console * @param message The Message that is always displayed * @param additionalObjects Additional Objects for Debugging - not displayed in Productionmode */ public static warn(message: string, ...additionalObjects: any[]): void { this.logToConsole(Severity.warn, `Warn: ${message}`, additionalObjects); } /** * Logs an Error to Console * @param message The Message that is always displayed * @param additionalObjects Additional Objects for Debugging - not displayed in Productionmode */ public static error(message: string, ...additionalObjects: any[]): void { this.logToConsole(Severity.error, message, additionalObjects); } /** * Logs an Debug-Message to Console * Disabled in Productionmode * @param message The Message that is always displayed * @param additionalObjects Additional Objects for Debugging - not displayed in Productionmode */ public static debug(message: string, ...additionalObjects: any[]): void { this.logToConsole(Severity.debug, message, additionalObjects); } private static logToConsole(severity: Severity, message: string, additionalObjects: any[]): void { const isProduction = process.env.NODE_ENV === 'production'; if (isProduction && !this.log) { // initialize Logger log4js.configure(path.join(__dirname, '/../../config/log4js.json')); this.log = log4js.getLogger('app'); } // if started locally log to the console, otherwise use log4js const logger = isProduction ? this.log : console; additionalObjects = additionalObjects.length === 0 ? null : additionalObjects switch (severity) { case Severity.info: logger.info(message, additionalObjects || ''); break; case Severity.warn: logger.warn(message, additionalObjects || ''); break; case Severity.error: logger.error(message, additionalObjects || ''); break; case Severity.debug: logger.debug(message, additionalObjects || ''); break; } } }
3544bf9e2806f2791ced6908176f23fc7a24b86d
TypeScript
dandevs/pipe-x
/src/finishStrategy.ts
3.03125
3
import { noop } from "./utils"; const immediateStrategy: FinishStrategy = () => ({ push: noop, pop: noop, canFinish: true, }); const counterStrategy: FinishStrategy<{counter: number}> = () => ({ counter: 0, get canFinish() { return this.counter <= 0; }, push() { this.counter++; }, pop() { this.counter--; }, }); const delayStrategy: FinishStrategy = () => ({ canFinish: true, push() { this.canFinish = false; }, pop() { this.canFinish = true; }, }); export const finishStrategies = { immediate: immediateStrategy, counter: counterStrategy, }; export interface FinishStrategy<T = {}> { (): { push(): any, pop(): any, canFinish: boolean, } & T; }
3585433a3f0cd7152efbc34940e0789f9a27ac42
TypeScript
stefanondisponibile/EventStore-Client-NodeJS
/src/events/binaryEvent.ts
2.921875
3
import { v4 as uuid } from "uuid"; import { convertMetadata } from "./convertMetadata"; import { MetadataType } from "./types"; export interface BinaryEventData< Type extends string = string, Metadata extends MetadataType = MetadataType > { id: string; contentType: "application/octet-stream"; type: Type; data: Uint8Array; metadata?: Metadata; } export interface BinaryEventOptions< Type extends string = string, Metadata extends MetadataType = MetadataType | Buffer > { /** * The id to this event. By default, the id will be generated. */ id?: string; /** * The event type */ type: Type; /** * The binary data of the event */ data: Uint8Array | Buffer; /** * The binary metadata of the event */ metadata?: Metadata; } export const binaryEvent = < Type extends string = string, Metadata extends MetadataType = MetadataType >({ type, data, metadata, id = uuid(), }: BinaryEventOptions<Type, Metadata>): BinaryEventData<Type, Metadata> => ({ id, contentType: "application/octet-stream", type, data: Uint8Array.from(data), metadata: convertMetadata<Metadata>(metadata), });
8885ccb17f60886918dbe5a6cbdcba1c5b5bbb84
TypeScript
lolo1208/cocos2dx-lolo
/src/lolo/utils/Timer.ts
2.9375
3
namespace lolo { /** * 基于帧频的定时器 * 解决丢帧和加速的情况 * @author LOLO */ export class Timer { /**可移除标记的最大次数*/ private static MAX_REMOVE_MARK: number = 5; /**定时器列表(以delay为key, _list[delay] = { list:已启动的定时器列表, removeMark:被标记了可以移除的次数 } )*/ private static _list: Object = {}; /**不重复的key*/ private static _onlyKey: number = 0; /**需要被添加到运行列表的定时器列表*/ private static _startingList: Timer[] = []; /**需要从运行列表中移除的定时器列表*/ private static _stoppingList: Timer[] = []; /**在列表中的key( _list[delay].list[_key] = this )*/ private _key: number; /**定时器间隔*/ private _delay: number = 0; /**定时器是否正在运行中*/ public running: boolean = false; /**定时器当前已运行次数*/ public currentCount: number = 0; /**定时器的总运行次数,默认值0,表示无限运行*/ public repeatCount: number; /**定时器上次触发的时间*/ public lastUpdateTime: number; /**每次达到间隔时的回调*/ public timerHander: Handler; /**定时器达到总运行次数时的回调*/ public timerCompleteHandler: Handler; /** * 帧刷新 * @param event */ private static enterFrameHandler(event: Event): void { let timer: Timer, i: number, delay: any, key: any, timerList: Object; let timerRunning: boolean, ignorable: boolean; let delayChangedList: number[] = [];//在回调中,delay有改变的定时器列表 //添加应该启动的定时器,以及移除该停止的定时器。 // 上一帧将这些操作延迟到现在来处理的目的,是为了防止循环和回调时造成的问题 while (Timer._startingList.length > 0) { timer = Timer._startingList.pop(); if (Timer._list[timer.delay] == null) Timer._list[timer.delay] = {list: {}, removeMark: 0}; Timer._list[timer.delay].removeMark = 0; Timer._list[timer.delay].list[timer.key] = timer; } while (Timer._stoppingList.length > 0) { timer = Timer._stoppingList.pop(); if (Timer._list[timer.delay] != null) delete Timer._list[timer.delay].list[timer.key]; } //处理回调 let time: number = TimeUtil.nowTime; let removedList: number[] = [];//需要被移除的定时器列表 for (delay in Timer._list) { delayChangedList.length = 0; timerList = Timer._list[delay].list; timerRunning = false; for (key in timerList) { timer = timerList[key]; if (!timer.running) continue;//这个定时器已经被停止了(可能是被之前处理的定时器回调停止的) //在FP失去焦点后,帧频会降低。使用加速工具,帧频会加快。计算次数可以解决丢帧以及加速问题 let count: number = Math.floor((time - timer.lastUpdateTime) / timer.delay); //次数过多,忽略掉(可能是系统休眠后恢复) if (count > 1000) { ignorable = true; count = 1; } else ignorable = false; for (i = 0; i < count; i++) { //定时器在回调中被停止了 if (!timer.running) break; //定时器在回调中更改了delay if (timer.delay != delay) { delayChangedList.push(key); break; } timer.currentCount++; if (timer.timerHander != null) timer.timerHander.execute(); //定时器已到达允许运行的最大次数 if (timer.repeatCount != 0 && timer.currentCount >= timer.repeatCount) { timer.stop(); if (timer.timerCompleteHandler != null) timer.timerCompleteHandler.execute(); break; } } //根据回调次数,更新 上次触发的时间(在回调中没有更改delay) if (count > 0 && timer.delay == delay) { timer.lastUpdateTime = ignorable ? time : (timer.lastUpdateTime + timer.delay * count); } if (timer.running) timerRunning = true; } while (delayChangedList.length > 0) { delete timerList[delayChangedList.pop()]; } //当前 delay,已经没有定时器在运行状态了 if (!timerRunning) { if (Timer._list[delay].removeMark > Timer.MAX_REMOVE_MARK) { removedList.push(delay); } else { Timer._list[delay].removeMark++; } } else { Timer._list[delay].removeMark = 0; } } while (removedList.length > 0) { delay = removedList.pop(); if (Timer._list[delay].removeMark > Timer.MAX_REMOVE_MARK) delete Timer._list[delay]; } if (Timer._startingList.length == 0) { for (delay in Timer._list) return; lolo.stage.event_removeListener(Event.ENTER_FRAME, Timer.enterFrameHandler, Timer); } } /** * 从 添加 或 移除 列表中移除指定的定时器 * @param list * @param timer */ private static removeTimer(list: Timer[], timer: Timer): void { for (let i = 0; i < list.length; i++) { if (list[i] == timer) { list.splice(i, 1); return; } } } /** * 创建一个Timer实例 * @param delay 定时器间隔 * @param timerHander 每次达到间隔时的回调 * @param repeatCount 定时器的总运行次数,默认值0,表示无限运行 * @param timerCompleteHandler 定时器达到总运行次数时的回调 * @return */ public constructor(delay: number = 1000, timerHander: Handler = null, repeatCount: number = 0, timerCompleteHandler: Handler = null) { this._key = ++Timer._onlyKey; this.delay = delay; this.repeatCount = repeatCount; this.timerHander = timerHander; this.timerCompleteHandler = timerCompleteHandler; } /** * 定时器间隔 */ public set delay(value: number) { value = Math.floor(value); if (value == 0) { this.stop(); throwError("定时器的间隔不能为 0"); } if (this._delay == value) return; let running: boolean = this.running; if (this._delay != 0) this.reset();//之前被设置或启动过,重置定时器 //创建当前间隔的定时器 this._delay = value; if (running) this.start(); } public get delay(): number { return this._delay; } /** * 开始定时器 */ public start(): void { if (this.running) return; //没达到设置的运行最大次数 if (this.repeatCount == 0 || this.currentCount < this.repeatCount) { this.running = true; this.lastUpdateTime = TimeUtil.nowTime; Timer.removeTimer(Timer._stoppingList, this); Timer.removeTimer(Timer._startingList, this); Timer._startingList.push(this); lolo.stage.event_addListener(Event.ENTER_FRAME, Timer.enterFrameHandler, Timer, 9); } } /** * 如果定时器正在运行,则停止定时器 */ public stop(): void { if (!this.running) return; this.running = false; Timer.removeTimer(Timer._startingList, this); Timer.removeTimer(Timer._stoppingList, this); Timer._stoppingList.push(this); } /** * 如果定时器正在运行,则停止定时器,并将currentCount设为0 */ public reset(): void { this.currentCount = 0; this.stop(); } /** * 在列表中的key(_list[delay].list[key]=this) */ public get key(): number { return this._key; } /** * 释放对象(只是停止定时器,还能继续使用) * 注意:在丢弃该对象时,并不强制您调用该方法,您只需停止定时器(调用stop()方法)即可 */ public destroy(): void { this.stop(); } // } }
ff79af8611b92373cc477dcabe545fec07aaee9d
TypeScript
lorenadl/angular4_examples
/typescript/main.ts
4.21875
4
let a: number = 10; // definisce variabile con tipo let b: string = 'Pippo'; // a='pippo'; // errore console.log(a); console.log(b); // arrow function //let log = (msg: string): void => console.log(msg); let log = (msg: string = 'this is the default'): void => console.log(msg); function sum(a: number, b: number): number { return a + b; } function biggerLog(msg: string ="prova", ...other: string[]) { console.log(`${msg} ${other.join(' ')}`); } log('Hello'); log(); biggerLog('Hello', 'a', 'b', 'f'); let c: any = 3; // usare any il meno possibile! c = 'pippo'; // Array //let d: number[] = [1, 2, 3]; //d.push('pippo'); // errore // Altra definizione di array // <> è un generics, ovvero definisco un array, ma di cosa? di numeri. Array è una classe che si prenderà oggetti number. let d: Array<number> = [1, 2, 4]; let e: string[] = ['a', 'b']; //let de: any[] = [...d, ...e]; // con i generics let de: Array<number|string> = [...d, ...e]; // destructuring let [first, second] = d; console.log(first); console.log(second); const person = { fistname: 'Pippo', lastname: 'PPP' }; let {fistname, lastname} = person; console.log(fistname); console.log(lastname); // per usare l'interfaccia all'interno della classe // Quando una classe implementa questa interfaccia, deve definire questi metodi/proprietà interface Greet { greet(): string; } // classi class Person implements Greet { firstname: string; // di default è public lastname: string; private _age: number = 10; // naming convention: prefisso '_' per private // private è ts, non ES6 constructor(firstname: string, lastname: string) { this.firstname = firstname; this.lastname = lastname; } sayHi(): string { return `Hi ${this.firstname}`; } greet(): string { return `Hello $(this.firstname) ${this.lastname}`; } } let pippo: Person = new Person('Pippo','Pluto'); console.log(pippo.sayHi()); // console.log(pippo._age); // dà errore ma in realtà funziona lo stesso perchè in js non ci sono proprietà private // Interfaces interface IPerson { firstname: string; lastname: string; age: number; street?: string; } let pluto: IPerson = { firstname: 'Pluto', lastname: 'iiii', age: 10, street: 'ppp' // senza definizione con '?' dà errore, parametro non definito } let paperino: IPerson = { firstname: 'Paperino', lastname: 'zzzz', age: 10 }
a1568f84a7e04c582bd51313d984153e9c87207a
TypeScript
zhaojieyuan/snake
/src/world.ts
3.109375
3
import Point from './point'; import Player from './player'; import beep from './sound'; import { Screen } from './screens'; export interface IWorld { screen: Screen; player: Player; width: number; height: number; food: Point; } const data: IWorld = { screen: Screen.INTRO, player: null, width: 0, height: 0, food: null }; export function setScreen(screen: Screen) { data.screen = screen; } function rand(min, max) { const { floor, random } = Math; return floor(random() * (max - min + 1)) + min; } /* check if food spawn point is on top * of the tail */ function blockingTail(target) { const { points } = data.player; for (let i = 0; i < points.length; ++i) { const p = points[i]; if (p.equals(target)) { return true; } } return false; } function moveFood() { const { width, height } = data; let potentialTarget; do { potentialTarget = new Point( rand(0, width - 1), rand(0, height - 1), ); } while (blockingTail(potentialTarget)); data.food.move( potentialTarget.x, potentialTarget.y, ); ++data.player.tail; } export function tick() { const { player } = data; const playerPos = player.getHead(); if (playerPos.x === data.food.x && playerPos.y === data.food.y) { moveFood(); player.consume(); beep(); } /* detect wall collisions */ const newPos = player.tick(); const { x, y } = newPos; if ( x < 0 || y < 0 || x > data.width - 1 || y > data.height - 1 ) { player.alive = false; } } export function init(width, height) { data.width = width; data.height = height; data.player = new Player(); data.food = new Point(); moveFood(); console.log('player', data.player); // eslint-disable-line no-console console.log('food', data.food); // eslint-disable-line no-console return data; }
8634ea8ac31ed201a0ce61a62c01e3d509ba75d1
TypeScript
jenisgadhiya/nestjs-task-app
/src/auth/auth.service.ts
2.578125
3
import { Injectable, UnauthorizedException, Logger } from '@nestjs/common'; import { Userrepository } from './user.repository'; import { InjectRepository } from '@nestjs/typeorm'; import { Usercredentioaldto } from './dto/user-credentioal.dto'; import { JwtService } from '@nestjs/jwt'; import { jwtpayload } from './jwt-payload.interface'; @Injectable() export class AuthService { private logger=new Logger('Authservice') constructor( @InjectRepository(Userrepository) private userrepository:Userrepository, private jwtservice:JwtService ){} async signup(usercredentioaldto:Usercredentioaldto):Promise<void>{ this.userrepository.signup(usercredentioaldto) } async signin(usercredentioaldto:Usercredentioaldto):Promise<{accesstoken:String}>{ const username=await this.userrepository.validateuserpassword(usercredentioaldto) if(!username){ throw new UnauthorizedException('invalid credentials') } const payload:jwtpayload={username} const accesstoken=await this.jwtservice.sign(payload) this.logger.debug(`Genrated jwt token with payload ${JSON.stringify(payload)}`) return {accesstoken} } }
af265c91a7d451d54690d87a3bb1bf9c6b756e8d
TypeScript
IvanBatsin/advanced_jwt_auth
/server/services/userService.ts
2.546875
3
import { UserModel, UserModelDocument } from '../models/User'; import bcrypt from 'bcrypt'; import * as uuid from 'uuid'; import { mailService } from './mailSevice'; import { tokenService } from './tokenService'; import { UserDto } from '../dtos/userDto'; import { ApiError } from '../exeptions/apiError'; type UserServiceReturnData = { accessToken: string; refreshToken: string; user: UserDto } class UserService { async registration(email: string, password: string): Promise<UserServiceReturnData | void> { try { const condidate = await UserModel.findOne({email}); if (condidate) { throw ApiError.BadRequest(`User with this email (${email}) already exists`); } const hashPassword = await bcrypt.hash(password, 10); const activationLink = uuid.v4(); const user = await UserModel.create({email, password: hashPassword, activationLink}); await mailService.sendActivationEmail(email, `${process.env.API_URL}/api/activate/${activationLink}`); const userDto = new UserDto(user.toJSON()); const tokens = tokenService.generateTokens({...userDto}); await tokenService.saveToken(user._id, tokens.refreshToken); return { ...tokens, user: userDto }; } catch (error) { console.log(error); } } async activateAccount(activationLink: string): Promise<void> { try { const user = await UserModel.findOne({activationLink}); if (!user) { throw ApiError.BadRequest('User not found'); } user.isActivate = true; await user.save(); } catch (error) { console.log(error); } } async login(email: string, password: string): Promise<UserServiceReturnData | void> { try { const user = await UserModel.findOne({email}); if (!user) { throw ApiError.BadRequest('User not found'); } const passwordsAreEqual = await bcrypt.compare(password, user.password); if (!passwordsAreEqual) { throw ApiError.BadRequest('Invalid password'); } const userDto = new UserDto(user.toJSON()); const tokens = tokenService.generateTokens({...userDto}); await tokenService.saveToken(user._id, tokens.refreshToken); return { ...tokens, user: userDto }; } catch (error) { console.log(error); } } async logout(refreshToken: string): Promise<any> { try { const token = await tokenService.removeToken(refreshToken); return token; } catch (error) { console.log(error); } } async refresh(refreshToken: string): Promise<UserServiceReturnData | void> { try { if (!refreshToken) { throw ApiError.UnauthorizedError(); } const userData = tokenService.validateRefreshToken(refreshToken); const tokenFromDB = await tokenService.findToken(refreshToken); if (!userData || !tokenFromDB) { throw ApiError.UnauthorizedError(); } const user = await UserModel.findById(userData.id); const userDto = new UserDto(user!.toJSON()); const tokens = tokenService.generateTokens({...userDto}); await tokenService.saveToken(user?._id, tokens.refreshToken); return { ...tokens, user: userDto }; } catch (error) { console.log(error); } } async getAllUsers(): Promise<UserModelDocument[] | void> { try { const users = await UserModel.find(); return users; } catch (error) { console.log(error); } } } const userService = new UserService(); export { userService };
8c4006b036ea42adcbaa59bcf14fad0d4dee62e5
TypeScript
lianghowe/zilswap-webapp
/src/app/utils/hexToRGB.ts
2.921875
3
const hexToRGB = (hex: string): number[] => { let array = hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i , (m, r, g, b) => '#' + r + r + g + g + b + b) .substring(1).match(/.{2}/g) if (array) return array.map(x => parseInt(x, 16)) return [0, 0, 0]; }; export default hexToRGB;
0cb3b943779368944f875001f67862666535738a
TypeScript
helmetjs/helmet
/middlewares/referrer-policy/index.ts
2.890625
3
import type { IncomingMessage, ServerResponse } from "http"; type ReferrerPolicyToken = | "no-referrer" | "no-referrer-when-downgrade" | "same-origin" | "origin" | "strict-origin" | "origin-when-cross-origin" | "strict-origin-when-cross-origin" | "unsafe-url" | ""; export interface ReferrerPolicyOptions { policy?: ReferrerPolicyToken | ReferrerPolicyToken[]; } const ALLOWED_TOKENS = new Set<ReferrerPolicyToken>([ "no-referrer", "no-referrer-when-downgrade", "same-origin", "origin", "strict-origin", "origin-when-cross-origin", "strict-origin-when-cross-origin", "unsafe-url", "", ]); function getHeaderValueFromOptions({ policy = ["no-referrer"], }: Readonly<ReferrerPolicyOptions>): string { const tokens = typeof policy === "string" ? [policy] : policy; if (tokens.length === 0) { throw new Error("Referrer-Policy received no policy tokens"); } const tokensSeen = new Set<ReferrerPolicyToken>(); tokens.forEach((token) => { if (!ALLOWED_TOKENS.has(token)) { throw new Error( `Referrer-Policy received an unexpected policy token ${JSON.stringify( token, )}`, ); } else if (tokensSeen.has(token)) { throw new Error( `Referrer-Policy received a duplicate policy token ${JSON.stringify( token, )}`, ); } tokensSeen.add(token); }); return tokens.join(","); } function referrerPolicy(options: Readonly<ReferrerPolicyOptions> = {}) { const headerValue = getHeaderValueFromOptions(options); return function referrerPolicyMiddleware( _req: IncomingMessage, res: ServerResponse, next: () => void, ) { res.setHeader("Referrer-Policy", headerValue); next(); }; } export default referrerPolicy;
73b22a7c8e6be5201cce2f79d2657a6bf5f889e1
TypeScript
vipe4ka-visko4ka/nest-starter-kit
/src/auth/auth.dto.ts
3.109375
3
import { ValidatorConstraint, ValidatorConstraintInterface, IsEmail, IsString, MinLength, Validate } from 'class-validator'; @ValidatorConstraint({ name: 'password', async: false }) export class PasswordValidation implements ValidatorConstraintInterface { public validate(text: string): boolean { return new RegExp(/^(?=.*[A-Z])(?=.*\d).*$/).test(text); } public defaultMessage(): string { return '$property should contain at least one digit, at least one upper case'; } } export class AuthDto { @IsEmail() public email: string; @IsString() @MinLength(6) @Validate(PasswordValidation) public password: string; }
1637ca57de340492c59ac9585eafada3970806be
TypeScript
sergeykurilov/MernAuthTS
/backend/middlewares/auth.ts
2.59375
3
import {NextFunction} from "express"; const jwt = require('jsonwebtoken') const User = require('../models/User') const ErrorResponse = require('../utils/ErrorResponse') type AuthorizedRequest = Express.Request & { user: any, headers: { authorization: string } }; exports.protect = async function (req: AuthorizedRequest, res: Response, next: NextFunction) { let token; if (req.headers.authorization && req.headers.authorization.startsWith("Bearer")) { token = req.headers.authorization.split(" ")[1] } if (!token) { return next(new ErrorResponse("Not authorized to access this route", 401)) } try { const decoded = jwt.verify(token, process.env.JWT_SECRET) const user = User.findById(decoded.id) if (!user) { return next(new ErrorResponse("No user found for that ID", 404)) } req.user = user next() } catch (e) { return next(new ErrorResponse("No authorized to access this route", 401)) } }
b564e9893717598daecfaf2126f9a959f5bcebd7
TypeScript
dimakovalevskyi/chord-editor
/src/app/song.ts
2.6875
3
export interface Song { name: string; author: string; lyrics: Lyrics; } export interface Chord { name: string; offset: number; } export interface Lyrics extends Array<any> { [index: number]: LyricsRow; } export interface LyricsRow { text: string; chords: Array<Chord>; }
c0a6bf3a52ba72014eef420e1e0c0963fdec0833
TypeScript
dzucconi/boredom-client
/src/lib/shuffle.ts
3.453125
3
export const shuffle = <T>(xs: T[]): T[] => { const shuffled = []; const array = xs; while (array.length !== 0) { const randomIndex = Math.floor(array.length * Math.random()); shuffled.push(array[randomIndex]); array.splice(randomIndex, 1); } return shuffled; };
32fced9f195e9f0a61597b1da42ee3efd85d14fd
TypeScript
AbedBadr/TypeScript-Collect-Words
/src/js/index.ts
3.0625
3
let words: string[] = []; let inputElement: HTMLInputElement = <HTMLInputElement>document.getElementById("wordInput"); let showButton: HTMLButtonElement = <HTMLButtonElement>document.getElementById("showButton"); showButton.addEventListener("click", showWords); let saveButton: HTMLButtonElement = <HTMLButtonElement>document.getElementById("saveButton"); saveButton.addEventListener("click", saveWord); let clearButton: HTMLButtonElement = <HTMLButtonElement>document.getElementById("clearButton"); clearButton.addEventListener("click", clearWords); let outputElement: HTMLOutputElement = <HTMLOutputElement>document.getElementById("outputDiv"); function showWords():void { if (words.length > 0) { outputElement.style.fontStyle = "normal"; outputElement.innerHTML = words.toString(); } else { words.push("empty"); outputElement.style.fontStyle = "italic"; outputElement.innerHTML = words.toString(); words = []; } } function saveWord(): void{ let word: string = inputElement.value; words.push(word); } function clearWords(): void{ words = []; }
532dbefd44925ac9764314f071903065b0d141c4
TypeScript
PattonHoffiman/green-house-back-end
/src/modules/plants/services/__tests__/UpdatePlantService.spec.ts
2.5625
3
import 'reflect-metadata'; import { addDays, format } from 'date-fns'; import AppError from '@shared/errors/AppError'; import FakeCacheProvider from '@shared/container/providers/CacheProvider/fakes/FakeCacheProvider'; import UpdatePlantService from '../UpdatePlantService'; import FakePlantsRepository from '../../repositories/fakes/FakePlantsRepository'; let updatePlant: UpdatePlantService; let fakeCacheProvider: FakeCacheProvider; let fakePlantsRepository: FakePlantsRepository; describe('Update Plant Service', () => { beforeEach(() => { fakePlantsRepository = new FakePlantsRepository(); updatePlant = new UpdatePlantService( fakeCacheProvider, fakePlantsRepository, ); }); it('should be able to update a plant', async () => { const today = new Date(); await fakePlantsRepository.create( 'user-id', 'Freddy', 2, addDays(today, 2), ); const plant = fakePlantsRepository.plants.find( plantArray => plantArray.name === 'Freddy', ); if (plant) { const updatedPlant = await updatePlant.execute({ id: plant.id, name: 'Fredy', days_to_water: 2, user_id: 'user-id', }); expect(updatedPlant.name).toEqual('Fredy'); } expect(plant).not.toBeUndefined(); }); it("should not be able to update if the plant doesn't exists", async () => { await expect( updatePlant.execute({ id: 'fake-id', name: 'Fredy', days_to_water: 2, user_id: 'fake-user-id', }), ).rejects.toBeInstanceOf(AppError); }); it('should be able to change the water day if the days to water change so', async () => { const today = new Date(); await fakePlantsRepository.create( 'user-id', 'Freddy', 2, addDays(today, 2), ); const plant = fakePlantsRepository.plants.find( plantArray => plantArray.name === 'Freddy', ); if (plant) { const updatedPlant = await updatePlant.execute({ id: plant.id, name: 'Fredy', days_to_water: 3, user_id: 'user_id', }); const formattedWaterDay = format(addDays(today, 3), 'dd/MM/yyyy'); expect(updatedPlant.name).toEqual('Fredy'); expect(updatedPlant.days_to_water).toEqual(3); expect(format(updatedPlant.water_day, 'dd/MM/yyyy')).toEqual( formattedWaterDay, ); } expect(plant).not.toBeUndefined(); }); });
72fa89a6eb1f042f2102cdc61f061341f85411c4
TypeScript
Polycapa/angular-migration-tool
/src/analysers/bracket-matcher.ts
3.703125
4
export class BracketMatcher { match(text: string, char: string, index: number): number { let count = 0; let i: number; for (i = index; i < text.length; i++) { if (text.charAt(i) === char) { count++; } else if (text.charAt(i) === this.matchingChar(char)) { count--; } if (count === 0) { break; } } return i; } private matchingChar(char: string) { switch (char) { case '{': return '}'; case '(': return ')'; case '[': return ']'; } } }
caf5be118ced2c9cf5694f4d95de72b3e48e85e9
TypeScript
cyberixae/generator-example
/src/zomg5.ts
2.796875
3
import { State, Fib, initialState, step, fromState, defaultAmount } from './zomg' function* fibonacci(): Generator<Fib, void, undefined> { let state: State = initialState while(true) { yield fromState(state) state = step(state) } } type GF<A> = () => Generator<A, void, undefined> function take<A>(c: number, as: GF<A>): GF<A> { return function*() { let i: number = 0 for (const a of as()) { yield a i += 1 if (i >= c) { return } } } } function* logFibs(): Generator<void, void, undefined> { const fibs = take(defaultAmount, fibonacci) for (const fib of fibs()) { yield console.log(fib) } } function tick(g: Generator<void, void, undefined>) { const r = g.next() if (r.done === true) { return } setTimeout(() => tick(g), 0) } function main() { tick(logFibs()) } main() export {}
4f361b8d0967bba9d105578ad15df01ca035f6ad
TypeScript
erento/nestjs-modules
/modules/common/src/pipes/boolean-validation.pipe.test.ts
2.609375
3
import {BooleanValidationPipe} from './boolean-validation.pipe'; describe('BooleanValidationPipe', (): void => { let pipe: BooleanValidationPipe; beforeEach((): void => { pipe = new BooleanValidationPipe(); }); test.each<[string | undefined, boolean | undefined]>([ ['true', true], ['false', false], [undefined, false], ['', false], ['asdf', false], ])( 'should transform string to value properly', (input: string | undefined, expected: boolean | undefined): void => { expect(pipe.transform(input)) .toEqual(expected); }, ); });
ab19c3fd8afc3c7f8dc2311526911f3e8ecd57ab
TypeScript
tycoon69-labs/mobile-wallet
/src/app/auth/shared/auth.service.spec.ts
2.53125
3
import { fakeAsync, tick } from "@angular/core/testing"; import { createServiceFactory, SpectatorService } from "@ngneat/spectator"; import { of } from "rxjs"; import { tap } from "rxjs/operators"; import { StorageProvider } from "@/services/storage/storage"; import { AuthConfig } from "./auth.config"; import { AuthService } from "./auth.service"; describe("Auth Service", () => { let spectator: SpectatorService<AuthService>; let service: AuthService; const createService = createServiceFactory({ service: AuthService, mocks: [StorageProvider], }); beforeEach(() => { spectator = createService(); service = spectator.service; }); it("should validate password as weak", () => { const weakPassword = "000000"; expect(service.isWeakPassword(weakPassword)).toEqual(true); }); it("should validate password as not weak", () => { const weakPassword = "AB@#$5"; expect(service.isWeakPassword(weakPassword)).toEqual(false); }); it("should get password hash stored", () => { const storage = spectator.get(StorageProvider); storage.get.and.returnValue(of("hash")); service.getPasswordHash().subscribe(); expect(storage.get).toHaveBeenCalled(); }); it("should hash password", () => { const password = "123456"; expect(service.hashPassword(password)).not.toEqual(password); }); it("should return true if the password matches the hash", (done) => { const password = "123456"; const hash = service.hashPassword(password); service.validatePassword(password, hash).subscribe((result) => { expect(result).toBeTrue(); done(); }); }); it("should return false if the password does not match the hash", (done) => { const password = "123456"; const hash = "abc"; service.validatePassword(password, hash).subscribe((result) => { expect(result).toBeFalse(); done(); }); }); it("should return undefined if the attempt limit is not reached", () => { const attempts = 1; expect(service.getNextUnlockDate(attempts)).toBeUndefined(); }); it("should return the unlock date if the attempt limit is reached", () => { const attempts = 3; const nowTime = new Date().getTime() - 1; const unlockDate = service.getNextUnlockDate(attempts); const expectedMilliseconds = AuthConfig.ATTEMPTS_LIMIT * 10000; expect(unlockDate).toEqual(jasmine.any(Date)); expect(unlockDate.getTime() - nowTime).toBeGreaterThanOrEqual( expectedMilliseconds, ); }); it("should get the unlock countdown", (done) => { const countdown = []; service .getUnlockCountdown(2) .pipe(tap((s) => countdown.push(s))) .subscribe({ complete: () => { expect(countdown).toEqual([2, 1, 0]); done(); }, }); }); it("should get the remaining seconds", () => { const nowTime = new Date().getTime(); const nowDate = new Date(nowTime + 3 * 1000); expect(service.getUnlockRemainingSeconds(nowDate)).toEqual(3); expect(service.getUnlockRemainingSeconds(undefined)).toBeUndefined(); }); it("should return true if date expired", fakeAsync(() => { const unlockDate = new Date(); tick(1000); expect(service.hasUnlockDateExpired(unlockDate)).toBeTrue(); expect(service.hasUnlockDateExpired(undefined)).toBeTrue(); })); it("should return false if the date has not expired", () => { const unlockTime = new Date().getTime(); const unlockDate = new Date(unlockTime + 1000); expect(service.hasUnlockDateExpired(unlockDate)).toBeFalse(); }); });
4aee3dca1cdcf38304e4721408d250cbba045c4d
TypeScript
brown-qs/PREACT.andranik-isma
/src/utils/parse-storage-get.ts
2.65625
3
/************************************************************************ * LOCALSTORAGE CACHES USER'S INFORMATION AND USE IT ON LATER SIGN-INS. * * THIS UTIL FUNCTION IS USED TO GET CERTAIN VALUE FROM STORAGE. * ************************************************************************/ export default function parseStorageGet (key: string) { try { const value = localStorage.getItem(key) || '' return JSON.parse(value) } catch (e) { return null } }
44f54355545816f6dd465789ba0c85958fd00938
TypeScript
undecidedapollo/pylot-flow
/src/operators/flatMap/index.ts
3.03125
3
import { NOOP_PASSTHROUGH, hasOrIsIterator, } from "../../shared"; export type FlatMapPredicate = (val: any, i?: number) => any; export default function flatMap(predicate : FlatMapPredicate = NOOP_PASSTHROUGH) { return function* flatMapGenerator(iterator) { let index = 0; for (const val of iterator) { const mappedVal = predicate(val, index); index += 1; if (hasOrIsIterator(mappedVal)) { yield* mappedVal; } else { yield mappedVal; } } }; }
93d67c1fa93a901f56474e1cd01de08eb05832be
TypeScript
Marceau38/generator-jhipster
/app/src/main/webapp/app/shared/model/address.model.ts
2.59375
3
import { ICustomer } from 'app/shared/model/customer.model'; export interface IAddress { id?: number; address1?: string; address2?: string; city?: string; postcode?: string; country?: string; customer?: ICustomer; } export class Address implements IAddress { constructor( public id?: number, public address1?: string, public address2?: string, public city?: string, public postcode?: string, public country?: string, public customer?: ICustomer ) {} }
4bfb3e1854bcfb242362dcefb77435e3f0d988cd
TypeScript
aykhanhuseyn/moberries
/src/util/requestHandler.ts
2.703125
3
import axios from 'axios'; export default async function requestHandler( func: Function, params: any[], showError: boolean = true ): Promise<any> { return new Promise(async (resolve, reject) => { try { const { data } = await func(...params); return resolve(data); } catch (e) { let error, message; if (showError && axios.isAxiosError(e) && e.response) { error = 'Error ' + e.response.status; message = e.response.data.message; return Promise.reject({ error, message }); } error = e?.request?.message || 'Internal Error'; message = e.response?.message || 'Unexpected error occured. Please, try again later.'; return reject({ error, message }); } }); }
72dcea7196d0117b151403615d8d9e33b5aa60e0
TypeScript
Torres-ssf/rent-car-api
/src/shared/utils/deleteMultipleFiles.ts
2.59375
3
import fs from 'fs'; export const deleteMultipleFiles = async ( filePaths: string[], ): Promise<unknown> => { return filePaths.map(async filePath => { try { await fs.promises.stat(filePath); } catch { return; } await fs.promises.unlink(filePath); }); };
0b8af3741656e2c606b24f8d76c69fd1685cc511
TypeScript
PoEManager/Backend-Server
/app/server/middleware/request-id.ts
2.796875
3
import winston from 'winston'; import User from '../../model/user'; import MiddlewareFunction from './middleware-function'; /** * Generates an ID for each request in order to track them. * Stores the ID in `req.locals.requestId`. * * @returns The middleware function. */ function makeRequestId(): MiddlewareFunction { let subCounter = 1000; return async (req, res, next) => { const milliseconds = new Date().getTime(); req.user = undefined as unknown as User; req.locals = { logger: undefined as unknown as winston.Logger, requestId: '', startTime: undefined as unknown as Date }; req.locals.requestId = `${milliseconds}-${subCounter++}`; if (subCounter > 9999) { subCounter = 1000; } next(); }; } export = makeRequestId;
2d386d6fc3fa40265cb4488b02a4ce1574dc2a02
TypeScript
enterstudio/brackets-git
/src/node/processUtils-test.ts
2.546875
3
/* eslint no-console:0 */ /* eslint-env node */ import * as ProcessUtils from "./process-utils"; /* var pid = 5064; ProcessUtils.getChildrenOfPid(pid, function (err, children) { console.log(children); children.push(pid); children.forEach(function (pid) { ProcessUtils.killSingleProcess(pid); }); }); */ [ "git", "C:\\Program Files (x86)\\Git\\cmd\\git.exe", "C:/Program Files (x86)/Git/cmd/git.exe", "C:/Program Files (x86)/Git/cmd/git2.exe", "C:/Program Files (x86)/Git/cmd/", "C:/Program Files (x86)/Git/cmd", "C:\\Program Files (x86)\\Git\\Git Bash.vbs" ].forEach((path) => { ProcessUtils.executableExists(path, (err, exists, resolvedPath) => { if (err) { console.error("executableExists error: " + err); } console.log("ProcessUtils.executableExists for: " + path); console.log(" - exists: " + exists); console.log(" - resolvedPath: " + resolvedPath); }); }); /* ProcessUtils.executableExists("git", function (err, result, resolvedPath) { console.log("git"); console.log(result); }); ProcessUtils.executableExists("C:\\Program Files (x86)\\Git\\cmd\\git.exe", function (err, result) { console.log("result for C:\\Program Files (x86)\\Git\\cmd\\git.exe"); console.log(result); }); ProcessUtils.executableExists("C:/Program Files (x86)/Git/cmd/git.exe", function (err, result) { console.log("result for C:/Program Files (x86)/Git/cmd/git.exe"); console.log(result); }); ProcessUtils.executableExists("C:/Program Files (x86)/Git/cmd/git2.exe", function (err, result) { console.log("result for C:/Program Files (x86)/Git/cmd/git2.exe"); console.log(result); }); ProcessUtils.executableExists("C:/Program Files (x86)/Git/cmd/", function (err, result) { console.log("result for C:/Program Files (x86)/Git/cmd/"); console.log(result); }); ProcessUtils.executableExists("C:/Program Files (x86)/Git/cmd", function (err, result) { console.log("result for C:/Program Files (x86)/Git/cmd"); console.log(result); }); */
3c76f050decde20c1a6642d2a01781434f3aa889
TypeScript
Stanislav1975/sourcegraph
/shared/src/api/client/services/notifications.ts
2.9375
3
import { Observable, Subject } from 'rxjs' import * as sourcegraph from 'sourcegraph' /** * The type of a notification. * This is needed because if sourcegraph.NotificationType enum values are referenced, * the `sourcegraph` module import at the top of the file is emitted in the generated code. */ export const NotificationType: typeof sourcegraph.NotificationType = { Error: 1, Warning: 2, Info: 3, Log: 4, Success: 5, } interface PromiseCallback<T> { resolve: (p: T | Promise<T>) => void } /** * The parameters of a notification message. */ export interface ShowNotificationParams { /** * The notification type. See {@link NotificationType} */ type: sourcegraph.NotificationType /** * The actual message */ message: string } export interface MessageActionItem { /** * A short title like 'Retry', 'Open Log' etc. */ title: string } export interface ShowMessageRequestParams { /** * The message type. See {@link NotificationType} */ type: sourcegraph.NotificationType /** * The actual message */ message: string /** * The message action items to present. */ actions?: MessageActionItem[] } /** The parameters for window/showInput. */ export interface ShowInputParams { /** The message to display in the input dialog. */ message: string /** The default value to display in the input field. */ defaultValue?: string } type ShowMessageRequest = ShowMessageRequestParams & PromiseCallback<MessageActionItem | null> type ShowInputRequest = ShowInputParams & PromiseCallback<string | null> export class NotificationsService { /** Messages from extensions intended for display to the user. */ public readonly showMessages = new Subject<ShowNotificationParams>() /** Messages from extensions requesting the user to select an action. */ public readonly showMessageRequests = new Subject<ShowMessageRequest>() /** Messages from extensions requesting the user to select an action. */ public readonly progresses = new Subject<{ title?: string; progress: Observable<sourcegraph.Progress> }>() /** Messages from extensions requesting text input from the user. */ public readonly showInputs = new Subject<ShowInputRequest>() }
38860e8096f1a631c878cd4b0ba275fdd7d482ca
TypeScript
iceycc/daydayup
/设计模式design/3.priciple/1.openclose.ts
3.890625
4
/** * 开放封装原则 对修改关闭,对扩展开放 */ class Customer { constructor(public rank: string) { } } class Product { constructor(public name: string, public price: number) { } //不同的顾客有不同的等级,普通会员 VIP会员 普通顾客,不同的等级打折不一样 cost(customer: Customer) { switch (customer.rank) { case 'member': return this.price * .8; case 'vip': return this.price * .6; case 'superVip': return this.price * .4; default: return this.price; } } } let product = new Product('笔记本电脑', 1000); let member = new Customer('member'); let vip = new Customer('vip'); let guest = new Customer('guest'); let superVip = new Customer('superVip'); console.log(product.cost(member)); console.log(product.cost(vip)); console.log(product.cost(guest)); //多态是一个功能,它的实现是要靠继承的, 多态是要靠继承来实现,没能 继承就没有多态
592078fc53ea984e8d5b9d98bd8f01f1c643610e
TypeScript
aem-design/aemdesign-aem-support
/aemdesign-aem-compose/src/core/js/modules/binder.ts
2.5625
3
import { isAuthorMode } from '@/core/utility/aem' /** * Vue.js components! * * @param {boolean} [force=false] Should the component be forced to load? * @return {Promoise<number>} Number of Vue components that exist */ export async function bindVueComponents(force = false): Promise<number> { const vueElements = document.querySelectorAll('[vue-component]:not([js-set])') if ((force || !(force && isAuthorMode())) && vueElements.length) { const { default: ComposeVue } = await import(/* webpackChunkName: "vue/compose" */ '@/core/components/compose-vue') ComposeVue(vueElements) } return Promise.resolve(vueElements.length) }
07129b8e7664ca3b298382c258861ad3c1063c9e
TypeScript
korobochka/heisenbug-protractor
/demo_ng4/app/app.component.ts
2.609375
3
import { Component } from '@angular/core'; import { Observable } from 'rxjs'; export class NickName { timestamp: Date; nick: string; age: number; result: string; } @Component({ selector: 'names', template: ` <form class="form-inline"> <input [(ngModel)]="nick" type="text" placeholder="nick" name="nick" class="input-nick input-large"> <input [(ngModel)]="age" type="text" placeholder="age" name="age" class="input-age input-small"> <button (click)="doAdd()" class="btn input-submit">Submit</button> </form> <h3 class="loader">{{loading}}</h3> <h4>Results</h4> <table class="table results-list"> <thead><tr> <th>Time</th> <th>Nick</th> <th>Age</th> <th>Result</th> </tr></thead> <tr *ngFor="let result of results" class="results-item"> <td> {{result.timestamp | date:'mediumTime'}} </td> <td>{{result.nick}}</td> <td>{{result.age}}</td> <td class="results-result">{{result.result}}</td> </tr> </table> ` }) export class NamesComponent { nick: string = 'CoolNick'; age: number = 30; loading: string = ''; results: NickName[] = []; doAdd(): void { this.loading = 'Loading...'; let result = { timestamp: new Date(), nick: this.nick, age: this.age, result: this.nick + (2017 - this.age) }; Observable.timer(3000).subscribe(x => { this.loading = ''; this.results.unshift(result); }); } } @Component({ selector: 'about', template: ` <h4>About</h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ipsum nisl, imperdiet a sem et, pellentesque gravida enim. Ut pellentesque, lacus sed feugiat ullamcorper, ante erat tincidunt turpis, tristique hendrerit enim felis sed turpis. Praesent luctus ultrices tortor, eu tincidunt dui interdum sit amet. Sed vel pulvinar eros. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; In ligula nibh, pretium eu ligula a, lobortis vehicula mi. Cras a euismod tortor, ut laoreet turpis. Nunc volutpat velit non ipsum luctus, id suscipit dolor porta. Suspendisse luctus eget odio eget faucibus. In iaculis tortor quis lectus sagittis porttitor. Nam rhoncus erat ut blandit eleifend. Curabitur accumsan, lectus eu ultricies vulputate, nibh quam accumsan diam, ac porta massa tellus id eros. Vestibulum ipsum erat, pretium vel turpis a, scelerisque interdum augue. Fusce venenatis nunc id felis interdum, vitae elementum justo commodo. </p> <p>Donec fringilla neque nisi, a suscipit ipsum posuere a. Aliquam erat volutpat. Proin accumsan ligula nec quam lacinia luctus. Cras at sodales tellus. In finibus feugiat nisi, sit amet auctor ante rutrum nec. Nullam ex augue, auctor ut pellentesque id, sagittis a tortor. Nunc eget turpis ut nisi sagittis commodo. Cras vehicula purus efficitur, tempor velit vitae, consequat est. Aliquam orci urna, laoreet ut justo a, aliquam porttitor ligula. Pellentesque vitae ex nunc. Donec semper diam et ligula pharetra tincidunt. Vivamus lacus turpis, posuere vitae tristique eu, tincidunt sed turpis. In quis blandit justo. Sed vehicula eros nec euismod ullamcorper. Aliquam vitae faucibus ex. Cras ullamcorper leo metus, vitae venenatis nunc dictum sed. </p> <p>Sed sodales enim sit amet dignissim interdum. Curabitur eget dapibus magna. Proin vel auctor purus, at molestie quam. Nulla orci quam, ullamcorper maximus laoreet at, pretium ullamcorper ex. Fusce varius tellus sed consectetur condimentum. Aliquam hendrerit diam at elit consequat gravida quis ac felis. Maecenas tempor mollis est, eu placerat felis porttitor a. Donec porttitor mi non est ultricies ultrices. Nunc blandit a nibh quis molestie. Maecenas a egestas lacus, vel varius turpis. </p> ` }) export class AboutComponent { } @Component({ selector: 'my-app', template: ` <nav> <a routerLink="/" routerLinkActive="active" class="nav-list">Home</a> <a routerLink="/about" routerLinkActive="active" class="nav-list">About</a> <a href="./login.html" class="nav-list">Login</a> </nav> <br /> <router-outlet></router-outlet> ` }) export class AppComponent { }
ab0077eaad4ac8e43fc321df9fb86a8f974389fe
TypeScript
yasu-s/ng-cli-sample
/src/app/ext/log.interceptor.ts
2.578125
3
import { Injectable } from '@angular/core'; import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { tap } from 'rxjs/operators'; /** * */ @Injectable() export class LogInterceptor implements HttpInterceptor { /** * * @param req * @param next */ intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { return next.handle(req).pipe( tap(event => { if (event instanceof HttpResponse) { console.log(`url: ${req.url}, method: ${req.method}, status: ${(<HttpResponse<any>>event).status}`); } }) ); } }
6f4587c966e2aba0a0a99899508530cba8245a17
TypeScript
nguyer/aws-sdk-js-v3
/clients/browser/client-fsx-browser/types/BackupRestoring.ts
2.75
3
import { ServiceException as __ServiceException__ } from "@aws-sdk/types"; /** * <p>You can't delete a backup while it's being used to restore a file system.</p> */ export interface BackupRestoring extends __ServiceException__<_BackupRestoringDetails> { name: "BackupRestoring"; } export interface _BackupRestoringDetails { /** * <p>A detailed error message.</p> */ Message?: string; /** * <p>The ID of a file system being restored from the backup.</p> */ FileSystemId?: string; }
c350849b1ccd7528f67e6b9e13b6f5d80433a216
TypeScript
rashiop/udra-library-api
/src/resources/book/book.type.ts
2.53125
3
import { Document, Model, Types } from 'mongoose'; enum ActiveStatus { A = 'active', D = 'deleted' } interface IBook { title: string; description: string; active_status: ActiveStatus; authors: Types.ObjectId[]; genres: Types.ObjectId[]; publisher: Types.ObjectId; created_by: Types.ObjectId; updated_by: Types.ObjectId; total: number; stock: number; } interface IBookDoc extends IBook, Document { url: string; returnBook(): void; borrowBook(): void; addTotal(): void; minTotal(): void; } interface IBookModel extends Model<IBookDoc> { getOneById(bookId: unknown): IBookDoc | null; getMany(): IBookDoc[] | null; } export { ActiveStatus, IBook, IBookDoc, IBookModel }
fdf4a24d2c72ea3d26369d595533a789d36b55cb
TypeScript
soketi/echo-server
/src/stats/stats-driver.ts
2.9375
3
import { App } from './../app'; export interface StatsDriver { /** * Mark in the stats a new connection. * Returns a number within a promise. */ markNewConnection(app: App): Promise<number>; /** * Mark in the stats a socket disconnection. * Returns a number within a promise. */ markDisconnection(app: App, reason?: string): Promise<number>; /** * Mark in the stats a new API message. * Returns a number within a promise. */ markApiMessage(app: App): Promise<number>; /** * Mark in the stats a whisper message. * Returns a number within a promise. */ markWsMessage(app: App): Promise<number>; /** * Get the compiled stats for a given app. */ getStats(app: App|string|number): Promise<StatsElement>; /** * Take a snapshot of the current stats * for a given time. */ takeSnapshot(app: App|string|number, time?: number): Promise<TimedStatsElement>; /** * Get the list of stats snapshots for a given interval. * Defaults to the last 7 days. */ getSnapshots(app: App|string|number, start?: number, end?: number): Promise<AppSnapshottedPoints>; /** * Delete points that are outside of the desired range * of keeping the history of. */ deleteStalePoints(app: App|string|number, time?: number): Promise<boolean>; /** * Register the app to know we have metrics for it. */ registerApp(app: App|string|number): Promise<boolean>; /** * Get the list of registered apps into stats. */ getRegisteredApps(): Promise<string[]>; } export interface StatsElement { connections?: number; peak_connections?: number; api_messages?: number; ws_messages?: number; } export interface AppsStats { [key: string]: StatsElement; } export interface TimedStatsElement { time?: string|number; stats: StatsElement; } export interface SnapshotPoint { time?: number|string; avg?: number|string; max?: number|string; value?: number|string; } export interface AppSnapshottedPoints { connections: { points: SnapshotPoint[] }; api_messages: { points: SnapshotPoint[] }; ws_messages: { points: SnapshotPoint[] }; } export interface Snapshots { [key: string]: AppSnapshottedPoints; }
7d270ee5a6123233df399a3fd35ea07b0e863058
TypeScript
glimmerjs/glimmer-vm
/packages/@glimmer/manager/lib/public/template.ts
2.859375
3
import type { TemplateFactory } from "@glimmer/interfaces"; import { debugToString } from '@glimmer/util'; const TEMPLATES: WeakMap<object, TemplateFactory> = new WeakMap(); const getPrototypeOf = Object.getPrototypeOf; export function setComponentTemplate(factory: TemplateFactory, obj: object) { if ( import.meta.env.DEV && !(obj !== null && (typeof obj === 'object' || typeof obj === 'function')) ) { throw new Error(`Cannot call \`setComponentTemplate\` on \`${debugToString!(obj)}\``); } if (import.meta.env.DEV && TEMPLATES.has(obj)) { throw new Error( `Cannot call \`setComponentTemplate\` multiple times on the same class (\`${debugToString!( obj )}\`)` ); } TEMPLATES.set(obj, factory); return obj; } export function getComponentTemplate(obj: object): TemplateFactory | undefined { let pointer = obj; while (pointer !== null) { let template = TEMPLATES.get(pointer); if (template !== undefined) { return template; } pointer = getPrototypeOf(pointer); } return undefined; }