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
95c87aacf8d3780ce76efeb8c119b5f37f18fe67
TypeScript
gellaig/boxorder
/boxorder-client/src/app/ecommerce/models/order.model.ts
2.578125
3
import { ProductOrder } from "./product-order.model"; import { Location } from "./location.model"; export class Order { id: number; dateCreated: string; status : string; location: Location; totalOrderPrice: number; orderProducts: ProductOrder[] = []; constructor(id: number, status: string,orderProducts: ProductOrder[],dateCreated: string, location : Location, totalOrderPrice: number) { this.id = id; this.status = status; this.location = location; this.orderProducts = orderProducts; this.dateCreated = dateCreated; this.totalOrderPrice = totalOrderPrice; } }
74db4a88d1ca1770591fa7d9b255f8e98e2c92fd
TypeScript
jamashita/publikum
/packages/digest/src/Digest.ts
2.796875
3
import bcrypt from 'bcrypt'; const ROUNDS: number = 14; export class Digest { public static async generate(str: string): Promise<string> { const salt: string = await bcrypt.genSalt(ROUNDS); return bcrypt.hash(str, salt); } public static compare(str: string, hash: string): Promise<boolean> { return bcrypt.compare(str, hash); } private constructor() { // NOOP } }
f41c819e093877cb198eeec20ec9528140cb2fc7
TypeScript
alfredohugueth/NodeJSTest
/src/controllers/products.controller.ts
2.625
3
/* Functional Imports*/ import { request, Request, Response } from "express"; import HttpStatusCode from "../interface/HttpStatusCode"; /* Database Import*/ import { connect } from "./database"; /* Querys */ import Querys from "../querys/products.query"; /* Interfaces */ import Query from "mysql2/typings/mysql/lib/protocol/sequences/Query"; export class ProductsController{ /* Route for GET /api/products? */ listProductsWithCategoriesByID=async(req: Request, res: Response)=> { if (req.body.hasOwnProperty('page') && req.body.hasOwnProperty('length') && req.body.hasOwnProperty('order')) await verifyParametersListProductsByID(req, res); else sendStatusFailListProductsByID(req, res); } /* Route for GET /api/products/search? */ searchProductsByNameCategoryOrSupplier= async(req: Request, res: Response)=> { if (req.body.hasOwnProperty('productName') || req.body.hasOwnProperty('categoryName') || req.body.hasOwnProperty('supplierName')) await verifyParametersSearchByProductCategorySupplierName(req, res); else sendStatusFailSearchProductsByNameCategoryOrSupplier(req, res); } /* Route for GET /api/products/:id*/ searchProductByID= async (req: Request, res: Response)=> { //Verify if the param id its in the url requested if (req.params.hasOwnProperty('id')) await queryProductByID(req, res); else sendStatusFailQueryProductsByID(req, res); } /* Route for POST /api/products */ createNewProduct= async(req:Request,res:Response)=> { /* Verify that the request send has the format */ let params = req.body; if(params.hasOwnProperty('categoryID') && params.hasOwnProperty('discontinued') && params.hasOwnProperty('productName') && params.hasOwnProperty('quantityPerUnit') && params.hasOwnProperty('reorderLevel') && params.hasOwnProperty('supplierID') && params.hasOwnProperty('unitPrice') && params.hasOwnProperty('unitsInStock') && params.hasOwnProperty('unitsOnOrder')) await testTypesOfDatas(req,res,params) else sendStatusFailInsertProducts(req,res); } } /*Functions for make the querys */ /* Functions for GET /api/products?*/ /* Send Status fail*/ function sendStatusFailListProductsByID(req: Request, res: Response) { let format = { 'page': 1, 'length': 5, 'order': (`ASC | DESC`) } res.statusCode = HttpStatusCode.BAD_REQUEST; res.json({ 'Status': 'Fail', 'Description': `No correct data posted, please insert data in this format:`, 'format': format }) } async function verifyParametersListProductsByID(req: Request, res: Response) { if (typeof (req.body.page) == 'number' && typeof (req.body.length) == 'number' && (req.body.order == 'ASC' || req.body.order == 'DESC')) await sendQueryListProductsByID(req, res); else sendStatusFailListProductsByID(req, res); } async function sendQueryListProductsByID(req: Request, res: Response): Promise<Response> { /* Extract page that user want to see*/ let page: number = req.body.page; /* Extract the desired length of the page */ let length: number = req.body.length; /* Extract the order that the user desired -- ASC or DES*/ let order = req.body.order; let condition = ` ORDER BY p.ProductID ${order} LIMIT ? OFFSET ?` let query = Querys.querysendQueryListProductsByID + condition /* Connecting to database*/ try { const connection = await connect(); /* First query for obtain the total of pages of the result query */ const resultQuery = await connection.query(Querys.queryNumberRowsProducts); const totalRows: any = resultQuery[0]; const total: any = { total: totalRows[0].total } let offset: number = (page - 1) * 5; /* Then query for items of products */ const items: any = await connection.query(query, [length, offset]); /* To desired format */ var answer = { 'currentPage': page, 'items': [], 'perPage': length, 'total': total.total } answer = transformToFormat(answer, items); res.statusCode = HttpStatusCode.OK; return res.json(answer); } catch (err) { console.log(err); sendCatchFailure(req, res); } } /* Functions for GET /api/products/search?*/ function transformToFormat(data, items) { if (data.hasOwnProperty('items')) { for (let item of items[0]) { data.items.push({ "category": { "description": item.Description, "id": item.CategoryID, "name": item.CategoryName, "picture": item.picture }, "discontinued": item.Discontinued, "id": item.ProductID, "productName": item.ProductName, "quantityPerUnit": item.QuantityPerUnit, "reorderLevel": item.ReorderLevel, "supplier": { "address": { "city": item.city, "country": item.country, "phone": item.phone, "postalCode": 70117, "region": item.region, "street": item.street }, "companyName": item.companyName, "contactName": item.contactName, "contactTitle": item.contactTitle, "id": item.id }, "unitPrice": 22, "unitsInStock": 53, "unitsOnOrder": 0 } ) } } else { for (let item of items[0]) { data.push( { "category": { "description": item.description, "id": item.CategoryID, "name": item.name, "picture": item.picture }, "discontinued": item.discontinued, "id": item.ProductID, "productName": item.productName, "quantityPerUnit": item.quantityPerUnit, "reorderLevel": item.reorderLevel, "supplier": { "address": { "city": item.city, "country": item.country, "phone": item.phone, "postalCode": item.postalCode, "region": item.region, "street": item.street }, "companyName": item.companyName, "contactName": item.contactName, "contactTitle": item.contactTitle, "id": item.SupplierID }, "unitPrice": item.unitPrice, "unitsInStock": item.unitsInStock, "unitsOnOrder": item.UnitsOnOrder } ) } } return data; } async function verifyParametersSearchByProductCategorySupplierName(req: Request, res: Response) { /* Verify wich param its in the body */ let productName = ''; let categoryName = ''; let supplierName = ''; if (req.body.hasOwnProperty('productName')) productName = req.body.productName; if (req.body.hasOwnProperty('categoryName')) categoryName = req.body.categoryName; if (req.body.hasOwnProperty('supplierName')) supplierName = req.body.supplierName; /* Query for resolve the task */ if(typeof(productName) == 'string' && typeof(categoryName) == 'string' && typeof(supplierName) == 'string') await tryCatchSearchProducts(req,res,productName,categoryName,supplierName) } async function tryCatchSearchProducts(req:Request,res:Response,productName:String,categoryName:String,supplierName:String) { try { await sendQuerySearchByProductCategorySupplierName(req, res, productName, categoryName, supplierName) } catch (err) { console.log(err); sendCatchFailure(req, res); } } async function sendQuerySearchByProductCategorySupplierName(req: Request, res: Response, productName: String, categoryName: String, supplierName: String) { const connection = await connect(); /* Send query and make the format */ const search: any = await connection.query(Querys.sendQuerySearchByProductCategorySupplierName, [productName, categoryName, supplierName]); let response = [] /*Transform response to desired format */ response = transformToFormat(response,search); res.statusCode = HttpStatusCode.OK; res.json(response); } function sendCatchFailure(req: Request, res: Response) { res.statusCode = HttpStatusCode.BAD_GATEWAY; res.json({ 'status': 'Fail', 'Description': 'Error Connecting database for the query' }) } async function sendStatusFailSearchProductsByNameCategoryOrSupplier(req: Request, res: Response) { res.statusCode = HttpStatusCode.BAD_REQUEST; let format = { 'productName': 'Example product name as string', 'categoryName': 'Example category name as string', 'supplierName': 'Example Supplier name as string' } res.json({ 'Status': 'Fail', 'Description': `No correct data posted, please insert data that at least one of this params`, 'format': format }) } /* Functions for GET /api/products/:id*/ async function queryProductByID(req: Request, res: Response) { let id = parseInt(req.params.id); if(isNaN(id)) sendStatusFailQueryProductsByID(req,res) else try { await productsByID(res, id) } catch (err) { console.log(err); sendCatchFailure(req, res) }; } async function productsByID(res: Response, id: Number) { const connection = await connect(); let inter:any = await connection.query(Querys.productsByID, [id]); let item = (inter[0])[0]; /* Transform to desierd format*/ let response = [] //response = transformToFormat(response, item[0]) response.push( { "category": { "description": item.description, "id": item.CategoryID, "name": item.name, "picture": item.picture }, "discontinued": item.discontinued, "id": item.ProductID, "productName": item.productName, "quantityPerUnit": item.quantityPerUnit, "reorderLevel": item.reorderLevel, "supplier": { "address": { "city": item.city, "country": item.country, "phone": item.phone, "postalCode": item.postalCode, "region": item.region, "street": item.street }, "companyName": item.companyName, "contactName": item.contactName, "contactTitle": item.contactTitle, "id": item.SupplierID }, "unitPrice": item.unitPrice, "unitsInStock": item.unitsInStock, "unitsOnOrder": item.UnitsOnOrder } ) res.statusCode = HttpStatusCode.OK; res.json(response); } function sendStatusFailQueryProductsByID(req: Request, res: Response) { res.statusCode = HttpStatusCode.BAD_REQUEST; let format = '/api/products/(theIdYouWantToSearch)' res.json({ 'Status': 'Fail', 'Description': `Please insert the id in the url like this`, 'format': format }) } /* functions for post /api/products*/ function sendStatusFailInsertProducts(req:Request,res:Response){ res.statusCode = HttpStatusCode.BAD_REQUEST; let format = { "categoryID": 3, "discontinued": true, "productName": "Chef Anton's Cajun Seasoning", "quantityPerUnit": "48 - 6 oz jars", "reorderLevel": 0, "supplierID": 2, "unitPrice": 22, "unitsInStock": 53, "unitsOnOrder": 0 } res.json({ 'Status': 'Fail', 'Description': `Please insert the data in this format`, 'format': format }); } async function testTypesOfDatas(req:Request,res:Response,params){ if(typeof(params.productName) == 'string' && typeof(params.supplierID) == 'number' && typeof(params.categoryID) == 'number' && typeof(params.quantityPerUnit) == 'number' && typeof(params.unitPrice) == 'number' && typeof(params.unitsInStock) == 'number' && typeof(params.unitsOnOrder) == 'number' && typeof(params.reorderLevel) == 'number' && typeof(params.discontinued)=='boolean')/* End of If Statement*/try{insertProduct(req,res,params)}catch{sendStatusFailInsertProducts(req,res)} else sendStatusFailInsertProducts(req,res); } async function insertProduct(req:Request,res:Response,params) { const connection = await connect(); let values = [params.productName,params.supplierID,params.categoryID, params.quantityPerUnit,params.unitPrice,params.unitsInStock,params.unitsOnOrder,params.reorderLevel,params.discontinued] await connection.query(Querys.insertProduct, values); res.statusCode = HttpStatusCode.OK res.json({ 'status':'Success', 'description':'Data Inserted correctly' }) }
5ebb05f9f5a99c9f18a73c6603ddf091649f4b32
TypeScript
Irev-Dev/React-hook-lazy-loading-pattern-demo
/src/useTabData.ts
2.875
3
import { useState, useEffect } from "react"; import { useStore } from "./store"; export const useTabData = ( tab: "sweet" | "rad" ): { data: string[]; loading: boolean; error: string } => { const [isLoading, setIsLoading] = useState<boolean>(true); const [state, dispatch] = useStore(); const coolData = state && state.coolData && state.coolData[tab]; const shouldFetchData = tab && !(coolData && coolData.length); const fetchData = async (tab: "sweet" | "rad") => { setIsLoading(true); const promise = new Promise<string[]>(resolve => { setTimeout( () => resolve(tab === "sweet" ? ["a", "b", "c", "d"] : ["x", "y", "z"]), 3000 ); }); const data = await promise; dispatch({ type: "UPDATE_COOL_DATA", payload: { type: tab, data } }); setIsLoading(false); }; useEffect(() => { if (shouldFetchData) fetchData(tab); }, [tab, shouldFetchData]); return { data: coolData || [], loading: isLoading, error: "" }; };
53a1cd9c71808c4f0ba3daa4510baa1433939811
TypeScript
ctrl-freaks/freezeframe.js
/packages/angular-freezeframe/projects/angular-freezeframe/src/lib/angular-freezeframe.component.spec.ts
2.546875
3
import { Component } from '@angular/core'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { AngularFreezeframeComponent } from './angular-freezeframe.component'; const src = 'http://localhost:8080/foo.gif'; @Component({ template: ` <angular-freezeframe> <img [src]="src" alt="one" /> </angular-freezeframe> `, }) class SingleChildComponent {} @Component({ template: ` <angular-freezeframe> <img [src]="src" alt="one" /> <img [src]="src" alt="two" /> <img [src]="src" alt="three" /> </angular-freezeframe> `, }) class MultipleChildComponent {} describe('AngularFreezeframe', () => { let component: AngularFreezeframeComponent; let singleChildComponent: SingleChildComponent; let multipleChildComponent: MultipleChildComponent; let fixture: ComponentFixture<AngularFreezeframeComponent>; let singleChildFixture: ComponentFixture<SingleChildComponent>; let multipleChildFixture: ComponentFixture<MultipleChildComponent>; beforeAll(() => { spyOn(window.HTMLCanvasElement.prototype, 'addEventListener') spyOn(window.HTMLImageElement.prototype, 'addEventListener') }); describe('basic usage', () => { beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ AngularFreezeframeComponent ] }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(AngularFreezeframeComponent); component = fixture.componentInstance; component.src = src; fixture.detectChanges(); }); it('renders image when url is passed into src prop', () => { expect(component).toBeTruthy(); const container = fixture.nativeElement.firstChild; const img = container.querySelector('img'); expect(container).toHaveClass('angular-freezeframe'); expect(img.src).toBe(src); }); }); describe('ng-content single usage', () => { beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ AngularFreezeframeComponent, SingleChildComponent ] }) .compileComponents(); singleChildFixture = TestBed.createComponent(SingleChildComponent); singleChildComponent = singleChildFixture.componentInstance; singleChildFixture.detectChanges(); }); it('renders images when single imgs are passed as children', () => { expect(singleChildComponent).toBeTruthy(); const container = singleChildFixture.nativeElement.firstChild; const imgs = container.querySelectorAll('img'); expect(imgs.length).toBe(1); }) }); describe('ng-content multiple usage', () => { beforeEach(async () => { await TestBed.configureTestingModule({ declarations: [ AngularFreezeframeComponent, MultipleChildComponent ] }) .compileComponents(); multipleChildFixture = TestBed.createComponent(MultipleChildComponent); multipleChildComponent = multipleChildFixture.componentInstance; multipleChildFixture.detectChanges(); }); it('renders images when multiple imgs are passed as children', () => { expect(multipleChildComponent).toBeTruthy(); const container = multipleChildFixture.nativeElement.firstChild; const imgs = container.querySelectorAll('img'); expect(imgs.length).toBe(3); }) }); });
dea686d65b99886a5e6ca02074272fdb35c91d3e
TypeScript
atSistemas/angular-base
/src/base/shared/spec/BaseError.shared.spec.ts
2.609375
3
import { expect } from 'chai'; import { BaseError } from '../BaseError'; describe('shared / Errors', () => { describe('Error', () => { it('should be an Error prototype', () => { const err = new BaseError('foo'); const isErr = err instanceof Error; expect(isErr).to.equal(true); }); it('should have a name and error msg ', () => { const msg = 'test'; const err = new BaseError(msg); expect(err.name).to.equal('Base Error'); expect(err.msg).to.equal('[BASE ERROR] test'); }); }); });
ea3a0dc5e833558094d7b6942c50f4c2bfd57a5d
TypeScript
getsentry/sentry-javascript
/packages/tracing-internal/src/browser/metrics/utils.ts
2.984375
3
import type { Transaction } from '@sentry/core'; import type { Span, SpanContext } from '@sentry/types'; /** * Checks if a given value is a valid measurement value. */ export function isMeasurementValue(value: unknown): value is number { return typeof value === 'number' && isFinite(value); } /** * Helper function to start child on transactions. This function will make sure that the transaction will * use the start timestamp of the created child span if it is earlier than the transactions actual * start timestamp. */ export function _startChild(transaction: Transaction, { startTimestamp, ...ctx }: SpanContext): Span { if (startTimestamp && transaction.startTimestamp > startTimestamp) { transaction.startTimestamp = startTimestamp; } return transaction.startChild({ startTimestamp, ...ctx, }); }
82ed1f4c4147a9c6f63712152662cd81c185afe4
TypeScript
memorycero/ui-aws-release-info
/src/api/amazonaws.api.ts
2.59375
3
import Axios, { AxiosError } from "axios"; import { baseApiUrl } from '../core/const'; export interface BuildInfoApi { rt: string, team: string, branch?: string, status?: string, step?: string, id?: number, build?: string } export const lastWeekReleasesInfoUrl = `${baseApiUrl}/latest/week`; export const upcomingReleaseInfoUrl = `${baseApiUrl}/latest/releaseInfo`; export const releaseInfoUrl = `${baseApiUrl}/latest/rt`; export const getInfo = (url: string): Promise<any> => { const promise = new Promise((resolve, reject) => { setTimeout(() => { Axios.get(url) .then((response) => resolve(response.data)) .catch((error: AxiosError) => { reject(error); console.log(getMessageError(error)); }); }, 500); }); return promise; } const getMessageError = (error: AxiosError): string => { if (error.response) { switch (error.response.status) { case 404: return 'Data not found'; case 503: return 'Service unavailable'; } } return 'Request cannot be processed'; }
0cf4c42de30fdadbdbd6697c4666b56610840285
TypeScript
raveeshm2/trello-dashboard
/src/forms/validators.ts
2.5625
3
import * as yup from "yup"; export const AddListItemValidationSchema = yup.object({ title: yup.string().required('Title is required'), body: yup.string().required('Body is required') }); export const AddListValidationSchema = yup.object({ title: yup.string().required('Title is required').test('duplicate', 'Duplicate List names not allowed', val => { const lists = Object.keys(JSON.parse(localStorage.getItem('lists')!) || {}); const result = lists.reduce((res, listTitle) => { return res && listTitle !== val }, true); return result; }) });
ec6378f09a28dfcb71809efeac76e094ee44cea7
TypeScript
dminatto/maryhelp-api
/src/App/Routes/CadastroRoute.ts
2.546875
3
import * as express from 'express'; import * as httpStatus from 'http-status'; import Controller from '../Controllers/UsuarioController' class CadastroRoute { private app: express.Application; constructor(app) { this.app = app; this.listaRotas(); } listaRotas() { /** * @api {post} novo-cadastro Cadastro de usuario * @apiVersion 1.0.0 * @apiName criaUsuario * @apiGroup Usuário * @apiParamExample {json} Request-Example: * { * "cadastro": { * "nome": "Gabriela", * "sobrenome": "Silva", * "dataNascimento": "11/10/1990", * "usuario": "gabis", * "senha": 1234, * "telefone": "000000000", * "email": "gabi.s@email.com", * "temfilhos": "0", * "foto" : "/.../.../foto.png" * }, * "endereco": { * "0": { * "tipoEndereco": "comercial", * "cep": "000000000", * "uf": "SC", * "cidade": "Cidade", * "bairro": "Centro", * "endereco": "rua das laranjeiras", * "numero": "20" * } * }, * "servicosOferecidos": { * "0": { * "codServico": "5f556a38363c4a936c0fd74c", * "tipoAtendimento": "Presencial", * "aceitaPermuta": "0", * "valor": "60.00" * }, * "1": { * "codServico": "5f556a40363c4a936c0fd74d", * "tipoAtendimento": "Online", * "aceitaPermuta": "1", * "valor": "00.00" * } * } * } * @apiSuccess (200) {String} data Ok * @apiSuccessExample Success-Response: * { * "result": [{ * "cadastro": { * "_id": "5f55a5e825a0cfbdfa30b078", * "nome": "Maria", * "sobrenome": "Mercedes", * "dataNascimento": "1990-11-10T02:00:00.000Z", * "usuario": "gabis", * "senha": "4654654", * "telefone": 88888888, * "email": "mariadobairro@email.com", * "dataRegistro": "2020-09-07T03:15:52.703Z", * "__v": 0 * }, * "endereco": [ * { * "codUsuario": [ * "5f55a5e825a0cfbdfa30b078" * ], * "_id": "5f55853275214ea4206e38ff", * "tipoEndereco": "residencial", * "cep": 8887777, * "uf": "SC", * "cidade": "Macieira", * "bairro": "Centro", * "endereco": "rua das laranjeiras", * "numero": 100, * "__v": 0 * }, * ], * "servicosOferecidos": [ * { * "_id": "5f55a5e825a0cfbdfa30b07a", * "tipoAtendimento": "Presencial", * "aceitaPermuta": false, * "valor": 60 * }, * { * "_id": "5f55a5e825a0cfbdfa30b07b", * "tipoAtendimento": "Online", * "aceitaPermuta": true, * "valor": 0 * }, * { * "_id": "5f55a9a07e521cc12883dc53", * "tipoAtendimento": "Presencial", * "aceitaPermuta": true, * "valor": 25 * }, * { * "_id": "5f55ae083301e9c3aace36e2" * } * ], * "usuariosBloqueados": [ * { * "_id": "5f55b9f5409e7ecbf4ecf98d", * "codUsuario": [ * "5f55a5e825a0cfbdfa30b078" * ], * "nomeCompleto": "Maria Mercedes", * "dataBloqueio": "2020-09-07T04:41:25.627Z" * } * ], * "notificacoes": [ * { * "codUsuario": [ * "5f55a5e825a0cfbdfa30b078" * ], * "lido": true, * "_id": "5f55a5e825a0cfbdfa30b07c", * "descricao": "Bem-vindo ao MaryHelp!", * "__v": 0 * } * ], * "avaliacoesFeitas": [], * "avaliacoesRecebidas": [], * "mensagens": [] * } * ]} * @apiError error * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "error": "UseNortFound" * } */ this.app.route('/novo-cadastro').post((req, res) => Controller.criaUsuario(req, res)); /** * @api {get} usuario/:id Busca usuario * @apiVersion 1.0.0 * @apiName buscaUsuario * @apiGroup Usuário * @apiParam (parameters) {String} id codigo do usuario * @apiSuccess (200) {String} message Ok * @apiSuccessExample Success-Response: * { * "result": [{ * "cadastro": { * "_id": "5f55a5e825a0cfbdfa30b078", * "nome": "Maria", * "sobrenome": "Mercedes", * "dataNascimento": "1990-11-10T02:00:00.000Z", * "usuario": "gabis", * "senha": "4654654", * "telefone": 88888888, * "email": "mariadobairro@email.com", * "dataRegistro": "2020-09-07T03:15:52.703Z", * "__v": 0 * }, * "endereco": [ * { * "codUsuario": [ * "5f55a5e825a0cfbdfa30b078" * ], * "_id": "5f55853275214ea4206e38ff", * "tipoEndereco": "residencial", * "cep": 8887777, * "uf": "SC", * "cidade": "Macieira", * "bairro": "Centro", * "endereco": "rua das laranjeiras", * "numero": 100, * "__v": 0 * }, * ], * "servicosOferecidos": [ * { * "_id": "5f55a5e825a0cfbdfa30b07a", * "tipoAtendimento": "Presencial", * "aceitaPermuta": false, * "valor": 60 * }, * { * "_id": "5f55a5e825a0cfbdfa30b07b", * "tipoAtendimento": "Online", * "aceitaPermuta": true, * "valor": 0 * }, * { * "_id": "5f55a9a07e521cc12883dc53", * "tipoAtendimento": "Presencial", * "aceitaPermuta": true, * "valor": 25 * }, * { * "_id": "5f55ae083301e9c3aace36e2" * } * ], * "usuariosBloqueados": [ * { * "_id": "5f55b9f5409e7ecbf4ecf98d", * "codUsuario": [ * "5f55a5e825a0cfbdfa30b078" * ], * "nomeCompleto": "Maria Mercedes", * "dataBloqueio": "2020-09-07T04:41:25.627Z" * } * ], * "notificacoes": [ * { * "codUsuario": [ * "5f55a5e825a0cfbdfa30b078" * ], * "lido": true, * "_id": "5f55a5e825a0cfbdfa30b07c", * "descricao": "Bem-vindo ao MaryHelp!", * "__v": 0 * } * ], * "avaliacoesFeitas": [], * "avaliacoesRecebidas": [], * "mensagens": [] * } * ]} * @apiError error * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "error": "UseNortFound" * } */ this.app.route('/usuario/:id').get((req, res) => Controller.buscaUsuario(req, res)); /** * @api {put} usuario/:id Edita dados do usuario * @apiVersion 1.0.0 * @apiName editaUsuario * @apiGroup Usuário * * @apiParam (parameters) {String} id codigo do usuario * @apiParam (parameters) {String} nome nome do usuario * @apiParam (parameters) {String} sobrenome sobrenome do usuario * @apiParam (parameters) {Date} dataNascimento cep * @apiParam (parameters) {String} usuario usuario * @apiParam (parameters) {String} senha senha do usuario * @apiParam (parameters) {Numeric} telefone telefone do usuario * @apiParam (parameters) {String} email email do usuario * @apiParam (parameters) {Boolean} temfilhos se tem filhos * * @apiParamExample {json} Request-Example: * { * "nome": "Maria", * "sobrenome": "Mercedes", * "dataNascimento": "11/10/1990", * "usuario": "gabis", * "senha": 4654654, * "telefone": "88888888", * "email": "mariadobairro@email.com", * "temfilhos": "1" * } * * @apiSuccess (200) {String} message Ok * @apiSuccessExample Success-Response: * { * "result": "Usuario alterado com sucesso!" * } * @apiError error * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "error": "UseNortFound" * } */ this.app.route('/usuario/:id').put((req, res) => Controller.editaUsuario(req, res)); /** * @api {post} usuario/:id/endereco Inclui novo endereco do usuario * @apiVersion 1.0.0 * @apiName incluiEndereco * @apiGroup Usuário - Endereço * * @apiParam (parameters) {String} id codigo do usuario * @apiParam (parameters) {String} tipoEndereco tipo de endereço * @apiParam (parameters) {Numeric} cep cep * @apiParam (parameters) {String} uf uf * @apiParam (parameters) {String} cidade cidade * @apiParam (parameters) {String} bairro bairro * @apiParam (parameters) {String} endereco endereço * @apiParam (parameters) {Numeric} numero numero do endereço * * @apiParamExample {json} Request-Example: * { * "tipoEndereco": "residencial", * "cep": "8887777", * "uf": "SC", * "cidade": "Macieira", * "bairro": "Centro", * "endereco": "rua das laranjeiras", * "numero": "100" * } * * @apiSuccess (200) {String} message Ok * @apiSuccessExample Success-Response: * { * result": [ * "codUsuario": [ * "5f55a5e825a0cfbdfa30b078" * ], * "_id": "5f55b4ef72de84c8f06e5cb4", * "tipoEndereco": "comercial", * "cep": 8887777, * "cidade": "A cor da cidade sou eu", * "bairro": "Centro", * "endereco": "rua das laranjeiras", * "numero": 100, * "__v": 0 * ]} * @apiError error * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "error": "UseNortFound" * } */ this.app.route('/usuario/:id/endereco').post((req, res) => Controller.incluiEndereco(req, res)); /** * @api {put} usuario/:id/endereco/:enderecoId Edita endereço do usuario * @apiVersion 1.0.0 * @apiName editaEndereco * @apiGroup Usuário - Endereço * * @apiParam (parameters) {String} id codigo do usuario * @apiParam (parameters) {String} enderecoId codigo do endereço * @apiParam (parameters) {String} tipoEndereco tipo de endereço * @apiParam (parameters) {Numeric} cep cep * @apiParam (parameters) {String} uf uf * @apiParam (parameters) {String} cidade cidade * @apiParam (parameters) {String} bairro bairro * @apiParam (parameters) {String} endereco endereço * @apiParam (parameters) {Numeric} numero numero do endereço * * @apiParamExample {json} Request-Example: * { * "tipoEndereco": "residencial", * "cep": "8887777", * "uf": "SC", * "cidade": "Macieira", * "bairro": "Centro", * "endereco": "rua das laranjeiras", * "numero": "100" * } * * @apiSuccess (200) {String} message Ok * @apiSuccessExample Success-Response: * { * result": [ * "codUsuario": [ * "5f55a5e825a0cfbdfa30b078" * ], * "_id": "5f55b4ef72de84c8f06e5cb4", * "tipoEndereco": "comercial", * "cep": 8887777, * "cidade": "A cor da cidade sou eu", * "bairro": "Centro", * "endereco": "rua das laranjeiras", * "numero": 100, * "__v": 0 * ]} * @apiError error * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "error": "UseNortFound" * } */ this.app.route('/usuario/:id/endereco/:enderecoId').put((req, res) => Controller.editaEndereco(req, res)); /** * @api {put} usuario/:id/endereco/:enderecoId' Exclui endereço do usuário * @apiVersion 1.0.0 * @apiName excluiEndereco * @apiGroup Usuário - Endereço * * @apiParam (parameters) {String} id codigo do usuario * @apiParam (parameters) {String} enderecoId codigo do endereço * * @apiSuccess (200) {String} message Ok * @apiSuccessExample Success-Response: * { * "result": "Endereço excluido com sucesso!!" * } * @apiError error * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "error": "UseNortFound" * } */ this.app.route('/usuario/:id/endereco/:enderecoId').delete((req, res) => Controller.excluiEndereco(req, res)); /** * @api {put} usuario/:id/notificacoes/:notificacaoId' Marca notificação como lida * @apiVersion 1.0.0 * @apiName marcarNotificacaoComoLida * @apiGroup Usuário - Notificação * * @apiParam (parameters) {String} id codigo do usuario * * @apiParam (parameters) {String} notificacaoId codigo da notificação * * @apiSuccess (200) {String} message Ok * @apiSuccessExample Success-Response: * { * "result": "Notificação lida com sucesso!!" * } * @apiError error * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "error": "UseNortFound" * } */ this.app.route('/usuario/:id/notificacoes/:notificacaoId').put((req, res) => Controller.marcarNotificacaoComoLida(req, res)); /** * @api {post} usuario/:id/block/ Bloqueia usuario * @apiVersion 1.0.0 * @apiName bloqueiaUsuario * @apiGroup Usuário - Lista de Bloqueio * * @apiParam (parameters) {String} id codigo do usuario * * @apiSuccess (200) {String} message Ok * @apiSuccessExample Success-Response: * { * "result": "Usuario bloqueado com sucesso!" * } * @apiError error * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "error": "UseNortFound" * } */ this.app.route('/usuario/:id/block').post((req, res) => Controller.bloqueiaUsuario(req, res)); /** * @api {delete} usuario/:id/block/:blockid Retira usuario da lista de bloqueio * @apiVersion 1.0.0 * @apiName deletaBloqueio * @apiGroup Usuário - Lista de Bloqueio * * @apiParam (parameters) {String} id codigo do usuario * @apiParam (parameters) {String} blockid codigo do bloqueio * * @apiSuccess (200) {String} message Ok * @apiSuccessExample Success-Response: * { * "result": "Usuario desbloqueado com sucesso!" * } * @apiError error * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "error": "UseNortFound" * } */ this.app.route('/usuario/:id/block/:blockid').delete((req, res) => Controller.deletaBloqueio(req, res)); /** * @api {get} privacidade Retorna o código de privacidade e termos de uso * @apiVersion 1.0.0 * @apiName privacidade * @apiGroup Sistema * * @apiSuccess (200) {String} message Ok * @apiSuccessExample Success-Response: * { * "result": [ * { * "titulo": "Termos de Uso", * "descricao": "Lorem ipsum dolor sit amet...." * }, * { * "titulo": "Politica de Privacidade", * "descricao": "Lorem ipsum dolor sit amet..." * }] * } * @apiError error * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "error": "UseNortFound" * } */ this.app.route('/privacidade').get((req, res) => Controller.privacidade(req, res)); /** * @api {get} login * @apiVersion 1.0.0 * @apiName logout * @apiGroup Sistema * @apiParam (parameters) {String} user usuario * @apiParam (parameters) {String} pass senha do usuario * @apiParamExample {json} Request-Example: * { * "user" : "maria", * "pass" : "1234" * } * @apiSuccess (200) {String} message Ok * @apiSuccessExample Success-Response: * { * "result": { * "auth": "true", * "token": "gas\douLKÇdassdasdasdASWA+F09DS6501G65AW445265W1feawsrfd.waetgojiszaidfu1FV65SZR4" * } * } * @apiError error * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "error": "UseNortFound" * } */ this.app.get('/login', function (req, res) { res.status(200).send(Controller.login(req, res)); }); /** * @api {get} logout * @apiVersion 1.0.0 * @apiName logout * @apiGroup Sistema * @apiSuccess (200) {String} message Ok * @apiSuccessExample Success-Response: * { * "result": { * "auth": "false", * "token": "null" * } * } * @apiError error * @apiErrorExample Error-Response: * HTTP/1.1 404 Not Found * { * "error": "UseNortFound" * } */ this.app.get('/logout', function (req, res) { res.status(200).send({ auth: false, token: null }); }); } } export default CadastroRoute;
ea5f538d4e8e21640ac88e9e917b644de2a44478
TypeScript
gonalobernad/unique-grade-values
/src/app/app.component.ts
2.859375
3
import { Component, Output } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'codeChallenge'; gradeA; gradeB; gradeC; constructor(){ this.gradeA = [12, 15, 11, 17, 19]; this.gradeB = [10, 15, 17, 13, 19]; this.gradeC = [18, 15, 19, 17, 14]; this.uniqueGradeValues(this.gradeA, this.gradeB, this.gradeC); } private uniqueGradeValues(array1: any, array2: any, array3: any ) { let arrayBuffer = []; arrayBuffer = [...array1, ...array2, ...array3]; let output = []; arrayBuffer.filter( item => { if (arrayBuffer.filter(a => a == item).length < 2) output = [...output, item]; }); // console.table(arrayBuffer); console.log('unique gradevalues', output); return output; } }
bdaa9e1d4d046cdb177da7ce5e9d7bae08e6195a
TypeScript
undym/rsm
/src/mix.ts
2.765625
3
import { Util, Flag } from "./util.js"; import { Color } from "./undym/type.js"; import { Item } from "./item.js"; import { Player } from "./player.js"; import { Eq, EqEar } from "./eq.js"; import { Prm } from "./unit.js"; import { SaveData } from "./savedata.js"; import { Dungeon } from "./dungeon/dungeon.js"; import { Sound } from "./sound.js"; export class Num{ static add(obj:Num, v:number){ v = v|0; if(v > 0){ const newItem = obj.totalGetCount === 0; if(newItem){ Util.msg.set("new", Color.rainbow); }else{ Util.msg.set(""); } obj.num += v; obj.totalGetCount += v; Util.msg.add(`[${obj}]を${v}個手に入れた(${obj.num})`, cnt=>Color.GREEN.wave(Color.YELLOW, cnt)); if(newItem && obj.info.length > 0){ Util.msg.set(`"`, Color.YELLOW); Util.msg.add(obj.info, Color.YELLOW); Util.msg.add(`"`, Color.YELLOW); } } if(v < 0){ obj.num += v; } } info:string; /**totalGetCountとの整合性を取るため、通常はadd()を通して増減させる。 */ num:number; totalGetCount:number; add:(v:number)=>void; } export class Mix{ private static _values:Mix[] = []; static get values():ReadonlyArray<Mix>{return this._values;} private static _valueOf = new Map<string,Mix>(); static valueOf(uniqueName:string):Mix|undefined{ return this._valueOf.get(uniqueName); } static readonly LIMIT_INF = Number.POSITIVE_INFINITY; get materials():ReadonlyArray<{object:Num, num:number}>{ let res:{object:Num, num:number}[] = []; for(const m of this.args.materials()){ res.push({object:m[0], num:m[1]}); } return res; } get result():{object:Num, num:number}|undefined{ const res = this.args.result; if(res){ const r = res(); return {object:r[0], num:r[1]}; } return undefined; } get countLimit(){return this.args.limit ? this.args.limit : Mix.LIMIT_INF;} get uniqueName(){return this.args.uniqueName;} get info():string|undefined{return this.args.info;} /**合成回数. */ count = 0; /** * * limit:合成限界. * action:合成時に発生する効果。 */ constructor( private args:{ uniqueName:string, limit:number, materials:()=>[Num, number][], result?:()=>[Num, number], info?:string, isVisible:()=>boolean, action?:()=>void, to_string?:string, } ){ Mix._values.push(this); if(Mix._valueOf.has(args.uniqueName)) {console.log("Mix._valueOf.has:", `"${args.uniqueName}"`);} else {Mix._valueOf.set( args.uniqueName, this );} } toString(){return this.args.to_string ? this.args.to_string : this.uniqueName;} isVisible():boolean{ return this.args.isVisible() && this.count < this.countLimit; // if(!this.materials){return false;} // if(this.args.isVisible && !this.args.isVisible()){return false;} // return this.materials[0].object.totalGetCount > 0 && this.count < this.countLimit; } canRun(){ if(this.countLimit !== Mix.LIMIT_INF && this.count >= this.countLimit){return false;} for(let m of this.materials){ if(m.object.num < m.num){ return false; } } return true; } run(){ if(!this.canRun()){return;} this.count++; for(let m of this.materials){ m.object.add(-m.num); } if(this.result){ this.result.object.add( this.result.num ); } if(this.args.action){ this.args.action(); } } } export namespace Mix{ //-------------------------------------------------------- // //建築 // //-------------------------------------------------------- const ルインドアースLv1:Mix = new Mix({ uniqueName:"ルインドアースLv1", limit:1, info:"", materials:()=>[[Item.石, 1],], isVisible:()=>true, }); const ルインドアースLv2:Mix = new Mix({ uniqueName:"ルインドアースLv2", limit:1, info:"", materials:()=>[[Item.水, 4],], isVisible:()=>ルインドアースLv1.count > 0, }); const ルインドアースLv3:Mix = new Mix({ uniqueName:"ルインドアースLv3", limit:1, info:"", materials:()=>[[Item.草, 5],], isVisible:()=>ルインドアースLv2.count > 0, }); const ルインドアースLv4:Mix = new Mix({ uniqueName:"ルインドアースLv4", limit:1, info:"", materials:()=>[[Item.竹, 3], [Item.かんな, 1],], isVisible:()=>ルインドアースLv3.count > 0, }); const ルインドアースLv5:Mix = new Mix({ uniqueName:"ルインドアースLv5", limit:1, info:"", materials:()=>[[Item.銅板, 1], [Item.針金, 1],], isVisible:()=>ルインドアースLv4.count > 0, }); const ルインドアースLv6:Mix = new Mix({ uniqueName:"ルインドアースLv6", limit:1, info:"", materials:()=>[[Item.銅板, 2], [Item.合板, 2],], isVisible:()=>ルインドアースLv5.count > 0, }); const ルインドアースLv7:Mix = new Mix({ uniqueName:"ルインドアースLv7", limit:1, info:"", materials:()=>[[Item.クワ, 10],], isVisible:()=>ルインドアースLv6.count > 0, }); const ルインドアースLv8:Mix = new Mix({ uniqueName:"ルインドアースLv8", limit:1, info:"", materials:()=>[[Item.粘土, 5], [Item.ガラス, 3], [Item.桜, 2]], isVisible:()=>ルインドアースLv7.count > 0, }); const ルインドアースLv9:Mix = new Mix({ uniqueName:"ルインドアースLv9", limit:1, info:"", materials:()=>[[Item.ファーストキス, 3],], isVisible:()=>ルインドアースLv8.count > 0, }); const ルインドアースLv10:Mix = new Mix({ uniqueName:"ルインドアースLv10", limit:1, info:"", materials:()=>[[Item.桜, 10], [Item.松, 10], [Item.エデン樹, 4], [Item.かんな, 20]], isVisible:()=>ルインドアースLv9.count > 0, }); const ルインドアースLv11:Mix = new Mix({ uniqueName:"ルインドアースLv11", limit:1, info:"", materials:()=>[[Item.杉, 20], [Item.ヒノキ, 20], [Item.クワ, 10]], isVisible:()=>ルインドアースLv10.count > 0, }); const ルインドアースLv12:Mix = new Mix({ uniqueName:"ルインドアースLv12", limit:1, info:"", materials:()=>[[Item.うんち, 3]], isVisible:()=>ルインドアースLv11.count > 0, }); const ルインドアースLv13:Mix = new Mix({ uniqueName:"ルインドアースLv13", limit:1, info:"", materials:()=>[[Item.たんぽぽ, 30]], isVisible:()=>ルインドアースLv12.count > 0, }); const ルインドアースLv14:Mix = new Mix({ uniqueName:"ルインドアースLv14", limit:1, info:"", materials:()=>[[Item.銅板, 20], [Item.発砲ツル, 20]], isVisible:()=>ルインドアースLv13.count > 0, }); const ルインドアースLv15:Mix = new Mix({ uniqueName:"ルインドアースLv15", limit:1, info:"", materials:()=>[[Item.サクラ材, 10], [Item.クワ, 10]], isVisible:()=>ルインドアースLv14.count > 0, }); const ルインドアースLv16:Mix = new Mix({ uniqueName:"ルインドアースLv16", limit:1, info:"", materials:()=>[[Item.アリラン型岩石, 10]], isVisible:()=>ルインドアースLv15.count > 0, }); const ルインドアースLv17:Mix = new Mix({ uniqueName:"ルインドアースLv17", limit:1, info:"", materials:()=>[[Item.クヌギ, 6], [Item.バーミキュライト, 20]], isVisible:()=>ルインドアースLv16.count > 0, }); const ルインドアースLv18:Mix = new Mix({ uniqueName:"ルインドアースLv18", limit:1, info:"", materials:()=>[[Item.肉まん, 1], [Item.月の石, 1], [Item.冥石, 1]], isVisible:()=>ルインドアースLv17.count > 0, }); const ルインドアースLv19:Mix = new Mix({ uniqueName:"ルインドアースLv19", limit:1, info:"", materials:()=>[[Item.退魔の十字架, 10], [Item.血粉末, 10]], isVisible:()=>ルインドアースLv18.count > 0, }); export const 瞑想所:Mix = new Mix({ uniqueName:"瞑想所", limit:1, info:"瞑想が可能になる", materials:()=>[[Item.ヒノキ, 1], [Item.草, 5]], isVisible:()=>ルインドアースLv1.count > 0, }); export const 転職所:Mix = new Mix({ uniqueName:"転職所", limit:1, info:"職業選択の自由を得る", materials:()=>[[Item.杉, 3], [Item.ヒノキ, 3], [Item.かんな, 3]], isVisible:()=>ルインドアースLv4.count > 0, }); export const 動く映写機:Mix = new Mix({ uniqueName:"動く映写機", limit:1, info:"動かない映写機を修理する", materials:()=>[[Item.にじゅうよん, 24], [Item.少女の心を持ったおっさん, 1],], isVisible:()=>ルインドアースLv10.count > 0, }); export const 月読転移装置:Mix = new Mix({ uniqueName:"月読転移装置", limit:1, info:"月に行けるようになる", materials:()=>[[Item.タンホイザーの砂飯, 1], [Item.惑星エネルギー, 10], [Item.イリジウム, 20], [Item.モーター, 10],], isVisible:()=>ルインドアースLv16.count > 0 && Dungeon.月狼の森.dungeonClearCount > 0, }); export const 封印の魔十字架:Mix = new Mix({ uniqueName:"封印の魔十字架", limit:1, info:"魔界門を開く", materials:()=>[[Item.退魔の十字架, 99], [Item.呪い水, 39],], isVisible:()=>Dungeon.魔水路.dungeonClearCount > 0, }); // export const 集会所:Mix = new Mix({ // uniqueName:"集会所", limit:1, info:"パーティースキルをセットできるようになる", // materials:()=>[[Item.エレタクレヨン, 6], [Item.エデン樹, 3]], // isVisible:()=>ルインドアースLv20.count > 0, // }); export const 月のレシピ:Mix = new Mix({ uniqueName:"月のレシピ", limit:1, info:"月小人に伝わる秘伝の装備レシピ", materials:()=>[[Item.月の石, 1], [Item.錫, 10], [Item.粘土, 10],], isVisible:()=>ルインドアースLv16.count > 0 && Dungeon.月狼の森.dungeonClearCount > 0, }); const 肉のスープ:Mix = new Mix({ uniqueName:"肉のスープ", limit:10, info:"ルインの最大HP+1", materials:()=>[[Item.石, 2], [Item.肉, 1], [Item.水, 1]], isVisible:()=>Player.ルイン.member && ルインドアースLv2.count > 0, action:()=>{ Player.ルイン.ins.prm(Prm.MAX_HP).base += 1; }, }); const 猫の秘薬:Mix = new Mix({ uniqueName:"猫の秘薬", limit:10, info:"ルインの最大HP+1", materials:()=>[[Item.肉, 1], [Item.水, 3]], isVisible:()=>Player.ルイン.member && ルインドアースLv6.count > 0 && 肉のスープ.count >= 肉のスープ.countLimit, action:()=>{ Player.ルイン.ins.prm(Prm.MAX_HP).base += 1; }, }); const ねこじゃらし:Mix = new Mix({ uniqueName:"ねこじゃらし", limit:10, info:"ルインの力+1", materials:()=>[[Item.竹, 4], [Item.バッタ, 2], [Item.草, 1]], isVisible:()=>Player.ルイン.member && ルインドアースLv3.count > 0, action:()=>{ Player.ルイン.ins.prm(Prm.STR).base += 1; }, }); const 銅像:Mix = new Mix({ uniqueName:"銅像", limit:5, info:"ルインの最大TP+1", materials:()=>[[Item.銅板, 1], [Item.少女の心を持ったおっさん, 3], [Item.たんぽぽ, 1]], isVisible:()=>Player.ルイン.member && ルインドアースLv10.count > 0, action:()=>{ Player.ルイン.ins.prm(Prm.MAX_TP).base += 1; }, }); const バッタのスープ:Mix = new Mix({ uniqueName:"バッタのスープ", limit:10, info:"ピアーの最大HP+1", materials:()=>[[Item.肉, 1], [Item.バッタ, 2], [Item.水, 1]], isVisible:()=>Player.ピアー.member && ルインドアースLv2.count > 0, action:()=>{ Player.ピアー.ins.prm(Prm.MAX_HP).base += 1; }, }); const ピアー家秘薬:Mix = new Mix({ uniqueName:"ピアー家秘薬", limit:10, info:"ピアーの最大HP+1", materials:()=>[[Item.肉, 1], [Item.草, 2]], isVisible:()=>Player.ピアー.member && ルインドアースLv6.count > 0 && バッタのスープ.count >= バッタのスープ.countLimit, action:()=>{ Player.ピアー.ins.prm(Prm.MAX_HP).base += 1; }, }); const ゴーグルケース:Mix = new Mix({ uniqueName:"ゴーグルケース", limit:5, info:"ピアーの最大MP+1", materials:()=>[[Item.ガラス, 3], [Item.ヒノキ, 2], [Item.針金, 1]], isVisible:()=>Player.ピアー.member && ルインドアースLv10.count > 0, action:()=>{ Player.ピアー.ins.prm(Prm.MAX_MP).base += 1; }, }); const 水晶玉:Mix = new Mix({ uniqueName:"水晶玉", limit:10, info:"ピアーの魔+1", materials:()=>[[Item.ガラス, 3], [Item.水, 2]], isVisible:()=>Player.ピアー.member && ルインドアースLv4.count > 0, action:()=>{ Player.ピアー.ins.prm(Prm.MAG).base += 1; }, }); const ウェルダン:Mix = new Mix({ uniqueName:"ウェルダン", limit:10, info:"一号の闇+1", materials:()=>[[Item.肉, 1], [Item.針金, 1]], isVisible:()=>Player.一号.member && Dungeon.テント樹林.dungeonClearCount > 0, action:()=>{ Player.一号.ins.prm(Prm.DRK).base += 1; }, }); const 大きなお弁当箱:Mix = new Mix({ uniqueName:"大きなお弁当箱", limit:10, info:"一号の最大HP+1", materials:()=>[[Item.杉, 10], [Item.ヒノキ, 10]], isVisible:()=>Player.一号.member && ルインドアースLv8.count > 0, action:()=>{ Player.一号.ins.prm(Prm.MAX_HP).base += 1; }, }); const ツルの銃:Mix = new Mix({ uniqueName:"ツルの銃", limit:10, info:"一号の闇+1", materials:()=>[[Item.発砲ツル, 2], [Item.土, 4]], isVisible:()=>Player.一号.member && ルインドアースLv10.count > 0, action:()=>{ Player.一号.ins.prm(Prm.DRK).base += 1; }, }); const レア:Mix = new Mix({ uniqueName:"レア", limit:10, info:"雪の鎖+1", materials:()=>[[Item.肉, 1], [Item.草, 2]], isVisible:()=>Player.雪.member && Dungeon.テント樹林.dungeonClearCount > 0, action:()=>{ Player.雪.ins.prm(Prm.CHN).base += 1; }, }); const ビー玉:Mix = new Mix({ uniqueName:"ビー玉", limit:10, info:"雪の最大HP+1", materials:()=>[[Item.ガラス, 4], [Item.砂, 8]], isVisible:()=>Player.雪.member && ルインドアースLv8.count > 0, action:()=>{ Player.雪.ins.prm(Prm.MAX_HP).base += 1; }, }); const おもちゃの鎖:Mix = new Mix({ uniqueName:"おもちゃの鎖", limit:10, info:"雪の力+1", materials:()=>[[Item.針金, 4], [Item.銅, 5]], isVisible:()=>Player.雪.member && ルインドアースLv10.count > 0, action:()=>{ Player.雪.ins.prm(Prm.CHN).base += 1; }, }); const ガンステーキ:Mix = new Mix({ uniqueName:"ガンステーキ", limit:10, info:"lukaの銃+1", materials:()=>[[Item.肉, 1], [Item.発砲ツル, 1]], isVisible:()=>Player.luka.member, action:()=>{ Player.luka.ins.prm(Prm.GUN).base += 1; }, }); const おもちゃの銃:Mix = new Mix({ uniqueName:"おもちゃの銃", limit:10, info:"lukaの銃+1", materials:()=>[[Item.石, 1], [Item.発砲ツル, 1]], isVisible:()=>Player.luka.member && ルインドアースLv8.count > 0, action:()=>{ Player.luka.ins.prm(Prm.GUN).base += 1; }, }); const 石焼き肉:Mix = new Mix({ uniqueName:"石焼き肉", limit:10, info:"ベガの最大HP+1", materials:()=>[[Item.肉, 1], [Item.石, 2]], isVisible:()=>Player.ベガ.member, action:()=>{ Player.ベガ.ins.prm(Prm.MAX_HP).base += 1; }, }); const ただれた肉:Mix = new Mix({ uniqueName:"ただれた肉", limit:10, info:"ベガの最大HP+1", materials:()=>[[Item.肉, 1], [Item.呪い水, 5]], isVisible:()=>Player.ベガ.member && ルインドアースLv8.count > 0, action:()=>{ Player.ベガ.ins.prm(Prm.MAX_HP).base += 1; }, }); const ししおどし:Mix = new Mix({ uniqueName:"ししおどし", limit:10, info:"ベガの力+1", materials:()=>[[Item.かんな, 7], [Item.竹, 5]], isVisible:()=>Player.ベガ.member && ルインドアースLv10.count > 0, action:()=>{ Player.ベガ.ins.prm(Prm.STR).base += 1; }, }); const ハンバーグ:Mix = new Mix({ uniqueName:"ハンバーグ", limit:10, info:"ジスロフの力+1", materials:()=>[[Item.肉, 1], [Item.岩塩, 2]], isVisible:()=>Player.ジスロフ.member, action:()=>{ Player.ジスロフ.ins.prm(Prm.STR).base += 1; }, }); const ミートボール:Mix = new Mix({ uniqueName:"ミートボール", limit:10, info:"ナナの光+1", materials:()=>[[Item.肉, 1], [Item.トマト, 2]], isVisible:()=>Player.ナナ.member, action:()=>{ Player.ナナ.ins.prm(Prm.LIG).base += 1; }, }); const ピアーの肉まんレシピ:Mix = new Mix({ uniqueName:"ピアーの肉まんレシピ", limit:10, info:"ピアー直伝肉まんレシピが解放される", materials:()=>[[Item.動かないゴーグル, 20]], isVisible:()=>ルインドアースLv17.count > 0, }); const たんぽぽまん:Mix = new Mix({ uniqueName:"たんぽぽまん", limit:5, info:"ルインの全ステータス+10", materials:()=>[[Item.肉まん, 1], [Item.たんぽぽ, 30]], isVisible:()=>ピアーの肉まんレシピ.count > 0 && Player.ルイン.member, action:()=>{ Prm.atkPrms.forEach(prm=> Player.ルイン.ins.prm(prm).base += 10); }, }); const 筍まん:Mix = new Mix({ uniqueName:"筍まん", limit:5, info:"ピアーの魔+10", materials:()=>[[Item.肉まん, 1], [Item.竹, 30]], isVisible:()=>ピアーの肉まんレシピ.count > 0 && Player.ピアー.member, action:()=>{ Player.ピアー.ins.prm(Prm.MAG).base += 10; }, }); const バッタまん:Mix = new Mix({ uniqueName:"バッタまん", limit:5, info:"一号の闇+10", materials:()=>[[Item.肉まん, 1], [Item.バッタ, 30]], isVisible:()=>ピアーの肉まんレシピ.count > 0 && Player.一号.member, action:()=>{ Player.一号.ins.prm(Prm.DRK).base += 10; }, }); const 水まん:Mix = new Mix({ uniqueName:"水まん", limit:5, info:"雪の鎖+10", materials:()=>[[Item.肉まん, 1], [Item.水, 30]], isVisible:()=>ピアーの肉まんレシピ.count > 0 && Player.雪.member, action:()=>{ Player.雪.ins.prm(Prm.CHN).base += 10; }, }); const かにまん:Mix = new Mix({ uniqueName:"かにまん", limit:5, info:"ベガの全ステータス+10", materials:()=>[[Item.肉まん, 1], [Item.かに, 30]], isVisible:()=>ピアーの肉まんレシピ.count > 0 && Player.ベガ.member, action:()=>{ Prm.atkPrms.forEach(prm=> Player.ベガ.ins.prm(prm).base += 10); }, }); const にじゅうよんまん:Mix = new Mix({ uniqueName:"にじゅうよんまん", limit:5, info:"ジスロフの全ステータス+10", to_string:"24万", materials:()=>[[Item.肉まん, 1], [Item.にじゅうよん, 24]], isVisible:()=>ピアーの肉まんレシピ.count > 0 && Player.ジスロフ.member, action:()=>{ Prm.atkPrms.forEach(prm=> Player.ジスロフ.ins.prm(prm).base += 10); }, }); const トマトまん:Mix = new Mix({ uniqueName:"トマトまん", limit:5, info:"ナナの光+10", materials:()=>[[Item.肉まん, 1], [Item.トマト, 30]], isVisible:()=>ピアーの肉まんレシピ.count > 0 && Player.ナナ.member, action:()=>{ Player.ナナ.ins.prm(Prm.LIG).base += 10; }, }); //Force export const 飛行:Mix = new Mix({ uniqueName:"飛行", limit:1, info:"白い鳥が特性[進む時稀に+1]を覚える", materials:()=>[[Item.小説38万キロの恋, 1], [Item.バッタ, 5]], isVisible:()=>Player.白い鳥.member && ルインドアースLv11.count > 0, }); export const 飛行2:Mix = new Mix({ uniqueName:"飛行2", limit:1, info:"白い鳥が特性[進む時稀に+1]を覚える", to_string:"飛行+", materials:()=>[[Item.小説38万キロの恋, 1], [Item.バッタ, 10]], isVisible:()=>Player.白い鳥.member && ルインドアースLv12.count > 0 && 飛行.count > 0, }); //-Force const 技の極み:Mix = new Mix({ uniqueName:"技の極み", limit:1, info:"技セット上限数増加アイテムの合成が解放される", materials:()=>[[Item.松, 20], [Item.クワ, 20]], isVisible:()=>ルインドアースLv9.count > 0, }); const 技の極み2:Mix = new Mix({ uniqueName:"技の極み2", limit:1, info:"技セット上限数増加アイテムの合成が解放される", to_string: "技の極み+", materials:()=>[[Item.エデン樹, 20], [Item.桜, 20]], isVisible:()=>ルインドアースLv12.count > 0 && 技の極み.count > 0, }); export const パン屋のごみ箱:Mix = new Mix({ uniqueName:"パン屋のごみ箱", limit:1, info:"お店に新しい商品が並ぶ", materials:()=>[[Item.ドラッグ, 5]], isVisible:()=>ルインドアースLv4.count > 0, }); export const 健康保険証:Mix = new Mix({ uniqueName:"健康保険証", limit:1, info:"お店に新しい商品が並ぶ", materials:()=>[[Item.ドラッグ, 5], [Item.草, 5]], isVisible:()=>ルインドアースLv5.count > 0, }); const 生命倫理:Mix = new Mix({ uniqueName:"生命倫理", limit:1, info:"新たなアイテムの合成が解放される", materials:()=>[[Item.思い出そのもの, 10], [Item.スカイフェアリーの死体, 1]], isVisible:()=>ルインドアースLv12.count > 0, }); // //-------------------------------------------------------- // // // //アイテム // // // //-------------------------------------------------------- // const 天地創造の書:Mix = new Mix({ // uniqueName:"天地創造の書", limit:Mix.LIMIT_INF, // result:()=>[Item.天地創造の書, 1], // materials:()=>[[Item.血粉末, 1], [Item.サファイア, 3], [Item.紙, 10]], // }); const 兵法指南の書:Mix = new Mix({ uniqueName:"兵法指南の書", limit:Mix.LIMIT_INF, result:()=>[Item.兵法指南の書, 1], materials:()=>[[Item.ファーストキス, 3], [Item.杉, 20], [Item.ヒノキ, 20], [Item.針金, 6],], isVisible:()=>技の極み.count > 0, }); const 五輪の書:Mix = new Mix({ uniqueName:"五輪の書", limit:Mix.LIMIT_INF, result:()=>[Item.五輪の書, 1], materials:()=>[[Item.クリスタル, 3], [Item.イズミジュエリー, 1], [Item.杉, 20], [Item.ヒノキ, 20]], isVisible:()=>技の極み2.count > 0, }); const 絵画母なる星の緑の丘:Mix = new Mix({ uniqueName:"絵画母なる星の緑の丘", limit:Mix.LIMIT_INF, result:()=>[Item.絵画母なる星の緑の丘, 1], materials:()=>[[Item.エレタの絵の具, 5], [Item.カンバス, 5], [Item.良い土, 5]], isVisible:()=>Item.リュサンデールの絵筆.totalGetCount > 0, }); const 絵画シェイクスピアの涙:Mix = new Mix({ uniqueName:"絵画シェイクスピアの涙", limit:Mix.LIMIT_INF, result:()=>[Item.絵画シェイクスピアの涙, 1], materials:()=>[[Item.エレタの絵の具, 5], [Item.カンバス, 5], [Item.清龍, 2]], isVisible:()=>Item.リュサンデールの絵筆.totalGetCount > 0, }); const 絵画彼女の髪:Mix = new Mix({ uniqueName:"絵画彼女の髪", limit:Mix.LIMIT_INF, result:()=>[Item.絵画彼女の髪, 1], materials:()=>[[Item.エレタクレヨン, 5], [Item.カンバス, 5], [Item.火と水と土と風と光と闇のアニムス, 2]], isVisible:()=>Item.リュサンデールの絵筆.totalGetCount > 0, }); const 絵画我が情熱の日:Mix = new Mix({ uniqueName:"絵画我が情熱の日", limit:Mix.LIMIT_INF, result:()=>[Item.絵画我が情熱の日, 1], materials:()=>[[Item.エレタクレヨン, 5], [Item.カンバス, 5], [Item.烈火, 10]], isVisible:()=>Item.リュサンデールの絵筆.totalGetCount > 0, }); const Dフラスコ:Mix = new Mix({ uniqueName:"Dフラスコ", limit:Mix.LIMIT_INF, result:()=>[Item.Dフラスコ, 1], materials:()=>[[Item.マーザン, 1], [Item.ガラス, 5],], isVisible:()=>生命倫理.count > 0, }); const マーメイド:Mix = new Mix({ uniqueName:"マーメイド", limit:Mix.LIMIT_INF, result:()=>[Item.マーメイド, 1], materials:()=>[[Item.マーザン, 1], [Item.呪い水, 4], [Item.少女の心を持ったおっさん, 1],], isVisible:()=>生命倫理.count > 0, }); const ホムンクルス:Mix = new Mix({ uniqueName:"ホムンクルス", limit:Mix.LIMIT_INF, result:()=>[Item.ホムンクルス, 1], materials:()=>[[Item.マーザン, 1], [Item.精霊の涙, 2], [Item.王子の素, 2],], isVisible:()=>生命倫理.count > 0, }); const フランケンシュタイン:Mix = new Mix({ uniqueName:"フランケンシュタイン", limit:Mix.LIMIT_INF, result:()=>[Item.フランケンシュタイン, 1], materials:()=>[[Item.マーザン, 1], [Item.思い出そのもの, 2], [Item.針金, 6],], isVisible:()=>生命倫理.count > 0, }); const 魔弾:Mix = new Mix({ uniqueName:"魔弾", limit:Mix.LIMIT_INF, result:()=>[Item.魔弾, 2], materials:()=>[[Item.地球塔粉末, 1], [Item.ロウ, 10],], isVisible:()=>ルインドアースLv11.count > 0, }); const 砲弾:Mix = new Mix({ uniqueName:"砲弾", limit:Mix.LIMIT_INF, result:()=>[Item.砲弾, 1], materials:()=>[[Item.地球塔粉末, 1], [Item.ロウ, 10],], isVisible:()=>ルインドアースLv11.count > 0, }); const パワータンク:Mix = new Mix({ uniqueName:"パワータンク", limit:Mix.LIMIT_INF, result:()=>[Item.パワータンク, 4], materials:()=>[[Item.月の石, 1], [Item.アステロイド, 10], [Item.発砲ツル, 10],], isVisible:()=>ルインドアースLv14.count > 0 && Item.月の石.totalGetCount > 0, }); const 林式ミサイル:Mix = new Mix({ uniqueName:"林式ミサイル", limit:Mix.LIMIT_INF, result:()=>[Item.林式ミサイル, 1], materials:()=>[[Item.黒色火薬, 1], [Item.サングラス, 3],], isVisible:()=>ルインドアースLv15.count > 0 && Item.黒色火薬.totalGetCount > 0, }); const エボリ製悪魔のミサイル:Mix = new Mix({ uniqueName:"エボリ製悪魔のミサイル", limit:Mix.LIMIT_INF, result:()=>[Item.エボリ製悪魔のミサイル, 1], materials:()=>[[Item.黒色火薬, 1], [Item.太陽の欠片, 3],], isVisible:()=>ルインドアースLv15.count > 0 && Item.黒色火薬.totalGetCount > 0, }); const メフィスト製悪魔のミサイル:Mix = new Mix({ uniqueName:"メフィスト製悪魔のミサイル", limit:Mix.LIMIT_INF, result:()=>[Item.メフィスト製悪魔のミサイル, 1], materials:()=>[[Item.黒色火薬, 1], [Item.うんち, 3],], isVisible:()=>ルインドアースLv15.count > 0 && Item.黒色火薬.totalGetCount > 0, }); const 原子爆弾:Mix = new Mix({ uniqueName:"原子爆弾", limit:Mix.LIMIT_INF, result:()=>[Item.原子爆弾, 4], materials:()=>[[Item.B火薬, 1], [Item.太陽の欠片, 4],], isVisible:()=>ルインドアースLv16.count > 0 && Item.B火薬.totalGetCount > 0, }); const 水素爆弾:Mix = new Mix({ uniqueName:"水素爆弾", limit:Mix.LIMIT_INF, result:()=>[Item.水素爆弾, 4], materials:()=>[[Item.B火薬, 1], [Item.水, 20],], isVisible:()=>ルインドアースLv16.count > 0 && Item.B火薬.totalGetCount > 0, }); const 重力子爆弾:Mix = new Mix({ uniqueName:"重力子爆弾", limit:Mix.LIMIT_INF, result:()=>[Item.重力子爆弾, 4], materials:()=>[[Item.B火薬, 1], [Item.重力, 2],], isVisible:()=>ルインドアースLv16.count > 0 && Item.B火薬.totalGetCount > 0, }); const lucifer製量子爆弾:Mix = new Mix({ uniqueName:"lucifer製量子爆弾", limit:Mix.LIMIT_INF, result:()=>[Item.lucifer製量子爆弾, 4], materials:()=>[[Item.B火薬, 1], [Item.重力, 1], [Item.ジスカルド, 1],], isVisible:()=>ルインドアースLv16.count > 0 && Item.B火薬.totalGetCount > 0, }); //-------------------------------------------------------- // //-アイテム //装備 // //-------------------------------------------------------- const アタックシールド:Mix = new Mix({ uniqueName:"アタックシールド", limit:1, result:()=>[Eq.アタックシールド, 1], materials:()=>[[Item.杉, 5], [Item.ヒノキ, 5], [Item.かんな, 4]], isVisible:()=>Item.レレシピ.totalGetCount > 0, }); const 星的:Mix = new Mix({ uniqueName:"星的", limit:1, result:()=>[Eq.星的, 1], materials:()=>[[Item.少女の心を持ったおっさん, 10], [Item.砂, 5]], isVisible:()=>Item.レレシピ.totalGetCount > 0, }); const 愛の盾:Mix = new Mix({ uniqueName:"愛の盾", limit:1, result:()=>[Eq.愛の盾, 1], materials:()=>[[Item.少女の心を持ったおっさん, 10], [Item.土, 5], [Item.針金, 1]], isVisible:()=>Item.イスレシピ.totalGetCount > 0, }); const 空飛ぶ靴:Mix = new Mix({ uniqueName:"空飛ぶ靴", limit:1, result:()=>[Eq.空飛ぶ靴, 1], materials:()=>[[Item.イズミミズ, 5], [Item.杉, 10], [Item.ヒノキ, 10], [Item.針金, 1]], isVisible:()=>Item.イスレシピ.totalGetCount > 0, }); const シャドウムーン:Mix = new Mix({ uniqueName:"シャドウムーン", limit:1, result:()=>[Eq.シャドウムーン, 1], materials:()=>[[Item.月の石, 1], [Item.粘土, 10], [Item.地球のひも, 10], [Item.針金, 5]], isVisible:()=>月のレシピ.count > 0, }); const 花水飾り:Mix = new Mix({ uniqueName:"花水飾り", limit:1, result:()=>[Eq.花水飾り, 1], materials:()=>[[Item.月の石, 1], [Item.たんぽぽ, 10], [Item.桜, 10], [Item.梅, 5]], isVisible:()=>月のレシピ.count > 0, }); const 天秤:Mix = new Mix({ uniqueName:"天秤", limit:1, result:()=>[Eq.天秤, 1], materials:()=>[[Item.月の石, 1], [Item.桐, 20], [Item.鉄, 10], [Item.銅, 10]], isVisible:()=>月のレシピ.count > 0, }); const 蔓の鎖:Mix = new Mix({ uniqueName:"蔓の鎖", limit:1, result:()=>[Eq.蔓の鎖, 1], materials:()=>[[Item.月の石, 1], [Item.発砲ツル, 30], [Item.石, 30], [Item.地球のひも, 10],], isVisible:()=>月のレシピ.count > 0, }); //-------------------------------------------------------- // //-装備 // //-------------------------------------------------------- }
f1b835d3dcbecdc33645582cecdfc2bccdbf224e
TypeScript
graphql-extended/gqlx-js
/src/helpers/transpile.test.ts
2.5625
3
import { transpileNode } from './transpile'; describe('transpileNode', () => { it('serializes a simple addition correctly', () => { const result = transpileNode( { type: 'BinaryExpression', left: { type: 'Identifier', name: 'a', }, right: { type: 'Identifier', name: 'b', }, operator: '+', }, [], ['a'], [], ); expect(result).toBe('($data.a + b)'); }); it('serializes a function call correctly', () => { const result = transpileNode( { type: 'CallExpression', callee: { type: 'Identifier', name: 'f', }, optional: false, arguments: [ { type: 'Identifier', name: 'a', }, { type: 'Literal', raw: '10', value: 10, }, ], }, [], ['a'], [], ); expect(result).toBe('f($data.a, 10)'); }); });
48fd3ed33a92887211aa7965694fa9f6d322e40a
TypeScript
gitsupportting/ReactNative_GraphQL
/apps/mobile-v1/types/redux-thunk.d.ts
2.890625
3
import { Action, Dispatch } from 'redux'; type ThunkAction<R, S, E, A extends Action> = (dispatch: Dispatch, getState: () => S, extraArgument: E) => R; /** * Redux behaviour changed by middleware, so overloads here */ declare module 'redux' { /* * Overload to add api middleware support to Redux's dispatch() function. * Useful for react-redux or any other library which could use this type. */ interface Dispatch { <R, S, E, A extends Action>(action: ThunkAction<R, S, E, A>): R; } }
ff4721f6b9b107b72274f4a469bc32084b6ff4e3
TypeScript
kkalamarski/redshift
/packages/core/parser/tests/strings.test.ts
3.140625
3
import { evaluate, compile } from "../../index" describe("Strings", () => { it("should parse string", () => { const code = ` let test = "a string" test ` const result = evaluate(code) expect(result).toBe("a string") }) it("should concat two strings", () => { const code = ` let str = "hello " <> "world!" str ` const result = evaluate(code) expect(result).toBe("hello world!") }) it("should concat two strings from variables", () => { const code = ` let str = "hello " let world = "world!" let result = str <> world result ` const result = evaluate(code) expect(result).toBe("hello world!") }) it("should be possible to pass string to function as argumnet", () => { const code = ` def greet(name) do "Hello " <> name end greet("Chris") ` const result = evaluate(code) expect(result).toBe("Hello Chris") }) })
5afbe5606c5d0c11e31fe06471622804d99d11f9
TypeScript
matt-winfield/raytracing
/src/classes/Segment.ts
3.1875
3
import { Color } from "./Color"; import { Drawable } from "./interfaces/Drawable"; export class Segment implements Drawable { private x: number; private height: number; private width: number; private color: Color; private brightness: number; constructor(x: number, height: number, width: number, color: Color, brightness: number) { this.x = x; this.height = height; this.width = width; this.color = color; this.brightness = brightness; } public draw(canvasContext: CanvasRenderingContext2D): void { const canvasHeight = canvasContext.canvas.clientHeight; canvasContext.beginPath(); canvasContext.fillStyle = `rgb(${this.color.red * this.brightness}, ${this.color.green * this.brightness}, ${this.color.blue * this.brightness})`; canvasContext.fillRect(this.x, canvasHeight / 2 - this.height / 2, this.width, this.height); } }
11b6e9ad9c91754b253922e84ba73680f7328feb
TypeScript
amoschoomy/pongrxjs
/pong.ts
3.0625
3
import { interval, fromEvent, from, zip, NextObserver, ObjectUnsubscribedError, Observable, timer, of, merge, pipe } from 'rxjs' import { map, scan, filter, flatMap, take, concat, takeUntil, takeWhile, groupBy, repeat, startWith, switchMap, first, publish, last, reduce,} from 'rxjs/operators' //Class RNG to generate pseudorandom numbers //Taken from Week 4 Tutorial FIT2102 class RNG { // LCG using GCC's constants m = 0x80000000// 2**31 a = 1103515245 c = 12345 state constructor(seed) { this.state = seed ? seed : Math.floor(Math.random() * (this.m - 1)); } nextInt() { this.state = (this.a * this.state + this.c) % this.m; return this.state; } nextFloat() { // returns in range [0,1] return this.nextInt() / (this.m - 1); } } //Interface for ball state //Avoid global mutable variables type BallState=Readonly<{ yvelocity:number xvelocity:number speedBall:number }> //Interface for player and computer score //Avoid global mutable variables type Scores=Readonly<{ playerscore:String computerscore:String }> //Interface for state of the paddle //Avoid global mutable variables type PaddleState=Readonly<{ xpos:number ypos:number }> //class for human paddle //Organises paddle element manipulations in a cleaner way class Human{constructor(public readonly paddle:HTMLElement){}} //class for AI paddle, difficulty is default unless specified by user //Organises paddle element manipulations in a cleaner way class AI{constructor(public readonly paddle:HTMLElement,public readonly difficulty=1){}} type Controller= AI|Human // Math vector calculations for ball x velocity and y velocity //Referenced from: //https://www.reddit.com/r/learnprogramming/comments/q7jl3/pong_ball_deflection/c3vh3p2/?context=8&depth=9 class Vector{ constructor(public readonly xspeed: number = 0,public readonly yspeed: number = 0,public readonly paddle:HTMLElement,public readonly posballY: number,public readonly ballSpeed:number){} readonly currentSpeed=():number=>Math.sqrt(this.xspeed*this.xspeed+this.yspeed*this.yspeed) readonly angle=():number=>((this.posballY-Number(this.paddle.getAttribute("y"))+25)/(10*0.428+Math.PI/2)) readonly vx=():number=>-Math.sign(this.xspeed)*Math.sin(this.angle())*this.currentSpeed() readonly vy=():number=>Math.cos(this.angle())*this.currentSpeed() readonly ballVelocity=():number=>Math.sqrt(Math.pow(this.vx()*this.ballSpeed,2)+Math.pow(this.vy()*this.ballSpeed,2)) } //Function to reset ball attributes const resetBall=(ball:HTMLElement)=>{ ball.setAttribute("cx","300") ball.setAttribute("cy","300") ball.setAttribute("vx",String(new RNG(69).nextFloat()*4-1)) ball.setAttribute("vy",String(new RNG(126).nextFloat()*4-1)) } //Function to construct the scoreboard on webpage //Appends element to webpage, function scoreboard():void { const div=document.getElementById("game") const playerScore=document.createElement("number") playerScore.setAttribute("value","0") playerScore.setAttribute("id","playerscore") div.append(playerScore) playerScore.innerHTML="Player Score: "+ playerScore.getAttribute("value") const computerScore=document.createElement("number") computerScore.style.marginLeft="15%" computerScore.setAttribute("value","0") computerScore.setAttribute("id","computerscore") computerScore.innerHTML="Computer Score: " + computerScore.getAttribute("value") div.appendChild(computerScore)} //function to update score of player or cpu //takes in a score state and then paddle to return update score state //ensure function has no side effects const updatescore=(s:Scores)=>(winner:HTMLElement):Scores=>{ if (winner.id==="playerscore"){ if(s.playerscore!=="6") return{ playerscore:String(Number(s.playerscore)+1), computerscore:s.computerscore } else{ return{ playerscore:String(Number(s.playerscore)+1)+" CONGRATS CHAMPION", computerscore:s.computerscore } } } else if(s.computerscore!=="6"){ return{ playerscore:s.playerscore, computerscore:String(Number(s.computerscore)+1) } } else{ return{ playerscore:s.playerscore+" YOU LOSER", computerscore:String(Number(s.computerscore)+1) } } } //update scoreboard html using score state const updateScoreboard=(s:Scores):void=>{ const playerscore=document.getElementById("playerscore") const aiscore=document.getElementById("computerscore") playerscore.innerHTML="Player Score: "+ s.playerscore aiscore.innerHTML="Computer Score: "+ s.computerscore playerscore.setAttribute("value",String(s.playerscore)) aiscore.setAttribute("value",String(s.computerscore)) } //Reset scoreboard in the event of someone restarting game. Resets HTML elements in scoreboard const resetScoreboard=():void=>{ const playerscore=document.getElementById("playerscore") const aiscore=document.getElementById("computerscore") playerscore.innerHTML="Player Score: "+ 0 aiscore.innerHTML="Computer Score: "+ 0 playerscore.setAttribute("value","0") aiscore.setAttribute("value","0") } //Pong function to run the game function pong():void { // Inside this function you will use the classes and functions // from rx.js // to add visuals to the svg element in pong.html, animate them, and make them interactive. // Study and complete the tasks in observable exampels first to get ideas. // Course Notes showing Asteroids in FRP: https://tgdwyer.github.io/asteroids/ // You will be marked on your functional programming style // as well as the functionality that you implement. // Document your code! //Get other elements from HTML const ball=document.getElementById("ball") const playerpaddle=document.getElementById("player") const computerpaddle=document.getElementById("computer") //Obseravble stream for keyboard input //arrow up movement //filters for ArrowUp key and player paddle being at the approirate position to move upwards(paddle must be in canvas) const arrowUp=fromEvent(document,"keydown"). pipe(filter((x:KeyboardEvent)=>x.key=="ArrowUp")). pipe(filter(x=>Number(playerpaddle.getAttribute("y"))>5)). pipe(map((x)=>(-10))) //Observable stream for keyboard input //arrow down movement //filters for ArrowUp key and player paddle being at the approirate position to move upwards(paddle must be in canvas) const arrowDown=fromEvent(document,'keydown'). pipe(filter((x:KeyboardEvent)=>x.key=="ArrowDown")). pipe(filter(x=>Number(playerpaddle.getAttribute("y"))<545)). pipe(map(x=>(10))) //Function to update player paddle movement const movement=(x:number,paddle:PaddleState):PaddleState=>{ return{ xpos:paddle.xpos, ypos:paddle.ypos+x } } //Initial state of player paddle: Following HTML hardcoded value const initialPlayerPaddleState:PaddleState={ xpos:20, ypos:300 } //Initial State of AI paddle: Following HTML hardcoded value const initialAIPaddleState:PaddleState={ xpos:570, ypos:280 } //Merge the keyboard input stream together and subscribe to movement function //Uses the scan function where it will accumulate value at each key arrow movement and emits the value at each correct key press for the paddle to move merge(arrowUp,arrowDown). pipe(scan((x:PaddleState,y:number)=>movement(y,x),initialPlayerPaddleState)). subscribe(x=>playerpaddle.setAttribute("y",String(x.ypos))) //Creates scoreboard at canvas //Function can be found at line 290++ scoreboard() const playerscore=document.getElementById("playerscore") const aiscore=document.getElementById("computerscore") const aiplayer=new AI(document.getElementById("computer"),1) //ai paddle object const humanplayer=new Human(document.getElementById("player")) //player paddle object //Initial state of player scores const initialScore:Scores={ playerscore:"0", computerscore:"0" } //Ball reflection referecned from: //https://developer.mozilla.org/en-US/docs/Games/Tutorials/2D_Breakout_game_pure_JavaScript/Bounce_off_the_walls //Function to modify physics of the state of ball, takes in a State type and returns a State object const physics=(s:BallState)=>(user:Controller,user2:Controller):BallState=> { if (Number(ball.getAttribute("cy"))>589||Number(ball.getAttribute("cy"))<11) //If ball touches the top and bottom wall, reverse y velocity return{ yvelocity:-s.yvelocity, xvelocity:s.xvelocity, speedBall:s.speedBall } // Logic of ball collision of paddle referenced from //https://www.informit.com/articles/article.aspx?p=2180417&seqNum=2 //Each condition checks for player paddle colliision with ball depending on pos of ball and paddle. //Takes in a state and return a new state of updated velcoties if(Number(ball.getAttribute("cx"))<(Number(user.paddle.getAttribute("x"))+Number(ball.getAttribute("r"))+Number(user.paddle.getAttribute("width"))+1) &&( (Number(ball.getAttribute("cx"))+1+Number(ball.getAttribute("r"))+Number(user.paddle.getAttribute("width"))+1>Number(user.paddle.getAttribute("x")))) &&(Number(ball.getAttribute("cy"))+Number(ball.getAttribute("r"))+4>Number(user.paddle.getAttribute("y")))&& Number(ball.getAttribute("cy"))<Number(user.paddle.getAttribute("y"))+Number(ball.getAttribute("r"))+4+Number(user.paddle.getAttribute("height"))){ return { yvelocity:new Vector(s.xvelocity,s.yvelocity,user.paddle,Number(ball.getAttribute("cy")),s.speedBall).vy(), xvelocity:new Vector(s.xvelocity,s.yvelocity,user2.paddle,Number(ball.getAttribute("cy")),s.speedBall).vx(), speedBall:s.speedBall } } //Same logic applied to user 2 if((Number(ball.getAttribute("cx"))<(Number(user2.paddle.getAttribute("x"))+1+Number(ball.getAttribute("r"))+Number(user.paddle.getAttribute("width"))) &&( (Number(ball.getAttribute("cx"))+Number(ball.getAttribute("r"))+Number(user.paddle.getAttribute("width"))+1>Number(user2.paddle.getAttribute("x"))))&& (Number(ball.getAttribute("cy"))+Number(ball.getAttribute("r"))+4>Number(user2.paddle.getAttribute("y")))&& Number(ball.getAttribute("cy"))<Number(user2.paddle.getAttribute("y"))+Number(ball.getAttribute("r"))+4+Number(user.paddle.getAttribute("height")))) { return{ yvelocity:new Vector(s.xvelocity,s.yvelocity,user2.paddle,Number(ball.getAttribute("cy")),s.speedBall).vy(), xvelocity:new Vector(s.xvelocity,s.yvelocity,user2.paddle,Number(ball.getAttribute("cy")),s.speedBall).vx(), speedBall:s.speedBall } } else{ //if no colliison remain original state return s } } //startGame$ observable created using interval. Interval emits numbers over a specified amount of time, //In game logic is basically how fast is the game frame. //takeWhile refers to the endgame condition of the game, which either player have to get a score of 7 before the game(observable) ends // Repeat the observable if "Restart Game" button is clicked const startGame$=interval(60).pipe(takeWhile(x=>(Number(aiscore.getAttribute("value"))<7 && Number(playerscore.getAttribute("value"))<7))).pipe(repeat()) //This is the logic for ball out of canvas. If the ball is out of canvas, we reset the ball position startGame$.pipe(filter(x=>(Number(ball.getAttribute("cx"))>590) || Number(ball.getAttribute("cx"))<10)).subscribe(x=>{resetBall(ball)}) //AI movement following the ball, going upwards movement startGame$.pipe(map((x:number)=>(Number(ball.getAttribute("cy"))))). subscribe(obj=>Number(computerpaddle.getAttribute("y"))<0?computerpaddle.setAttribute("y",String(obj-20)):computerpaddle.setAttribute("y",String(-obj-20))) // //AI movement following the ball, going downwards movement startGame$.pipe(map((x:number)=>(Number(ball.getAttribute("cy"))))). subscribe((obj)=>Number(computerpaddle.getAttribute("y"))<545?computerpaddle.setAttribute("y",String(obj-20)):computerpaddle.setAttribute("y",String(-obj-20))) //This is for ball movement //First we map the observable to the current ball State //Apply physics function to the current ball state //Result of the function, we apply the values to the ball to move the ball accordingly const ballMovement=startGame$.pipe(map(x=>({yvelocity:Number(ball.getAttribute("vy")), xvelocity:Number(ball.getAttribute("vx")), speedBall:6,}))). pipe(map((x:BallState)=>physics(x)(humanplayer,aiplayer))). subscribe((x:BallState)=>{ ball.setAttribute("cx",String(Number(ball.getAttribute("cx"))+x.xvelocity*x.speedBall)), ball.setAttribute("cy",String((Number(ball.getAttribute("cy")))+x.yvelocity*x.speedBall)), ball.setAttribute("vy",String(x.yvelocity)), ball.setAttribute("vx",String(x.xvelocity)) }) //update score when player win the round, if the ball is past the canvas of CPU side, then we update the score for player //using updateScoreboard and update score function --- details of the functions below startGame$ .pipe(filter((x:number)=>Number(ball.getAttribute("cx"))>590)) .subscribe((x:number)=>(updateScoreboard(updatescore({playerscore:(playerscore.getAttribute("value")),computerscore:(aiscore.getAttribute("value"))})(playerscore)))) //update score when CPU win the round, if the ball is past the canvas of player side, then we update the score for player //using updateScoreboard and update score function --- details of the functions below startGame$ .pipe(filter((x:number)=>Number(ball.getAttribute("cx"))<10)) .subscribe((x:number)=>(updateScoreboard(updatescore( {playerscore:(playerscore.getAttribute("value")), computerscore:(aiscore.getAttribute("value")) } )(aiscore)))) const restart=document.getElementById("restart") //Get restart game button element from HTML //Creates an mouse event observable that subsribes on click of the restart game button. //Resets the scoreboard //Resets the ball position fromEvent(restart,"click").subscribe((x:Event)=>{resetScoreboard(),resetBall(document.getElementById("ball"))}) } // the following simply runs your pong function on window load. Make sure to leave it in place. if (typeof window != 'undefined') window.onload = ()=>{ fromEvent(document.getElementById("start"),"click").pipe(take(1)).subscribe(x=>pong()) // //start game button needs to be clicked to start game //Can only be clicked once }
f1595342264191577615c9f5531069db64bd697a
TypeScript
dps/notable
/src/renderer/utils/path.ts
3
3
/* IMPORT */ import * as filenamify from 'filenamify'; import * as fs from 'fs'; import * as path from 'path'; import * as pify from 'pify'; /* PATH */ const Path = { _allowedPaths: {}, // Map of filePath => timestamp, ensuring we don't return the same path mutliple times within some amount of time, in order to avoid race conditions //UGLY _checkAllowedPath ( filePath: string ): boolean { if ( !Path._allowedPaths[filePath] || ( Path._allowedPaths[filePath] + 5000 ) < Date.now () ) { Path._allowedPaths[filePath] = Date.now (); return true; } return false; }, async getAllowedPath ( folderPath: string, baseName: string ): Promise<{ folderPath: string, filePath: string, fileName: string }> { baseName = baseName.replace ( /\//g, '∕' ); // Preserving a dash-like character let {name, ext} = path.parse ( baseName ); name = name.replace ( / \(\d+\)$/, '' ); // Removing already existent suffix name = Path.sanitize ( name ); // Removing weird characters for ( let i = 1;; i++ ) { const suffix = i > 1 ? ` (${i})` : '', fileName = `${name}${suffix}${ext}`, filePath = path.join ( folderPath, fileName ); try { await pify ( fs.access )( filePath ); } catch ( e ) { if ( !Path._checkAllowedPath ( filePath ) ) continue; return { folderPath, filePath, fileName }; } } }, sanitize ( filePath: string ): string { return filenamify ( filePath, { replacement: ' ' } ) .replace ( /#/g, ' ' ) .trim (); } }; /* EXPORT */ export default Path;
1e18c66d929335a4f651c325f3ff2e997baa9579
TypeScript
DiceGraph/DiceGraph
/source/util/text.ts
2.640625
3
export const textCut = (str: string, maxLen: number) => { return str.length > maxLen - 3 ? str.slice(0, maxLen - 3) + '...' : str }
aaa56f29c7b5d42ceaf3a7ea628b7b21b33ad62c
TypeScript
lhoang/advent-of-code-2019
/src/day4/secure-container.spec.ts
2.78125
3
import { containsDouble, findAllPossiblePasswords, findAllPossiblePasswordsWithOneDouble, hasAdjacentNumbers, onlyIncrease, } from "./secure-container"; describe('Secure Container', () => { it('should find adjacent numbers', () => { expect(hasAdjacentNumbers('111345')).toBeTruthy(); expect(hasAdjacentNumbers('102344')).toBeTruthy(); expect(hasAdjacentNumbers('102245')).toBeTruthy(); expect(hasAdjacentNumbers('102345')).toBeFalsy(); }); it('should find only increasing sequence', () => { expect(onlyIncrease('123456')).toBeTruthy(); expect(onlyIncrease('122456')).toBeTruthy(); expect(onlyIncrease('111111')).toBeTruthy(); expect(onlyIncrease('121111')).toBeFalsy(); expect(onlyIncrease('123450')).toBeFalsy(); }); it('should generate all possible passwords', () => { const res = findAllPossiblePasswords(147981, 691423); expect(res.length).toEqual(1790); }); it('should contains 1 double', () => { expect(containsDouble('119599')).toBeTruthy(); expect(containsDouble('111699')).toBeTruthy(); expect(containsDouble('111133')).toBeTruthy(); expect(containsDouble('112233')).toBeTruthy(); expect(containsDouble('111122')).toBeTruthy(); expect(containsDouble('111134')).toBeFalsy(); expect(containsDouble('111113')).toBeFalsy(); expect(containsDouble('341113')).toBeFalsy(); expect(containsDouble('111111')).toBeFalsy(); expect(containsDouble('123444')).toBeFalsy(); expect(containsDouble('144441')).toBeFalsy(); expect(containsDouble('111444')).toBeFalsy(); }); it('should generate all possible passwords with one double', () => { const res = findAllPossiblePasswordsWithOneDouble(147981, 691423); expect(res.length).toEqual(1206); }); });
b7091dae7f53e614fd6c209d7008b0b440e1ebaf
TypeScript
agawrysiuk/the-ring-2.0
/the-ring-client-angular/src/app/modules/menu/pages/game/model/deck.ts
2.609375
3
import {Card} from "./card"; export class Deck { commander: string; cards: Card[]; constructor(commander: string, cards: Card[]) { this.commander = commander; this.cards = cards; } }
6a89770ee625178e47ec4a51b1a82222be70ecbf
TypeScript
ahmdammarr/cyper-shop-app
/src/store/categories/categoriesSlice.ts
2.515625
3
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"; import { RootState } from "../store"; import axios from "axios"; import { CategoriesState } from "./types"; const initialState: CategoriesState = { categories: [], status: "loading", }; export const getCategories = createAsyncThunk( "category/category", async (_, { rejectWithValue }) => { try { const response = await axios.get("https://fakestoreapi.com/products/categories"); return response.data; } catch (err) { return rejectWithValue(err); } } ); export const categoriesSlice = createSlice({ name: "categories", initialState, reducers: {}, extraReducers: { [getCategories.pending.toString()]: (state) => { state.status = "loading"; }, [getCategories.fulfilled.toString()]: (state, action) => { state.status = "done"; state.categories = action.payload; }, [getCategories.rejected.toString()]: (state, action) => { state.status = "failed"; state.categories = action.payload; } }, }); export const selectCategories = (state: RootState) => state.categories.categories; export const selectStatus = (state: RootState) => state.categories.status; export default categoriesSlice.reducer;
301fa6a311f5ddb8a1a133184ecc4969f4a22c88
TypeScript
ramzan545/jiber
/packages/jiber-client/src/store/room.test.ts
2.703125
3
import { JOIN_ROOM } from 'jiber-core' import { Room } from './room' let dispatchCalledWith: any[] = [] const store = { dispatch: (action: any) => { dispatchCalledWith.push(action) }, getState: () => { return { rooms: { room1: { confirmed: 'one', optimistic: 'two', members: {} } }, users: {}, lastUpdatedAt: 0 } }, subscribe: () => () => 'do nothing' } as any beforeEach(() => { dispatchCalledWith = [] }) test('auto join room', () => { const room = new Room(store, 'room1') expect(room).toBeTruthy() expect(dispatchCalledWith).toEqual([ { type: JOIN_ROOM, $roomId: 'room1' } ]) }) test('dispatch actions to roomId', () => { const room = new Room(store, 'room1') room.dispatch({ type: 'hi' }) expect(dispatchCalledWith).toEqual([ { type: JOIN_ROOM, $roomId: 'room1' }, { type: 'hi', $roomId: 'room1' } ]) }) test('get confirmed state if it exists', () => { const room = new Room(store, 'room1') expect(room.getConfirmedState()).toBe('one') }) test('get optimistic state if it exists', () => { const room = new Room(store, 'room1') expect(room.getState()).toBe('two') }) // I think the room should always exist, since the room creates itself /* test('get confirmed returns undefined if room does not exist', () => { const room = new Room(store, 'room2') expect(room.getConfirmedState()).toBeUndefined() }) test('get optimistic state returns undefined if room does not exist', () => { const room = new Room(store, 'room2') expect(room.getState()).toBeUndefined() }) */
b63e515e0beb9e8ec330169bcc9eaf527bb63bee
TypeScript
antondavidenko/threejs-test-game
/src/components/characters/characters-collection.component.ts
2.625
3
import { Character } from '@antondavidenko/modular-character-threejs'; import { playerCharacter, friendsCharacters, enemiesCharacters } from './controls'; class CharactersCollection { init(scene: THREE.Scene, callback: () => void): void { playerCharacter.init(scene, callback); enemiesCharacters.init(scene); friendsCharacters.init(scene); this.update(); } selected(): Character { return playerCharacter.getCharacter(); } onTouchMove(forward: number, turn: number): void { playerCharacter.move(forward, turn); } onPressB() { playerCharacter.jump(); } onPressA() { playerCharacter.hit(); const playerPos = playerCharacter.getCharacter().position; const distance = playerPos.distanceTo(enemiesCharacters.getCharacter().position); if (distance <= 2) { enemiesCharacters.die(); } } onPressC() { playerCharacter.wave(); const playerPos = playerCharacter.getCharacter().position; const distance = playerPos.distanceTo(friendsCharacters.getCharacter().position); if (distance <= 2) { friendsCharacters.wave(); } } private update(): void { playerCharacter.update(); enemiesCharacters.update(); friendsCharacters.update(); requestAnimationFrame(this.update.bind(this)); } } export const charactersCollection = new CharactersCollection();
e64862289c13bdd437cc49d52977ec61a7f7ff4b
TypeScript
stuyy/discord-dashboard-livestream-repo
/codering-bot-nest/src/database/schemas/bot/Command.ts
2.84375
3
import * as mongoose from 'mongoose'; /** * BASIC - All users can use this, no permissions * MODERATION - Only Moderation Roles can use these commands * ADMIN - Only Admin Roles can use these commands * OWNER - Only the owner can use these commands */ export const CommandSchema = new mongoose.Schema({ name: { type: String, required: true, lowercase: true, unique: true, }, description: { type: String, required: true, }, enabled: { type: Boolean, default: true, }, type: { type: String, required: true, default: 'BASIC', }, roles: { type: Array, required: false, default: [], }, });
8f8f68f30cc9c8824ae250a51167100ffeeb46fb
TypeScript
chromium/chromium
/tools/json_schema_compiler/test/idl_basics_expected.d.ts
2.578125
3
// Copyright 2023 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview Definitions for chrome.idl_basics API * Generated from: file.idl * run `tools/json_schema_compiler/compiler.py file.idl -g ts_definitions` to * regenerate. */ import {ChromeEvent} from './chrome_event.js'; declare global { export namespace chrome { export namespace idl_basics { export enum EnumType { NAME1 = 'name1', NAME2 = 'name2', } export enum EnumTypeWithNoDoc { NAME1 = 'name1', NAME2 = 'name2', } export enum EnumTypeWithNoDocValue { NAME1 = 'name1', NAME2 = 'name2', NAME3 = 'name3', } export interface MyType1 { x: number; y: string; z: string; a: string; b: string; c: string; } export interface MyType2 { x: string; } export interface UnionType { x?: EnumType|string; y: string|EnumType; } export function function1(): void; export function function2(x: number): void; export function function3(arg: MyType1): void; export function function4(): Promise<void>; export function function5(): Promise<number>; export function function6(): Promise<MyType1>; export function function7(arg?: number): void; export function function8(arg1: number, arg2?: string): void; export function function9(arg?: MyType1): void; export function function10(x: number, y: number[]): void; export function function11(arg: MyType1[]): void; export function function12(): Promise<MyType2[]>; export function function13(type: EnumType): Promise<EnumType>; export function function14(types: EnumType[]): void; export function function15(switch: number): void; export function function16(): Promise<number>; export function function17(): Promise<number>; export function function18(): Promise<number>; export function function20(value: idl_other_namespace.SomeType): void; export function function21(values: idl_other_namespace.SomeType[]): void; export function function22( value: idl_other_namespace.sub_namespace.AnotherType): void; export function function23( values: idl_other_namespace.sub_namespace.AnotherType[]): void; export function function24(): number; export function function25(): MyType1; export function function26(): MyType1[]; export function function27(): EnumType; export function function28(): EnumType[]; export function function29(): idl_other_namespace.SomeType; export function function30(): idl_other_namespace.SomeType[]; export const onFoo1: ChromeEvent<() => void>; export const onFoo2: ChromeEvent<(arg: MyType1) => void>; export const onFoo3: ChromeEvent<(type: EnumType) => void>; } } }
e0e5a67d7b3b917b8e19affae6d7368e70ece3b6
TypeScript
Wahbi90/kofti
/frontend/src/redux/products/productsActions.ts
2.65625
3
import { FETCH_PRODUCTS, FILTER_PRODUCTS_BY_SIZE, ORDER_PRODUCTS_BY_PRICE, CHANGE_CATEGORY, } from './productsTypes'; export const changeCategory = (category) => ({ type: CHANGE_CATEGORY, payload: category, }); export const fetchProducts = () => (dispatch) => { fetch('http://localhost:8000/products') .then((res) => res.json()) .catch((err) => fetch('db.json') .then((res) => res.json()) .then((data) => { console.log(data, 'from fetching qt fetch products'); data.products; }), ) .then((data) => { dispatch({ type: FETCH_PRODUCTS, payload: data }); }); }; export const filterProducts = (products, size) => (dispatch) => { dispatch({ type: FILTER_PRODUCTS_BY_SIZE, payload: { size: size, items: size === '' ? products : products.filter( (x) => x.availableSizes.indexOf(size.toUpperCase()) >= 0, ), }, }); }; export const sortProducts = (items, sort) => (dispatch) => { const products = items.slice(); if (sort !== '') { products.sort((a, b) => sort === 'lowestprice' ? a.price > b.price ? 1 : -1 : a.price < b.price ? 1 : -1, ); } else { products.sort((a, b) => (a.id > b.id ? 1 : -1)); } dispatch({ type: ORDER_PRODUCTS_BY_PRICE, payload: { sort: sort, items: products, }, }); };
0a779a664c82afd40d2f9f3f27ae831f71fbab2d
TypeScript
benzhemin/typescript-demo
/src/simpleInherit.ts
3.515625
4
export {} function Foo(who) { this.me = who; } Foo.prototype.identify = function() { return `I am ${this.me}`; } function Bar(who) { Foo.call(this, who); } // inheritance Bar.prototype = Object.create(Foo.prototype); Bar.prototype.speak = function() { console.log(`hello, ${this.identify()}.`) } const b1 = new Bar('b1'); const b2 = new Bar('b2'); b1.speak(); b2.speak();
d20c3d7807464d4b1458f4c77723b7748ad8a111
TypeScript
theresasogunle/paymentAPI
/src/helpers/user.helpers.ts
2.6875
3
import { Gender, prisma, User } from "../schema/generated/prisma-client"; const dateFormat = require("dateformat"); const bcrypt = require("bcryptjs"); import { sign } from "jsonwebtoken"; import { salt } from "../const"; import mail from "../functions/mail"; import { verifyToken } from "../middleware/utils"; require("dotenv").config(); /** * Function to validate email address * @param {String} email {Required} The email to be validated * @return {Boolean} A Boolean value indicating if the email is valid * N/B * This isn't fool proof and there is no fool proof way of * validating an email address. */ const validateEmail = (email: string) => { const pattern = /^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; if (!email.match(pattern)) { throw new Error("Email address not supported"); } }; const validateTransactionPin = (pin: string, repeatPin: string) => { const pattern = /^[0-9]*$/gm; if (pin.length !== 4) { throw new Error("Invalid transaction pin"); } if (pin !== repeatPin) { throw new Error("Your pin is not the same"); } if (!pin.match(pattern)) { throw new Error("Invalid transaction pin"); } }; const validateFullName = (fullname: string) => { const pattern1 = /^[a-zA-Z]+ [a-zA-Z]+ [a-zA-Z]+$/; const pattern2 = /^[a-zA-Z]+ [a-zA-Z]+$/; if (fullname.match(pattern1) || fullname.match(pattern2)) { return true; } else { throw new Error("Invalid name"); } }; export async function authenticateUser(phonenumber: string) { // check if phone number is an actual phone number if (phonenumber.length < 11) { throw new Error("Your phone number is incomplete"); } // convert phone number to +234 format if (phonenumber.startsWith("0")) { let tel = phonenumber; phonenumber = "+234" + tel.substr(1); } const user = await prisma.user({ phonenumber }); if (user == null) { return { phonenumber, status: "register" }; } if (!user.verified) { return { phonenumber, status: "verify" }; } return { phonenumber, status: "login" }; } export async function createUser(data: User) { // extract the date of birth and password for modifications let { DOB, password, email, phonenumber, fullname, profile_picture } = data; // check if phone number is an actual phone number if (phonenumber.length < 11) { throw new Error("Your phone number is incomplete"); } // validate the geniunity of email address await validateEmail(email); // validate users name await validateFullName(fullname); // convert phone number to +234 format if (phonenumber.startsWith("0")) { let tel = phonenumber; phonenumber = "+234" + tel.substr(1); } // check if password is greater than 7 characters if (password.length < 8) { throw new Error("Your password should be greater than 7 characters"); } let formatDate; // format the date formatDate = dateFormat(DOB, "yyyy-mm-dd HH:MM:ss"); // put in a format the database understands formatDate = new Date(formatDate); // hash password password = bcrypt.hashSync(password, salt); // add it back to the data object data.DOB = formatDate; data.password = password; data.phonenumber = phonenumber; const user = await prisma.createUser(data); return sendVerificationCode(user.phonenumber); } export async function setTransactionPin( token: string, // tslint:disable-next-line: variable-name transaction_pin: string, repeat_transaction_pin: string ) { // validate the transaction pin await validateTransactionPin(transaction_pin, repeat_transaction_pin); // hash transaction pin transaction_pin = bcrypt.hashSync(transaction_pin, salt); } export async function sendVerificationCode(phonenumber: string, code?: number) { // convert phone number to +234 format if (phonenumber.startsWith("0")) { let tel = phonenumber; phonenumber = "+234" + tel.substr(1); } const user = await prisma.user({ phonenumber }); // check if it has been verified if (user.verified) { throw new Error("User has been verified"); } // generate a 6 digit number for verification if code is not present if (!code) { code = Math.floor(Math.random() * 900000) + 100000; } if (String(code).length !== 6) { throw new Error("Code must be 6 digits"); } // check if an activation Code exists before for the user const verificationCodes = await prisma.verificationCodes({ where: { user: { phonenumber } } }); let verificationCode; // if it exists delete the verification code if (verificationCodes.length > 0) { verificationCode = verificationCodes[0]; await prisma.deleteVerificationCode({ id: verificationCode.id }); } // create the verification const newVerificationCode = await prisma.createVerificationCode({ code, user: { connect: { phonenumber } } }); await mail({ user, message: `Hello ${user.fullname}. Welcome to Payment App. Enter this ${ newVerificationCode.code }, to verify your account`, subject: `Welcome to Payment App` }); return { user, status: "successful", message: "Please verify with the code sent to you" }; } export async function verifyUser(phonenumber: string, code?: number) { // convert phone number to +234 format if (phonenumber.startsWith("0")) { let tel = phonenumber; phonenumber = "+234" + tel.substr(1); } // check if an activation Code exists before for the user const verificationCodes = await prisma.verificationCodes({ where: { user: { phonenumber } } }); if (verificationCodes.length < 1) { throw new Error("Error occured while trying to verify"); } const verificationCode = verificationCodes[0]; if (verificationCode.code === code) { const expTime = new Date(verificationCode.updatedAt); let now = new Date(); // subtract date let diffMs = now.getTime() - expTime.getTime(); let diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes if (diffMins <= 60) { // update the user verified status to true await prisma.updateUser({ where: { phonenumber }, data: { verified: true } }); // create Wallet await prisma.createWallet({ amount: 0, user: { connect: { phonenumber } } }); // delete verification code await prisma.deleteVerificationCode({ id: verificationCode.id }); const user = await prisma.user({ phonenumber }); return { user, token: sign( { id: user.id, email: user.email, user: "user" }, process.env.JWT_SECRET ) }; } throw new Error("Verification code expired"); } throw new Error("Incorrect verification code"); } interface LoginData { phonenumber: string; password: string; } export async function login(loginData: LoginData) { let { phonenumber, password } = loginData; // convert phone number to +234 format if (phonenumber.startsWith("0")) { let tel = phonenumber; phonenumber = "+234" + tel.substr(1); } const user = await prisma.user({ phonenumber }); // if no user if (!user) { throw new Error("Invalid Details"); } // Confirm Password const valid = await bcrypt.compare(password, user.password); if (!valid) { throw new Error("Invalid Details"); } // return json web token return { user, token: sign( { id: user.id, email: user.email, phonenumber: user.phonenumber, user: "user" }, process.env.JWT_SECRET ) }; } export async function sendPasswordResetCode( phonenumber: string, code?: number ) { // convert phone number to +234 format if (phonenumber.startsWith("0")) { let tel = phonenumber; phonenumber = "+234" + tel.substr(1); } if (!code) { code = Math.floor(Math.random() * 900000) + 100000; } if (String(code).length !== 6) { throw new Error("Code must be 6 digits"); } // fetch user const user = await prisma.user({ phonenumber }); // password reset codes const passwordResetCodes = await prisma.passwordResetCodes({ where: { user: { phonenumber } } }); // check if reset code exist before if (passwordResetCodes.length > 0) { // password reset code const passwordResetCode = passwordResetCodes[0]; await prisma.deletePasswordResetCode({ id: passwordResetCode.id }); } await prisma.createPasswordResetCode({ code, user: { connect: { phonenumber } } }); try { await mail({ user, message: `Hi ${ user.fullname }. Use this code: ${code} to reset your password`, subject: "Payment App Password Reset" }); return { user, status: "successful", message: "Please reset your password with the code sent to you" }; } catch (error) {} } export async function resetPassword( phonenumber: string, code: number, password: string ) { // convert phone number to +234 format if (phonenumber.startsWith("0")) { let tel = phonenumber; phonenumber = "+234" + tel.substr(1); } const passwordResetCodes = await prisma.passwordResetCodes({ where: { user: { phonenumber } } }); if (passwordResetCodes.length === 0) { throw new Error("Request for a password reset"); } const passwordResetCode = passwordResetCodes[0]; // if code align change the password if (passwordResetCode.code === code) { const expTime = new Date(passwordResetCode.updatedAt); let now = new Date(); // subtract date let diffMs = now.getTime() - expTime.getTime(); let diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes if (diffMins <= 60) { const user = await prisma.updateUser({ where: { phonenumber }, data: { password: await bcrypt.hashSync(password, salt) } }); return { user, token: sign( { id: user.id, email: user.email, user: "user" }, process.env.JWT_SECRET ) }; } throw new Error("Password reset code expired"); } throw new Error("Wrong password reset code"); } export async function user(token?: string, phonenumber?: string) { if (token) { const { id, user } = verifyToken(token) as any; if (user === "user") { return prisma.user({ id }); } throw new Error("Not Authorized"); } else if (phonenumber) { if (phonenumber.length < 11) { throw new Error("Your phone number is incomplete"); } // convert phone number to +234 format if (phonenumber.startsWith("0")) { let tel = phonenumber; phonenumber = "+234" + tel.substr(1); } return prisma.user({ phonenumber }); } throw new Error("Not Authorized"); } export async function updatePassword( token: string, oldPassword: string, newPassword: string ) { const { id, email, user } = verifyToken(token) as any; // checks if the type of user is a user if (user === "user") { const person = await prisma.user({ email }); // Confirm Old Password const valid = await bcrypt.compare(oldPassword, person.password); if (!valid) { throw new Error("Old Password Incorrect"); } // confirm user is not using the same password const newValid = await bcrypt.compare(newPassword, person.password); if (newValid) { throw new Error("Choose a new password"); } await prisma.updateUser({ where: { email }, data: { password: await bcrypt.hashSync(newPassword, salt) } }); return { user: person, token: sign( { id: user.id, email: user.email, user: "user" }, process.env.JWT_SECRET ) }; } throw new Error("Not Authorized"); } export async function updateProfile( token: string, fullname: string, gender: Gender ) { const { id, email, user } = verifyToken(token) as any; // checks if the type of user is a user if (user === "user") { const person = await prisma.user({ email }); await prisma.updateUser({ where: { email }, data: { fullname, gender } }); return { user: person, status: "successful", message: "Your profile has been updated" }; } throw new Error("Not Authorized"); }
95b5c9ae72d777618e386047fd55ce8cd437ed5e
TypeScript
cesargalindo/prysm-web-ui
/src/app/modules/core/validators/password.validator.spec.ts
2.84375
3
import { AbstractControl, FormBuilder, FormControl } from '@angular/forms'; import { PasswordValidator } from './password.validator'; describe('PasswordValidator', () => { describe('Password strength checks', () => { it('should error if password does not contain uppercase characters', () => { const validator = new PasswordValidator(); const validationFunc = validator.strongPassword; const formControl = { value: 'passwordpassword123$', }; const errors = validationFunc( formControl as AbstractControl, ); expect(errors).not.toBeNull(); }); it('should error if password does not contain at least one number', () => { const validator = new PasswordValidator(); const validationFunc = validator.strongPassword; const formControl = { value: 'Passwordpassword$', }; const res = validationFunc( formControl as AbstractControl, ); expect(res).not.toBeNull(); }); it('should error if password does not contain at least one special character', () => { const validator = new PasswordValidator(); const validationFunc = validator.strongPassword; const formControl = { value: 'Passwordpassword2020', }; const res = validationFunc( formControl as AbstractControl, ); expect(res).not.toBeNull(); }); it('should error if password meets all requirements but is too short', () => { const validator = new PasswordValidator(); const validationFunc = validator.strongPassword; const formControl = { value: '1Pass$', }; const res = validationFunc( formControl as AbstractControl, ); expect(res).not.toBeNull(); }); it('should not error if password meets all requirements', () => { const validator = new PasswordValidator(); const validationFunc = validator.strongPassword; const formControl = { value: '%%Str0ngpAsswordz2020%%', }; const res = validationFunc( formControl as AbstractControl, ); expect(res).toBeNull(); }); }); describe('Password confirmation mismatches', () => { it('should error if password does not match confirmation', () => { const validator = new PasswordValidator(); const formControl = new FormBuilder().group({ password: new FormControl('Passw0rdz0202$', []), passwordConfirmation: new FormControl('Passw0rdz0202$$', []), }); const validationFunc = validator.matchingPasswordConfirmation; validationFunc( formControl as AbstractControl, ); expect(formControl?.get('passwordConfirmation')?.errors).not.toBeNull(); }); it('should not error if password matches confirmation', () => { const validator = new PasswordValidator(); const password = 'Passw0rdz0202$'; const formControl = new FormBuilder().group({ password: new FormControl(password, []), passwordConfirmation: new FormControl(password, []), }); const validationFunc = validator.matchingPasswordConfirmation; validationFunc( formControl as AbstractControl, ); expect(formControl?.get('passwordConfirmation')?.errors).toBeNull(); }); }); });
ab8e06126b6f677e5af20db0e9b708964393817f
TypeScript
pxapi/click-in-group-select
/src/plugin.ts
2.5625
3
/* Double Click in a group selects clicked element in group Source https://github.com/fabricjs/fabric.js/issues/6776#issuecomment-783326800 Author: @harm-less */ import { fabric } from 'fabric'; export class ClickInGroupSelectPlugin { canvas: fabric.Canvas; private _cachedGroups: Array<CachedGroup> = []; constructor(canvas: fabric.Canvas) { this.canvas = canvas; this.init(canvas); } init(canvas: fabric.Canvas) { const groupNavigator = this; // @ts-ignore canvas.on('mouse:dblclick', (event) => { const target = event.target; if (target && target.isType('group')) { groupNavigator.goIntoGroup(target as fabric.Group); } else { groupNavigator.groupBack(); } }); } goIntoGroup(group: fabric.Group) { this.checkGroupCanvas(group); const groupSequence: Array<fabric.Group> = [group]; let parentGroup: fabric.Group | undefined = group.group; while (parentGroup) { groupSequence.unshift(parentGroup); parentGroup = parentGroup.group; } groupSequence.forEach((group) => { this.goIntoRootGroup(group); }); this.canvas.requestRenderAll(); } goIntoObjectGroup(object: fabric.Object) { // todo: Potential performance improvement: It would be perfect if we could detect IF we have to go to the root or just go back to the commen parent and traverse back down this.goToRoot(); if (object.group) { this.goIntoGroup(object.group); } } groupBack() { const highestGroup = this.popCurrentGroup(); if (!highestGroup) { return; } const canvas = this.canvas; const activeSelection = new fabric.ActiveSelection( this.filterCachedObjects(highestGroup.objects), {canvas} ); canvas.setActiveObject(activeSelection); // eslint-disable-next-line @typescript-eslint/no-explicit-any const newGroup = (canvas.getActiveObject() as any).toGroup(); const previousGroupUnfiltered = this.getCurrentGroup(); if (previousGroupUnfiltered) { replaceItemInArray(previousGroupUnfiltered.objects, null, newGroup); } const previousGroup = this.getCurrentGroup(); this.restoreObjects( previousGroup ? this.filterCachedObjects(previousGroup.objects) : canvas.getObjects() ); canvas.discardActiveObject(); canvas.requestRenderAll(); } goToRoot() { while (this._cachedGroups.length) { this.groupBack(); } } isOnRoot() { return this._cachedGroups.length === 0; } private goIntoRootGroup(group: fabric.Group) { if (group.group) { throw new Error('Must be a root group'); } const currentGroup = this.getCurrentGroup(); if (currentGroup) { replaceItemInArray(currentGroup.objects, group, null); } this._cachedGroups.push({objects: group.getObjects()}); const canvas = this.canvas; const parentObjects = currentGroup ? this.filterCachedObjects(currentGroup.objects) : canvas.getObjects(); // @ts-ignore this.disableObjects(parentObjects.filter((object) => object !== group)); this.ungroup(group); } private getCurrentGroup() { const groupLength = this._cachedGroups.length; return groupLength ? this._cachedGroups[groupLength - 1] : null; } private popCurrentGroup() { return this._cachedGroups.pop(); } private filterCachedObjects(objects: Array<fabric.Object | null>): Array<fabric.Object> { return objects.filter(<TValue>(value: TValue | null | undefined): value is TValue => { return value !== null && value !== undefined; }); } private disableObjects(objects: Array<fabric.Object>) { objects.forEach((object) => { object.opacity = 0.3; object.selectable = false; object.hasControls = false; }); } private restoreObjects(objects: Array<fabric.Object>) { objects.forEach((object) => { object.opacity = 1; object.selectable = true; object.hasControls = true; }); } private ungroup(group: fabric.Group) { const canvas = this.canvas; const items = group.getObjects(); group._restoreObjectsState(); canvas.remove(group); for (const object of items) { canvas.add(object); } canvas.discardActiveObject(); } private checkGroupCanvas(group: fabric.Group) { if (!group.canvas) { throw new Error('Group not placed on any canvas'); } if (group.canvas !== this.canvas) { throw new Error('Group not placed on the target canvas'); } } } export interface CachedGroup { objects: Array<fabric.Object | null>; } export function replaceItemInArray(items: Array<unknown>, search: unknown, replaceWith: unknown) { const foundIndex = items.findIndex((item) => item === search); items[foundIndex] = replaceWith; }
ecd18363703501f050d65c0b18de8492ddc028e9
TypeScript
musa-zulu/DotNetArchitecture
/Web/UserInterface/ClientApp/src/app/shared/services/validation.service.ts
2.625
3
import { Injectable } from "@angular/core"; @Injectable({ providedIn: "root" }) export class ValidationService { private date = /^((((0?[1-9]|[12]\d|3[01])[\.\-\/](0?[13578]|1[02])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|[12]\d|30)[\.\-\/](0?[13456789]|1[012])[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|((0?[1-9]|1\d|2[0-8])[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?\d{2}))|(29[\.\-\/]0?2[\.\-\/]((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))|(((0[1-9]|[12]\d|3[01])(0[13578]|1[02])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|[12]\d|30)(0[13456789]|1[012])((1[6-9]|[2-9]\d)?\d{2}))|((0[1-9]|1\d|2[0-8])02((1[6-9]|[2-9]\d)?\d{2}))|(2902((1[6-9]|[2-9]\d)?(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)|00)))) ?((20|21|22|23|[01]\d|\d)(([:.][0-5]\d){1,2}))?$/; private decimal = /^((-?[1-9]+)|[0-9]+)(\.?|\,?)([0-9]*)$/; private email = /^([a-z0-9_\.\-]{3,})@([\da-z\.\-]{3,})\.([a-z\.]{2,6})$/; private hex = /^#?([a-f0-9]{6}|[a-f0-9]{3})$/; private integer = /^-?[0-9]+$/; private zeros = /^0+$/; private time = /^(20|21|22|23|[01]\d|\d)(([:.][0-5]\d){1,2})$/; private url = /^(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})$/; isDate(value: any) { return this.date.test(value); } isDecimal(value: any) { return this.decimal.test(value); } isEmail(value: any) { return this.email.test(value); } isEmpty(value: any) { return !value || value.toString().trim() === ""; } isHex(value: any) { return this.hex.test(value); } isInteger(value: any) { return this.integer.test(value); } isMax(value: any, max: string) { return (!value || !max) || (value && max && parseFloat(value) <= parseFloat(max)); } isMin(value: any, min: string) { return (!value || !min) || (value && min && parseFloat(value) >= parseFloat(min)); } isOnlyZeros(value: any) { return this.zeros.test(value); } isTime(value: any) { return this.time.test(value); } isUrl(value: any) { return this.url.test(value); } }
bd1e9335a3fedee069e6fb4c4045eddd0116b034
TypeScript
GAMS-Organization/GAMS-Repository
/packages/api/src/Application/Handlers/Users/UpdateUserHandler.ts
2.5625
3
import IUserRepository from '../../../Domain/Interfaces/IUserRepository'; import { inject, injectable } from 'inversify'; import { INTERFACES } from '../../../Infrastructure/DI/interfaces.types'; import UpdateUserCommand from '../../Commands/Users/UpdateUserCommand'; import User from '../../../Domain/Entities/User'; import EntityNotFoundException from '../../Exceptions/EntityNotFoundException'; import UserRoleService from '../../../Domain/Services/UserRoleService'; @injectable() export default class UpdateUserHandler { private userRepository: IUserRepository; private userRoleService: UserRoleService; public constructor( @inject(INTERFACES.IUserRepository) userRepository: IUserRepository, @inject(UserRoleService) userRoleService: UserRoleService, ) { this.userRepository = userRepository; this.userRoleService = userRoleService; } public async execute(command: UpdateUserCommand): Promise<User> { const user = await this.userRepository.findOneById(command.getId()); if (!user) { throw new EntityNotFoundException(`No se encontró el usuario con id: ${command.getId()}`); } user.setName(command.getName()); user.setSurname(command.getSurname()); user.setEmail(command.getEmail()); user.setUserState(command.getUserState()); await this.userRoleService.destroyUserRolesFromUser(command.getId()); return await this.userRoleService.setUserRolesToUser(await this.userRepository.persist(user), command.getRoles()); } }
51eaede4ae52bad0a9c1bdf411728b43aa73b89b
TypeScript
angular-berlin/ngry-chat
/src/app/core/text-analysis.service.ts
2.71875
3
import {Injectable} from '@angular/core'; import {HttpClient, HttpHeaders} from '@angular/common/http'; import {SentimentResult} from '../models/sentiment-result'; import {Observable} from 'rxjs'; import {LanguageCode} from '../models/language-code-enum'; import {environment} from '../../environments/environment'; import {SentimentRequest} from '../models/sentiment-request'; import {filter, map} from 'rxjs/operators'; export const createSentimentRequest = (msg: string, language: LanguageCode): SentimentRequest => { return { documents: [{ language: language, id: 'not-needed-yet', text: msg }] }; }; @Injectable() export class TextAnalysisService { constructor(private httpClient: HttpClient) { } /** * This method returns a json with documents being an array with the first (and only) element * being the result score for the given message. The important part here is the score, which says * if the message has a negative or positive mood. Below .5 means it's a negative tone if it is * above .5 it is a more positive message. * */ getSentimentScoreForText(msg: string, language: LanguageCode): Observable<SentimentResult> { return this.httpClient .post<SentimentResult>( environment.azureSentimentServiceUrl, createSentimentRequest(msg, language), { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': environment.azureTextAnalysisToken }) } ); } isMessagePositiveSentiment(msg: string, language: LanguageCode): Observable<boolean> { return this.getSentimentScoreForText(msg, language).pipe( filter(sentimentResult => sentimentResult.documents.length > 0), map(sentimentResult => (sentimentResult.documents[0].score >= .5)) ); } }
f4f4ad675abdce54aebe002ead7acfd94c5db4f6
TypeScript
jamesmilord/reddit-application
/src/app/reddit.service.ts
2.546875
3
import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/Rx'; @Injectable() export class RedditService { http:any; url:string; favorites=[]; favoritesCounts:number; constructor(http:Http) { this.http = http; this.url = 'https://www.reddit.com/r'; } fetchposts(subrerdit, limit){ return this.http.get(this.url+'/'+subrerdit+'/top.json?limit='+limit) .map(res => res.json()); } addToFavorites(reddit) { function contains(arr, value) { var i = arr.length; while (i--) { if (arr[i] === value) return true; } return false; } if(!contains(this.favorites, reddit)){ this.favorites.push(reddit); this.favoritesCounts = this.favorites.length; } } getFavoritesCount(){ return this.favoritesCounts; } pushToFavorites(){ return this.favorites; } }
0e1b3f21f70292720a8b18b0a8598441de19b1d6
TypeScript
tedchoward/advent-of-code-2018
/src/08/__tests__/sum-values.test.ts
2.609375
3
import { parser } from '../parser'; import { sumValues } from '../sum-values'; describe('sumValues', () => { it('adds up the values of the nodes', () => { const input = '2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2'.split(/\W/).map(s => parseInt(s, 10)); const tree = parser(input); const sum = sumValues(tree); expect(sum).toBe(66); }); });
e519796b0d065dd8d28d296c0ee9f4970c4abc74
TypeScript
brahms116/datecounterReact
/src/services/DbService.ts
2.578125
3
import IDateItemResponse from "../models/outputModels/IDateItemResponse"; import IGetItemsResponse from "../models/outputModels/IGetItemsResponse"; import ILoginResponse from "../models/outputModels/ILoginResponse"; import IRegisterResponse from "../models/outputModels/IRegisterResponse"; const url = "https://backend.davidkwong.net/datecounter/api"; const handleResult = async <T>(result: Response) => { if (!result.ok) { console.log(result); } try { const resultData: T = await result.json(); return resultData; } catch (err) { console.log(err); throw err; } }; const DbService = { checkToken: async (token: string) => { const result = await fetch(url + "/user/checktoken", { method: "GET", headers: { Authorization: `bearer ${token}` }, }); if (result.ok) return { isSuccess: true }; return { isSuccess: false }; }, login: async (email: string, password: string) => { const result = await fetch(url + "/user/login", { method: "POST", body: JSON.stringify({ email: email, password: password, }), headers: { "Content-Type": "application/json", }, }); return await handleResult<ILoginResponse>(result); }, register: async (email: string, password: string) => { const result = await fetch(url + "/user/register", { method: "POST", body: JSON.stringify({ email: email, password: password, }), headers: { "Content-Type": "application/json", }, }); return await handleResult<IRegisterResponse>(result); }, createItem: async (title: string, date: string, token: string) => { const result = await fetch(url + "/dateitem/create", { method: "POST", body: JSON.stringify({ title, date, }), headers: { "Content-Type": "application/json", Authorization: `bearer ${token}`, }, }); return await handleResult<IDateItemResponse>(result); }, deleteItem: async (id: number, token: string) => { const result = await fetch(url + `/dateitem/delete/${id}`, { method: "DELETE", headers: { Authorization: `bearer ${token}`, }, }); return await handleResult<IDateItemResponse>(result); }, assignCoverItem: async (token: string, id: number) => { const result = await fetch(url + "/dateitem/coveritem", { method: "POST", body: JSON.stringify({ id: id, }), headers: { "Content-Type": "application/json", Authorization: `bearer ${token}`, }, }); console.log(result); return await handleResult<IDateItemResponse>(result); }, getItems: async (token: string) => { const result = await fetch(url + "/dateitem/items", { method: "GET", headers: { Authorization: `bearer ${token}`, }, }); return await handleResult<IGetItemsResponse>(result); }, }; export default DbService;
5cbb16fe2b0ba1cb2a77b8b9429243556c499bb9
TypeScript
arthurshayne/finisher
/src/extension.ts
2.578125
3
'use strict'; import * as vscode from 'vscode'; export function activate(context: vscode.ExtensionContext) { console.log('decorator sample is activated'); // create a decorator type that we use to decorate small numbers const loggerDecoration = vscode.window.createTextEditorDecorationType({ backgroundColor: 'rgba(255,165,0,0.2)', }); // create a decorator type that we use to decorate large numbers const assertionDecoration = vscode.window.createTextEditorDecorationType({ backgroundColor: 'rgba(0,255,0,0.2)', }); let activeEditor = vscode.window.activeTextEditor; if (activeEditor) { triggerUpdateDecorations(); } vscode.window.onDidChangeActiveTextEditor(editor => { activeEditor = editor; if (editor) { triggerUpdateDecorations(); } }, null, context.subscriptions); vscode.workspace.onDidChangeTextDocument(event => { if (activeEditor && event.document === activeEditor.document) { triggerUpdateDecorations(); } }, null, context.subscriptions); var timeout = null; function triggerUpdateDecorations() { if (timeout) { clearTimeout(timeout); } timeout = setTimeout(updateDecorations, 500); } function updateDecorations() { decorateAssertions(); decorateLoggers(); } function decorateLoggers() { const loggerRegex = /this\.logger\.(info|debug|warn)/g; decorateMatches(loggerRegex, loggerDecoration); } function decorateAssertions() { const assertionRegex = /(assert|expect)/g; decorateMatches(assertionRegex, assertionDecoration); } function decorateMatches(regex, decorator) { console.log("Updating decorations"); if (!activeEditor) { return; } const text = activeEditor.document.getText(); const decors: vscode.DecorationOptions[] = []; let match; while (match = regex.exec(text)) { const startPos = activeEditor.document.positionAt(match.index); const endPos = activeEditor.document.positionAt(match.index + match[0].length); const decoration = { range: new vscode.Range(startPos, endPos) }; //, hoverMessage: 'Number **' + match[0] + '**' }; decors.push(decoration); } activeEditor.setDecorations(decorator, decors); } }
06b51acef31aab5b420d69b72c70ab5e7e5c8dcb
TypeScript
RichCannon/test_halo_lab
/client/src/logic/saga/orderSaga.ts
2.734375
3
import { Action } from '@reduxjs/toolkit'; import { AxiosResponse } from 'axios'; import { call, put, takeLeading } from 'redux-saga/effects'; import { api } from '../api/api'; import { orderActions, OrderResponseT } from '../reducers/orderReducer'; // Функция-генератор для обработки запроса через сагу function* postOrderRequest(action: Action) { if (orderActions.requestOrder.match(action)) { try { // Делаем запрос через еффект call const reponse: AxiosResponse<OrderResponseT> = yield call(api.postOrder, action.payload) // При успешном запросе кладём данные в стейт yield put(orderActions.successOrder(reponse.data)) } catch (e) { // При неудачном запросе кладём ошибку в стейт yield put(orderActions.failureOrder(e)) } } } // Собираем все генератор-функции. // Исползуется takeLeading чтоб не было много одинаковых запросов и выполнялся тот которые первый пришёл // а остальные блочились export function* OrderSaga() { yield* [ takeLeading(orderActions.requestOrder.type, postOrderRequest), ]; }
887ef423ff5408762f5b3227f722d0f08107da95
TypeScript
xchsp/Weakling
/entities/item.ts
2.84375
3
import {itemsData} from "../data/itemsData.js"; export default class Item implements ItemData{ public itemId: string; public displayName: string; public description: string; public possibleSlots: Slots[]; public sprite: SpriteParameters; public stackable: boolean; public modified: boolean; public quantity: number; public specifics: any; public sellPrice: number; public buyPrice: number; constructor(itemId: string, quantity = 1, options = {}) { let itemParams = {}; if (itemId) { if (itemsData[itemId]) { itemParams = JSON.parse(JSON.stringify(itemsData[itemId])); } else { throw `Can't create "${itemId}" because there is no data for it.` } } if (itemParams['stackable'] === false && quantity > 1) { throw `Trying to create unstackable item "${itemId}" with quantity of ${quantity}.` } itemParams = {...itemParams, ...options, quantity: quantity}; Object.entries(itemParams).forEach(([key, value]) => this[key] = value); } }
77756af626dfaade92946609f64b8e2ad3d62b57
TypeScript
runem/web-component-analyzer
/src/analyze/flavors/lwc/discover-members.ts
2.59375
3
import { Node, PropertyLikeDeclaration, PropertySignature, SetAccessorDeclaration } from "typescript"; import { ComponentMember } from "../../types/features/component-member"; import { getMemberVisibilityFromNode, getModifiersFromNode } from "../../util/ast-util"; import { getJsDoc } from "../../util/js-doc-util"; import { lazy } from "../../util/lazy"; import { resolveNodeValue } from "../../util/resolve-node-value"; import { camelToDashCase } from "../../util/text-util"; import { AnalyzerDeclarationVisitContext } from "../analyzer-flavor"; import { hasLwcApiPropertyDecorator } from "./utils"; /** * Parses LWC related declaration members. * This is primary by looking at the "@api" decorator * @param node * @param context */ export function discoverMembers(node: Node, context: AnalyzerDeclarationVisitContext): ComponentMember[] | undefined { const { ts } = context; // Never pick up members not declared directly on the declaration node being traversed if (node.parent !== context.declarationNode) { return undefined; } // @api myProp = "hello"; if (ts.isSetAccessor(node) || ts.isGetAccessor(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node)) { return parsePropertyDecorator(node, context); } } /** * Visits a LWC property decorator and returns members based on it. * @param node * @param context */ function parsePropertyDecorator( node: SetAccessorDeclaration | PropertyLikeDeclaration | PropertySignature, context: AnalyzerDeclarationVisitContext ): ComponentMember[] | undefined { const { ts, checker } = context; // Parse the content of a possible lit "@api" decorator. const lwcApi = hasLwcApiPropertyDecorator(node, context); if (lwcApi) { const propName = node.name.getText(); // In LWC, the attribute name is deduced from the property name // There is currently no way to for it to a different value const attrName = lwcAttrName(propName); // Find the default value for this property const initializer = "initializer" in node ? node.initializer : undefined; const resolvedDefaultValue = initializer != null ? resolveNodeValue(initializer, context) : undefined; const def = resolvedDefaultValue != null ? resolvedDefaultValue.value : initializer?.getText(); // Find if the property/attribute is required //const required = ("initializer" in node && isPropertyRequired(node, context.checker)) || undefined; const required = undefined; const jsDoc = getJsDoc(node, ts); // Emit a property with "attrName" return [ { priority: "high", kind: "property", propName, attrName, type: lazy(() => { const propType = checker.getTypeAtLocation(node); return propType; }), node, default: def, required, jsDoc, visibility: getMemberVisibilityFromNode(node, ts), reflect: undefined, modifiers: getModifiersFromNode(node, ts) } ]; } return undefined; } const HTMLAttrs: { [name: string]: string } = { accessKey: "accesskey", bgColor: "bgcolor", colSpan: "colspan", contentEditable: "contenteditable", crossOrigin: "crossorigin", dateTime: "datetime", htmlFor: "for", formAction: "formaction", isMap: "ismap", maxLength: "maxlength", minLength: "minlength", noValidate: "novalidate", readOnly: "readonly", rowSpan: "rowspan", tabIndex: "tabindex", useMap: "usemap" }; // LWC attribute names // https://lwc.dev/guide/javascript#html-attribute-names function lwcAttrName(propName: string) { // Look for a global HTML name const htmlAttr: string = HTMLAttrs[propName]; if (htmlAttr) { return htmlAttr; } // Calculate the attribute name from the property return camelToDashCase(propName).toLowerCase(); }
e211ad0a5a775728c65019d7b1b7069cab56d260
TypeScript
wenshunxin/angular6
/src/app/shared/pipes/time1.pipe.ts
2.984375
3
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'time1' }) export class Time1Pipe implements PipeTransform { transform(value: any, args?: any): any { let dateTimeStamp = new Date(value).getTime(); var minute = 1000 * 60; //把分,时,天,周,半个月,一个月用毫秒表示 var hour = minute * 60; var day = hour * 24; var week = day * 7; var halfamonth = day * 15; var month = day * 30; var now = new Date().getTime(); //获取当前时间毫秒 let result:any; var diffValue = now - dateTimeStamp;//时间差 if(diffValue < 0){ return; } var minC = diffValue/minute; //计算时间差的分,时,天,周,月 var hourC = diffValue/hour; var dayC = diffValue/day; var weekC = diffValue/week; var monthC = diffValue/month; if(monthC >= 1 && monthC <= 3){ result = `${parseInt(String(monthC))}月前`; }else if(weekC >= 1 && weekC <= 4){ result = `${parseInt(String(weekC))}周前`; }else if(dayC >= 1 && dayC <= 7){ result = `${parseInt(String(dayC))}天前`; }else if(hourC >= 1 && hourC <= 24){ result = `${parseInt(String(hourC))}小时前`; }else if(minC >= 1 && minC <= 59){ result =`${parseInt(String(minC))}分钟前`; }else if(diffValue >= 0 && diffValue <= minute){ result = "刚刚" }else { var datetime = new Date(); datetime.setTime(dateTimeStamp); var Nyear = datetime.getFullYear(); var Nmonth = datetime.getMonth() + 1 < 10 ? "0" + (datetime.getMonth() + 1) : datetime.getMonth() + 1; var Ndate = datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate(); var Nhour = datetime.getHours() < 10 ? "0" + datetime.getHours() : datetime.getHours(); var Nminute = datetime.getMinutes() < 10 ? "0" + datetime.getMinutes() : datetime.getMinutes(); var Nsecond = datetime.getSeconds() < 10 ? "0" + datetime.getSeconds() : datetime.getSeconds(); result = Nyear + "-" + Nmonth + "-" + Ndate } return result; } }
a6b2af31d00904167c9275ed76a4098797c3a0d7
TypeScript
zaydek/retro-legacy
/go/scripts/types.ts
2.734375
3
// Props describes props ambiguously. export type Props = { [key: string]: any } // DescriptiveServerProps describes props ambiguously and the current path. export type DescriptiveServerProps = Props & { path: string } // ServerRouter describes the server-resolved router. export interface ServerRouter { // The static or server-resolved dynamic path. Static paths are inferred from // filenames and dynamic paths are inferred by [dynamic] filenames and // resolving serverPaths. [key: string]: { route: FilesystemRoute props: DescriptiveServerProps } } //////////////////////////////////////////////////////////////////////////////// // PageModule ambiguously describes a page module. interface PageModule { Head?: (resolvedProps: DescriptiveServerProps) => JSX.Element default?: (resolvedProps: DescriptiveServerProps) => JSX.Element } // StaticPageModule describes a static page module. export interface StaticPageModule extends PageModule { serverProps: Promise<DescriptiveServerProps> } export type DescriptiveServerPaths = { path: string; props?: Props }[] // DynamicPageModule describes a dynamic page module. export interface DynamicPageModule extends PageModule { serverPaths: Promise<DescriptiveServerPaths> } //////////////////////////////////////////////////////////////////////////////// // DevCommand describes 'retro dev ...'. // prettier-ignore export interface DevCommand { cached: boolean // retro dev --cached sourcemap: boolean // retro dev --sourcemap port: number // retro dev --port } // ExportCommand describes 'retro export ...'. // prettier-ignore export interface ExportCommand { cached: boolean // retro export --cached sourcemap: boolean // retro export --sourcemap } // DirConfiguration describes directory configuration. // prettier-ignore export interface DirectoryConfiguration { publicDir: string // e.g. "public" pagesDir: string // e.g. "src/pages" cacheDir: string // e.g. "__cache__" exportDir: string // e.g. "__export__" } // FilesystemRoute describes a page-based route. // prettier-ignore export interface FilesystemRoute { inputPath: string // e.g. "src/pages/index.js" outputPath: string // e.g. "index.html" path: string // e.g. "/" component: string // e.g. "PageIndex" } // Runtime describes the runtime emitted from the Go backend. export interface Runtime { command: DevCommand | ExportCommand directoryConfiguration: DirectoryConfiguration filesystemRouter: FilesystemRoute[] baseHTML: string }
8db9da69cb9e3e1970da75c002e51374bdb1f576
TypeScript
LancerComet/node-ftp
/src/cmder/cmds/cmd.quit.ts
2.609375
3
import Client from '../../client' /** * Quit Command. * Drop connection gracefully. * * @export * @param {string} clientInput - Content sent from client, Always be "quit". * @returns {boolean} */ export default function QUIT (clientInput: string, client: Client) : boolean { client.disconnect() return true }
6b40485e16f7481591990d4cff6d8ae7272b8eef
TypeScript
swc-project/swc
/crates/swc_ecma_parser/tests/tsc/computedPropertyNames10_ES5.ts
2.609375
3
// @target: es5 var s: string; var n: number; var a: any; var v = { [s]() { }, [n]() { }, [s + s]() { }, [s + n]() { }, [+s]() { }, [""]() { }, [0]() { }, [a]() { }, [<any>true]() { }, [`hello bye`]() { }, [`hello ${a} bye`]() { } }
92c8842883d2672b5765641478884e3667afa086
TypeScript
rqbazan/zeit-toast-clone
/src/helpers/inverse-indexed-queue.ts
3.53125
4
import { Indexable } from '../types' /** * Keeps the index property of the items in the inversed order, also it * has a static capacity which is required by default. * * [{ index: n - 1 }, { index: n - 2 }, ..., { index: 0 }] */ class InverseIndexedQueue<Item extends Indexable> { private capacity: number readonly items: Item[] constructor(capacity: number, items: Item[] = []) { this.capacity = capacity this.items = items } get length() { return this.items.length } add(newItem: Item) { if (this.items.length + 1 > this.capacity) { this.items.shift() } this.items.forEach(item => { // eslint-disable-next-line no-param-reassign item.index += 1 }) this.items.push(newItem) } pop() { this.items.shift() } clone() { return new InverseIndexedQueue(this.capacity, this.items) } } export default InverseIndexedQueue
d26195d7e79a446693bd1423982264507b93adda
TypeScript
smartdata-sdei/angular_sample_code
/src/app/core/directives/number-only.directive.ts
2.625
3
import { Directive, ElementRef, HostListener, Input } from '@angular/core'; @Directive({ selector: '[appNumberOnly]' }) export class NumberOnlyDirective { constructor(private _el: ElementRef) { } @HostListener('keydown', ['$event']) onKeyDown(evt: KeyboardEvent) { var charCode = (evt.which) ? evt.which : evt.keyCode; var number = this._el.nativeElement.value.split('.'); if(number.length>1 && (charCode == 190 || charCode == 110)){ evt.preventDefault(); } else if ( (charCode < 48 || charCode > 57) && (charCode < 96 || charCode > 105) && charCode > 8 && charCode > 46 ) { evt.preventDefault(); } } @HostListener('paste', ['$event']) onPaste(event: ClipboardEvent) { event.preventDefault(); const pastedInput: string = event.clipboardData .getData('text/plain') .replace(/[^0-9.]*/g, ''); // get a digit-only string document.execCommand('insertText', false, pastedInput); } }
85d52d847806cb0dfe5401eee3bc8389851d4051
TypeScript
benfortenberry/mazeofmonsters
/src/providers/countdown-service.ts
2.6875
3
import { Injectable } from '@angular/core'; import { timer, Subject, Observable } from 'rxjs'; import { takeWhile, map } from 'rxjs/operators'; @Injectable() export class CountdownService { private _countdown = new Subject<number>(); private isCounting = false; public count; private timer; public mapObservable = this._countdown.asObservable(); countdown(): Observable<number> { return this.mapObservable; } stop() { this.timer.unsubscribe(); this.isCounting = false; } start(): void { // Ensure that only one timer is in progress at any given time. if (!this.isCounting) { this.isCounting = true; this.timer = timer(0, 1000) .pipe( takeWhile(t => t < this.count), map(t => this.count - t) ) .subscribe(t => this._countdown.next(t), null, () => { this._countdown.complete(); this.isCounting = false; // Reset the countdown Subject so that a // countdown can be performed more than once. this._countdown = new Subject<number>(); }); } } }
4ee93237a02921afc90577071e31c4ec7b5843a1
TypeScript
fevalani/pokedex-back-end
/tests/factories/pokemonFactory.ts
2.8125
3
import { getRepository } from "typeorm"; import faker from "faker"; import Pokemons from "../../src/entities/Pokemons"; interface Pokemon { name: string; number: number; image: string; weight: number; height: number; baseExp: number; description: string; } export function createPokemon() { const pokemon = { name: faker.name.findName(), number: faker.datatype.number(), image: faker.internet.url(), weight: faker.datatype.number(), height: faker.datatype.number(), baseExp: faker.datatype.number(), description: faker.lorem.paragraph(), }; return pokemon; } export async function insertPokemon() { const pokemon: Pokemon = createPokemon(); return (await getRepository(Pokemons).insert(pokemon)).identifiers[0].id; }
f669b09f8feea992a88716d9a1deb05a448d10a7
TypeScript
fizk/NewBuzz
/src/elements/PatternColumnCount.ts
2.640625
3
import Node from './Node'; import {NOTE_TYPE} from "../types/NOTE_TYPE"; export default class PatternColumnCount extends Node { label: string; hightlight: boolean = false; constructor(key: any, label) { super(key); this.type = NOTE_TYPE.IN_LINE; this.label = label; } get height() { return 20; } get width() { return 50; } draw(x: number = 0, y: number = 0): void { this.context.save(); this.context.fillStyle = this. hightlight ? '#bdb5a0' : '#dad6ca'; this.context.fillRect(0, 0, 50, 20); this.context.fillStyle = 'black'; this.context.textBaseline = 'ideographic'; this.context.font = '11px sans-serif'; this.context.fillText(this.label, 4, 16); this.context.restore(); super.draw(x, y); } }
fb8681c7053441f79fbb860eb6c3a8bc8c5ff051
TypeScript
routexjs/deroutex
/tests/error.test.ts
2.703125
3
import { superdeno } from "https://deno.land/x/superdeno@main/mod.ts"; import { Deroutex, ErrorWithBody, ErrorWithStatusCode, ICtx, Router, TextBody, } from "../mod.ts"; Deno.test("It handles 404", async () => { const app = new Deroutex(); await superdeno(app.handler) .get("/") .expect(404); }); Deno.test("It handles sub-routers error propagation", async () => { const app = new Deroutex(); // Uses app/default error handler app.child("/1"); const child2 = new Router(); child2.errorHandler = () => undefined; app.child("/2", child2); const handler = superdeno(app.handler); await Promise.all([ handler.get("/1").expect(404), handler.get("/2").expect(200), ]); }); Deno.test("It handles error", async () => { const app = new Deroutex(); app.get("/", () => { throw new Error("Error"); }); await superdeno(app.handler).get("/").expect("Error").expect(500); }); Deno.test("It handles error with status", async () => { const app = new Deroutex(); app.get("/", () => { throw new ErrorWithStatusCode(400, "Error"); }); await superdeno(app.handler).get("/").expect("Error").expect(400); }); Deno.test("It handles error with body", async () => { const app = new Deroutex(); app.get("/", () => { throw new ErrorWithBody(401, new TextBody("Error!")); }); await superdeno(app.handler).get("/").expect("Error!").expect(401); }); Deno.test("It handles customer handler", async () => { const app = new Deroutex({ errorHandler: (ctx: ICtx) => (ctx.body = new TextBody("Error!")), }); app.get("/", () => { throw new Error(); }); await superdeno(app.handler).get("/").expect("Error!"); });
6fa6a15eb3dbf866e825bc3a936498258240a73a
TypeScript
dvens/atomify
/packages/kit/src/utilities/inview/utils/build-treshhold-list.ts
2.984375
3
/** * @export * @returns { array } */ export function buildThresholdList() { const numSteps = 1000; const thresholds = []; for (let i = 1.0; i <= numSteps; i++) { const ratio = i / numSteps; thresholds.push(ratio); } thresholds.push(0); return thresholds; }
c66152e57ae99d3638e60ebf53b0a912db55532e
TypeScript
christophgysin/aws-sdk-js-v3
/deno/smithy-client/client.ts
2.546875
3
import { constructStack } from "../middleware-stack/mod.ts"; import { Client as IClient, Command, MetadataBearer, MiddlewareStack, RequestHandler } from "../types/mod.ts"; export interface SmithyConfiguration<HandlerOptions> { requestHandler: RequestHandler<any, any, HandlerOptions>; /** * The API version set internally by the SDK, and is * not planned to be used by customer code. * @internal */ readonly apiVersion: string; } export type SmithyResolvedConfiguration<HandlerOptions> = SmithyConfiguration<HandlerOptions>; export class Client< HandlerOptions, ClientInput extends object, ClientOutput extends MetadataBearer, ResolvedClientConfiguration extends SmithyResolvedConfiguration<HandlerOptions> > implements IClient<ClientInput, ClientOutput, ResolvedClientConfiguration> { public middlewareStack: MiddlewareStack<ClientInput, ClientOutput> = constructStack<ClientInput, ClientOutput>(); readonly config: ResolvedClientConfiguration; constructor(config: ResolvedClientConfiguration) { this.config = config; } send<InputType extends ClientInput, OutputType extends ClientOutput>( command: Command<ClientInput, InputType, ClientOutput, OutputType, SmithyResolvedConfiguration<HandlerOptions>>, options?: HandlerOptions ): Promise<OutputType>; send<InputType extends ClientInput, OutputType extends ClientOutput>( command: Command<ClientInput, InputType, ClientOutput, OutputType, SmithyResolvedConfiguration<HandlerOptions>>, cb: (err: any, data?: OutputType) => void ): void; send<InputType extends ClientInput, OutputType extends ClientOutput>( command: Command<ClientInput, InputType, ClientOutput, OutputType, SmithyResolvedConfiguration<HandlerOptions>>, options: HandlerOptions, cb: (err: any, data?: OutputType) => void ): void; send<InputType extends ClientInput, OutputType extends ClientOutput>( command: Command<ClientInput, InputType, ClientOutput, OutputType, SmithyResolvedConfiguration<HandlerOptions>>, optionsOrCb?: HandlerOptions | ((err: any, data?: OutputType) => void), cb?: (err: any, data?: OutputType) => void ): Promise<OutputType> | void { const options = typeof optionsOrCb !== "function" ? optionsOrCb : undefined; const callback = typeof optionsOrCb === "function" ? (optionsOrCb as (err: any, data?: OutputType) => void) : cb; const handler = command.resolveMiddleware(this.middlewareStack as any, this.config, options); if (callback) { handler(command) .then( (result) => callback(null, result.output), (err: any) => callback(err) ) .catch( // prevent any errors thrown in the callback from triggering an // unhandled promise rejection () => {} ); } else { return handler(command).then((result) => result.output); } } destroy() { if (this.config.requestHandler.destroy) this.config.requestHandler.destroy(); } }
5db7f47310fef5cc20d18a0aa882faa5f7edae3b
TypeScript
kawamurashin/DecimalClockSVGTypeScript
/src/analog/hands/SecondHand.ts
2.734375
3
///<reference path="../../decimal/DecimalTime.ts"/> namespace hands { import DecimalTime = decimal.DecimalTime; export class SecondHand extends Hand { constructor(svg: HTMLElement) { super(svg); this._radius = 100; this._path.setAttribute("stroke", "#333"); this._path.setAttribute("fill", "none"); this._path.setAttribute("stroke-width", "2"); this._path.setAttribute("stroke-linejoin", "round"); this.enterFrame(); } enterFrame(): void { super.enterFrame(); //let theta:number = 2*Math.PI *((DecimalTime.decimalSecond + (DecimalTime.decimalMilliSecond/1000)) / 100) - Math.PI*0.5; this._theta = 2 * Math.PI * ((DecimalTime.decimalSecond + (DecimalTime.decimalMilliSecond / 1000)) / 100) - Math.PI * 0.5; this.draw(); } } }
8a2f4422a09223d2295b9ac5b19149657e7dce69
TypeScript
kwhong95/ts_study
/SkillsForProductivity/TypeInference/src/3.ts
2.84375
3
export {}; const arr1 = [10, 20, 30]; const [n1, n2, n3] = arr1; // arr1.push('a'); const obj = { id: 'abcd', age: 123, language: 'korean' }; const { id, age, language } = obj; // console.log(id === age);
b201dd3ad6686ed25ae418c744a62c085d4a7886
TypeScript
david2999999/PokeLegend-Angular
/src/app/shared/models/pokemon-pc/pokemon-box.model.ts
3.21875
3
import { Pokemon } from '../pokemon/pokemon.model'; export class PokemonBox { constructor(private pokemonList : Pokemon[] = [], private maxCapacity: number = 30) {} addPokemon(pokemon: Pokemon) { if (this.pokemonList.length >= this.maxCapacity) { return false; } this.pokemonList.push(pokemon); return true; } isFull() { return this.pokemonList.length === this.maxCapacity; } getPokemon(index: number) { return this.pokemonList[index]; } releasePokemon(index: number) { if (!this.pokemonList[index]) { return false; } this.pokemonList.splice(index, 1); return true; } numberOfPokemons() { return this.pokemonList.length; } }
dfaa968e2d62a646594ad56ae04acc2f8374aad9
TypeScript
daretodave/ursa-service
/lib/model/user/user.ts
2.546875
3
import {Table, Column, Model, HasMany, Unique, AutoIncrement, PrimaryKey, NotEmpty} from 'sequelize-typescript'; import {JWT_SECRET} from "../../config"; const jwt = require('jsonwebtoken'); @Table export default class User extends Model<User> { @PrimaryKey @AutoIncrement @Column id: number; @Unique @Column name: string; @Unique @Column email: string; @NotEmpty @Column hash: string; @Column admin: boolean; } export async function findUser(properties: Partial<User>) { return User.findOne({ where: <any>properties }); } export async function hasUser(properties: Partial<User>) { const user = await findUser(properties); return !!user; } export function userToJWT(user: User) { delete user.hash; const payload: any = { user: user }; const token = jwt.sign(payload, JWT_SECRET); return token; } export function jwtToUser(token: string) { try { return jwt.verify(token, JWT_SECRET); } catch (e) { return null; } } export {User};
cb7831ff5be63a9de51193809f71bc4dca25ec0b
TypeScript
nocch12/DevChallenges-Auth-App
/resources/js/validation/responseValidation.ts
3.265625
3
type ErrorMessage = string | string[]; type ResponseErrors = { [key: string]: ErrorMessage; } type FormatErrors = { [key: string]: string; } export const makeErrorMessage = (errors: ErrorMessage): string => { if(!errors.length) return ''; if(Array.isArray(errors)) { return errors[0]; } return errors; } export const makeErrors = (responseErrors: ResponseErrors): FormatErrors => { let data = {}; for (const key in responseErrors) { if (Object.prototype.hasOwnProperty.call(responseErrors, key)) { const error = responseErrors[key]; data = { ...data, [key]: error } } } return data; }
ef1a8c8298c837410dac5e0b60c824ff04c2f1ba
TypeScript
liruidong1/algorithm011-class01
/Week_01/plus-one.ts
3.578125
4
function plusOne(digits: number[]): number[] { for (let i = digits.length - 1; i >= 0; i--) { digits[i]++; //等价于 digits[i] += 1 digits[i] %= 10; if (digits[i] !== 0) { //不等于0证明无进位 return digits; } } //走到此处,证明有进位,且是[9], [9,9], [9,...,9]这种特殊情况 let arr: number[] = [...new Array(digits.length+1)].map(()=>0); arr[0] = 1; return arr; }
853feb1206383e6c72816df582190fee6d4ce69f
TypeScript
RaduW/TsTests
/src/ts/tree.spec.ts
2.921875
3
import HierarchyWalker = ModificationEditor.HierarchyWalker; import HtmlNavigator = ModificationEditor.HtmlNavigator; import HtmlHierarchyWalker = ModificationEditor.HtmlHierarchyWalker; import getSoforHtmlNodePath = ModificationEditor.getSoforHtmlNodePath; interface ITestNode{ type:string; id: string; parent: ITestNode; children: ITestNode[]; } class TestNode implements ITestNode{ constructor ( public type:string, public id:string, public children:ITestNode[] = null, public parent:ITestNode = null){} toString(){ return `<${this.type} id=${this.id}>`;} } /* The tree n1------------- | \ \ a-- n5 b--- | \ | | \ n2 e-- n6 n7- h |\ | \ | \ c d n3 g n8 n9 | \ f n4 */ const testTree:ITestNode = new TestNode('node','n1',[ new TestNode('other','a',[ new TestNode('node', 'n2',[ new TestNode('other', 'c'), new TestNode('other', 'd'), ]), new TestNode('other', 'e', [ new TestNode('node', 'n3',[ new TestNode('other', 'f'), new TestNode('node', 'n4'), ]), new TestNode('other', 'g'), ]), ]), new TestNode('node','n5', [ new TestNode('node', 'n6'), ]), new TestNode('other','b',[ new TestNode('node', 'n7',[ new TestNode('node', 'n8'), new TestNode('node', 'n9'), ]), new TestNode('other', 'h'), ]), ]); //same tree as html const innerHtml:string = ` <div id='n1' legalid='n1' sfr-node> <div id='a'> <div id='n2' legalid='n2'sfr-node> <div id='c'></div> <div id='d'></div> </div> <div id='e'> <div id='n3' legalid='n3' sfr-node> <div id='f'></div> <div id='n4' legalid='n4' sfr-node></div> </div> <div id='g'></div> </div> </div> <div id='n5' legalid='n5' sfr-node> <div id='n6' legalid='n6' sfr-node></div> </div> <div id='b'> <div id='n7' legalid='n7' sfr-node> <div id='n8' legalid='n8' sfr-node></div> <div id='n9' legalid='n9' sfr-node></div> </div> <div id='h'></div> </div> </div> `; //patch the parent back pointer (function patch(node:ITestNode, parent:ITestNode){ node.parent = parent; if ( node.children) for( let child of node.children){ patch(child,node); } } )(testTree, null); function findNode(nodeName:string):ITestNode{ return findNodeInternal(testTree,nodeName); } function findNodeInternal(node:ITestNode, nodeName:string):ITestNode{ var retVal: ITestNode = null; if ( ! node ) return null; if ( node.id === nodeName) return node; var idx = 0; if ( !node.children || node.children.length == 0) return null; var numElm = node.children.length; do { retVal = findNodeInternal(node.children[idx], nodeName); ++idx; }while(retVal == null && idx < numElm); return retVal; } function testMatcher(node:ITestNode){ if ( !node) return false; return node.type === 'node'; } class TestNavigator implements ModificationEditor.INodeNavigator<ITestNode>{ nextSibling(node: ITestNode):ITestNode { if (!node || !node.parent) return null; var parent = node.parent; var currentNodeIndex = _.indexOf(parent.children, node); if (currentNodeIndex < parent.children.length - 1) return parent.children[currentNodeIndex + 1]; return null; }; previousSibling(node: ITestNode): ITestNode { if (!node || !node.parent) return null; var parent = node.parent; var currentNodeIndex = _.indexOf(parent.children, node); if (currentNodeIndex > 0) return parent.children[currentNodeIndex - 1]; return null; }; parent(node: ITestNode): ITestNode { if (!node) return null; return node.parent; }; firstChild = function (node: ITestNode): ITestNode { if (node && node.children && node.children.length > 0){ return node.children[0]; } return null; }; lastChild = function (node: ITestNode): ITestNode { if (node && node.children && node.children.length > 0) return node.children[node.children.length - 1]; return null; }; hasChildren = function (node: ITestNode):boolean { if (node && node.children && node.children.length > 0) return true; return false; }; hasParent = function (node: ITestNode): boolean { return !!node && !!node.parent; }; } describe("Testing Hierarchy Walker", function(){ let walker:HierarchyWalker<ITestNode> = new HierarchyWalker<ITestNode>( new TestNavigator(),testMatcher,testTree); all("goNext should navigate to the next node", [ ["n1","n1"], ["a", "n5"], ["n2","n3"], ["c", "c"], ["d", "d"], ["e", "n5"], ["n3","n5"], ["f", "n4"], ["n4","n4"], ["g", "n5"], ["n5","n7"], ["n6","n6"], ["b", "b"], ["n7","n7"], ["n8","n9"], ["n9","n9"], ["h", "h"] ], function(startNodeName:string,endNodeName:string){ const startNode = findNode(startNodeName); const endNode = endNodeName==null ? null : findNode(endNodeName); const result = walker.goNext(startNode); expect(result).toEqual(endNode); }); all("goPrevious should navigate to the previous node", [ ["n1","n1"], ["a", "a"], ["n2","n2"], ["c", "c"], ["d", "d"], ["e", "n2"], ["n3","n2"], ["f", "f"], ["n4","n4"], ["g", "n3"], ["n5","n3"], ["n6","n6"], ["b", "n5"], ["n7","n5"], ["n8","n8"], ["n9","n8"], ["h", "n7"] ], function(startNodeName:string,endNodeName:string){ const startNode = findNode(startNodeName); const endNode = endNodeName==null ? null : findNode(endNodeName); const result = walker.goPrevious(startNode); expect(result).toEqual(endNode); }); all("goIn should navigate to the next node", [ ["n1","n2"], ["a", "n2"], ["n2","n2"], ["c", "c"], ["d", "d"], ["e", "n3"], ["n3","n4"], ["f", "f"], ["n4","n4"], ["g", "g"], ["n5","n6"], ["n6","n6"], ["b", "n7"], ["n7","n8"], ["n8","n8"], ["n9","n9"], ["h", "h"] ], function(startNodeName:string,endNodeName:string){ const startNode = findNode(startNodeName); const endNode = endNodeName==null ? null : findNode(endNodeName); const result = walker.goIn(startNode); expect(result).toEqual(endNode); }); all("goOut should navigate to the next node", [ ["n1","n1"], ["a", "n1"], ["n2","n1"], ["c", "n2"], ["d", "n2"], ["e", "n1"], ["n3","n1"], ["f", "n3"], ["n4","n3"], ["g", "n1"], ["n5","n1"], ["n6","n5"], ["b", "n1"], ["n7","n1"], ["n8","n7"], ["n9","n7"], ["h", "n1"] ], function(startNodeName:string,endNodeName:string){ const startNode = findNode(startNodeName); const endNode = endNodeName==null ? null : findNode(endNodeName); const result = walker.goOut(startNode); expect(result).toEqual(endNode); }); }); describe("Testing HtmlHierarchyWalker", function(){ let testTreeRoot: HTMLElement; let htmlNavigator: HtmlNavigator; let container:HTMLElement; beforeAll(function(){ container = document.createElement('div'); container.style.display = 'none'; document.body.appendChild(container); container.innerHTML = innerHtml; testTreeRoot = container.firstElementChild as HTMLElement; htmlNavigator = new HtmlNavigator(testTreeRoot); }); afterAll(function(){ //celanup the inserted html container.parentNode.removeChild(container); }); let walker:HtmlHierarchyWalker = new HtmlHierarchyWalker(testTreeRoot); all("goNext should navigate to the next node", [ ["n1","n1"], ["a", "n5"], ["n2","n3"], ["c", "c"], ["d", "d"], ["e", "n5"], ["n3","n5"], ["f", "n4"], ["n4","n4"], ["g", "n5"], ["n5","n7"], ["n6","n6"], ["b", "b"], ["n7","n7"], ["n8","n9"], ["n9","n9"], ["h", "h"] ], function(startNodeName:string,endNodeName:string){ const startNode = document.getElementById(startNodeName); const endNode = endNodeName==null ? null : document.getElementById(endNodeName);; const result = walker.goNext(startNode); expect(result).toEqual(endNode); }); all("goPrevious should navigate to the previous node", [ ["n1","n1"], ["a", "a"], ["n2","n2"], ["c", "c"], ["d", "d"], ["e", "n2"], ["n3","n2"], ["f", "f"], ["n4","n4"], ["g", "n3"], ["n5","n3"], ["n6","n6"], ["b", "n5"], ["n7","n5"], ["n8","n8"], ["n9","n8"], ["h", "n7"] ], function(startNodeName:string,endNodeName:string){ const startNode = document.getElementById(startNodeName); const endNode = endNodeName==null ? null : document.getElementById(endNodeName);; const result = walker.goPrevious(startNode); expect(result).toEqual(endNode); }); all("goIn should navigate to the next node", [ ["n1","n2"], ["a", "n2"], ["n2","n2"], ["c", "c"], ["d", "d"], ["e", "n3"], ["n3","n4"], ["f", "f"], ["n4","n4"], ["g", "g"], ["n5","n6"], ["n6","n6"], ["b", "n7"], ["n7","n8"], ["n8","n8"], ["n9","n9"], ["h", "h"] ], function(startNodeName:string,endNodeName:string){ const startNode = document.getElementById(startNodeName); const endNode = endNodeName==null ? null : document.getElementById(endNodeName);; const result = walker.goIn(startNode); expect(result).toEqual(endNode); }); all("goOut should navigate to the next node", [ ["n1","n1"], ["a", "n1"], ["n2","n1"], ["c", "n2"], ["d", "n2"], ["e", "n1"], ["n3","n1"], ["f", "n3"], ["n4","n3"], ["g", "n1"], ["n5","n1"], ["n6","n5"], ["b", "n1"], ["n7","n1"], ["n8","n7"], ["n9","n7"], ["h", "n1"] ], function(startNodeName:string,endNodeName:string){ const startNode = document.getElementById(startNodeName); const endNode = endNodeName==null ? null : document.getElementById(endNodeName);; const result = walker.goOut(startNode); expect(result).toEqual(endNode); }); }); describe("Testing tree navigation", function(){ beforeEach(function(){ //do your init }); // The tree // n1------------- n1---------------------------- // | \ \ \ \ \ \ // a-- n5 b--- a n2 c d e n3 g n5 b n7-- h // | \ | | \ ==> | | | \ // n2 e-- n6 n7- h f n4 n6 n8 n9 // |\ | \ | \ // c d n3 g n8 n9 // | \ // f n4 all("findNext should navigate from startNode to endNode",[ ["n1", true, "n1"], ["n1", false, null], ["a", true, "n2"], ["a", false, "n5"], ["n2", true, "n2"], ["n2", false, "n3"], ["c", true, "n3"], ["c", false, "n3"], ["d", true, "n3"], ["d", false, "n3"], ["e", true, "n3"], ["e", false, "n5"], ["n3", true, "n3"], ["n3", false, "n5"], ["f", true, "n4"], ["f", false, "n4"], ["n4", true, "n4"], ["n4", false, "n5"], ["g", true, "n5"], ["g", false, "n5"], ["n5", true, "n5"], ["n5", false, "n7"], ["n6", true, "n6"], ["n6", false, "n7"], ["b", true, "n7"], ["b", false, null], ["n7", true, "n7"], ["n7", false, null], ["n8", true, "n8"], ["n8", false, "n9"], ["n9", true, "n9"], ["n9", false, null], ["h", true, null], ["h", false, null] ], function(startNodeName:string,including:boolean,endNodeName:string){ const navigator = new TestNavigator(); const startNode = findNode(startNodeName); const endNode = endNodeName==null ? null : findNode(endNodeName); expect(ModificationEditor.findNext(startNode,navigator,testMatcher,including)).toEqual(endNode); } ); // The tree // n1------------- n1---------------------------- // | \ \ \ \ \ \ // a-- n5 b--- a n2 c d e n3 g n5 b n7-- h // | \ | | \ ==> | | | \ // n2 e-- n6 n7- h f n4 n6 n8 n9 // |\ | \ | \ // c d n3 g n8 n9 // | \ // f n4 all("findPrevious should navigate from startNode to endNode",[ ["n1", true, "n9"], ["n1", false, null], ["a", true, "n4"], ["a", false, "n1"], ["n2", true, "n2"], ["n2", false, "n1"], ["c", true, "n2"], ["c", false, "n2"], ["d", true, "n2"], ["d", false, "n2"], ["e", true, "n4"], ["e", false, "n2"], ["n3", true, "n4"], ["n3", false, "n2"], ["f", true, "n3"], ["f", false, "n3"], ["n4", true, "n4"], ["n4", false, "n3"], ["g", true, "n4"], ["g", false, "n4"], ["n5", true, "n6"], ["n5", false, "n4"], ["n6", true, "n6"], ["n6", false, "n5"], ["b", true, "n9"], ["b", false, "n6"], ["n7", true, "n9"], ["n7", false, "n6"], ["n8", true, "n8"], ["n8", false, "n7"], ["n9", true, "n9"], ["n9", false, "n8"], ["h", true, "n9"], ["h", false, "n9"] ], function(startNodeName:string,including:boolean,endNodeName:string){ const navigator = new TestNavigator(); const startNode = findNode(startNodeName); const endNode = endNodeName==null ? null : findNode(endNodeName); expect(ModificationEditor.findPrevious(startNode,navigator,testMatcher,including)).toEqual(endNode); } ); }); describe("Testing HtmlNavigator", function(){ let testTreeRoot: HTMLElement; let htmlNavigator: HtmlNavigator; let container:HTMLElement; beforeEach(function(){ container = document.createElement('div'); container.style.display = 'none'; document.body.appendChild(container); container.innerHTML = innerHtml; testTreeRoot = container.firstElementChild as HTMLElement; htmlNavigator = new HtmlNavigator(testTreeRoot); }); afterEach(function(){ //celanup the inserted html container.parentNode.removeChild(container); }); // The tree // n1------------- // | \ \ // a-- n5 b--- // | \ | | \ // n2 e-- n6 n7- h // |\ | \ | \ // c d n3 g n8 n9 // | \ // f n4 all('should evaluate hasParent',[ ['n1', false], ['a', true], ['n2', true], ['c', true], ['d', true], ['e', true], ['n3', true], ['f', true], ['n4', true], ['g', true], ['n5', true], ['n6', true], ['b', true], ['n7', true], ['n8', true], ['n9', true], ['h', true], ], function(startNodeName:string, hasParent:boolean){ let startNode = document.getElementById(startNodeName); let result = htmlNavigator.hasParent(startNode); expect(result).toBe(hasParent); }); all('should evaluate hasChildren',[ ['n1', true], ['a', true], ['n2', true], ['c', false], ['d', false], ['e', true], ['n3', true], ['f', false], ['n4', false], ['g', false], ['n5', true], ['n6', false], ['b', true], ['n7', true], ['n8', false], ['n9', false], ['h', false], ], function(startNodeName:string, hasChildren:boolean){ let startNode = document.getElementById(startNodeName); let result = htmlNavigator.hasChildren(startNode); expect(result).toBe(hasChildren); }); all('should navigate to lastChild',[ ['n1', 'b'], ['a', 'e'], ['n2', 'd'], ['c', null], ['d', null], ['e', 'g'], ['n3', 'n4'], ['f', null], ['n4', null], ['g', null], ['n5', 'n6'], ['n6', null], ['b', 'h'], ['n7', 'n9'], ['n8', null], ['n9', null], ['h', null], ], function(startNodeName:string, endNodeName:string){ let startNode = document.getElementById(startNodeName); let endNode = endNodeName? document.getElementById(endNodeName): null ; let result = htmlNavigator.lastChild(startNode); expect(result).toEqual(endNode); }); all('should navigate to firstChild',[ ['n1', 'a'], ['a', 'n2'], ['n2', 'c'], ['c', null], ['d', null], ['e', 'n3'], ['n3', 'f'], ['f', null], ['n4', null], ['g', null], ['n5', 'n6'], ['n6', null], ['b', 'n7'], ['n7', 'n8'], ['n8', null], ['n9', null], ['h', null], ], function(startNodeName:string, endNodeName:string){ let startNode = document.getElementById(startNodeName); let endNode = endNodeName? document.getElementById(endNodeName): null ; let result = htmlNavigator.firstChild(startNode); expect(result).toEqual(endNode); }); all('should navigate to previous sibling',[ ['n1', null], ['a', null], ['n2', null], ['c', null], ['d', 'c'], ['e', 'n2'], ['n3', null], ['f', null], ['n4', 'f'], ['g', 'n3'], ['n5', 'a'], ['n6', null], ['b', 'n5'], ['n7', null], ['n8', null], ['n9', 'n8'], ['h', 'n7'], ], function(startNodeName:string, endNodeName:string){ let startNode = document.getElementById(startNodeName); let endNode = endNodeName? document.getElementById(endNodeName): null ; let result = htmlNavigator.previousSibling(startNode); expect(result).toEqual(endNode); }); all('should navigate to parent',[ ['n1', null], ['a', 'n1'], ['n2', 'a'], ['c', 'n2'], ['d', 'n2'], ['e', 'a'], ['n3', 'e'], ['f', 'n3'], ['n4', 'n3'], ['g', 'e'], ['n5', 'n1'], ['n6', 'n5'], ['b', 'n1'], ['n7', 'b'], ['n8', 'n7'], ['n9', 'n7'], ['h', 'b'], ], function(startNodeName:string, endNodeName:string){ let startNode = document.getElementById(startNodeName); let endNode = endNodeName? document.getElementById(endNodeName): null ; let result = htmlNavigator.parent(startNode); expect(result).toEqual(endNode); }); all('should navigate to next sibling',[ ['n1', null], ['a', 'n5'], ['n2', 'e'], ['c', 'd'], ['d', null], ['e', null], ['n3', 'g'], ['f', 'n4'], ['n4', null], ['g', null], ['n5', 'b'], ['n6', null], ['b', null], ['n7', 'h'], ['n8', 'n9'], ['n9', null], ['h', null], ], function(startNodeName:string, endNodeName:string){ let startNode = document.getElementById(startNodeName); let endNode = endNodeName? document.getElementById(endNodeName): null ; let result = htmlNavigator.nextSibling(startNode); expect(result).toEqual(endNode); }); }); describe("Testing soforHtmlNodePath", function(){ let testTreeRoot: HTMLElement; let htmlNavigator: HtmlNavigator; let container:HTMLElement; beforeAll(function(){ container = document.createElement('div'); container.style.display = 'none'; document.body.appendChild(container); container.innerHTML = innerHtml; testTreeRoot = container.firstElementChild as HTMLElement; htmlNavigator = new HtmlNavigator(testTreeRoot); }); afterAll(function(){ //celanup the inserted html container.parentNode.removeChild(container); }); all('getSoforHtmlNodePath should return the correct paths',[ ['n1','/n1'], ['a','/n1'], ['n2','/n1/n2'], ['c','/n1/n2'], ['d','/n1/n2'], ['e','/n1'], ['n3','/n1/n3'], ['f','/n1/n3'], ['n4','/n1/n3/n4'], ['g','/n1'], ['n5','/n1/n5'], ['n6','/n1/n5/n6'], ['b','/n1'], ['n7','/n1/n7'], ['n8','/n1/n7/n8'], ['n9','/n1/n7/n9'], ['h','/n1'], ], function(startNodeName:string, path:string){ const startNode = document.getElementById(startNodeName); const result:string = getSoforHtmlNodePath(startNode, htmlNavigator); expect(result).toEqual(path); }); });
7147bfd64ac4986d27c4ace7456a855a99936f49
TypeScript
dotCMS/dotcms-webcomponents
/src/utils/utils.spec.ts
2.71875
3
import { getClassNames, getDotOptionsFromFieldValue, getErrorClass, getHintId, getId, getLabelId, getOriginalStatus, getStringFromDotKeyArray, getTagError, getTagHint, isFileAllowed, updateStatus } from './utils'; describe('getClassNames', () => { it('should return field CSS classes', () => { let status = { dotValid: false, dotTouched: false, dotPristine: true }; expect(getClassNames(status, true)).toEqual({ 'dot-valid': true, 'dot-invalid': false, 'dot-pristine': true, 'dot-dirty': false, 'dot-touched': false, 'dot-untouched': true }); status = { dotValid: true, dotTouched: true, dotPristine: false }; expect(getClassNames(status, true)).toEqual({ 'dot-dirty': true, 'dot-invalid': false, 'dot-pristine': false, 'dot-required': undefined, 'dot-touched': true, 'dot-untouched': false, 'dot-valid': true }); }); }); describe('getDotOptionsFromFieldValue', () => { it('should return label/value', () => { const items = getDotOptionsFromFieldValue('key1|A,key2|B'); expect(items.length).toBe(2); expect(items).toEqual([{ label: 'key1', value: 'A' }, { label: 'key2', value: 'B' }]); }); it('should support \r\n as option splitter', () => { const items = getDotOptionsFromFieldValue('key1|A\r\nkey2|B'); expect(items.length).toBe(2); expect(items).toEqual([{ label: 'key1', value: 'A' }, { label: 'key2', value: 'B' }]); }); it('should support \r\n and semicolon as option splitter', () => { const items = getDotOptionsFromFieldValue('key1|A\r\nkey2|B,key3|C'); expect(items.length).toBe(3); expect(items).toEqual([ { label: 'key1', value: 'A' }, { label: 'key2', value: 'B' }, { label: 'key3', value: 'C' } ]); }); it('should empty array when invalid format', () => { const items = getDotOptionsFromFieldValue('key1A, key2/B, @'); expect(items.length).toBe(0); }); it('should handle other type', () => { const items = getDotOptionsFromFieldValue(null); expect(items.length).toBe(0); }); }); describe('getErrorClass', () => { it('should return error CSS', () => { expect(getErrorClass(false)).toEqual('dot-field__error'); }); it('should not return error CSS', () => { expect(getErrorClass(true)).toBeUndefined(); }); }); describe('getHintId', () => { it('should return hint id correctly', () => { expect(getHintId('***^^^HelloWorld123$$$###')).toEqual('hint-helloworld123'); }); it('should return undefined', () => { expect(getHintId('')).toBeUndefined(); }); }); describe('getId', () => { it('should return id', () => { expect(getId('some123Name#$%^&')).toBe('dot-some123name'); }); }); describe('getLabelId', () => { it('should return label id correctly', () => { expect(getLabelId('***^^^HelloWorld123$$$###')).toEqual('label-helloworld123'); }); it('should return undefined', () => { expect(getLabelId('')).toBeUndefined(); }); }); describe('getOriginalStatus', () => { it('should return initial field Status', () => { expect(getOriginalStatus()).toEqual({ dotValid: true, dotTouched: false, dotPristine: true }); }); it('should return field Status with overwrite dotValid equal false', () => { expect(getOriginalStatus(false)).toEqual({ dotValid: false, dotTouched: false, dotPristine: true }); }); }); describe('getStringFromDotKeyArray', () => { it('should transform to string', () => { expect( getStringFromDotKeyArray([ { key: 'some1', value: 'val1' }, { key: 'some45', value: 'val99' } ]) ).toBe('some1|val1,some45|val99'); }); }); describe('getTagError', () => { it('should return error tag', () => { const message = 'Error Msg'; const jsxTag: any = getTagError(true, message); expect(jsxTag.$attrs$).toEqual({ class: 'dot-field__error-message' }); expect(jsxTag.$children$[0].$text$).toEqual(message); }); it('should not return Error tag', () => { expect(getTagError(false, 'Error Msg')).toEqual(null); }); }); describe('getTagHint', () => { it('should return Hint tag', () => { const jsxTag: any = getTagHint('this is a hint'); expect(jsxTag.$attrs$).toEqual({ class: 'dot-field__hint', id: 'hint-this-is-a-hint' }); expect(jsxTag.$children$[0].$text$).toEqual('this is a hint'); }); it('should not return Hint tag', () => { expect(getTagHint('')).toBeNull(); }); }); describe('updateStatus', () => { it('should return updated field Status', () => { const status = { dotValid: false, dotTouched: false, dotPristine: true }; expect(updateStatus(status, { dotTouched: true })).toEqual({ dotValid: false, dotTouched: true, dotPristine: true }); }); }); describe('isValidURL', () => { // new URL is not available in headless browser. }); describe('isFileAllowed', () => { it('should return true when file extension is in the allow types', () => { expect(isFileAllowed('file.pdf', 'application/pdf', '.png, .pdf')).toBe(true); }); it('should return true when allowedExtensions are any', () => { expect(isFileAllowed('file.pdf', 'application/pdf', '*')).toBe(true); }); it('should return false when allowedExtensions when types are different', () => { expect(isFileAllowed('file.pdf', 'application/pdf', 'image/*')).toBe(false); }); it('should return true when types are the same', () => { expect(isFileAllowed('file.pdf', 'application/pdf', 'application/*')).toBe(true); }); it('should return true when allowedExtensions are empty', () => { expect(isFileAllowed('file.pdf', 'application/pdf', '')).toBe(true); }); it('should return false when file extension is not valid', () => { expect(isFileAllowed('file.pdf', 'application/pdf', '.png')).toBe(false); }); });
d0c76da24d135fb948a06c04c2ef10f19722d60a
TypeScript
Maria-Eduarda-080902/arcade
/base/004/solver.ts
3.5
4
class Grafite { calibre: number; dureza: string; tamanho: number; constructor(calibre: number, dureza: string, tamanho: number) { this.calibre = calibre; this.dureza = dureza; this.tamanho = tamanho; } gastoPorFolha(): number { if (this.dureza === 'HB') return 1; if (this.dureza === '2B') return 2; if (this.dureza === '4B') return 4; if (this.dureza === '6B') return 6; return 0; } toString(): string { //return "Grafite: " + this.calibre + ":" + this.dureza + ":" + this.tamanho; return `Grafite ${this.calibre}:${this.dureza}:${this.tamanho}`; } } //agregação class Lapiseira { calibre: number; private grafite: Grafite | null; constructor(calibre: number) { //é a lapiseira que cria o grafite? this.calibre = calibre; this.grafite = null; } setGrafite(grafite: Grafite): boolean { if (this.grafite != null) { console.log("A lapiseira já possui um grafite"); return false; } if (grafite.calibre != this.calibre) { console.log("O grafite não é compatível com a lapiseira"); return false; } this.grafite = grafite; return true; } removerGrafite(): Grafite | null { if (this.grafite == null) { console.log("A lapiseira não possui um grafite"); return null; } let grafite = this.grafite; this.grafite = null; return grafite; } escrever(folhas: number): boolean { //verificar se existe grafite if (this.grafite == null) { console.log("A lapiseira não possui um grafite"); return false; } let gasto = this.grafite.gastoPorFolha() * folhas; if (gasto <= this.grafite.tamanho) { console.log("Escrita concluida"); this.grafite.tamanho -= gasto; } else { let realizado = this.grafite.tamanho / this.grafite.gastoPorFolha() console.log("Escrita parcial: " + realizado + " folhas"); this.grafite.tamanho = 0; } if (this.grafite.tamanho == 0) { this.grafite = null; } } } let pentel = new Lapiseira(0.5); pentel.setGrafite(new Grafite(0.5, "HB", 40)); pentel.escrever(10); pentel.escrever(40); console.log(pentel);
f49aa011d3a6de5ff92be4a098861733a1252201
TypeScript
TylorS167/167
/src/list/aperture/types.ts
2.578125
3
export interface ApertureArity2 { <A>(n: 0, list: Array<A>): ReadonlyArray<never> <A>(n: 1, list: Array<A>): ReadonlyArray<[A]> | ReadonlyArray<never> <A>(n: 2, list: Array<A>): ReadonlyArray<[A, A]> | ReadonlyArray<never> <A>(n: 3, list: Array<A>): ReadonlyArray<[A, A, A]> | ReadonlyArray<never> <A>(n: 4, list: Array<A>): ReadonlyArray<[A, A, A, A]> | ReadonlyArray<never> <A>(n: 5, list: Array<A>): ReadonlyArray<[A, A, A, A, A]> | ReadonlyArray<never> <A>(n: 6, list: Array<A>): ReadonlyArray<[A, A, A, A, A, A]> | ReadonlyArray<never> <A>(n: 7, list: Array<A>): ReadonlyArray<[A, A, A, A, A, A, A]> | ReadonlyArray<never> <A>(n: 8, list: Array<A>): ReadonlyArray<[A, A, A, A, A, A, A, A]> | ReadonlyArray<never> <A>(n: 9, list: Array<A>): ReadonlyArray<[A, A, A, A, A, A, A, A, A]> | ReadonlyArray<never> <A>(n: number, list: Array<A>): ReadonlyArray<ReadonlyArray<A>> <A>(n: number, list: ArrayLike<A>): ReadonlyArray<ReadonlyArray<A>> <A>(n: 0, list: ReadonlyArray<A>): ReadonlyArray<never> <A>(n: 1, list: ReadonlyArray<A>): ReadonlyArray<[A]> | ReadonlyArray<never> <A>(n: 2, list: ReadonlyArray<A>): ReadonlyArray<[A, A]> | ReadonlyArray<never> <A>(n: 3, list: ReadonlyArray<A>): ReadonlyArray<[A, A, A]> | ReadonlyArray<never> <A>(n: 4, list: ReadonlyArray<A>): ReadonlyArray<[A, A, A, A]> | ReadonlyArray<never> <A>(n: 5, list: ReadonlyArray<A>): ReadonlyArray<[A, A, A, A, A]> | ReadonlyArray<never> <A>(n: 6, list: ReadonlyArray<A>): ReadonlyArray<[A, A, A, A, A, A]> | ReadonlyArray<never> <A>(n: 7, list: ReadonlyArray<A>): ReadonlyArray<[A, A, A, A, A, A, A]> | ReadonlyArray<never> <A>(n: 8, list: ReadonlyArray<A>): ReadonlyArray<[A, A, A, A, A, A, A, A]> | ReadonlyArray<never> <A>(n: 9, list: ReadonlyArray<A>): ReadonlyArray<[A, A, A, A, A, A, A, A, A]> | ReadonlyArray<never> <A>(n: number, list: ReadonlyArray<A>): ReadonlyArray<ReadonlyArray<A>> (n: number): ApertureArity1 } export interface ApertureArity1 { <A>(list: Array<A>): ReadonlyArray<ReadonlyArray<A>> <A>(list: ArrayLike<A>): ReadonlyArray<ReadonlyArray<A>> <A>(list: ReadonlyArray<A>): ReadonlyArray<ReadonlyArray<A>> }
c341b58d1c014af2dbe1328aea76109e4c536fb4
TypeScript
mvetois/MySQLDump
/src/functions.ts
2.78125
3
export const getDate = (date = new Date) : string => { const year : string = String(date.getUTCFullYear()); const month : string = String(date.getUTCMonth()); const day : string = String(date.getUTCDay()); const hours : string = String(date.getUTCHours()); return (year + "_" + month + "_" + day + "_" + hours); }
349ea7d2fcfaa3632a32292af4fd31018da29ee8
TypeScript
enbock/Time-Tracker
/src/Language/Manager.test.ts
2.765625
3
import Loader from './Loader'; import Manager from './Manager'; import Translator, {LanguageData} from './Translator'; import Factory from './Translator/Factory'; describe('Language.Manager', () => { let loaderSpy: jest.MockedFunction<(languageCode: string) => Promise<any>>, createSpy: jest.MockedFunction<(languageData: LanguageData) => Translator>, loader: Loader, factory: Factory; beforeEach(() => { loader = {loadLanguage: jest.fn()}; factory = new Factory(); factory.createTranslator = jest.fn(); loaderSpy = loader.loadLanguage as jest.MockedFunction<typeof loaderSpy>; createSpy = factory.createTranslator as jest.MockedFunction<typeof createSpy>; }); it('Loads language', async () => { const languageData: LanguageData = {'language': 'data'}; const translator: Translator = new Translator(languageData); loaderSpy.mockResolvedValueOnce(languageData); createSpy.mockReturnValueOnce(translator); const manager: Manager = new Manager(loader, factory); const result: Translator = await manager.getTranslator('de-de'); expect(result).toBe(translator); expect(loaderSpy).toHaveBeenCalledWith('de-de'); expect(createSpy).toHaveBeenCalledWith(languageData); }); it('Reuse loaded language translator', async () => { const languageData: LanguageData = {'language': 'data'}; const translator: Translator = new Translator(languageData); loaderSpy.mockResolvedValueOnce(languageData); createSpy.mockReturnValueOnce(translator); const manager: Manager = new Manager(loader, factory); const result1: Translator = await manager.getTranslator('de-de'); expect(result1).toBe(translator); expect(loaderSpy).toHaveBeenCalledWith('de-de'); expect(createSpy).toHaveBeenCalledWith(languageData); const result2: Translator = await manager.getTranslator('de-de'); expect(result2).toBe(translator); expect(loaderSpy).toHaveBeenCalledTimes(1); expect(createSpy).toHaveBeenCalledTimes(1); }); });
9764b64b9ffad8a7ec45601e62b26c9873dbe3db
TypeScript
Flaavius/basic-grpc-example
/src/client/client.ts
2.65625
3
import { createClient, createClientCreds } from "basic-grpc"; import { ILogin } from "../protos/login"; import { join } from "path"; ((async () => { const protoLoaderOptions = { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true }; // accepts and array of Buffers or strings (truple) [ rootCerts, cert_chain, private_key ] // or it can create an insecure connection if nothing is passed const credentials = createClientCreds(); const loginService = createClient<ILogin>({ url: "localhost", // url of the gRPC Server port: "50051", // port of the gRPC server protoPath: join(__dirname, ".." , "protos", "login.proto"), // root folder of your .protoFiles packageName: "login", // packageName (what is defined in the .proto file as package) serviceName: "Login", // serviceName (what is defined in the .proto file as Service) options: protoLoaderOptions, // if not passed it will use the default values credentials, // if not passed it will create an insecure connection calls: [ "login" ] // the available rpc calls to that service defined in the .proto file }); try { // you can then call the login function for the loginService :) // it will return a promise with the data or it Will throw an RPCError with code and details. const data = await loginService.login({ username: "", password: "noooope" }); console.log(JSON.stringify(data, undefined, 2)); } catch ({ code, details }) { console.log("ERR", code, details); } })());
9d826559f86a88b089bd5659dbf1524f9f214fc6
TypeScript
chrissc6/prs-client-solution
/src/app/system/ven-search.pipe.ts
2.640625
3
import { Pipe, PipeTransform } from '@angular/core'; import { Vendor } from '../vendor/vendor.class'; @Pipe({ name: 'venSearch' }) export class VenSearchPipe implements PipeTransform { transform(vendors: Vendor[], crit: string): Vendor[] { if(crit == "") { return vendors; } let arrOut: Vendor[] = []; for(let v of vendors) { if(v.code.toLowerCase().includes(crit.toLowerCase())) { arrOut.push(v); continue; } if(v.name.toLowerCase().includes(crit.toLowerCase())) { arrOut.push(v); continue; } if(v.address.toLowerCase().includes(crit.toLowerCase())) { arrOut.push(v); continue; } if(v.city.toLowerCase().includes(crit.toLowerCase())) { arrOut.push(v); continue; } if(v.state.toLowerCase().includes(crit.toLowerCase())) { arrOut.push(v); continue; } if(v.zip.toLowerCase().includes(crit.toLowerCase())) { arrOut.push(v); continue; } if(v.phone.toLowerCase().includes(crit.toLowerCase())) { arrOut.push(v); continue; } if(v.email.toLowerCase().includes(crit.toLowerCase())) { arrOut.push(v); continue; } } return arrOut; } }
abf0d4f9adccad64c0d654bb9960f8a38d41f052
TypeScript
ThomasDupont/core
/packages/system/src/Stream/Stream/chunks.ts
2.734375
3
import * as A from "../../Collections/Immutable/Chunk" import type { Stream } from "./definitions" import { mapChunks_ } from "./mapChunks" /** * Exposes the underlying chunks of the stream as a stream of chunks of elements */ export function chunks<R, E, A>(self: Stream<R, E, A>): Stream<R, E, A.Chunk<A>> { return mapChunks_(self, A.single) }
e6d4a25ec3c3486df4f13cfc40c7b6a086fa155b
TypeScript
lluixhi/blog
/src/server/entities/User.ts
2.84375
3
import crypto from 'crypto'; import { Entity, Column, PrimaryColumn, OneToMany, OneToOne, BeforeInsert, BeforeUpdate, JoinColumn } from 'typeorm'; import { Post } from './Post'; import { Login } from './Login'; const salt: string = 'picklejuice'; @Entity() export class User { @PrimaryColumn() username!: string; @Column() password!: string; @BeforeInsert() @BeforeUpdate() hashPassword() { if (this.password) { this.password = hash(this.password); } } @Column() email!: string; @OneToMany('Post', 'user') posts!: Post[]; @OneToOne(() => Login) @JoinColumn() login!: Login; } const hash = (password: string): string => { crypto.pbkdf2(password, salt, 200000, 64, 'sha512', (err, derivedKey) => { if (err) throw err; return derivedKey.toString('hex'); }); return ''; } export const comparePassword = (password: string, hashedPassword: string): boolean => { return hash(password).localeCompare(hashedPassword) == 0; }
3fdceb8e474e0b08393329f2c5d93022fe242a8b
TypeScript
dexpenses/dexpenses-extract
/src/extractor/date-time-matchers.ts
2.5625
3
import { DateTime } from 'luxon'; import { MatchersDef, statically } from '../utils/matcher/matcher-def'; function currentYear() { return DateTime.local().setZone('Europe/Berlin').year; } export default { d: { pattern: /(?:[l1-9]|[l12]\d|3[01l])/, replacements: [['l', 1]] }, dd: { pattern: /(?:0[l1-9]|[l12]\d|3[01l])/, replacements: [['l', 1]] }, M: /(?:[1-9]|1[0-2])/, MM: /(?:0[1-9]|1[0-2])/, MMM: /(?:jan|feb|märz|apr|mai|jun|jul|aug|sep|okt|nov|dez)/i, yyyy: { pattern: /(?:19|2\d)\d{2}/, check: (m) => parseInt(m, 10) <= currentYear(), }, yy: { pattern: /[1-6][0-9]/, check(m) { return ( DateTime.fromFormat(m, 'yy', { zone: 'Europe/Berlin', }).year <= currentYear() ); }, }, h: { pattern: /(?:[1i][0-2i]|[1-9])/i, replacements: [['i', 1]], }, HH: { pattern: /(?:[01i][0-9i]|2[0-4i])/i, replacements: [['i', 1]], }, mm: { pattern: /[0-5i][0-9i]/, replacements: [['i', 1]], }, ss: { pattern: /[0-5i][0-9i]/, replacements: [['i', 1]], }, a: /[AP]M/i, ':': statically(/ ?[:;] ?/), '.': statically(/ ?[\.,] ?/), '-': statically(/ ?- ?/), '^': statically(/(?:^| )/, ''), $: statically(/(?: |$)/, ''), } as MatchersDef;
1245d02fa07879d7136aa427ad5f93f9b3ad5b9f
TypeScript
ArrowheadFramework/ahfc-configuration-rest-ws
/source/test/apes/TestWriterAnnotatedXML.ts
2.890625
3
import * as apes from "../../main/apes"; import * as unit from "../unit"; import * as utils from "./utils"; function writeAndCompare(f: (writer: apes.Writer) => void, expected: string) { utils.writeAndCompare(sink => f(new apes.WriterAnnotatedXML(sink)), expected); } export const TestWriterAnnotatedXML: unit.Suite = { name: "WriterAnnotatedXML", units: [ { name: "Write Map of Null", test: recorder => writeAndCompare(writer => writer .writeMap(writer => writer .addNull("a")), '<root semantics="APES" type="Map">' + '<entry key="a" type="Null">null</entry>' + '</root>'), }, { name: "Write Map of Booleans", test: recorder => writeAndCompare(writer => writer .writeMap(writer => writer .addBoolean("a", true) .addBoolean("b", false)), '<root semantics="APES" type="Map">' + '<entry key="a" type="Boolean">true</entry>' + '<entry key="b" type="Boolean">false</entry>' + '</root>'), }, { name: "Write Map of Numbers", test: recorder => writeAndCompare(writer => writer .writeMap(writer => writer .addNumber("A", 1) .addNumber("B", 12) .addNumber("C", 123)), '<root semantics="APES" type="Map">' + '<entry key="A" type="Number">1</entry>' + '<entry key="B" type="Number">12</entry>' + '<entry key="C" type="Number">123</entry>' + '</root>'), }, { name: "Write Map of Texts", test: recorder => writeAndCompare(writer => writer .writeMap(writer => writer .addText("alpha", "Hello") .addText("beta", "<World!>")), '<root semantics="APES" type="Map">' + '<entry key="alpha" type="Text">Hello</entry>' + '<entry key="beta" type="Text">&lt;World!&gt;</entry>' + '</root>'), }, { name: "Write Map of Lists", test: recorder => writeAndCompare(writer => writer .writeMap(writer => writer .addList("a", writer => writer .addNull() .addNull()) .addList("b", writer => writer .addNumber(1) .addBoolean(false))), '<root semantics="APES" type="Map">' + '<entry key="a" type="List">' + '<item type="Null">null</item>' + '<item type="Null">null</item>' + '</entry>' + '<entry key="b" type="List">' + '<item type="Number">1</item>' + '<item type="Boolean">false</item>' + '</entry>' + '</root>'), }, { name: "Write Map of Maps", test: recorder => writeAndCompare(writer => writer .writeMap(writer => writer .addMap("a", writer => writer .addNull("a0") .addNull("a1")) .addMap("b", writer => writer .addNumber("b0", 1) .addBoolean("b1", false))), '<root semantics="APES" type="Map">' + '<entry key="a" type="Map">' + '<entry key="a0" type="Null">null</entry>' + '<entry key="a1" type="Null">null</entry>' + '</entry>' + '<entry key="b" type="Map">' + '<entry key="b0" type="Number">1</entry>' + '<entry key="b1" type="Boolean">false</entry>' + '</entry>' + '</root>'), }, { name: "Write List of Nulls", test: recorder => writeAndCompare(writer => writer .writeList(writer => writer .addNull() .addNull() .addNull()), '<root semantics="APES" type="List">' + '<item type="Null">null</item>' + '<item type="Null">null</item>' + '<item type="Null">null</item>' + '</root>'), }, { name: "Write List of Booleans", test: recorder => writeAndCompare(writer => writer .writeList(writer => writer .addBoolean(false) .addBoolean(true)), '<root semantics="APES" type="List">' + '<item type="Boolean">false</item>' + '<item type="Boolean">true</item>' + '</root>'), }, { name: "Write List of Number", test: recorder => writeAndCompare(writer => writer .writeList(writer => writer .addNumber(1.234e+56)), '<root semantics="APES" type="List">' + '<item type="Number">1.234e+56</item>' + '</root>'), }, { name: "Write List of Texts", test: recorder => writeAndCompare(writer => writer .writeList(writer => writer .addText("Hello") .addText("World!")), '<root semantics="APES" type="List">' + '<item type="Text">Hello</item>' + '<item type="Text">World!</item>' + '</root>'), }, { name: "Write List of Lists", test: recorder => writeAndCompare(writer => writer .writeList(writer => writer .addList(writer => writer .addNull() .addNull()) .addList(writer => writer .addNumber(1) .addBoolean(false))), '<root semantics="APES" type="List">' + '<item type="List">' + '<item type="Null">null</item>' + '<item type="Null">null</item>' + '</item>' + '<item type="List">' + '<item type="Number">1</item>' + '<item type="Boolean">false</item>' + '</item>' + '</root>'), }, { name: "Write List of Maps", test: recorder => writeAndCompare(writer => writer .writeList(writer => writer .addMap(writer => writer .addNull("a0") .addNull("a1")) .addMap(writer => writer .addNumber("b0", 1) .addBoolean("b1", false))), '<root semantics="APES" type="List">' + '<item type="Map">' + '<entry key="a0" type="Null">null</entry>' + '<entry key="a1" type="Null">null</entry>' + '</item>' + '<item type="Map">' + '<entry key="b0" type="Number">1</entry>' + '<entry key="b1" type="Boolean">false</entry>' + '</item>' + '</root>'), }, ] };
3021a12e554ec7f406ceb2552954cee2ae8e2228
TypeScript
jasonaibrahim/thoughts
/spec/functions/SearchFunction.spec.ts
2.625
3
import {SearchFunction, SearchResult} from '../../lib/src/functions/SearchFunction'; import {CLIFunctionHelper} from '../../lib/src/functions/CLIFunctionHelper'; import * as fs from 'fs'; import * as path from 'path'; import * as rimraf from 'rimraf'; import minimist = require('minimist'); describe('SearchFunction', () => { let args = {}; let namespace = '.thoughts-cli-test'; let functionUnderTest: SearchFunction; let storagePath = path.join(__dirname, '..', '..', 'test', 'data'); let topLevelStorageDir = path.join(__dirname, '..', '..', 'test'); beforeEach(() => { args = minimist(['search', 'foo']); }); function initTestDirectory(): Promise<any> { return new Promise((resolve, reject) => { rimraf(storagePath, () => { try { fs.mkdirSync(topLevelStorageDir); } catch (err) { console.log('test data already exists. skipping creation'); } fs.mkdirSync(storagePath); resolve(); }); }); } describe('Run', () => { it('should load content into an internal index', async (done) => { await initTestDirectory(); functionUnderTest = CLIFunctionHelper.instantiateFromArgs(args, namespace, storagePath) as SearchFunction; // no documents exist yet functionUnderTest.find('oracle database profit').subscribe((docs: SearchResult[]) => { expect(docs.length).toEqual(0); // add 3 documents to test storage path. one of them contains the string `foo` fs.writeFileSync(`${storagePath}/1.txt`, 'yesterday Oracle has released its new database Oracle 12g, this would make more money for this company and lead to a nice profit report of annual year.'); fs.writeFileSync(`${storagePath}/2.txt`, 'As expected, Oracle released its profit report of 2015, during the good sales of database and hardware, Oracle profit of 2015 reached 12.5 Billion.'); fs.writeFileSync(`${storagePath}/3.txt`, 'If music be the food of love, play on: Give me excess of it'); // one document should be returned containing the text `foo` functionUnderTest.find('oracle database profit').subscribe((results: SearchResult[]) => { expect(results.length).toEqual(2); done(); }); }); }); }); });
bc699726e901a5b6d0615f5dcd0a2606043d4337
TypeScript
LabES-2021-Q3-AppJusto/admin
/src/common/components/form/input/pattern-input/formatters.ts
2.953125
3
export const cpfMask = '000.000.000-00'; export const cpfFormatter = (value: string = '') => { return value.split('').reduce((result, digit, index) => { if (index === 3 || index === 6) return `${result}.${digit}`; if (index === 9) return `${result}-${digit}`; return `${result}${digit}`; }, ''); }; export const cnpjMask = '00.000.000/0000-00'; export const cnpjFormatter = (value: string = '') => { return value.split('').reduce((result, digit, index) => { if (index === 2 || index === 5) return `${result}.${digit}`; if (index === 8) return `${result}/${digit}`; if (index === 12) return `${result}-${digit}`; return `${result}${digit}`; }, ''); }; export const cepMask = '00000-000'; export const cepFormatter = (value: string | undefined) => { if (!value) return ''; if (value.length <= 5) return value; return [value.slice(0, 5), value.slice(5)].join('-'); }; export const phoneMask = '(81) 99999-9999'; export const phoneFormatter = (value: string | undefined) => { let formatedNumber = ''; if (value) { const ddd = value.slice(0, 2); let firstPart; let secondPart; if (value.length < 11) { firstPart = value.slice(2, 6); secondPart = value.slice(6, 10); } else { firstPart = value.slice(2, 7); secondPart = value.slice(7, 11); } if (secondPart === '' && firstPart !== '') { formatedNumber = `(${ddd}) ${firstPart}`; } else if (secondPart === '' && firstPart === '') { formatedNumber = `(${ddd}`; } else { formatedNumber = `(${ddd}) ${firstPart}-${secondPart}`; } } return formatedNumber; }; export const TimeMask = '00:00'; export const TimeFormatter = (value: string | undefined) => { let formatedNumber = ''; if (value) { let hours = value.slice(0, 2); let minutes = value.slice(2, 4); if (parseInt(hours) > 23) { hours = '00'; } if (parseInt(minutes) > 59) { minutes = '00'; } if (minutes === '') { formatedNumber = `${hours}`; } else if (minutes !== '') { formatedNumber = `${hours}:${minutes}`; } } return formatedNumber; }; export const hyphenFormatter = (hyphenLocation: number) => (value: string | undefined) => { if (!value) return ''; if (hyphenLocation < 0) return value; if (value.length <= hyphenLocation) return value; return [value.slice(0, hyphenLocation), value.slice(hyphenLocation)].join('-'); }; export const addZerosToBeginning = (account: string, patterLen: number) => { const accountLen = account.length; if (patterLen > accountLen) { const diff = patterLen - accountLen; let zeros = ''; for (let i = 0; i < diff; i++) { zeros += '0'; } return `${zeros + account}`; } else { return account; } };
ceed5c240b3b2dbffcabc1b4f1844914b0cce10f
TypeScript
daryl-cecile/AlphaDeck-Mock-Stock-Market-client
/public/scripts/XModal.ts
2.859375
3
enum XModalType{ INFORMATION, WARNING, ALERT, QUESTION } enum XModalButtonType{ PRIMARY, DANGER, CANCEL } interface XModalButtons { [buttonIdentifier:string]:{ type: XModalButtonType, text: string, callback?: Function }; } class XModal extends HTMLElement{ private _shadow:ShadowRoot = null; private _title:string = ""; private _message:string = ""; private _type:XModalType = XModalType.INFORMATION; static get observedAttributes() { return ['type','open']; } constructor(message:string=null, title:string="Message", type:XModalType=XModalType.INFORMATION) { super(); this._shadow = this.attachShadow({ mode: "closed" }); this._type = type; this._message = message; this._title = title ? title : this._getTitle(); let eb = Tools.ElementBuilder; let s = eb("link",{ href: "/public/styles/xmodal.css", rel: "stylesheet" }).create(); let h3 = eb("h3", {id:"title"} ,this._title).create(); let p = eb("p",{id:"message"}, this._message).create(); let div = eb("div",{id : "btn-container"}).create(); this._shadow.appendChild(s); this._shadow.appendChild(h3); this._shadow.appendChild(p); this._shadow.appendChild(div); this.style.display = "none"; document.body.appendChild(this); } private _getTitle(){ switch (this._type) { case XModalType.INFORMATION: return "Information"; case XModalType.WARNING: return "Important!"; case XModalType.ALERT: return "Attention!"; case XModalType.QUESTION: return "Are you sure?"; } } private _getButtonClass(buttonType:XModalButtonType){ this._title = this._title + ""; switch (buttonType) { case XModalButtonType.PRIMARY: return "primary filled"; case XModalButtonType.DANGER: return "danger filled"; case XModalButtonType.CANCEL: return ""; } } public setType(type:XModalType){ this._type = type; return this; } public setTitle(title:string){ this._title = title; return this; } public setMessage(message:string){ this._message = message; return this; } close(){ this.setAttribute("open","close"); return new Promise(resolve => { setTimeout(()=>{ this.remove(); resolve(); },300); }); } open(buttons:XModalButtons){ setTimeout(()=>{ let eb = Tools.ElementBuilder; let el = this._shadow.querySelector("#btn-container"); el.innerHTML = ""; this._shadow.querySelector("#title").innerHTML = this._title; this._shadow.querySelector("#message").innerHTML = this._message; Object.keys(buttons).forEach(buttonIdentifier => { let buttonInfo = buttons[buttonIdentifier]; let button = eb("button",{ id: buttonIdentifier, class: this._getButtonClass(buttonInfo.type) }, buttonInfo.text).create(); button.addEventListener("click", (e)=>{ if (buttonInfo.callback) buttonInfo.callback(e); this.close(); }); el.appendChild(button); }); if (this.isConnected === false){ document.body.appendChild(this); } this.removeAttribute("style"); setTimeout(()=>{ this.setAttribute("open","true"); },300); }, 10); } } customElements.define('x-modal', XModal);
78441d0381b2b7d7b7cb64b869cc8c2ca3050f45
TypeScript
lotooo/terraforming-mars
/src/cards/ArtificialLake.ts
2.671875
3
import {IProjectCard} from './IProjectCard'; import {Tags} from './Tags'; import {CardType} from './CardType'; import {Player} from '../Player'; import {Game} from '../Game'; import {ISpace} from '../ISpace'; import {SelectSpace} from '../inputs/SelectSpace'; import {SpaceType} from '../SpaceType'; import * as constants from '../constants'; export class ArtificialLake implements IProjectCard { public cost: number = 15; public tags: Array<Tags> = [Tags.STEEL]; public name: string = 'Artificial Lake'; public cardType: CardType = CardType.AUTOMATED; public canPlay(player: Player, game: Game): boolean { return game.getTemperature() >= -6 - ( player.getRequirementsBonus(game) * 2 ); } public play(player: Player, game: Game) { if (game.board.getOceansOnBoard() >= constants.MAX_OCEAN_TILES) return undefined; return new SelectSpace( 'Select a land space to place an ocean', game.board.getAvailableSpacesOnLand(player), (foundSpace: ISpace) => { game.addOceanTile(player, foundSpace.id, SpaceType.LAND); return undefined; } ); } public getVictoryPoints() { return 1; } }
1fe276460afb8d2cc0e4dadc615eea2c0f95068f
TypeScript
gregbacchus/validata
/src/boolean.test.ts
3.140625
3
import { asBoolean, isBoolean, maybeAsBoolean, maybeBoolean } from './boolean'; import { expectIssue, expectSuccess, expectValue, runTests } from './test-helpers'; describe('isBoolean', () => { it('incorrect type will cause an issue', () => { const fut = isBoolean(); runTests(fut, { input: 'test', issues: [{ reason: 'incorrect-type' }] }, { input: 123, issues: [{ reason: 'incorrect-type' }] }, { input: new Date(), issues: [{ reason: 'incorrect-type' }] }, { input: [], issues: [{ reason: 'incorrect-type' }] }, { input: {}, issues: [{ reason: 'incorrect-type' }] }, ); }); it('null, undefined or NaN will cause an issue', () => { const fut = isBoolean(); runTests(fut, { input: null, issues: [{ reason: 'not-defined' }] }, { input: undefined, issues: [{ reason: 'not-defined' }] }, { input: NaN, issues: [{ reason: 'incorrect-type' }] }, ); }); it('will accept boolean', () => { const fut = isBoolean(); expectSuccess(fut, true); expectSuccess(fut, false); }); it('will check custom validator', () => { const fut = isBoolean({ validator: (value) => !value }); expectSuccess(fut, false); expectIssue(fut, true, 'validator'); }); }); describe('maybeBoolean', () => { it('incorrect type will cause issue', () => { const fut = maybeBoolean(); expectIssue(fut, 'test', 'incorrect-type'); expectIssue(fut, 123, 'incorrect-type'); expectIssue(fut, new Date(), 'incorrect-type'); expectIssue(fut, [], 'incorrect-type'); expectIssue(fut, {}, 'incorrect-type'); }); it('incorrect type will not cause issue', () => { const fut = maybeBoolean({ incorrectTypeToUndefined: true }); expectValue(fut, 'test', undefined); expectValue(fut, 123, undefined); expectValue(fut, new Date(), undefined); expectValue(fut, [], undefined); expectValue(fut, {}, undefined); }); it('null, undefined will be coerced to undefined', () => { const fut = maybeBoolean(); expectValue(fut, null, undefined); expectValue(fut, undefined, undefined); }); it('will handle boolean', () => { const fut = maybeBoolean(); expectSuccess(fut, true); expectSuccess(fut, false); }); it('will check custom validator', () => { const fut = maybeBoolean({ validator: (value) => !value }); expectSuccess(fut, false); expectIssue(fut, true, 'validator'); }); }); describe('asBoolean', () => { it('null or undefined will be an issue', () => { const fut = asBoolean(); expectIssue(fut, null, 'not-defined'); expectIssue(fut, undefined, 'not-defined'); }); it('incorrect type with no conversion will be an issue', () => { const fut = asBoolean(); expectIssue(fut, 'test', 'no-conversion'); expectIssue(fut, [], 'no-conversion'); expectIssue(fut, {}, 'no-conversion'); }); it('Values will be converted', () => { const fut = asBoolean(); expectValue(fut, 'true', true); expectValue(fut, 'false', false); expectValue(fut, '', false); expectValue(fut, 0, false); expectValue(fut, NaN, false); expectValue(fut, 1, true); expectValue(fut, 123, true); expectValue(fut, -123, true); }); it('Custom values will be converted by custom converter', () => { const fut = asBoolean({ converter: (value) => value === 'yes' ? true : value === 'no' ? false : undefined }); expectValue(fut, 'yes', true); expectValue(fut, 'no', false); expectIssue(fut, 'maybe', 'no-conversion'); }); it('incorrect type that cannot be converted will have default used', () => { const fut = asBoolean({ default: false }); expectValue(fut, true, true); expectValue(fut, false, false); expectValue(fut, null, false); expectValue(fut, undefined, false); expectValue(fut, 'test', false); expectValue(fut, '123.4', false); expectValue(fut, [], false); expectValue(fut, {}, false); expectValue(fut, NaN, false); }); it('will handle boolean', () => { const fut = asBoolean(); expectSuccess(fut, true); expectSuccess(fut, false); }); it('will check custom validator', () => { const fut = asBoolean({ validator: (value) => !value }); expectSuccess(fut, false); expectIssue(fut, true, 'validator'); }); }); describe('maybeAsBoolean', () => { it('incorrect type will be converted to undefined', () => { const fut = maybeAsBoolean(); expectValue(fut, 'test', undefined); expectValue(fut, [], undefined); expectValue(fut, ['test'], undefined); expectValue(fut, {}, undefined); }); it('Values will be converted', () => { const fut = maybeAsBoolean(); expectValue(fut, 'true', true); expectValue(fut, 'false', false); expectValue(fut, '', false); expectValue(fut, 0, false); expectValue(fut, NaN, false); expectValue(fut, 1, true); expectValue(fut, 123, true); expectValue(fut, -123, true); }); it('Custom values will be converted by custom converter', () => { const fut = maybeAsBoolean({ converter: (value) => value === 'yes' ? true : value === 'no' ? false : undefined }); expectValue(fut, 'yes', true); expectValue(fut, 'no', false); expectValue(fut, 'maybe', undefined); }); it('null or undefined will be converted to undefined', () => { const fut = maybeAsBoolean(); expectValue(fut, null, undefined); expectValue(fut, undefined, undefined); }); it('incorrect type, null, undefined or NaN that cannot be converted will have default used', () => { const fut = maybeAsBoolean({ default: false }); expectValue(fut, true, true); expectValue(fut, false, false); expectValue(fut, null, false); expectValue(fut, undefined, false); expectValue(fut, 'test', false); expectValue(fut, '123.4', false); expectValue(fut, [], false); expectValue(fut, {}, false); expectValue(fut, NaN, false); }); it('will handle boolean', () => { const fut = maybeAsBoolean(); expectSuccess(fut, 123); expectSuccess(fut, 0); expectSuccess(fut, 1.23234); expectSuccess(fut, -1.23234); }); it('will check custom validator', () => { const fut = maybeAsBoolean({ validator: (value) => !value }); expectSuccess(fut, false); expectIssue(fut, true, 'validator'); }); });
8d3250d34584a9935fab535fb584af42dec5a77e
TypeScript
johanneslumpe/styled-props
/src/utils/fonts/fontVariant.ts
2.75
3
import { FontVariantProperty } from '@johanneslumpe/css-types'; import { style } from '../../style'; import { StyleOptions } from '../../types'; export interface FontVariantProps<T> { /** * The **font-variant** CSS property is a shorthand for the longhand properties `font-variant-caps`, `font-variant-numeric`, `font-variant-alternates`, `font-variant-ligatures`, and `font-variant-east-asian`. You can also set the CSS Level 2 (Revision 1) values of `font-variant`, (that is, `normal` or `small-caps`), by using the `font` shorthand. * * @see https://developer.mozilla.org/docs/Web/CSS/font-variant */ style$FontVariant: T; } export const fontVariant = < T = FontVariantProperty, Theme = never, Breakpoints = never >({ themeProp, }: Partial<StyleOptions<FontVariantProps<T>, Theme>> = {}) => style<FontVariantProps<T>, Theme, Breakpoints>({ cssProp: 'fontVariant', prop: 'style$FontVariant', themeProp, });
45d9d80d8a000c4d9e41f1146026a4004e915a80
TypeScript
subspace/subspace-core
/src/experiments/consensus.ts
2.609375
3
// setup phase // generate many random values (through hashing) // add them to a binary search tree // evaluation phase // given a random challenge // find all values within some minimum proximity (take the subtree)
c464148e0d5e388332ce8824a9c3c9cbb64f52df
TypeScript
zfs533/game_lobby
/test/assets/script/g-ebg/ebgAudio.ts
2.53125
3
//游戏相关音效 import Audio from "../g-share/audio" const { ccclass, property } = cc._decorator @ccclass export default class EbgnAudio extends Audio { //游戏背景 @property({ type: cc.AudioClip }) private bgm: cc.AudioClip = undefined //游戏开始 提示 @property({ type: cc.AudioClip }) private StartGame: cc.AudioClip = undefined; //开始下注 @property({ type: cc.AudioClip }) private StartDoBet: cc.AudioClip = undefined; //stop下注 @property({ type: cc.AudioClip }) private StopBoBets: cc.AudioClip = undefined; //下注 @property({ type: cc.AudioClip }) private DoBet: cc.AudioClip = undefined; //骰子 @property({ type: cc.AudioClip }) private Dice: cc.AudioClip = undefined; //金币 @property({ type: cc.AudioClip }) private coin: cc.AudioClip = undefined //发牌 @property({ type: cc.AudioClip }) private sendCard: cc.AudioClip = undefined //赢 @property({ type: cc.AudioClip }) private win: cc.AudioClip = undefined //输 @property({ type: cc.AudioClip }) private lose: cc.AudioClip = undefined //牌型 @property({ type: cc.AudioClip }) private CardTyep: cc.AudioClip[] = [] //同杀 @property({ type: cc.AudioClip }) private TSTP_Win: cc.AudioClip = undefined //同赔 @property({ type: cc.AudioClip }) private TSTP_Lose: cc.AudioClip = undefined onLoad() { this.playMusic() } A_TSTP_Win() { this.play(this.TSTP_Win) } A_TSTP_Lose() { this.play(this.TSTP_Lose) } playMusic() { Audio.playMusic(this.bgm) } playgameStart() { this.play(this.StartGame) } startDoBets() { this.play(this.StartDoBet); } StopDoBets() { this.play(this.StopBoBets); } DoBets() { this.play(this.DoBet); } aDice() { this.play(this.Dice) } Aduio_CardType(index: number) { this.play(this.CardTyep[index]); } playCoin() { this.play(this.coin) } playSendCard() { this.play(this.sendCard) } playWin() { this.play(this.win) } playLose() { this.play(this.lose) } onDestroy() { this.stopMusic() } }
61898c75e43f60237c78c1e0f5ef7915fbec8580
TypeScript
robin-thomas/twitr
/assembly/model.ts
2.515625
3
// Exporting a new class Tweet so it can be used outside of this file. export class Tweet { id: i32; sender: string; text: string; author: string; created: string; avatar: string; img: string; likes: i32; likeHistory: Array<String> retweets: i32; retweetHistory: Array<String> hasLiked: bool; hasRetweeted: bool; deleted: bool; } export class TweetLike { likes: i32; hasLiked: bool; } export class TweetRetweet { retweets: i32; hasRetweeted: bool; retweet: Tweet; }
17158b0452871b3206b851735427dadfce528600
TypeScript
shawbena/dom-scripting
/improved-gallery/index.ts
2.5625
3
import './index.css'; import { addLoadEvent } from '../lib'; function showPic(whichPic: HTMLAnchorElement): boolean { let source = whichPic.getAttribute('href'); let placeholder = document.getElementById('placeholder'); let description = document.getElementById('description'); if(!placeholder){ return false; } if (placeholder.nodeName != 'IMG') { return false; } placeholder.setAttribute('src', source as string); if (description) { let text = whichPic.getAttribute('title') || ''; if(description.firstChild && description.firstChild.nodeType === 3){ description.firstChild.nodeValue = text; } } return true; } function prepareGallary(): void { if (!document.getElementsByTagName) { return; } if (!document.getElementById) { return; } if (!document.getElementById('imagegallery')) { return; } let gallery = document.getElementById('imagegallery'); if(gallery){ let links = gallery.getElementsByTagName('a'); for (let i = 0; i < links.length; i++) { links[i].onclick = function(this: HTMLElement) { return !showPic(this as HTMLAnchorElement); }; } } } addLoadEvent(prepareGallary);
65df7e69302cbdbc2c83880965f5f050b708c1fe
TypeScript
Source-Research/async-validator
/__tests__/array.spec.ts
2.890625
3
import Schema from '../src'; describe('array', () => { it('works for type', done => { new Schema({ v: { type: 'array', }, }).validate( { v: '', }, errors => { expect(errors.length).toBe(1); expect(errors[0].message).toBe('v is not an array'); done(); }, ); }); it('works for type and required', done => { new Schema({ v: { required: true, type: 'array', }, }).validate( { v: '', }, (errors, fields) => { expect(errors.length).toBe(1); expect(fields).toMatchInlineSnapshot(` Object { "v": Array [ Object { "field": "v", "fieldValue": "", "message": "v is not an array", }, ], } `); expect(errors[0].message).toBe('v is not an array'); done(); }, ); }); it('works for none require', done => { new Schema({ v: { type: 'array', }, }).validate( { v: [], }, errors => { expect(errors).toBe(null); done(); }, ); }); it('works for empty array', done => { new Schema({ v: { required: true, type: 'array', }, }).validate( { v: [], }, errors => { expect(errors.length).toBe(1); expect(errors[0].message).toBe('v is required'); done(); }, ); }); it('works for undefined array', done => { new Schema({ v: { type: 'array', }, }).validate( { v: undefined, }, errors => { expect(errors).toBe(null); done(); }, ); }); it('works for undefined array and required', done => { new Schema({ v: { required: true, type: 'array', }, }).validate( { v: undefined, }, errors => { expect(errors.length).toBe(1); expect(errors[0].message).toBe('v is required'); done(); }, ); }); it('works for undefined array and defaultField', done => { new Schema({ v: { type: 'array', defaultField: { type: 'string' }, }, }).validate( { v: undefined, }, errors => { expect(errors).toBe(null); done(); }, ); }); it('works for null array', done => { new Schema({ v: { required: true, type: 'array', }, }).validate( { v: null, }, errors => { expect(errors.length).toBe(1); expect(errors[0].message).toBe('v is required'); done(); }, ); }); it('works for none empty', done => { new Schema({ v: { required: true, type: 'array', message: 'haha', }, }).validate( { v: [1], }, errors => { expect(errors).toBe(null); done(); }, ); }); it('works for empty array with min', done => { new Schema({ v: { min: 1, max: 3, type: 'array', }, }).validate( { v: [], }, errors => { expect(errors.length).toBe(1); expect(errors[0].message).toBe('v must be between 1 and 3 in length'); done(); }, ); }); it('works for empty array with max', done => { new Schema({ v: { min: 1, max: 3, type: 'array', }, }).validate( { v: [1, 2, 3, 4], }, errors => { expect(errors.length).toBe(1); expect(errors[0].message).toBe('v must be between 1 and 3 in length'); done(); }, ); }); });
21ca1b9eb46956f650e7c973ca15052daae19115
TypeScript
simpler-one/node.state-machine
/src/state-machine/type-wrapper/named-state-type.ts
2.84375
3
import { StateChangedEvent } from "../../event-args"; import { NamedState, OnEnterState, OnLeaveState, StateType } from "../../interface"; export class NamedType<S extends NamedState, A extends string, P> implements StateType<S, A, P>, OnEnterState.Any, OnLeaveState.Any { public get name(): string { return this.state.name; } public readonly onEnterState: (event: StateChangedEvent<S, A, P>) => void; public readonly onLeaveState: (event: StateChangedEvent<S, A, P>) => void; constructor( private readonly state: S, ) { this.onEnterState = OnEnterState.get(state); this.onLeaveState = OnLeaveState.get(state); } public getState(): S { return this.state; } }
e015ee1094d7d4bb7b14e8fdb484b061b63bf566
TypeScript
carnesen/cli
/packages/cli/src/__tests__/c-cli-description.test.ts
3.015625
3
import { CCliDescription, renderCCliDescription, RenderCCliDescriptionOptions, } from '../c-cli-description'; import { cCliColorFactory } from '../c-cli-color-factory'; import { CCliColor } from '../c-cli-color'; const data: { title: string; description: CCliDescription; text: string; }[] = [ { title: 'Returns an empty string when passed undefined', description: undefined, text: '', }, { title: 'Returns the string if provided one', description: 'foo', text: 'foo', }, { title: 'Runs the function if provided one', description() { return 'foo'; }, text: 'foo', }, { title: 'Runs the function injecting the correct ansi', description(input) { return input.color.red('foo'); }, text: 'bar', }, ]; const color: CCliColor = { ...cCliColorFactory(false), red() { return 'bar'; }, }; const options: RenderCCliDescriptionOptions = { color, }; describe(renderCCliDescription.name, () => { for (const { title, description, text: output } of data) { it(title, () => { expect(renderCCliDescription(description, options)).toBe(output); }); } it('throws if provided an invalid description', () => { expect(() => renderCCliDescription(42 as any as string, options)).toThrow( 'Unexpected description', ); }); });
2073afff62f1fafd8ba61af75d7d8538ffb6e727
TypeScript
0xGabi/connect
/packages/connect-core/src/utils/address.ts
3.34375
3
import { ethers } from 'ethers' export const ANY_ENTITY = '0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF' /** * Checks if the given string is a checksummed address * * @method checkAddressChecksum * @param {String} address the given HEX address * @return {Boolean} */ function checkAddressChecksum(address: string): boolean { // Check each case address = address.replace(/^0x/i, '') const addressHash = ethers.utils .keccak256(address.toLowerCase()) .replace(/^0x/i, '') for (let i = 0; i < 40; i++) { // the nth letter should be uppercase if the nth digit of casemap is 1 if ( (parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i]) ) { return false } } return true } /** * Checks if the given string is an address * * @method isAddress * @param {String} address the given HEX address * @return {Boolean} */ export function isAddress(address: string): boolean { // check if it has the basic requirements of an address if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { return false // If it's ALL lowercase or ALL upppercase } else if ( /^(0x|0X)?[0-9a-f]{40}$/.test(address) || /^(0x|0X)?[0-9A-F]{40}$/.test(address) ) { return true // Otherwise check each case } else { return checkAddressChecksum(address) } } // Check address equality without checksums export function addressesEqual(first: string, second: string): boolean { first = first && first.toLowerCase() second = second && second.toLowerCase() return first === second } // "Safer" version of [].includes() for addresses export function includesAddress(arr: string[], address: string): boolean { return arr.some((a) => addressesEqual(a, address)) }
3406b7e8b4319688f0d0c228123e7b7f04a57e59
TypeScript
bizoru/angular-io-datepicker
/src/datepicker/selectors/minuteSelector.ts
2.5625
3
import { Component, EventEmitter, Input, Output } from "@angular/core"; import { Moment } from "moment"; import { AbstractSelector } from "./abstractSelector"; @Component({ selector: "minute-selector", styles: [ `.date-set{line-height:2em;text-align:center;vertical-align:middle}.date-set.hidden{display:none}.date-set__dates{display:flex;flex-direction:row;margin:0;padding:0;list-style-type:none;flex-wrap:wrap;justify-content:space-between;align-items:stretch}.date-set__date{cursor:pointer;flex-grow:1;flex-shrink:0;flex-basis:33%}` ], template: ` <div class="date-set"> <ul class="date-set__dates"> <li *ngFor="let minute of minutes()" [ngClass]=" { 'date-set__date': true }" (mousedown)="dateChange.emit(minute); $event.preventDefault(); $event.stopPropagation();"> {{ minute.format("mm") }} </li> </ul> </div> ` }) export class MinuteSelector extends AbstractSelector { @Input() public date: Moment; @Output() public dateChange: EventEmitter<Moment>; @Output() public dateSelected: EventEmitter<Moment>; @Output() public modeChanged: EventEmitter<any>; public minutes(): Moment[] { const result: Moment[] = []; for (let i = 0; i < 60; i = i + 5) { result.push(this.value.clone().minute(i)); } return result; } }
3f760094b1a58b2e8eacef2492c691dd18da087a
TypeScript
StoneT2000/brain.js
/src/cross-validate.ts
2.625
3
import NeuralNetwork from './neural-network'; import { INeuralNetworkBinaryTestResult, INeuralNetworkOptions, INeuralNetworkTestResult, INeuralNetworkTrainingData, INeuralNetworkTrainingOptions, } from './neural-network-types'; export type ICrossValidateOptions = INeuralNetworkOptions; export type ICrossValidateJSON = | ICrossValidateStats | ICrossValidateBinaryStats; export interface ICrossValidateStatsAverages { trainTime: number; testTime: number; iterations: number; error: number; } export interface ICrossValidateStats { avgs: ICrossValidateStatsAverages; stats: ICrossValidateStatsResultStats; sets: ICrossValidationTestPartitionResults[]; } export interface ICrossValidateBinaryStats { avgs: ICrossValidateStatsAverages; stats: ICrossValidateStatsResultBinaryStats; sets: ICrossValidationTestPartitionBinaryResults[]; } export interface ICrossValidateStatsResultStats { total: number; testSize: number; trainSize: number; } export interface ICrossValidateStatsResultBinaryStats extends ICrossValidateStatsResultStats { total: number; truePos: number; trueNeg: number; falsePos: number; falseNeg: number; precision: number; recall: number; accuracy: number; } export interface ICrossValidationTestPartitionResults extends INeuralNetworkTestResult { trainTime: number; testTime: number; iterations: number; learningRate: number; hiddenLayers: number[]; network: NeuralNetwork; total: number; } export type ICrossValidationTestPartitionBinaryResults = INeuralNetworkBinaryTestResult & ICrossValidationTestPartitionResults; export default class CrossValidate { Classifier: typeof NeuralNetwork; options: ICrossValidateOptions = {}; json: ICrossValidateJSON | null = null; /** * * @param {NeuralNetwork|constructor} Classifier * @param {object} [options] */ constructor( Classifier: typeof NeuralNetwork, options: ICrossValidateOptions = {} ) { this.Classifier = Classifier; this.options = options; } testPartition<T>( trainOpts: INeuralNetworkTrainingOptions, trainSet: INeuralNetworkTrainingData[] | T[], testSet: INeuralNetworkTrainingData[] | T[] ): | ICrossValidationTestPartitionResults | ICrossValidationTestPartitionBinaryResults { const classifier = new this.Classifier(this.options); const beginTrain = Date.now(); const trainingStats = classifier.train(trainSet, trainOpts); const beginTest = Date.now(); const testStats: | INeuralNetworkTestResult | INeuralNetworkBinaryTestResult = classifier.test(testSet); const endTest = Date.now(); const stats: | ICrossValidationTestPartitionResults | ICrossValidationTestPartitionBinaryResults = { ...testStats, trainTime: beginTest - beginTrain, testTime: endTest - beginTest, iterations: trainingStats.iterations, error: trainingStats.error, total: testStats.total, // TODO: fix these type assertions once neural network types are all typed learningRate: (classifier.trainOpts as any).learningRate, hiddenLayers: (classifier as any).hiddenLayers, network: classifier.toJSON(), }; return stats; } /** * Randomize array element order in-place. * Using Durstenfeld shuffle algorithm. * source: http://stackoverflow.com/a/12646864/1324039 */ shuffleArray<K>(array: K[]): K[] { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); const temp = array[i]; array[i] = array[j]; array[j] = temp; } return array; } static isBinaryStats = ( stats: ICrossValidateStatsResultStats | ICrossValidateStatsResultBinaryStats ): stats is ICrossValidateStatsResultBinaryStats => { return ( (stats as ICrossValidateStatsResultBinaryStats).accuracy !== undefined ); }; static isBinaryResults = ( stats: ICrossValidateStats | ICrossValidateBinaryStats ): stats is ICrossValidateBinaryStats => (stats as ICrossValidateBinaryStats).stats.accuracy !== undefined; static isBinaryPartitionResults = ( stats: | ICrossValidationTestPartitionResults | ICrossValidationTestPartitionBinaryResults ): stats is ICrossValidationTestPartitionBinaryResults => (stats as ICrossValidationTestPartitionBinaryResults).accuracy !== undefined; train<T>( data: INeuralNetworkTrainingData[] | T[], trainOpts: INeuralNetworkTrainingOptions = {}, k = 4 ): ICrossValidateStats { if (data.length < k) { throw new Error( `Training set size is too small for ${data.length} k folds of ${k}` ); } this.shuffleArray<INeuralNetworkTrainingData | T>(data); const size = data.length / k; const avgs: ICrossValidateStatsAverages = { trainTime: 0, testTime: 0, iterations: 0, error: 0, }; const stats: | ICrossValidateStatsResultStats | ICrossValidateStatsResultBinaryStats = { total: 0, testSize: 0, trainSize: 0, }; const binaryStats: ICrossValidateStatsResultBinaryStats = { total: 0, testSize: 0, trainSize: 0, truePos: 0, trueNeg: 0, falsePos: 0, falseNeg: 0, precision: 0, recall: 0, accuracy: 0, }; const results = []; let isBinary = null; for (let i = 0; i < k; i++) { const dclone = data.slice(0); const testSet = dclone.splice(i * size, size); const trainSet = dclone; const result = this.testPartition(trainOpts, trainSet, testSet); if (isBinary === null) { isBinary = result.hasOwnProperty('falseNeg') && result.hasOwnProperty('falsePos') && result.hasOwnProperty('trueNeg') && result.hasOwnProperty('truePos'); if (isBinary) { Object.assign(stats, binaryStats); } } avgs.iterations += result.iterations; avgs.testTime += result.testTime; avgs.trainTime += result.trainTime; avgs.error += result.error; stats.total += result.total; if ( CrossValidate.isBinaryStats(stats) && CrossValidate.isBinaryPartitionResults(result) ) { stats.accuracy += result.accuracy; stats.falseNeg += result.falseNeg; stats.falsePos += result.falsePos; stats.precision += result.precision; stats.recall += result.recall; stats.trueNeg += result.trueNeg; stats.truePos += result.truePos; } results.push(result); } avgs.error /= k; avgs.iterations /= k; avgs.testTime /= k; avgs.trainTime /= k; if (CrossValidate.isBinaryStats(stats)) { stats.precision = stats.truePos / (stats.truePos + stats.falsePos); stats.recall = stats.truePos / (stats.truePos + stats.falseNeg); stats.accuracy = (stats.trueNeg + stats.truePos) / stats.total; } stats.testSize = size; stats.trainSize = data.length - size; this.json = { avgs: avgs, stats: stats, sets: results, }; return this.json; } toNeuralNetwork(): NeuralNetwork { if (this.json == null) { throw new Error( 'CV json is null, you must call .train() first before getting the neural network' ); } return this.fromJSON(this.json); } toJSON(): ICrossValidateJSON | null { return this.json; } fromJSON(crossValidateJson: ICrossValidateJSON): NeuralNetwork { const Classifier = this.Classifier; const json: | ICrossValidationTestPartitionResults | ICrossValidationTestPartitionBinaryResults = (crossValidateJson as ICrossValidateStats).sets.reduce( (prev, cur) => (prev.error < cur.error ? prev : cur) ); if (Classifier.fromJSON) { return Classifier.fromJSON(json); } const instance = new Classifier(this.options); instance.fromJSON(json.network); return instance; } }
0d2478a9ef0f38c137869752a4126da9de800f5d
TypeScript
thatvineyard/songbook
/backend/src/database/entry.ts
2.9375
3
import { randomBytes } from 'crypto'; import { Id, IdGenerator } from './id'; export class Entry<T extends object> { id: Id; type: string; revision: number; created: Date; lastModified: Date; entryData: T | null; constructor(entryData: T | null, idGenerator: IdGenerator) { this.entryData = entryData; if (entryData != null) { this.type = entryData.constructor.name; } else { this.type = 'null'; } this.id = idGenerator.generate(); this.revision = 1; this.created = new Date(); this.lastModified = this.created; } public update(newEntryData: T | null) { this.entryData = newEntryData; if (newEntryData != null) { this.type = newEntryData.constructor.name; } else { this.type = 'null'; } this.revision += 1; this.lastModified = new Date(); } public getId(): string { return this.id.toString(); } public idEquals(otherId: string): boolean { return this.id.toString() === otherId; } }
3b338aef7c282bc95976849680600f53093b3aa6
TypeScript
HenryAlms/research-assistant
/src-outline/src/project-view.ts
2.59375
3
import {Source} from './source'; import {Model} from './model'; import {Observer} from './observer'; import {ProjectController as Controller} from './projectControl'; export class ProjectView implements Observer { //HTML reference protected docRef:NodeList = document.getElementsByTagName("input"); //on input, check val. if project, update display private newProj:HTMLInputElement; private selectedProj:string; // protected logIn:HTMLElement = document.getElementById("logIn") Get user info from index.js protected loginBtn:HTMLInputElement; private user:string|null = null; //Refence current move //add variable to store action private controller:Controller; constructor(private model:Model) { this.controller = new Controller(this, model); this.newProj = document.getElementById("newP") as HTMLInputElement; this.newProj.addEventListener("click", () => this.addNewProject()); this.loginBtn = document.getElementById("signIn") as HTMLInputElement; this.loginBtn.addEventListener("submit", () => this.verifyUser()); //add event listeners for HTML manip let buttons = document.getElementsByTagName("input:radio"); let btnArray = Array.prototype.slice.call(buttons,0); this.selectedProj = ""; let projectButtons = btnArray.forEach((element:HTMLElement) => { element.addEventListener("click", () => { this.selectedProj = element.innerText as string; //might need to cahnge to vlaue ????? }) }); // this.selectedProj = projectButtons.val() as string; // projectButtons.change((e) => { // this.selectedProj = $(e).target.val() as string; // }) //add controller function //add listener for action } notify() { this.display(); } display() { //load sources this.displayProjects(); this.displaySources(); } displayProjects() { //something } displaySources() { //soem let sourceList:Source[]; sourceList = this.model.getSources("/" + this.selectedProj); sourceList.forEach((source) => { source.createSourceElement(source); //probably need project ref? }) } addNewProject() { let projTitle = document.createElement("input"); // let title:string; // projTitle.addEventListener("input", (e) => { // title = e.target.; // }) this.newProj.insertAdjacentElement("afterend", projTitle); this.controller.addProject(); } verifyUser() { console.log("verify"); let uRef = document.getElementById("uName"); let pRef = document.getElementById("pWord"); let email:string = ""; let password:string = ""; let auth:boolean = false; if(uRef && pRef) { email = uRef.innerText; password = pRef.innerText; auth = this.controller.verifyUser(email, password); } if(auth) { console.log("auth"); this.user = email; let logInDisplay = document.getElementById("logIn") as HTMLDivElement; logInDisplay.remove(); let enable = document.getElementById("newP") as HTMLInputElement; enable.disabled = false; this.display(); } } nameElement(stlye:string) { //this } changeProject() { //something } }
d4c1d3b896373eda9a47c848a7b95157c47d45ed
TypeScript
NWZX/react-firebase-pagination-hooks
/src/util/usePaginationValue.ts
2.84375
3
import { firestore } from "firebase"; import * as React from "react"; import { addItem, deleteItem, updateItem } from "./operation"; const { useReducer } = React; type ReducerState = { hasMore: boolean; value: firestore.QueryDocumentSnapshot[]; after: firestore.QueryDocumentSnapshot | null; lastLoaded: firestore.QueryDocumentSnapshot | null; loadingMore: boolean; limit: number; loaded: boolean; error?: Error; }; export type PaginationValue = ReducerState & { loadMore: () => void; reest: () => void; setError: (error: Error) => void; setValue: (limit: number) => (value: firestore.QuerySnapshot) => void; }; export type PaginationHook<T> = [ T[], { loaded: boolean; hasMore: boolean; loadingMore: boolean; loadMore: () => void; }, Error | undefined ]; const initialState: ReducerState = { hasMore: false, after: null, limit: 0, value: [], lastLoaded: null, loaded: false, loadingMore: false, }; type LoadMoreAction = { type: "loadMore" }; type ErrorAction = { type: "error"; error: Error }; type ResetAction = { type: "reset" }; type LoadedAction = { type: "loaded"; value: firestore.QuerySnapshot; limit: number; }; export type ActionType = | LoadMoreAction | ErrorAction | ResetAction | LoadedAction; function reducer(state: ReducerState, action: ActionType): ReducerState { switch (action.type) { case "loaded": { const value = [...state.value]; let isAdding = false; action.value.docChanges().forEach((change) => { if (change.type === "added") { isAdding = true; addItem(change.doc, value); } else if (change.type === "modified") { updateItem(change.doc, value); } else if (change.type === "removed") { deleteItem(change.doc, value); } }); const nextLimit = value.length + action.limit; const end = value.length < action.limit || nextLimit === state.limit; return { ...state, hasMore: isAdding ? !end : state.hasMore, limit: nextLimit, loaded: true, lastLoaded: action.value.docs[action.value.docs.length - 1], loadingMore: false, value, }; } case "error": return { ...state, error: action.error, value: [], }; case "reset": { return { ...initialState, }; } case "loadMore": { return { ...state, loadingMore: true, after: state.lastLoaded, }; } } } const usePaginationValue = (): PaginationValue => { const [state, dispatch] = useReducer(reducer, initialState); const loadMore = () => { dispatch({ type: "loadMore" }); }; const setValue = (limit: number) => (value: firestore.QuerySnapshot) => { dispatch({ type: "loaded", value, limit }); }; const setError = (error: Error) => { dispatch({ type: "error", error }); }; const reest = () => { dispatch({ type: "reset" }); }; return { ...state, reest, setValue, loadMore, setError, }; }; export default usePaginationValue;
b2c32321c1aefc71a7b48a6f3b3d1753e532c581
TypeScript
PatriciaCSouza/CRUD-Usuarios
/EF.AspNetCore.CrudUsuario/Views/Home/Index/src/app/utils/validations.util.ts
3.109375
3
export class Validator { static IsValidEmail(email: string): boolean { const EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i; if (email && (email.length <= 5 || !EMAIL_REGEXP.test(email))) { return false; } return true; } }
16ba31d562e2f4c59d9201b8f2256af68d62fe2f
TypeScript
DefinitelyTyped/DefinitelyTyped
/types/sort-json/index.d.ts
3.125
3
// Type definitions for sort-json 2.0 // Project: https://github.com/kesla/sort-json // Definitions by: Florian Keller <https://github.com/ffflorian> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace visit { interface VisitOptions { /** * Depth's level sorting keys on a multidimensional object * (default: `Infinity`) */ depth?: number | undefined; /** * When sorting keys, converts all keys to lowercase so that * capitalization doesn't interfere with sort order (default: `false`) */ ignoreCase?: boolean | undefined; /** Default: `1` */ level?: number | undefined; /** Reverse the ordering z -> a (default: `false`) */ reverse?: boolean | undefined; } interface OverwriteOptions extends VisitOptions { /** * Formats the file content with an indentation of spaces. Use a number * greater then 0 for the value (default: detects the used indentation * of the file) */ indentSize?: number | undefined; /** Default: `false` */ noFinalNewLine?: boolean | undefined; } /** * Sorts the JSON files with the `visit()` function and then overwrites the * file with sorted JSON * @param absolutePaths * * String: Absolute path to JSON file to sort and overwrite * * Array: Absolute paths to JSON files to sort and overwrite */ function overwrite(absolutePaths: string | string[], options?: OverwriteOptions): any; } /** * Sorts the keys on objects * @param old An object to sort the keys of, if not object just returns whatever * was given */ declare function visit<T>(old: T, options?: visit.VisitOptions): T; export = visit;
51d27f30fcb8b7c443edee612bcff16833ffb25b
TypeScript
qzx1991/x-reactive
/src/lib/Lazyable.ts
2.90625
3
/**是否是代理对象 */ export const LAZYABLE_FLAG = Symbol('_$$__$$__is_lazyable'); /**是否是一个已经proxy */ export const LAZYABLED_FLAG = Symbol('_$$__$$__is_lazyabled'); /** 代理对象的原生对象属性标识 */ export const ORIGIN_TARGET_FLAG = Symbol('_$$__$$__origin_target_flag'); export type LazyableGetHandlerType<T> = ( object: T, key: string | number | symbol, value: any ) => void; export type LazyableSetHandlerType<T> = ( object: T, key: string | number | symbol, value: any, oldValue: any, isAdd: boolean ) => void; export type LazyableDeleteHandlerType<T> = ( object: T, key: string | number | symbol, oldValue: any ) => void; export type LazyableAddHandlerType<T> = ( object: T, key: string | number | symbol, value: any ) => void; export type LazyableHandlerType<T> = | LazyableGetHandlerType<T> | LazyableSetHandlerType<T> | LazyableDeleteHandlerType<T> | LazyableAddHandlerType<T>; export type LazyableOptType = 'get' | 'set' | 'add' | 'delete'; export function isLazyabledData(v: any): boolean { return v && v[LAZYABLED_FLAG]; } /** * 代理一个对象让它变得可以被监听 * @param value 需要被监听的值 */ type LazyableKeyType = { include?: (string | symbol)[]; exclude?: (string | symbol)[]; }; function canKeyLazyable( k: string | symbol, { include, exclude }: LazyableKeyType = {} ) { if (exclude && exclude.includes(k)) return false; if (include) { return include.includes(k); } return true; } const GET_HANDLERS_MAP = new Map<any, Set<LazyableGetHandlerType<any>>>(); const SET_HANDLERS_MAP = new Map<any, Set<LazyableSetHandlerType<any>>>(); const DELETE_HANDLERS_MAP = new Map<any, Set<LazyableDeleteHandlerType<any>>>(); const ADD_HANDLERS_MAP = new Map<any, Set<LazyableSetHandlerType<any>>>(); function getHandlersMapByType(type: LazyableOptType) { switch (type) { case 'get': return GET_HANDLERS_MAP; case 'set': return SET_HANDLERS_MAP; case 'delete': return DELETE_HANDLERS_MAP; case 'add': return ADD_HANDLERS_MAP; } } function onLazyableOpt( map: Map<any, Set<any>>, t: any = 'default', ...args: any[] ) { map.get(t)?.forEach((h) => h(...args)); } let id = 0; let LAZYABLE_GET_TRANSFORMERS: { id: number; handler: (v: any, t: any, k: string | number | symbol, r?: any) => any; }[] = []; // 转换获取值的逻辑 export function transformLazyable( h: (v: any, t: any, k: string | number | symbol, r?: any) => any ) { const myId = ++id; LAZYABLE_GET_TRANSFORMERS.push({ id: myId, handler: h, }); return () => (LAZYABLE_GET_TRANSFORMERS = LAZYABLE_GET_TRANSFORMERS.filter( (i) => i.id !== myId )); } export function Lazyable<T extends object>( value: T, opt: LazyableKeyType = {} ): T { if (!value) return value; if (typeof value !== 'object') return value; if (hasTargetLazyabled(value)) return (Raw(value) as any)?.[LAZYABLE_FLAG]; const R: any = new Proxy(value, { get(t, k, r) { if (k === ORIGIN_TARGET_FLAG) return t; if (k === LAZYABLED_FLAG) return true; const v = Reflect.get(t, k, r); if (!canKeyLazyable(k, opt)) { return v; } const Rv = hasTargetLazyabled(v) ? (getLazyableRawData(v) as any)?.[LAZYABLE_FLAG] // 已经是代理对象了 获取这个对象存储的代理结果 : k !== '__proto__' && (v?.__proto__ === ([] as any).__proto__ || v?.__proto__ === ({} as any).__proto__) // 是一个普通的对象而非一个类 ? Lazyable(v) // 响应化 : v; onLazyableOpt(GET_HANDLERS_MAP, t, R, k, Rv); onLazyableOpt(GET_HANDLERS_MAP, 'default', R, k, Rv); return LAZYABLE_GET_TRANSFORMERS.reduce( (lastv, h) => h.handler(lastv, R, k, r), Rv ); }, set(t, k, v, r) { const isAdd = !t.hasOwnProperty(k); const oldValue = Reflect.get(t, k); // 将原生的值放进去 const res = Reflect.set(t, k, getLazyableRawData(v), r); onLazyableOpt(SET_HANDLERS_MAP, t, R, k, v, oldValue, isAdd); onLazyableOpt( SET_HANDLERS_MAP, 'default', R, k, v, oldValue, isAdd ); if (isAdd) { onLazyableOpt(ADD_HANDLERS_MAP, t, R, k, v, oldValue, isAdd); onLazyableOpt( ADD_HANDLERS_MAP, 'default', R, k, v, oldValue, isAdd ); } return res; }, deleteProperty(t, p) { const oldValue = Reflect.get(t, p); const res = Reflect.deleteProperty(t, p); onLazyableOpt(DELETE_HANDLERS_MAP, t, R, p, oldValue); onLazyableOpt(DELETE_HANDLERS_MAP, 'default', R, p, oldValue); return res; }, }); // 在原生对象中记录这个代理对象 保证所有的原生对象其实指向同一个代理对象 是否有必要 有待实践 (value as any)[LAZYABLE_FLAG] = R; return R; } /** * 判断一个对象是否已经被代理过 * @param value * @returns */ export function hasTargetLazyabled<T>(value: T): boolean { return (value as any)?.[LAZYABLE_FLAG]; } /** * 获取一个被代理过的对象的原始数据 * @param value * @returns */ export function getLazyableRawData<T>(value: T): T { return (value as any)?.[ORIGIN_TARGET_FLAG] || value; } export const Raw = getLazyableRawData; /** * 让一个值变得可被代理 * @param value */ export function Ref<T>(value: T): { value: T } { return Lazyable({ value }); } export function onLazyable<T>( type: 'get', t: T, h: LazyableGetHandlerType<T> ): () => void; export function onLazyable<T>( type: 'get', h: LazyableGetHandlerType<T> ): () => void; export function onLazyable<T>( type: 'set', t: any, h: LazyableSetHandlerType<T> ): () => void; export function onLazyable<T>( type: 'set', h: LazyableSetHandlerType<T> ): () => void; export function onLazyable<T>( type: 'add', t: any, h: LazyableAddHandlerType<T> ): () => void; export function onLazyable<T>( type: 'add', h: LazyableAddHandlerType<T> ): () => void; export function onLazyable<T>( type: 'delete', t: any, h: LazyableDeleteHandlerType<T> ): () => void; export function onLazyable<T>( type: 'delete', h: LazyableDeleteHandlerType<T> ): () => void; export function onLazyable(type: LazyableOptType, t: any, h?: any) { if (!h) { const temp = t; t = 'default'; h = temp; } const map = getHandlersMapByType(type); if (!map) return () => {}; if (!map.has(t)) { map.set(t, new Set()); } map.get(t)?.add(h); return () => { map.get(t)?.delete(h); if (map.get(t)?.size === 0) map.delete(t); }; } //记录哪些属性是stateable的 export const STATE_FLAG = Symbol('state_flag');
9a4b7fe4597d97fdecf36bb99a7c471d6a00cb0f
TypeScript
NoworksM/koa-typescript-microservice-template
/src/middleware/user.ts
2.53125
3
import {Context, Next} from "koa"; import ITokenPayload from "../models/ITokenPayload"; import ErrorResponseViewModel from "../models/ErrorResponseViewModel"; import cache from "../cache/SiteMemoryCache"; async function userMiddleware(ctx: Context, next: Next): Promise<void> { if (ctx.request.method === "OPTIONS") { await next(); return; } if (!/^\/auth\/?/.test(ctx.request.path)) { const token: ITokenPayload | undefined = ctx.state.user; if (!token) { ctx.status = 401; ctx.body = new ErrorResponseViewModel("User not signed in"); return; } ctx.state.token = token; const user = await cache.getUser(token.userId, true); if (user) { ctx.state.user = user; } else { ctx.state.user = null; } } await next(); } export default userMiddleware;
2d9c7c89e65b77dfb7128432fc08e752c4279045
TypeScript
dfeshed/nw-ueba-saas
/presidio-ui/presidio-ui-ui/app/app/shared/services/device-utils-service/device-utils-service.ts
2.703125
3
/** * */ module Fortscale.shared.services.deviceUtilsService{ 'use strict'; const OTHERS_NAME = 'Others'; import IActivityUserDevice = Fortscale.shared.services.entityActivityUtils.IActivityUserDevice; import IActivityTopApplication = Fortscale.shared.services.entityActivityUtils.IActivityTopApplication; import IActivityTopDirectory = Fortscale.shared.services.entityActivityUtils.IActivityTopDirectory; export interface IUserActivityExtend{ percent?: number, active?: boolean, count: number } export interface IUserDevice extends IActivityUserDevice,IUserActivityExtend { } export interface IUserTopApplication extends IActivityTopApplication,IUserActivityExtend { } export interface IUserTopRecipientDomain extends IActivityTopApplication,IUserActivityExtend { } export interface IUserTopDirectory extends IActivityTopApplication,IUserActivityExtend { } /** * Service interfaces */ export interface IDeviceUtilsService{ updatePercentageOnDevice(devices: IUserActivityExtend[]): IUserActivityExtend[]; removeZeroCount (devices: IUserActivityExtend[]):IUserActivityExtend[]; repositionOthers (devices: IUserDevice[]); } class DeviceUtilsService implements IDeviceUtilsService { /** * Calculates a device's percent, and store on the device object * @param {number} sum * @param {Array<IUserDevice>} device * @private */ private _calcDevicePercent (sum: number, device: IUserActivityExtend) { if (sum) { device.percent = Math.round(device.count / sum * 10000) / 100; } else { device.percent = 0; } } /** * This method calculate the sum of all count fields on user device, * and for each device calculate its count / sum * 100 and save it as percentage field on the device * @param devices * @returns {IUserActivityExtend[]} */ updatePercentageOnDevice(devices: IUserActivityExtend[]): IUserActivityExtend[]{ // calc sum let sum = _.sumBy<IUserActivityExtend>(<any>devices, 'count'); // iterate and calc percent _.each(devices, this._calcDevicePercent.bind(this, sum)); return devices; } /** * Create and return new device list which not contain the devices with count = 0 * @param devices * @returns {T[]} */ removeZeroCount (devices: IUserActivityExtend[]):IUserActivityExtend[] { return _.filter(devices, (device) => device.count > 0); } /** * Pulls out 'other' member and puts it in the end of the list. * @param devices * @private */ repositionOthers (devices: IUserDevice[]) { let pluckIndex = -1; _.some(devices, (device: IUserDevice, index: number) => { if (device.deviceName === OTHERS_NAME) { pluckIndex = index; return true; } }); if (pluckIndex !== -1) { let device = devices[pluckIndex]; device.deviceName = 'Others'; devices.splice(pluckIndex, 1); devices.push(device); } } constructor() { } } angular.module('Fortscale.shared.services') .service('deviceUtilsService', DeviceUtilsService) }
f5a33acb52aecbd3e2f64dd24e257ff0b379b800
TypeScript
dinerojs/dinero.js
/packages/dinero.js/src/api/isNegative.ts
2.9375
3
import { isNegative as coreIsNegative } from '@dinero.js/core'; import type { IsNegativeParams } from '@dinero.js/core'; /** * Check whether a Dinero object is negative. * * @param dineroObject - The Dinero object to check. * * @returns Whether the Dinero object is negative. * * @public */ export function isNegative<TAmount>( ...[dineroObject]: IsNegativeParams<TAmount> ) { const { calculator } = dineroObject; const isNegativeFn = coreIsNegative(calculator); return isNegativeFn(dineroObject); }
7ae700f9cbb00f199b23c893979bf6e9d9239c0f
TypeScript
codingdojo-mean-03-19/gresamjeku
/05-angular/02-fetch-data/02_api/public/src/app/http.service.ts
3.109375
3
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class HttpService { constructor(private _http: HttpClient){ this.getPokemon(); } getPokemon(){ let tempObservable = this._http.get<ChlorophyllData>('https://pokeapi.co/api/v2/pokemon/1/'); tempObservable.subscribe(data => { console.log("Got our POKEMON! Chlorophyll has the following abilities:"); for (const item of data.abilities){ console.log('Ability:', item.ability.name); } this.getCount(data.abilities[1].ability.url); }); } getCount(url){ let tempObservable = this._http.get<Count>(url) tempObservable.subscribe(data => { console.log(data.pokemon.length + " pokemons have the " + data.name.toUpperCase() + " ability."); }); }; } interface ChlorophyllData { abilities: Array<Ability> } interface Ability { ability: { name: string, url: string } } interface Count { name: string, pokemon: Array<Pokemon> } interface Pokemon{ length: number }
1b1c106a92dad4bf2d16ad988ef7398a0122eeb0
TypeScript
simon-lammes/angular-app
/src/app/minesweeper/difficulty.ts
3.109375
3
export class Difficulty { name: string; rowCount: number; columnCount: number; bombCount: number; get description(): string { return `${this.name} ||| ${this.rowCount}X${this.columnCount} ||| ${this.bombCount} bombs`; } get cellCount(): number { return this.rowCount * this.columnCount; } constructor(name: string, rowCount: number, columnCount: number, bombCount: number) { this.name = name; this.rowCount = rowCount; this.columnCount = columnCount; this.bombCount = bombCount; } }
91623bf9a1d4f21aded0077b047da9f898c6d2a7
TypeScript
andrewhead/torii-store
/src/code/types/chunk.ts
3.015625
3
import { SimpleStore } from "../../common/types"; /** * Order of chunks in "all" field is meaningless, as these chunks will be from many different files. * Use the lineNumber and path properties of chunks if you want to sort them. */ export interface Chunks extends SimpleStore<ChunkId, Chunk> {} export interface Chunk { location: Location; versions: ChunkVersionId[]; } export type ChunkId = string; /** * Spec for making a chunk; use to create a new snippet from text in a reference implementation. */ export interface InitialChunk { location: Location; text: string; } /** * Location of chunk in the reference version of the program (initial version, before edits * are made to the chunk in later stages of the tutorial.) */ export interface Location { /** * Line numbers start at one (first line has number '1'). */ line: number; path: Path; } export type Path = string; export interface ChunkVersions extends SimpleStore<ChunkVersionId, ChunkVersion> {} export interface ChunkVersion { text: string; chunk: ChunkId; } export type ChunkVersionId = string;
17521b085a2e89f855293fbf8e09a047d79a4de6
TypeScript
NativeScript/NativeScript
/apps/automated/src/ui/label/label-tests-native.android.ts
2.6875
3
import * as labelModule from '@nativescript/core/ui/label'; import { CoreTypes } from '@nativescript/core'; import * as colorModule from '@nativescript/core/color'; export function getNativeTextAlignment(label: labelModule.Label): string { let gravity = label.android.getGravity(); if ((gravity & android.view.Gravity.HORIZONTAL_GRAVITY_MASK) === android.view.Gravity.LEFT) { return CoreTypes.TextAlignment.left; } if ((gravity & android.view.Gravity.HORIZONTAL_GRAVITY_MASK) === android.view.Gravity.CENTER_HORIZONTAL) { return CoreTypes.TextAlignment.center; } if ((gravity & android.view.Gravity.HORIZONTAL_GRAVITY_MASK) === android.view.Gravity.RIGHT) { return CoreTypes.TextAlignment.right; } return 'unexpected value'; } export function getNativeBackgroundColor(label: labelModule.Label): colorModule.Color { let bg = <any>label.android.getBackground(); if (bg instanceof org.nativescript.widgets.BorderDrawable) { return new colorModule.Color(bg.getBackgroundColor()); } else if (bg instanceof android.graphics.drawable.ColorDrawable) { return new colorModule.Color(bg.getColor()); } else { return new colorModule.Color(bg.backgroundColor); } }