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
6b410cd33016870e37438afbab95fa01b957c22a
TypeScript
I-vasilich-I/rslang
/src/store/action-creators/userWords.ts
2.671875
3
import { Dispatch } from 'redux'; import { UserWordsAction, UserWordsActionTypes } from '../../types/userWords'; import { getUserWords } from '../../helpers/helpers'; export const fetchUserWords = (userId: string, token: string) => { return async (dispatch: Dispatch<UserWordsAction>): Promise<void> => { try { dispatch({ type: UserWordsActionTypes.FETCH_USER_WORDS }); const userWords = await getUserWords({ userId, token }); dispatch({ type: UserWordsActionTypes.FETCH_USER_WORDS_SUCCESS, payload: userWords }); } catch (e) { dispatch({ type: UserWordsActionTypes.FETCH_USER_WORDS_ERROR, payload: e.message, }); } }; }; export function setUserWordsError(): UserWordsAction { return { type: UserWordsActionTypes.FETCH_USER_WORDS_ERROR, payload: null, }; }
15cf8caa8d39766ae9292f40972099f938ed7a95
TypeScript
YenKaPhuThi/react-bulding
/src/api/APIUtils.ts
2.5625
3
import Axios, { AxiosRequestConfig} from 'axios'; const axiosInstance = Axios.create({ baseURL: process.env.REACT_APP_URL, timeout: 10000, params: {}, headers: {'X-Custom-Header': 'foobar'} }); class API { private coreAPI = axiosInstance; private route: string = ''; private config: AxiosRequestConfig = { }; constructor(route: string, config?: object){ this.route = route; if(config){ this.config = config; } this.setupAxiosInterceptors(); } protected get(){ return this.coreAPI.get(this.route); } protected delete(){ return this.coreAPI.delete(this.route, this.config); } protected patch(data?: any){ return this.coreAPI.patch(this.route, data, this.config); } protected post(data?: any, endpoint: string = ''){ return this.coreAPI.post(this.route + endpoint, data, this.config); } protected update(data?: any){ return this.coreAPI.put(this.route, data, this.config); } protected all(arrayPromise: Iterable<[] |PromiseLike<[]>>): Promise<[][]> { return Promise.all(arrayPromise); } private setupAxiosInterceptors() { // const onRequestSuccess = (config: any) => { // const token = Storage.local.get('jhi-authenticationToken') || Storage.session.get('jhi-authenticationToken'); // if (token) { // config.headers.Authorization = `Bearer ${token}`; // } // return config; // }; // Add a request interceptor this.coreAPI.interceptors.request.use( config => { // Do something before request is sent return config; }, (error: Error) => { // Do something with request error return Promise.reject(error); }); // Add a response interceptor this.coreAPI.interceptors.response.use( response => response , error => { // Do something with response error Promise.reject(error); }); } } export default API
9bb0e51d4cb7be9ce7dd796fe7fdb2a6ed453c58
TypeScript
josefuentesfsnz/cachipun-front
/src/app/components/game/result/result.component.ts
2.515625
3
import { Component, OnInit } from '@angular/core'; import { RoundModel } from 'src/app/models/round-model'; import { MatchService } from 'src/app/service/match.service'; export interface Iwinners { player_name: string; player: string; } @Component({ selector: 'app-result', templateUrl: './result.component.html', styleUrls: ['./result.component.css'] }) export class ResultComponent implements OnInit { rounds: RoundModel[] = []; constructor( private matchService: MatchService ) { this.rounds = this.matchService.get().rounds; } _getWinnerParty(): Iwinners { let winner: Iwinners = { player_name: "Nadie", player: "DRAW" }; const pl1wins = this.rounds.filter(d => { return d.winner_player === "player_one"; }); const pl2wins = this.rounds.filter(d => { return d.winner_player === "player_two"; }); if (pl1wins.length === pl2wins.length) { winner.player_name = "EMPATE"; winner.player = "DRAW"; } if (pl1wins.length > pl2wins.length) { winner.player_name = pl1wins[0].winner_name; winner.player = "player_one"; } if (pl1wins.length < pl2wins.length) { winner.player_name = pl2wins[0].winner_name; winner.player = "player_two"; } return winner; } _getMatch() { return this.matchService.get(); } ngOnInit(): void { } }
7b7fe7a0ab03a39ca8f0e10d99e4b606007bb93b
TypeScript
ItaloFL/Super_Market
/src/modules/products/UseCases/searchProducts/SearchProductsUseCase.ts
2.640625
3
import { IProductRepository } from "@modules/products/Repositories/IProductRepository"; import { inject, injectable } from "tsyringe"; interface IRequest{ productName: string } @injectable() export class SearchProductsUseCase{ constructor( @inject("ProductRepository") private productRepository: IProductRepository ){} async execute({ productName }: IRequest){ const product = await this.productRepository.search(productName) return product } }
433ac48b8114b01ab43c7e9deb60a424bd1cf437
TypeScript
Maissacrement/BruteForce
/src/providers/BruteForceService.ts
2.8125
3
const { spawn } = require('child_process'); export default class BruteForceService { private omega: string; private target: string ; private hashCount: number; public passwordTable: string[] = []; /** * @params: * - ensembleOfLetter: string * description: Interval of letter you want use * - pathFileToBruteForce: string * description: path where is defined the target bruteforce file * - hashLength: number * description: password length */ constructor( private readonly ensembleOfLetter = 'abcdef0123456789', private readonly pathFileToBruteForce = './source/WebTarget.zip', private readonly hashLength = 32, ) { this.omega = ensembleOfLetter; this.target = pathFileToBruteForce; this.hashCount = hashLength; } /** Main Function **/ public init() { const firstLetterInOmega = this.omega[0]; for(let i=0;i<this.hashCount;i++) { this.passwordTable.push(firstLetterInOmega); } } public bruteForce() { const passwordLength = this.passwordTable.length - 1; const omegaLength = this.omega.length - 1; let arrayPosition = 0, i = 0; this._chageValueOfPasswordTableIndex(0, passwordLength, omegaLength, i); while(i < 19) { console.log('i,', i, 'omegaLength: ', (i % (omegaLength + 1))) if( (i % (omegaLength + 1)) == 0 && i !=0 ) { console.log('hello'); const newIndex = (passwordLength - arrayPosition) % passwordLength this.passwordTable[30] = this.omega[1]; console.log(this.passwordTable); arrayPosition += 1; } this._chageValueOfPasswordTableIndex( arrayPosition, passwordLength, omegaLength, i ); const password = this._getCurrentPassword(); console.log('test', password); this._7zTryFindPassword( password ); i++; } } /** End Main **/ private _getCurrentPassword(): string { const newPass = this.passwordTable; return newPass.join().replace(/[.\,$+]/g, ''); } private _7zTryFindPassword(password: string): void { const tryPasswordBruteForce = spawn('7z', [`${this.target}`, `-P${password}`]); tryPasswordBruteForce.stdout.on('data', (data: any) => { // console.log(`stdout: ${data}`); console.log(`success`); }); tryPasswordBruteForce.stderr.on('data', (data: any) => { console.error(`error`); }); tryPasswordBruteForce.on('close', (code: any) => { // console.log(`child process exited with code ${code}`); }); } private _chageValueOfPasswordTableIndex( previousIndex: number, passLength: number, omegaLength: number, newIndex: number, ): void { this.passwordTable[(passLength - previousIndex) % ( passLength + 1 )] = this.omega[newIndex % ( omegaLength + 1 )]; } }
4002470530f73bbbcef7ed956eac5ba99be36fbc
TypeScript
mauriciabad/ALE1-Fall-2019
/src/scripts/gate.ts
3.65625
4
type operator = '¬' | '|' | '&' | '=' | '>' type objectOfBooleans = {[key: string]: boolean} class Gate { operator:operator operands:(Gate|Value)[] constructor(operator:operator, operands:(Gate|Value)[]) { this.operator = operator this.operands = operands } evaluate(values:objectOfBooleans):boolean { switch (this.operator) { case '¬': return !this.operands[0].evaluate(values) case '|': return this.operands[0].evaluate(values) || this.operands[1].evaluate(values) case '&': return this.operands[0].evaluate(values) && this.operands[1].evaluate(values) case '=': return (this.operands[0].evaluate(values) && this.operands[1].evaluate(values)) || (!this.operands[0].evaluate(values) && !this.operands[1].evaluate(values)) case '>': return !this.operands[0].evaluate(values) || this.operands[1].evaluate(values) } } static parse(rawData:string): Gate|Value{ rawData = rawData.replace(/\s/g, ''); if('¬|&=>'.indexOf(rawData[0]) > -1){ let operator:operator = rawData[0] as operator let operands:string[] = [] let level = 0; let operandBegining = 2 for (let i = 2; i < rawData.length - 1; i++) { switch (rawData[i]) { case '(': ++level; break; case ')': --level; break; case ',': if(level === 0) { operands.push(rawData.slice(operandBegining,i)) operandBegining = i + 1; } break; } } operands.push(rawData.slice(operandBegining,rawData.length - 1)) if(level !== 0) { throw "Error parsing Gate, parenthesis are wrong."; } return new Gate(operator, operands.map((operand) => Gate.parse(operand))) }else{ return new Value(rawData) } } get variables():string[]{ let variables:string[] = [] this.getVariablesRecursive(variables) return variables } get variablesObj():objectOfBooleans{ return this.variables.reduce((result:objectOfBooleans, variableName) => { result[variableName] = false; return result; }, {}) } getVariablesRecursive(variables:string[]) { for (const operand of this.operands) { operand.getVariablesRecursive(variables) } } } class Value{ name:string constructor(name:string) { this.name = name } evaluate(values:objectOfBooleans) { return values[this.name] } getVariablesRecursive(variables:string[]) { if(!variables.includes(this.name)) variables.push(this.name) } get variables():string[]{ let variables:string[] = [] this.getVariablesRecursive(variables) return variables } get variablesObj():objectOfBooleans{ return this.variables.reduce((result:objectOfBooleans, variableName) => { result[variableName] = false; return result; }, {}) } }
e091668be8edf7b32880300f8d0e2c2775da6d12
TypeScript
antiwise/GameTemplateTS
/assets/scripts/framework/platform/AppBridge.ts
2.796875
3
/** * Created by xujiawei on 2020-07-07 17:05:26 */ /** * Native Bridge * 用法参考:http://wiki.putao-inc.com/display/ZYTech/Webview+JS+Bridge+API * web和native(app)交互使用 */ const callAppBacks = {}; const callWebHandlers = {}; let uniqueId = 1; import { reportError } from './../common/Reportor'; import { Device } from './../common/Device'; import { isArray, isFunction, isPlainObject, isString } from './../common/TypeOf'; // 性能分析用 function _now() { return (new Date().valueOf()); } // 处理 nativeBridge 注入之前,Web 发起的 callApp 请求 let _callAppQueue = []; if (!window.nativeBridge) { // nativeBridge ready 后,将 callApp 的 message 逐一发送 once('bridgeReady', function () { _callAppQueue.forEach(function (message) { _postMessageToApp(message); }); _callAppQueue = null; }); } // 通过 Native 注入的方法传送数据 function _postMessageToApp(message) { if (window.nativeBridge) { try { window.nativeBridge.postMessage(Device.isAndroidApp ? JSON.stringify(message) : message); } catch (err) { const errMsg = 'nativeBridge.postMessage 通信异常'; callWeb({ callbackId: message.callbackId, code: 1, msg: err.message || errMsg, }); reportError(err, errMsg); // 上报错误 } } else { // nativeBridge ready 前,将 callApp 的 message 存入队列 _callAppQueue && _callAppQueue.push(message); } } // Web 调用 Native function callApp(params: {action: string, data?: any, success?:Function, fail?: Function, complete?: Function, error?: Function}) { let { action, data = {}, success, fail, complete } = params; const message = { action, data, callbackId:0 }; let callbackId; if (success || fail || complete) { callbackId = uniqueId++; callAppBacks[callbackId] = { success, fail, complete, timestamp: _now() }; message.callbackId = callbackId; } console.log('webCallApp', message.callbackId || 0, message); _postMessageToApp(message); return () => { if (callbackId) { delete callAppBacks[callbackId]; } }; } // Native 调用 Web function callWeb(params: any) { let { action, data = {}, code = -2, msg = '', callbackId = 0, responseId = 0 } = params; console.log('appCallWeb', callbackId || 0, arguments[0]); // 处理 Web callApp 的回调 // 没有回调,客户端默认 callAppBackId = 0 if (callbackId) { const callAppBack = callAppBacks[callbackId]; if (callAppBack) { console.log('appCallback', callbackId, _now() - callAppBack.timestamp + 'ms'); try { if (code === 0) { isFunction(callAppBack.success) && callAppBack.success(data || {}); } else { isFunction(callAppBack.fail) && callAppBack.fail({ code, msg }); } isFunction(callAppBack.complete) && callAppBack.complete({ code, data, msg }); } catch (err) { reportError(err, 'appBridge 回调函数执行异常'); // 上报错误 } delete callAppBacks[callbackId]; } return; } // 触发 action const returnData = action && _triggerAction(action, data); // 向 Native 发送触发 action 的回调 if (responseId && returnData) { callApp({ responseId, data: returnData, }); } } // 触发 action handler function _triggerAction(action, data) { const handler = callWebHandlers[action]; if (action === 'goBack' && !handler) { //如果这里是goBack方法,但是页面中没有监听该方法,那么把该方法交回app处理 callApp({ action: 'goBack' }) } return handler && handler(data || {}); } // 执行移除 action hander function _removeHandler(action) { delete callWebHandlers[action]; } // 注册 action handler function on(action, handler) { if (typeof action === 'string' && isFunction(handler)) { callWebHandlers[action] = handler; } // 返回当前 handler 的销毁方法 return function () { _removeHandler(action); } } // 销毁 action handler function off(action) { if (typeof action === 'string') { _removeHandler(action); } } // 注册一次性 action handler function once(action, handler) { if (typeof action === 'string' && isFunction(handler)) { callWebHandlers[action] = function (data) { // handler.apply(this, arguments); handler(data); // 如果回参只有 data,用这种方式直接高效 _removeHandler(action); }; } } // 广播通信 const dsn = 'web:' + (Math.random() * 1e6 | 0).toString(16); function broadcast(data) { // 数据拼装 const list = []; const pushData = itemData => isPlainObject(itemData) && isString(itemData.key) && itemData.key && list.push({ ...itemData, dsn, }); if (isArray(data)) { data.forEarch(item => pushData(item)); } else { pushData(data); } // 发送广播 list.length && callApp({ action: 'broadcast', data: { list }, fail: (err) => { const { code, msg } = err; cc.warn('broadcast failed', list); reportError(err, { msg: `appBridge 广播异常,#${code} ${msg}`, group: ['appBridge', 'callApp.broadcast', '' + code + msg], level: 'error', }); } }); } // 对 Native 公开 callWeb 方法 // 对 Web 公开 callApp, on, off, once 方法 // @ts-ignore window.JSBridge = { callWeb, callApp, on, off, once, broadcast, dsn }; export { callApp, on, off, once, broadcast, dsn};
7e7aad1f43923385dea81c568d9c647f7c57843e
TypeScript
rafaeltgt/nlwValoriza
/src/services/AuthenticateUserService.ts
2.640625
3
import { compare } from "bcryptjs" import { sign } from "jsonwebtoken" import { getCustomRepository } from "typeorm" import { UserRepositories } from "../repositories/userRepositories" interface IAuthRequest { email: string password: string } class AuthenticateUserService { async execute({ email, password }: IAuthRequest) { const userRepositories = getCustomRepository(UserRepositories) //verifica se email existe const user = await userRepositories.findOne({ email }) if (!user) { throw Error("Email / Password incorrect") } //verifica se senha correta const passMatch = await compare(password, user.password) if (!passMatch) { throw Error("Email / Password incorrect") } //gera token const token = sign({ email: user.email }, process.env.PRIVATE_KEY, { subject: user.id, expiresIn: "1d" }) return token } } export { AuthenticateUserService }
c719f75faba91ee8809ea7e7e21616b5258f1435
TypeScript
mitmedialab/prg-extension-boilerplate
/extensions/scripts/factories/customArgument.ts
2.625
3
import chalk from "chalk"; import path from "path"; import { copyTemplateToDestinationAndIncrementIfExists, processDirectoryArg } from "."; const directory = processDirectoryArg(); const destination = copyTemplateToDestinationAndIncrementIfExists(directory, "CustomArgument.svelte"); const name = path.basename(destination).replace(path.extname(destination), ""); const invocation = `this.openUI("${name}");`; const msg = [ chalk.greenBright("Success! A new ui componenent has been added to your extension at:"), chalk.cyan(`\n\n\t${destination}\n`), chalk.greenBright(`Use it in your extension by calling`), chalk.cyan(`\n\n\t${invocation}\n\n`), chalk.greenBright("You should also change the name of the file to be more reflective of it's usage (which will affect the first argument you give to the 'openUI' function)") ]; console.log(...msg);
04304b17d7d549c389e9051ee9d06a8b5c2c0137
TypeScript
mopcweb/gentool
/src/templates/typescript/fullstack/widget-starter/src/server/middlewares/checkParams.ts
2.6875
3
/* ################################################################### */ /* /* Middleware to check if request include necessary params /* /* ################################################################### */ import { Request, Response, NextFunction } from 'express'; /* ------------------------------------------------------------------- */ /* Config /* ------------------------------------------------------------------- */ // =====> StatusCodes import { BAD_REQUEST } from 'http-status'; // =====> Constants import { noParamsMsg } from '../utils/constants'; // =====> Services import { send, removeParams } from '../services'; /* ------------------------------------------------------------------- */ /* Middleware /* ------------------------------------------------------------------- */ export const checkParams = ( req: Request, res: Response, next: NextFunction ): Response | void => { // Get necessary request params const { originalUrl, method, headers, query } = req; const { referer } = headers; const { clientId, clientSecret, client, app, instance } = query; // Remove params form url const responseUrl = removeParams(originalUrl); // If no one pf params -> send error if (!clientId || !clientSecret || !client || !app || !instance) return send( res, BAD_REQUEST, noParamsMsg, responseUrl, method, referer, query ); // Pass further if everything is ok next(); };
05aaa5a42f1d9c72eb436ecaab52461841ba9ca0
TypeScript
wavesplatform/node-state
/src/utils/console.ts
2.90625
3
import { blue, green, yellow, red } from 'cli-color'; module log { const call = (color: (...args: Array<any>) => string) => (item: any) => color(item); export let level: 'verbose' | 'errors' = 'errors'; export function log(...args: Array<any>) { if (level === 'verbose') { console.log(...args.map(call(green))); } } export function info(...args: Array<any>) { console.info(...args.map(call(blue))); } export function warn(...args: Array<any>) { console.warn(...args.map(call(yellow))); } export function error(...args: Array<any>) { console.error(...args.map(call(red))); } } export default log;
ec1394974757e0a8134fc0c72412df7b10fcb12c
TypeScript
ineveraskedforthis/2
/static/modules/Battle/battle_image_events.ts
2.546875
3
import { battle_position, UnitSocket, unit_id } from "../../../shared/battle_data" import { socket } from "../globals.js"; import { IMAGES } from "../load_images.js"; import { BattleImage, battle_canvas, battle_canvas_context, camera, player_unit_id, units_views } from "./battle_image.js"; import { position_c } from "./battle_image_helper.js"; import { BattleUnitView } from "./battle_view.js"; import { BATTLE_MOVEMENT_SPEED } from "./constants.js"; const INSTANT_EVENT_DURATION = 1 //seconds function new_log_message(msg: string) { if (msg == null) { return } if (msg == 'ok') return; var log = document.getElementById('log')!; var new_line = document.createElement('p'); var text = document.createTextNode(msg); new_line.append(text); log.appendChild(new_line); log.scrollTop = log.scrollHeight } export class BattleImageEvent { // ap_before: number ap_change_left: number ap_change: number hp_change_left: number hp_change: number unit: unit_id logged: boolean time_passed: number duration: number event_id: number constructor(event_id: number, unit_id: unit_id, ap_change: number, hp_change: number, duration: number) { this.unit = unit_id this.ap_change = ap_change this.ap_change_left = ap_change this.hp_change = hp_change this.hp_change_left = hp_change this.logged = false this.event_id = event_id this.time_passed = 0 this.duration = duration // this.ap_before = unit.ap } /** * returns true if effect is finished * @param dt number: time passed */ effect(dt: number): boolean { if (!this.logged) { this.on_start() this.logged = true let unit = units_views[this.unit] if (unit == undefined) return true unit.hp = unit.hp + this.hp_change unit.ap = unit.ap + this.ap_change unit.ap_change = this.ap_change_left unit.hp_change = this.hp_change_left return false } this.time_passed += dt this.update(dt) if (this.time_passed >= this.duration) { this.ap_change_left = 0 this.hp_change_left = 0 return true } this.ap_change_left = this.ap_change * (this.duration - this.time_passed) / this.duration this.hp_change_left = this.hp_change * (this.duration - this.time_passed) / this.duration let unit = units_views[this.unit] if (this.hp_change_left < -1) { unit.a_image.set_action('attacked') } else { unit.a_image.set_action('idle') } unit.ap_change = this.ap_change_left unit.hp_change = this.hp_change_left camera.x = Math.sin(this.hp_change_left / 4) * 30 return false } /** * Set up data and logs it in chat for the event when it is updated for the first time */ on_start() { new_log_message('some event') } /** * Updates data during event */ update(dt: number) { } /** * Calculates required time to finish event * @returns Seconds required for an event */ estimated_time_left(): number { return this.duration - this.time_passed } } export class MoveEvent extends BattleImageEvent { target_position: battle_position; total_distance: number; constructor(event_id: number, unit_id: unit_id, ap_change: number, target: battle_position) { const unit = units_views[unit_id] let direction = position_c.diff(unit.position, target) let norm = position_c.norm(direction) super(event_id, unit_id, ap_change, 0, norm / BATTLE_MOVEMENT_SPEED) this.target_position = target this.total_distance = norm } on_start(): void { let unit = units_views[this.unit] let message = unit.name + ' moved (' + this.target_position.x + ' ' + this.target_position.y + ')' // let unit= units_views[this.unit] let direction_vec = position_c.diff(this.target_position, unit.position) if (direction_vec.x < 0) { unit.orientation = 'left' } else { unit.orientation = 'right' } new_log_message(message) } update(dt: number): void { const unit = units_views[this.unit] let direction = position_c.diff(this.target_position, unit.position) let norm = position_c.norm(direction) const move = position_c.scalar_mult(BATTLE_MOVEMENT_SPEED / norm * dt, direction) if (norm < BATTLE_MOVEMENT_SPEED * dt) { unit.position = this.target_position unit.a_image.set_action('idle') if (player_unit_id == unit.id) { socket.emit('req-flee-chance') } } else { unit.position = position_c.sum( unit.position, move ) unit.a_image.set_action('move') } } } export class EndTurn extends BattleImageEvent { time_passed: number constructor(event_id: number, unit_id: unit_id, ap_change: number){ super(event_id, unit_id, ap_change, 0, INSTANT_EVENT_DURATION) this.time_passed = 0 } on_start(): void { let unit = units_views[this.unit] if (unit != undefined) new_log_message('end turn' + unit.name) this.logged = true } } export class NewUnitEvent extends BattleImageEvent { time_passed: number data: UnitSocket constructor(event_id: number, unit_id: unit_id, data: UnitSocket) { super(event_id, unit_id, 0, 0, 0) this.unit = unit_id this.data = data this.time_passed = 0 } on_start(): void { let unit = units_views[this.unit] if (unit != undefined) return BattleImage.load_unit(this.data) unit = units_views[this.unit] new_log_message('new fighter: ' + unit.name) } } export class UpdateDataEvent extends BattleImageEvent { type: 'update' unit: unit_id time_passed: number data: UnitSocket constructor(event_id: number, unit_id: unit_id, data: UnitSocket) { super(event_id, unit_id, 0, 0, INSTANT_EVENT_DURATION) this.unit = unit_id this.data = data this.type = 'update' this.time_passed = 0 } on_start(): void { let unit = units_views[this.unit] if (unit == undefined) return new_log_message('update data of ' + unit.name) this.ap_change = this.data.ap - unit.ap this.hp_change = this.data.hp - unit.hp this.ap_change_left = this.ap_change this.hp_change_left = this.hp_change unit.range = this.data.range let direction_vec = position_c.diff(this.data.position, unit.position) if (direction_vec.x < 0) { unit.orientation = 'left' } else if (direction_vec.x > 0) { unit.orientation = 'right' } unit.position = this.data.position unit.next_turn = this.data.next_turn BattleImage.update_unit_displays(unit.id) } } export class UnitLeftEvent extends BattleImageEvent { on_start(): void { BattleImage.unload_unit_by_id(this.unit) } } export class ClearBattleEvent extends BattleImageEvent { effect(dt: number) { console.log('clear battle') BattleImage.reset() return true } } function get_attack_direction(a: BattleUnitView, d: BattleUnitView) { let hor = 'left' if (a.position.x < d.position.x) { hor = 'right' } let ver = 'up' if (a.position.y < d.position.y) { ver = 'down' } return hor + '_' + ver } // write attack stages // stand // prepare // hit const ATTACK_DURATION = 2 const STAND_UNTIL = 0.2 const PREPARE_UNTIL = 1.8 const HIT_UNTIL = 2 export class AttackEvent extends BattleImageEvent { target: unit_id constructor(event_id: number, unit_id: unit_id, ap_change: number, hp_change: number, target_id: unit_id) { super(event_id, unit_id, ap_change, hp_change, ATTACK_DURATION) this.target = target_id } on_start(): void { let unit_view_attacker = units_views[this.unit] let unit_view_defender = units_views[this.target] if (unit_view_attacker == undefined || unit_view_defender == undefined) return let direction_vec = position_c.diff(unit_view_attacker.position, unit_view_defender.position) direction_vec = position_c.scalar_mult(1/position_c.norm(direction_vec), direction_vec) if (direction_vec.x < 0) { unit_view_attacker.orientation = 'left' } else { unit_view_attacker.orientation = 'right' } unit_view_defender.current_animation = {type: 'attacked', data: {direction: direction_vec, dodge: false}} unit_view_attacker.current_animation = {type: 'attack', data: direction_vec} new_log_message(unit_view_attacker.name + ' attacks ' + unit_view_defender.name) } update(dt: number): void { let attacker = units_views[this.unit] let defender = units_views[this.target] if (attacker == undefined || defender == undefined) return if (this.time_passed <= STAND_UNTIL) { attacker.a_image.set_action('idle') } else if (this.time_passed <= PREPARE_UNTIL) { attacker.a_image.set_action('prepare') } else if (this.time_passed <= HIT_UNTIL) { attacker.a_image.set_action('attack') let position = position_c.battle_to_canvas(defender.position, camera) battle_canvas_context.drawImage(IMAGES['attack_' + 0], position.x - 50, position.y - 80, 100, 100) } } } export class RangedAttackEvent extends BattleImageEvent { target: unit_id constructor(event_id: number, unit_id: unit_id, ap_change: number, hp_change: number, target_id: unit_id) { const unit = units_views[unit_id] const unit2 = units_views[target_id] let direction = position_c.diff(unit.position, unit2.position) let norm = position_c.norm(direction) super(event_id, unit_id, ap_change, hp_change, norm * 2) this.target = target_id } on_start(): void { let unit_view_attacker = units_views[this.unit] let unit_view_defender = units_views[this.target] let direction_vec = position_c.diff(unit_view_attacker.position, unit_view_defender.position) direction_vec = position_c.scalar_mult(1/position_c.norm(direction_vec), direction_vec) if (direction_vec.x < 0) { unit_view_attacker.orientation = 'left' } else { unit_view_attacker.orientation = 'right' } unit_view_defender.current_animation = {type: 'attacked', data: {direction: direction_vec, dodge: false}} unit_view_attacker.current_animation = {type: 'attack', data: direction_vec} new_log_message(unit_view_attacker.name + ' attacks ' + unit_view_defender.name) } update(dt: number): void { let attacker = units_views[this.unit] let defender = units_views[this.target] const t = this.time_passed / this.duration const A = position_c.battle_to_canvas(attacker.position, camera) const B = position_c.battle_to_canvas(defender.position, camera) const projx = A.x * (1 - t) + B.x * (t) const projy = A.y * (1 - t) + B.y * (t) battle_canvas_context.beginPath(); battle_canvas_context.fillStyle = "rgba(200, 0, 0, 0.5)" battle_canvas_context.arc(projx, projy, 50, 0, 2 * Math.PI) battle_canvas_context.fill(); if (this.time_passed <= STAND_UNTIL) { attacker.a_image.set_action('idle') } else if (this.time_passed <= PREPARE_UNTIL) { attacker.a_image.set_action('prepare') } else if (this.time_passed <= HIT_UNTIL) { attacker.a_image.set_action('attack') let position = position_c.battle_to_canvas(defender.position, camera) battle_canvas_context.drawImage(IMAGES['attack_' + 0], position.x - 50, position.y - 80, 100, 100) } else { attacker.a_image.set_action('idle') } } } // export class MissEvent { // type: 'miss' // unit_id: unit_id // target_id: unit_id // constructor(unit: unit_id, target: unit_id) { // this.type = 'miss' // this.unit_id = unit // this.target_id = target // } // effect() { // let unit_view_attacker = units_views[this.unit_id] // let unit_view_defender = units_views[this.target_id] // let direction_vec = position_c.diff(unit_view_attacker.position, unit_view_defender.position) // direction_vec = position_c.scalar_mult(1/position_c.norm(direction_vec), direction_vec) // unit_view_defender.animation_sequence.push({type: 'attacked', data: {direction: direction_vec, dodge: true}}) // } // generate_log_message():string { // let unit = units_data[this.unit_id] // let target = units_data[this.target_id] // let result = unit.name + ' attacks ' + target.name + ': ' // return result + ' MISS!'; // } // } export class RetreatEvent extends BattleImageEvent { constructor(event_id: number, unit_id: unit_id, cost: number) { super(event_id, unit_id, 0, 0, cost) } on_start(): void { let unit = units_views[this.unit] if (unit != undefined) { unit.killed = true } if (this.unit == player_unit_id) { new_log_message('You had retreated from the battle') } else { new_log_message(this.unit + 'had retreated from the battle') } } } export class NewTurnEvent extends BattleImageEvent { data: UnitSocket constructor(event_id: number, unit_id: unit_id, data: UnitSocket) { super(event_id, unit_id, 0, 0, INSTANT_EVENT_DURATION) this.unit = unit_id this.data = data this.time_passed = 0 } on_start(): void { let time_passed = this.data.next_turn BattleImage.set_current_turn(this.unit, time_passed) } }
96006ec448f135e2ee621df7884928ff5155122c
TypeScript
maariacasasola/cbd-2021
/src/assets/controllers/artist-tracks.controller.ts
2.53125
3
import 'reflect-metadata'; import { injectable, inject } from 'inversify'; import { interfaces, controller, httpGet, requestParam, } from 'inversify-express-utils'; import { ApiPath, SwaggerDefinitionConstant, ApiOperationGet, } from 'swagger-express-ts'; import * as express from 'express'; import { ArtistsService } from '../services/artists.service'; @ApiPath({ name: 'Artist Tracks', path: '/tracks/artist/{id}', }) @controller('/tracks/artist/:id') @injectable() export class ArtistTracksController implements interfaces.Controller { constructor(@inject(ArtistsService.name) private artistsService: ArtistsService) { } @ApiOperationGet({ description: 'Get artist tracks objects', parameters: { path: { id: { required: true, type: SwaggerDefinitionConstant.Parameter.Type.STRING, }, }, }, responses: { 500: { description: 'Internal server error' }, 404: { description: 'Not found' }, 400: { description: 'Parameters fail' }, 200: { description: 'Successful' } }, summary: 'Get tracks of artist' }) @httpGet('/') public async getArtistTracks( @requestParam('id') id: string, request: express.Request, response: express.Response, next: express.NextFunction ) { try { const message = await this.artistsService.getArtistTracks(id); if (message === 'Artist with id ' + id + ' does not exist') { return response.status(404).end(); } else if (message === 'An error occurred') { return 'An error occurred'; } return message; } catch (error) { return response.status(500).end(); } } }
bcdde7e74893e56a43c0f9fdd36ad432ac5bea6a
TypeScript
tcgdex/cards-database
/data/Sun & Moon/Celestial Storm/76.ts
2.625
3
import { Card } from '../../../interfaces' import Set from '../Celestial Storm' const card: Card = { name: { en: "Meditite", fr: "Méditikka", es: "Meditite", it: "Meditite", pt: "Meditite", de: "Meditie" }, illustrator: "Shibuzoh.", rarity: "Common", category: "Pokemon", set: Set, dexId: [ 307, ], hp: 70, types: [ "Fighting", ], stage: "Basic", attacks: [ { cost: [ "Fighting", ], name: { en: "Bide", fr: "Patience", es: "Venganza", it: "Pazienza", pt: "Aguardar", de: "Geduld" }, effect: { en: "Flip a coin. If heads, if this Pokémon would be Knocked Out by damage from an attack during your opponent’s next turn, it is not Knocked Out, and its remaining HP becomes 10.", fr: "Lancez une pièce. Si c’est face, et si ce Pokémon doit être mis K.O. par les dégâts d’une attaque pendant le prochain tour de votre adversaire, il n’est pas mis K.O., mais il n’a plus que 10 PV.", es: "Lanza 1 moneda. Si sale cara, si este Pokémon fuese a quedar Fuera de Combate por el daño de un ataque durante el próximo turno de tu rival, este Pokémon no queda Fuera de Combate, y sus PS restantes pasan a ser 10.", it: "Lancia una moneta. Se esce testa, se questo Pokémon sta per essere messo KO dai danni di un attacco durante il prossimo turno del tuo avversario, non viene messo KO e i suoi PS rimanenti diventano 10.", pt: "Jogue 1 moeda. Se sair cara, se este Pokémon estiver prestes a ser Nocauteado pelo dano de um ataque durante a próxima vez de jogar do seu oponente, ele não será Nocauteado e o PS restante dele será 10.", de: "Wirf 1 Münze. Bei Kopf, wenn dieses Pokémon während des nächsten Zuges deines Gegners durch Schaden einer Attacke kampfunfähig würde, wird es nicht kampfunfähig und seine verbleibenden KP sind gleich 10." }, }, { cost: [ "Fighting", "Fighting", ], name: { en: "Kick", fr: "Koud’Pied", es: "Patada", it: "Calcio", pt: "Chute", de: "Tritt" }, damage: 30, }, ], weaknesses: [ { type: "Psychic", value: "×2" }, ], retreat: 1, } export default card
ef60a1e054ebf8d7985704bac129de536e5d8f6a
TypeScript
huynv81/react-web-editor
/src/hooks/useResize.ts
2.53125
3
import React, { useEffect, useState } from "react"; import { changeComponentLocationByHandler, convertPointsByUnit } from "../utils/ui"; import { ComponentSize, ComponentStyle, Dispatcher, ResizeProps } from "../types/ui"; import { MIN_HEIGHT, MIN_WIDTH } from "../constants/ui"; interface ComponentInformation { isResizing: boolean; direction: string; currentX: number; currentY: number; } interface UseResizeProps extends ComponentStyle { onResize: Dispatcher<ResizeProps>; resizeBoardOption?: ComponentSize; unit: string; } interface UseResizeReturns { handleMouseDown: (ev: React.MouseEvent<HTMLDivElement>) => void; isResizing: boolean; } const useResize = ({ width, height, top, left, onResize, resizeBoardOption, unit, }: UseResizeProps): UseResizeReturns => { const [componentInformation, setComponentInformation] = useState<ComponentInformation>({ isResizing: false, direction: "", currentX: 0, currentY: 0, }); useEffect(() => { if (!componentInformation.isResizing) { return; } const handleMouseMove = (ev: MouseEvent): void => { ev.stopPropagation(); const { clientX, clientY } = convertPointsByUnit(unit, ev.clientX, ev.clientY); const { currentX, currentY, direction } = componentInformation; const deltaX = clientX - currentX; const deltaY = clientY - currentY; const { newWidth, newHeight, newLeft, newTop } = changeComponentLocationByHandler( direction, left, top, width, height, deltaX, deltaY, resizeBoardOption, ); if (newWidth < MIN_WIDTH || newHeight < MIN_HEIGHT) { return; } onResize((prev) => ({ ...prev, width: newWidth, height: newHeight, left: newLeft, top: newTop, })); setComponentInformation((prev) => ({ ...prev, currentX: clientX, currentY: clientY, })); }; const handleMouseUp = (): void => { setComponentInformation((prev) => ({ ...prev, direction: "", isResizing: false, })); }; document.addEventListener("mousemove", handleMouseMove); document.addEventListener("mouseup", handleMouseUp); return () => { document.removeEventListener("mousemove", handleMouseMove); document.removeEventListener("mouseup", handleMouseUp); }; }, [componentInformation, onResize, width, top, left, height, resizeBoardOption, unit]); const handleMouseDown = (ev: React.MouseEvent<HTMLDivElement>): void => { ev.preventDefault(); const { currentTarget: { className } } = ev; const { clientX, clientY } = convertPointsByUnit(unit, ev.clientX, ev.clientY); setComponentInformation((prev) => ({ ...prev, isResizing: true, direction: className, currentX: clientX, currentY: clientY, })); }; return { handleMouseDown, isResizing: componentInformation.isResizing, }; }; export default useResize;
d05aff1788ea3e68e48366f384d8ac20b452c0e4
TypeScript
dggluz/typescript-node-starter
/scripts/init/init.ts
2.671875
3
import {resolve, join} from 'path'; import {IPackageJson} from './package.json'; import {readJSON, writeFile} from './promise-fs'; import {askDefault, close} from './promise-readline'; import {which, exec, rm} from 'shelljs'; const root = resolve(__dirname, '../../../'); if (!which('git')) { console.error('You need to have git installed :\'('); process.exit(1); } async function main () { // Read package json and prompt for the project information const [projectInfo, packageJSON] = await Promise.all([promptProjectInfo(), readPackageJSON()]); // Replace package json defaults const newPackage = { ...packageJSON, version: '0.0.1', description: '', author: getGitAuthor(), name: projectInfo.name, license: projectInfo.license }; // Remove post install delete newPackage.scripts['postinstall']; // Write the new package json back await writeFile(join(root, 'package.json'), JSON.stringify(newPackage, null, 2)); // Reset git and make first commit resetGit(projectInfo.name, packageJSON.version); } // Function to read the project package json const readPackageJSON = () => readJSON<IPackageJson>(join(root, 'package.json')); // Prompt the user for the project information async function promptProjectInfo () { const folderName = root.split('/').pop(); const name = await askDefault(`Name [${folderName}]: `, folderName || ''); const license = await askDefault('License [MIT]: ', 'MIT'); close(); return {name, license}; } // Get a string with the users git info, like "Hernan Rajchert <hrajchert@gmail.com>" function getGitAuthor () { const {name, email} = getGitUserInfo(); return `${name} <${email}>`; } // Reads git user info function getGitUserInfo () { const name = exec('git config user.name', {silent: true}).stdout.toString().trim(); const email = exec('git config user.email', {silent: true}).stdout.toString().trim(); return {name, email}; } function resetGit (projectName: string, tnsVersion: string) { // Delete current git rm('-rf', join(root, '.git')); // Initialize git with a new first commit exec(`git init "${root}"`); exec('git add .'); exec(`git commit -m "chore(general): Initialize ${projectName} using typescript-node-starter:${tnsVersion}"`); } main();
73dbde75438f9eed7815966304f31c6c10952c4c
TypeScript
edgesite/ts-serialize
/index.ts
3.078125
3
import 'reflect-metadata'; interface SerializableAttrOptions { level?: string | symbol; transformer?: (value: any) => any; } interface SerializationOptions { // if strict mode is enable, only @SerializableAttr will be emit. strict?: boolean; } type ISerializeInfo = SerializationOptions & { fields: { [key: string]: SerializableAttrOptions }; }; const SerializeInfo = Symbol('SerializeInfo'); const getMetadata = (target: object): ISerializeInfo | undefined => { return Reflect.getMetadata(SerializeInfo, target); } const getMetadataOrNew = (target: object) => { let info = getMetadata(target); if (info === undefined) { info = { fields: {} }; Reflect.defineMetadata(SerializeInfo, info, target); } return info!; } export const Serializable = (options: SerializationOptions = {}): ClassDecorator => { return (target) => { const info = getMetadataOrNew(target); simpleMerge(info, options); return target; } } const simpleMerge = (dst: any, src: any) => { Object.keys(src).forEach(k => { if (src[k] !== undefined) dst[k] = src[k]; }); } export const SerializableAttr = (options: SerializableAttrOptions = {}): PropertyDecorator => { return (target, key: string) => { getMetadataOrNew(target.constructor).fields[key] = options; } } const NonSerializedSymbol = Symbol('NonSerializedSymbol'); export const NonSerialized = () => SerializableAttr({level: NonSerializedSymbol}); interface SerializeOptions { level?: string; } export const serialize = (object: any, options: SerializeOptions = {}) => { const info = getMetadata(object.constructor); const getReplacer = () => { if (!info) return null; return ((key: string, value: string) => { if (key === '') return value; const field = info.fields[key]; if (field) { if (field.level !== undefined && field.level !== options.level) return undefined; return field.transformer ? field.transformer(value) : value; } else if (!info.strict) { return value; } }); } return JSON.stringify(object, getReplacer() as any); }
ad696193941f25a80c7715b55587a1624a48dcdd
TypeScript
cordeirolucas42/device-manager-interface
/src/app/server-api.service.ts
2.53125
3
import { Injectable } from '@angular/core'; import { Category } from './category'; import { Device } from './device'; import { Observable, of } from 'rxjs'; import { MessageService } from './message.service'; import { HttpClient, HttpHeaders } from '@angular/common/http'; import { catchError, map, tap } from 'rxjs/operators'; @Injectable({ providedIn: 'root', }) export class ServerApiService { private apiURL = 'https://device-manager-api42.herokuapp.com'; // URL to web api httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }), }; constructor( private messageService: MessageService, private http: HttpClient ) {} createDevice(newDevice: Device): Observable<Device> { return this.http .post<Device>(`${this.apiURL}/devices`, newDevice, this.httpOptions) .pipe( tap((newDevice: Device) => this.messageService.add(`Created new device with id=${newDevice.id}`) ), catchError(this.handleError<Device>(`createDevice`)) ); } getDevices(): Observable<Device[]> { return this.http.get<Device[]>(`${this.apiURL}/devices`).pipe( tap((_) => this.messageService.add('')), catchError(this.handleError<Device[]>('getDevices', [])) ); } getDevice(id: number): Observable<Device> { return this.http.get<Device>(`${this.apiURL}/devices/${id}`).pipe( tap((_) => this.messageService.add('')), catchError(this.handleError<Device>(`getDevice id=${id}`)) ); } deleteDevice(id: number): Observable<Device> { return this.http .delete<Device>(`${this.apiURL}/devices/${id}`, this.httpOptions) .pipe( tap((_) => this.messageService.add(`Deleted device id=${id}`)), catchError(this.handleError<Device>(`deleteDevice id=${id}`)) ); } createCategory(newCategory: Category): Observable<Category> { return this.http .post<Category>( `${this.apiURL}/categories`, newCategory, this.httpOptions ) .pipe( tap((newCategory: Category) => this.messageService.add( `Created new category with id=${newCategory.id}` ) ), catchError(this.handleError<Category>(`createCategory`)) ); } getCategories(): Observable<Category[]> { return this.http.get<Category[]>(`${this.apiURL}/categories`).pipe( tap((_) => this.messageService.add('')), catchError(this.handleError<Category[]>('getCategories', [])) ); } getCategory(id: number): Observable<Category> { return this.http.get<Category>(`${this.apiURL}/categories/${id}`).pipe( tap((_) => this.messageService.add('')), catchError(this.handleError<Category>(`getCategory id=${id}`)) ); } deleteCategory(id: number): Observable<Category> { return this.http .delete<Category>(`${this.apiURL}/categories/${id}`, this.httpOptions) .pipe( tap((_) => this.messageService.add(`Deleted category id=${id}`)), catchError(this.handleError<Category>(`deleteCategory id=${id}`)) ); } /** * Handle Http operation that failed. * Let the app continue. * @ param operation - name of the operation that failed * @ param result - optional value to return as the observable result */ private handleError<T>(operation = 'operation', result?: T) { return (error: any): Observable<T> => { // TODO: send the error to remote logging infrastructure console.error(error); // log to console instead // TODO: better job of transforming error for user consumption this.messageService.add(`${operation} failed: ${error.message}`); // Let the app keep running by returning an empty result. return of(result as T); }; } }
8c97a14b0eb7e043425cc519beaac3971ba5bb2a
TypeScript
torqu4to/ITE002-2021
/src/modules/products/controllers/ProductController.ts
2.6875
3
import { Request, Response } from "express"; import CreateProductService from "../services/CreateProductService"; class ProductController { public async create(req: Request, res: Response): Promise<Response> { // recuperar dados para insercao let {name, price, quantity} = req.body; let createProduct = new CreateProductService() let product = await createProduct.execute({ name, price, quantity }) return res.json(product) } } export default ProductController;
97af1c93b80518a1184edea7e6a2a1830357efd4
TypeScript
phsarah/backend-project
/src/data/userDatabase.ts
2.734375
3
import { userOutputDTO } from "../business/entities/user"; import BaseDatabase from "./baseDatabase"; import { Model } from "./model/models"; export class UserDatabase extends BaseDatabase{ private static TABLE_NAME = "PIXALABON_USERS"; public async createUser(input: any, id: string): Promise<void>{ try{ const {name, email, nickname, password } = input await BaseDatabase.connection.raw(` INSERT INTO ${UserDatabase.TABLE_NAME}(id, name, email, nickname, password) VALUES( "${id}", "${name}", "${email}", "${nickname}", "${password}" )`) } catch(e){ throw new Error(e.message && e.sqlMessage) } } public async getUserByEmailOrNickname(emailOrNickname: string): Promise<any>{ try{ const result = await BaseDatabase.connection.raw(` SELECT * FROM ${UserDatabase.TABLE_NAME} WHERE email = "${emailOrNickname}" OR nickname = "${emailOrNickname}" `) return result[0][0] } catch(e){ throw new Error(e.message && e.sqlMessage) } } public async getUserById(id: string): Promise<userOutputDTO>{ try{ const result = await BaseDatabase.connection.raw(` SELECT * FROM ${UserDatabase.TABLE_NAME} WHERE id = "${id}" `) return Model.toUserModel(result[0][0]) } catch(e){ throw new Error(e.message && e.sqlMessage) } } }
40a9344ea181d94ec2bc8b096f2b205320543541
TypeScript
alelode/flightlog-dump
/db/database.ts
2.875
3
import { Pilot, Club, Flight, TakeOff } from "../types"; const sqlite3 = require("sqlite3").verbose(); class Database { db; initDb() { var filename = "flightlog"; this.db = new sqlite3.Database( "./" + filename + ".sqlite3", sqlite3.OPEN_READWRITE | sqlite3.OPEN_CREATE, function(err) { if (err) console.log(err.message); } ); this.db.serialize(() => { this.db.run( "CREATE TABLE IF NOT EXISTS flights (id NUMBER, pilotid NUMBER, date TEXT, country TEXT, takeoff TEXT, glider TEXT, duration TEXT, distance TEXT, maxaltitude NUMBER, description TEXT, opendistance TEXT, trackloglink TEXT)" ); this.db.run( "CREATE TABLE IF NOT EXISTS pilots (id NUMBER, name TEXT, country NUMBER, club TEXT, license TEXT, wings TEXT)" ); this.db.run("CREATE TABLE IF NOT EXISTS clubs (id NUMBER, name TEXT)"); this.db.run( "CREATE TABLE IF NOT EXISTS takeoffs (id NUMBER, name TEXT, region TEXT, toptobottom NUMBER, asl NUMBER, description TEXT, directions TEXT)" ); }); } insertClub(club: Club) { this.db.serialize(() => { var stmt = this.db.prepare("INSERT INTO clubs VALUES (?,?)"); stmt.run(club.id, club.name); stmt.finalize(); }); } insertPilot(pilot: Pilot) { this.db.serialize(() => { var stmt = this.db.prepare( "INSERT INTO pilots (id, name, club, country, license, wings) VALUES (?,?,?,?,?,?)" ); stmt.run( pilot.id, pilot.name, pilot.club, pilot.country, pilot.license, pilot.wings ); stmt.finalize(); }); } insertTakeOff(takeoff: TakeOff) { this.db.serialize(() => { var stmt = this.db.prepare( "INSERT INTO takeoffs (id, name, region, toptobottom, asl, description) VALUES (?,?,?,?,?,?)" ); stmt.run( takeoff.id, takeoff.name, takeoff.region, takeoff.toptobottom, takeoff.asl, takeoff.description ); stmt.finalize(); }); } insertFlight(flight: Flight) { this.db.serialize(() => { var stmt = this.db.prepare( "INSERT INTO flights (id, pilotid, date, country, takeoff, glider, duration, distance, maxaltitude, description, opendistance, trackloglink) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)" ); stmt.run( flight.id, flight.pilotid, flight.date, flight.country, flight.takeoff, flight.glider, flight.duration, flight.distance, flight.maxaltitude, flight.description, flight.opendistance, flight.trackloglink ); stmt.finalize(); }); } getHighestIndex(table: string, callback: (id: number) => void) { this.db.get("SELECT MAX(id) from " + table, (err, row) => { if (err) { console.log(err); return null; } else { callback(row["MAX(id)"]); } }); } insertPilots(pilots: Pilot[]) { this.db.serialize(() => { var stmt = this.db.prepare( "INSERT INTO pilots (id,name, club, country, license, wings) VALUES (?,?,?,?,?)" ); for (let pilot of pilots) { stmt.run( pilot.id, pilot.name, pilot.club, pilot.country, pilot.license, pilot.wings ); } stmt.finalize(); }); } closeDb() { this.db.close(); } emptyTable(table: string) { this.db.run("DELETE FROM " + table); } } export default Database;
ef97b34819984d182d85b75d6e397551ede4520b
TypeScript
nginformatica/flipper-ui
/src/core/types.ts
2.53125
3
import type { CSSProperties } from 'react' export interface DefaultProps { /** * The children of the component. * @optional */ children?: React.ReactNode /** * The style of the component. * @optional */ style?: CSSProperties /** * The class name of the component. * @optional */ className?: string /** * The id of the component. * @optional */ margin?: number | string /** * The padding of the component. * @optional */ padding?: number | string /** * The name of the component. * @optional */ name?: string /** * The id of the component. * @optional */ id?: string }
83717f4a5700ee23f11c0a370d3c40e92a7110a8
TypeScript
jeroenmaas/advent-of-code
/2022/day9.ts
3.25
3
import {readFileSync} from "fs"; import {range} from "lodash"; const file: string = readFileSync('./day9', 'utf-8'); interface Action { direction: string; count: number } const actions = file.trim().split('\r\n').map(i => i.split(' ')).map(i => { return { direction: i[0], count: parseInt(i[1]) } as Action }); let headPos = [0, 0] let tailPos = [0, 0] let uniqueCoordinates = new Set<string>(); uniqueCoordinates.add([0, 0].join('_')); actions.forEach(a => { let dir = [0, 0]; if(a.direction == 'U') { dir[1] = 1; }else if (a.direction == 'D') { dir[1] = -1; }else if (a.direction == 'L') { dir[0] = -1; }else if (a.direction == 'R') { dir[0] = 1; }else { throw new Error("Unknown dir: " + dir); } range(0, a.count).forEach(_ => { headPos[0] += dir[0]; headPos[1] += dir[1]; // 2, 0 / -2, 0 const dist = [headPos[0] - tailPos[0], headPos[1] - tailPos[1]]; // No need to move. We are still touching to the head if(Math.abs(dist[0]) <= 1 && Math.abs(dist[1]) <= 1) { return; }else if(Math.abs(dist[0]) > 1 && Math.abs(dist[1]) == 0) { tailPos[0] += dist[0] > 0 ? 1 : -1; }else if(Math.abs(dist[1]) > 1 && Math.abs(dist[0]) == 0) { tailPos[1] += dist[1] > 0 ? 1 : -1; }else { tailPos[0] += dist[0] > 0 ? 1 : -1; tailPos[1] += dist[1] > 0 ? 1 : -1; } uniqueCoordinates.add(tailPos.join('_')) }); }); console.log('part1: ', uniqueCoordinates.size); let knotsPositions = range(0, 9).map(r => [0, 0]); headPos = [0, 0] uniqueCoordinates = new Set<string>(); uniqueCoordinates.add([0, 0].join('_')); actions.forEach(a => { let dir = [0, 0]; if(a.direction == 'U') { dir[1] = -1; }else if (a.direction == 'D') { dir[1] = 1; }else if (a.direction == 'L') { dir[0] = -1; }else if (a.direction == 'R') { dir[0] = 1; }else { throw new Error("Unknown dir: " + dir); } range(0, a.count).forEach(_ => { headPos[0] += dir[0]; headPos[1] += dir[1]; let previous = headPos; knotsPositions.forEach(k => { // 2, 0 / -2, 0 const dist = [previous[0] - k[0], previous[1] - k[1]]; if(Math.abs(dist[0]) <= 1 && Math.abs(dist[1]) <= 1) { // No need to move. We are still touching to the head }else if(Math.abs(dist[0]) > 1 && Math.abs(dist[1]) == 0) { k[0] += dist[0] > 0 ? 1 : -1; }else if(Math.abs(dist[1]) > 1 && Math.abs(dist[0]) == 0) { k[1] += dist[1] > 0 ? 1 : -1; }else { k[0] += dist[0] > 0 ? 1 : -1; k[1] += dist[1] > 0 ? 1 : -1; } previous = k; }); uniqueCoordinates.add(knotsPositions.at(-1)!.join('_')) }); }); console.log('part2: ', uniqueCoordinates.size);
801778d602bda463513a8bce691f03d363f2ec4c
TypeScript
teemukaaria/useful-checklists
/client/src/store/modules/app/actions.ts
2.65625
3
import { ActionTree, ActionContext } from 'vuex'; import firebase from 'firebase'; import { createModuleActions } from '@/store/utils'; import { State, User } from './state'; import { CombinedState } from '@/store'; import { Mutations } from './mutations'; type AugmentedActionContext = { commit<K extends keyof Mutations>( key: K, payload: Parameters<Mutations[K]>[1] ): ReturnType<Mutations[K]>; } & Omit<ActionContext<State, CombinedState>, 'commit'>; enum ActionTypes { LOGOUT = 'LOGOUT', LOGIN = 'LOGIN', FETCH_USER = 'FETCH_USER' } export const Actions = createModuleActions('APP', ActionTypes); export interface ActionsInterface { [Actions.LOGOUT](context: AugmentedActionContext): void; [Actions.LOGIN](context: AugmentedActionContext, user: User): void; [Actions.FETCH_USER](context: AugmentedActionContext, id: string): void; } export default { [Actions.LOGOUT]({ commit }) { commit(Mutations.SET_USER, null); }, [Actions.LOGIN]({ commit, dispatch }, user: User) { dispatch(Actions.FETCH_USER, user.id); commit(Mutations.SET_USER, user); }, async [Actions.FETCH_USER]({ commit }, id: string) { const snap = await firebase .firestore() .doc(`users/${id}`) .get(); commit(Mutations.SET_USER, { ...snap.data(), id: snap.id } as User); } } as ActionTree<State, CombinedState> & ActionsInterface;
fa27c86b4de076f97698079a0afaf8cebf1d5240
TypeScript
zcmjs/TypeScript
/src/commonFunctionProblem.ts
3.1875
3
class CommonFunctionProblem { message: string = 'Hello Bitch'; printFunction() { return function () { console.log(this.message); } }; printFunction2() { return () => { console.log(this.message); } }; } let example = new CommonFunctionProblem(); let exampleFunction = example.printFunction(); exampleFunction(); // --> undefinied let exampleFunction2 = example.printFunction2(); exampleFunction2(); //'Hello Bitch!';
875fa98432080fb3f4f6b9579dc8a86a29caa5b9
TypeScript
olli158/Samples
/TypeScript/AngularjsTypeScript/AngularjsTypeScript/Scripts/app/ParticleCtrl.ts
2.546875
3
/// <reference path="../typings/jquery/jquery.d.ts" /> /// <reference path="../typings/angularjs/angular.d.ts" /> module ParticleApp { // Model export class Particle { constructor(public name: string, public symbol: string, public massMeV: number, public subsymbol: string = "", public supsymbol: string = "") { } } export interface Scope { title: string; particles: Particle[]; orderProp: string; } // Controller export class ParticleCtrl { constructor($scope: Scope, $http: any) { //$scope.particles = [ // new Particle("muon", "μ", 105.7, "", "-"), // new Particle("taon", "τ", 1777, "", "-"), // new Particle("electron", "e", 0.511, "", "-"), // new Particle("neutrino (electron)", "ν", 0, "e"), // new Particle("neutrino (muon)", "ν", 0, "μ"), // new Particle("neutrino (taon)", "ν", 0, "τ")]; $http.get('Particle/ListLeptons').success(function (data) { $scope.particles = data; }); $scope.title = "Leptons"; $scope.orderProp = "name"; } } }
14d4a3e84f70b0f7dffd9b717057082e3f92b03b
TypeScript
rajatvijay/production-ts
/src/exhaustiveSwitch.ts
3.25
3
type FieldType = "single_select" | "checkbox"; class UnreachableError extends Error { constructor(val: never, message: string) { super(`Unreachable code reached!`); } } function getFieldCmpStr(fieldType: FieldType) { switch (fieldType) { case "single_select": return "Select"; case "checkbox": return "Checkbox"; default: return new UnreachableError(fieldType, ""); } }
c3a9a6e1efc6930daeab9ae5607d250be644abc7
TypeScript
sanity-io/sanity
/packages/@sanity/cli/src/util/parseArguments.ts
2.859375
3
import minimist from 'minimist' export interface ParsedArguments<F = Record<string, string>> { /** * Group or command name, eg `dataset` (`sanity dataset`) or `import` (`sanity dataset import`) */ groupOrCommand: string // Raw, forwarded arguments, for commands that want to be more explicit about parsing argv: string[] /** * Command flags, without the core options (help, debug, version etc) */ extOptions: F /** * Command arguments, eg any arguments after `sanity <command>` (no flags) */ argsWithoutOptions: string[] /** * Arguments after the ended argument list (--) */ extraArguments: string[] /** * Options mostly relevant for the core CLI runner */ coreOptions: { h: boolean help: boolean d: boolean debug: boolean v: boolean version: boolean } } export function parseArguments(argv = process.argv): ParsedArguments { /* eslint-disable id-length */ // prettier-ignore const { _, h, help, d, debug, v, version, '--': extraArguments, ...extOptions } = minimist(argv.slice(2), { '--': true, boolean: ['h', 'help', 'd', 'debug', 'v', 'version'] }) const [groupOrCommand, ...argsWithoutOptions] = _ return { groupOrCommand, argv, extOptions, argsWithoutOptions, extraArguments: extraArguments || [], // prettier-ignore coreOptions: { h, help, d, debug, v, version, }, } /* eslint-enable id-length */ }
e4907a78a0bc5fb972ffc53c582bab1c73d734b5
TypeScript
khanguslee/GTD
/src/models/todos.ts
2.8125
3
export interface Todo { id: string; created: Date; content: string; status: TodoStatus; } export enum TodoStatus { TODO = 'TODO', AWAITING = 'AWAITING', DONE = 'DONE', } export type TodoState = { allIds: string[]; byIds: { [key: string]: Todo }; };
a245372a137aa088e3a738f95c1d76bb91447de1
TypeScript
six-two/react_payload_builder
/src/app/hex/String.ts
3.34375
3
import ByteString from "./ByteString"; export interface Values { repeatCount: number, pattern: string, type: string, } export const TYPE = "String"; export const TYPE_REVERSED = "String (reversed)"; export class Utils { static defaultValues(): Values { return { pattern: "A", repeatCount: 1, type: TYPE, }; } static stringToBytes(values: Values): ByteString { let bytes = ByteString.fromString(values.pattern); return bytes.repeated(values.repeatCount); } } export class ReversedUtils { static defaultValues(): Values { return { pattern: "A", repeatCount: 1, type: TYPE_REVERSED, }; } static stringToBytes(values: Values): ByteString { let bytes = ByteString.fromString(values.pattern); return bytes.reversed().repeated(values.repeatCount); } } export default Values;
4416957ec15279cedcb48afff62ced28127d1166
TypeScript
Provinite/halloween-2018
/packages/constants/lib/constants.d.ts
3.421875
3
declare module "@clovercoin/constants" { /** * An object mapping named roles to string literals. */ export const ROLES: { admin: string; moderator: string; user: string; } export type Omit<T, K> = Pick<T, Exclude<keyof T, K>>; /** * The type T with all keys optional except those specified. */ export type PartialExcept<T, K extends keyof T> = Omit<Partial<T>, K> & Pick<T, K>; export type PartialKeys<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K> /** * The argument types of the functional type T */ export type ArgumentTypes<T> = T extends (...args: infer U) => infer R ? U : never; /** * "Spread" type U onto type T. Example: * interface Base { * a: string; * b: number; * } * type PartiallyExtendsBase = Assign<Base, {a: number, c: boolean}>; * // { a: number; b: number; c: boolean } */ export type Assign<T, U> = Omit<T, keyof U> & U; }
81b458fc2d1cd0cb3802e172dbc91fc8b7d872e7
TypeScript
patroza/fp-app-framework
/packages/framework/src/infrastructure/mediator/request.ts
2.640625
3
import { NamedHandlerWithDependencies, NamedRequestHandler, requestType } from "./registry" const request = (get: getRequestType): requestType => (requestHandler, input) => { const handler = get(requestHandler) return handler(input) } export default request type getRequestType = <TInput, TOutput, TError>( key: NamedHandlerWithDependencies<any, TInput, TOutput, TError>, ) => NamedRequestHandler<TInput, TOutput, TError>
4113fba460924f4d508e238ac8c592fd3417efdb
TypeScript
ConnorUllmann/engine-ts
/tools/stack.ts
3.609375
4
export class Stack<T> { public readonly elements: T[] = []; constructor() {} public get length(): number { return this.elements.length; } public isEmpty(): boolean { return this.elements.length <= 0; } public pop(): T | null { return this.elements.pop() ?? null; } public push(item: T): void { this.elements.push(item); } public get top(): T | null { return this.elements.last(); } }
55eb402421909560ff921811fdd5aa2b098c393f
TypeScript
morninng/redux_tutorial
/ts/OwnStore_Redux.ts
3.1875
3
/// <reference path="./../typings/globals/redux/index.d.ts" /> const counter = (state = 0, action) => { switch(action.type){ case 'INCREMENT': return state+1; case 'DECREMENT': return state-1; default: return state; } } class OwnStore{ constructor(private reducer){ this.dispatch({}) } state; listeners = []; getState = () =>{ return this.state; } dispatch = (action) => { this.state = this.reducer(this.state, action); this.listeners.forEach((listener) =>{ listener(); return; } ) } subscribe = (listener) => { this.listeners.push(listener); return () => { this.listeners = this.listeners.filter( (l)=>{ return (l !==listener) }) } }; } /* const createStore_own = (reducer) =>{ let state; let listeners = []; const getState = () =>{ return state; } const dispatch = (action) => { state = reducer(state, action); this.listeners.forEach((listener) =>{ listener(); return; } ) } const subscribe = (listener) => { this.listeners.push(listener); return () => { this.listeners = listeners.filter( (l)=>{ return (l !==listener) }) } }; dispatch({}) } */ const test_execute = () =>{ console.log("test execute"); const store = new OwnStore(counter); console.log('state', store.getState()); store.dispatch({type:"INCREMENT"}); store.dispatch({type:"INCREMENT"}); store.dispatch({type:"INCREMENT"}); console.log('state', store.getState()); store.dispatch({type:"DECREMENT"}); store.dispatch({type:"DECREMENT"}); console.log('state', store.getState()); const render = () => { console.log("render is called"); let num = store.getState(); document.body.innerText = String(num); } store.subscribe(()=>{ console.log("subscribe is called"); render(); }) console.log("after subscription"); store.dispatch({type:"DECREMENT"}); console.log('state', store.getState()); document.addEventListener('click', ()=>{ store.dispatch({type:"INCREMENT"}); }) } export default test_execute;
9b683b91aedd07639a78d7fb32e111c223d1073f
TypeScript
tainguyenthe/antd-scss-theme-plugin
/src/loaderUtils.js
2.640625
3
import AntdScssThemePlugin from './index'; /** * Get path to SCSS theme file specified in loader options or through the plugin's constructor. * @param {Object} options - Loader options. * @return {string} Path to SCSS theme file. */ // eslint-disable-next-line import/prefer-default-export export const getScssThemePath = (options) => { const scssThemePath = options.scssThemePath || AntdScssThemePlugin.SCSS_THEME_PATH; if (!scssThemePath) { throw new Error( 'Path to an SCSS theme file must be specified through the scssThemePath loader option, ' + 'or passed to the plugin\'s constructor.', ); } return scssThemePath; };
33c61d71cbaebfc9312b4a57fd39eb00931d09b8
TypeScript
SpectralOne/bmstu-evm-web
/lab5/src/controller.ts
2.65625
3
import { Request, Response, NextFunction } from "express"; import { User } from './user'; import path from "path"; import fs from "fs"; const SECOND: string = path.join(__dirname, "..", "public", "second.html"); const HOME: string = path.join(__dirname, '..', "public", "index.html"); const DB: string = path.join(__dirname, "db.txt"); export const default_controller = (_: Request, res: Response) => res.sendFile(HOME); export const second_page = (_: Request, res: Response) => { res.sendFile(SECOND); } export const set_headers = (_: Request, res: Response, next: NextFunction) => { res.header("Cache-Control", "no-cache, no-store, must-revalidate"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); res.header("Access-Control-Allow-Origin", "*"); next(); } export const add_user = (req: Request, res: Response) => { let user: User = req.body; const users = get_all_db(); const target = users.find((value: User) => value.email == user.email && value.phone == user.phone); let code: number = 200; let result: string = "Added!"; if (!target) { add_db(user as User); } else { code = 401; result = "Found!" user = target; } res.status(code).send(JSON.stringify({ result, ...user })); }; export const find_user = (req: Request, res: Response) => { const target: User | undefined = find_user_db(req.query.email as string); console.log(req.query); if (target) { res.status(200).send(JSON.stringify({ result: "User found!", ...target })); } else { res.status(404).send(JSON.stringify({ result: "User not found!" })); } } export const get_all_db = (): User[] => { return JSON.parse(fs.readFileSync(DB).toString()); } export const add_db = (user: User) => { const users: User[] = get_all_db(); users.push(user); fs.writeFileSync(DB, JSON.stringify(users)); } const find_user_db = (email: string): User | undefined => { const users: User[] = get_all_db(); return users.find((user: User) => user.email === email); }
39ebd751058151d28b99c0f5b8fd5ba237533ed7
TypeScript
PandaCats/YuJudge
/src/common/programLanguage.ts
2.640625
3
/* * File: programLanguage.ts * Description: 编程语言相关配置内容 * Created: 2020-8-2 10:28 * Author: yuzhanglong * Email: yuzl1123@163.com */ import {LanguageTypeEnum} from './enumerations'; // C_PLUS_PLUS的昵称 export const C_PLUS_PLUS_NICK_NAME = 'C++'; // 展示给用户,支持的编程语言的执行脚本内容 export const PROGRAM_LANGUAGE_SCRIPT_CONTENT: { [key: string]: string; } = { [LanguageTypeEnum.C]: 'gcc -Wall -O2 -std=gnu11 CODE_PATH -o CODE_PATH -lm', [LanguageTypeEnum.C_PLUS_PLUS]: 'g++ -Wall -O2 CODE_PATH -o CODE_PATH', [LanguageTypeEnum.JAVA]: 'java Main', [LanguageTypeEnum.PYTHON]: 'python3 CODE_PATH', } // 展示给用户,编程语言的名称 export const PROGRAM_LANGUAGE_NAME: { [key: string]: string; } = { [LanguageTypeEnum.C]: 'C', [LanguageTypeEnum.C_PLUS_PLUS]: C_PLUS_PLUS_NICK_NAME, [LanguageTypeEnum.JAVA]: 'JAVA', [LanguageTypeEnum.PYTHON]: 'PYTHON', }
ef0cfd04de0c1d922a537d271f88013547f62368
TypeScript
Enhmunh-E/tsparticles
/engine/src/Interactions/External/Trail/TrailMaker.ts
2.6875
3
import type { Container } from "../../../Core/Container"; import { isInArray } from "../../../Utils"; import { ClickMode, HoverMode } from "../../../Enums"; import type { ICoordinates, IDelta } from "../../../Core/Interfaces"; import { ExternalInteractorBase } from "../../../Core/ExternalInteractorBase"; /** * @category Interactions */ export class TrailMaker extends ExternalInteractorBase { private delay: number; private lastPosition?: ICoordinates; constructor(container: Container) { super(container); this.delay = 0; } interact(delta: IDelta): void { if (!this.container.retina.reduceFactor) { return; } const container = this.container, options = container.actualOptions, trailOptions = options.interactivity.modes.trail, optDelay = (trailOptions.delay * 1000) / this.container.retina.reduceFactor; if (this.delay < optDelay) { this.delay += delta.value; } if (this.delay < optDelay) { return; } let canEmit = true; if (trailOptions.pauseOnStop) { if ( container.interactivity.mouse.position === this.lastPosition || (container.interactivity.mouse.position?.x === this.lastPosition?.x && container.interactivity.mouse.position?.y === this.lastPosition?.y) ) { canEmit = false; } } if (container.interactivity.mouse.position) { this.lastPosition = { x: container.interactivity.mouse.position.x, y: container.interactivity.mouse.position.y, }; } else { delete this.lastPosition; } if (canEmit) { container.particles.push(trailOptions.quantity, container.interactivity.mouse, trailOptions.particles); } this.delay -= optDelay; } isEnabled(): boolean { const container = this.container, options = container.actualOptions, mouse = container.interactivity.mouse, events = options.interactivity.events; return ( (mouse.clicking && mouse.inside && !!mouse.position && isInArray(ClickMode.trail, events.onClick.mode)) || (mouse.inside && !!mouse.position && isInArray(HoverMode.trail, events.onHover.mode)) ); } reset(): void { // nothing to do } }
bd9581307adf48ac710f4f09318783916330da2c
TypeScript
betopinheiro1005/curso-typescript-sys4soft
/aula-11/code.ts
3.453125
3
function executar(){ // classe - modifiers class humano{ private nome: string; protected genero: string; constructor(n: string){ this.nome = n; } setNome(n:string){ this.nome = n; } getNome(){ return this.nome; } private falar(texto: string){ return `Eu, ` + this.nome + `, disse ` + texto; } public gritar(){ return this.falar('OLÁ'); } } class homem extends humano{ setGenero(g:string){ this.genero = g; } getGenero(){ return this.genero; } } let pessoa = new humano('José'); pessoa.setNome('João'); let pn = pessoa.getNome(); let h = new homem('João'); h.setGenero('masculino'); let g = h.getGenero(); document.getElementById("info1").innerHTML = pessoa.gritar(); document.getElementById("info2").innerHTML = "Genero: " + g; }
8f2c6708e7e25cf6b2d311eab801569efcf8643e
TypeScript
rickmugridge/mismatched
/src/examples/egMatchString.micro.ts
2.5625
3
import {assertThat} from "../assertThat"; import {match} from "../match"; describe("string:", () => { const actual = "abcdefghijkl"; it("string.match:", () => { assertThat(actual).is(match.string.match(actual)); assertThat(actual).is(actual); }); it("string.startsWith:", () => { assertThat(actual).is(match.string.startsWith("abc")); }); it("string.endsWith:", () => { assertThat(actual).is(match.string.endsWith("jkl")); }); it("string.includes:", () => { assertThat(actual).is(match.string.includes("abc")); assertThat(actual).is(match.string.includes("cde")); }); });
df6f1f1c9877f622f661cdc44a1f67f963c0a26f
TypeScript
xiaxzp/angular-workers-in-action
/src/ITodo.ts
2.59375
3
export interface ITodo { id: number; title: string; description: string; url: string; done: string; } export interface IList { list: ITodo[]; }
9b18e38d456d1d608498e25530dfb1cddbec2264
TypeScript
covidtop/covidtop
/packages/shared/src/metric/metric-format.ts
2.953125
3
import { format } from 'd3-format' import { mapValues } from '../utils' export type MetricFormatType = 'decimal' | 'percent' type NumberFormatter = (value?: number) => string | undefined export interface MetricFormat { readonly metricFormatType: MetricFormatType readonly apply: NumberFormatter } const createFormatter = (pattern: string): NumberFormatter => { const formatter = format(pattern) return (value) => { if (typeof value === 'undefined') { return 'N/A' } return formatter(value) } } const decimalFormatter = createFormatter(',d') const percentFormatter = createFormatter(',.1%') const partialMetricFormatByType: Readonly<Record<MetricFormatType, Omit<MetricFormat, 'metricFormatType'>>> = { decimal: { apply: decimalFormatter, }, percent: { apply: percentFormatter, }, } export const metricFormatByType: Readonly<Record<MetricFormatType, MetricFormat>> = mapValues( partialMetricFormatByType, (partialMetricFormat, metricFormatType) => ({ metricFormatType, ...partialMetricFormat, }), )
7e12077fac04bc9891684ec07092556814ed3ffd
TypeScript
etherik/eth-hooks
/src/useBalance.ts
2.765625
3
import { Provider } from '@ethersproject/providers'; import { BigNumber } from 'ethers'; import { useState, useCallback } from 'react'; import { useOnRepetition } from '~~/useOnRepetition'; const zero = BigNumber.from(0); /** * Gets your balance in ETH from given address and provider * * ~ Features ~ - Provide address and get balance corresponding to given address - Change provider to access balance on different chains (ex. mainnetProvider) - If no pollTime is passed, the balance will update on every new block * @param provider (ethers->Provider) * @param address (string) * @param pollTime (number) :: if >0 use polling, else use instead of onBlock event * @returns (Bignumber) :: current balance */ export const useBalance = (provider: Provider | undefined, address: string, pollTime: number = 0): BigNumber => { const [balance, setBalance] = useState<BigNumber>(); const pollBalance = useCallback( async (provider?: Provider, address?: string): Promise<void> => { if (provider && address) { const newBalance = await provider.getBalance(address); if (!newBalance.eq(balance ?? zero)) { setBalance(newBalance); console.log(address, newBalance.toString(), balance); } } }, [balance] ); useOnRepetition( pollBalance, { pollTime, provider, leadingTrigger: address != null && address !== '' && provider != null }, provider, address ); return balance ?? zero; };
e953046981b7d09075514e41556576168a40f36a
TypeScript
SocialGouv/domifa
/packages/portail-admins/src/app/modules/shared/services/data/searchCore.spec.ts
2.6875
3
import { searchCore } from "./searchCore"; it("trim", () => { expect(searchCore.trim(" \ttwo words\n \t ")).toEqual("two words"); }); it("clean", () => { expect(searchCore.clean("à la C@mpagne éÂ!")).toEqual("a la c@mpagne ea!"); }); it("buildWords", () => { expect(searchCore.buildWords("a few words")).toEqual(["a", "few", "words"]); expect(searchCore.buildWords("one_word")).toEqual(["one_word"]); });
993469a214920faecc3ba60cb0d183512163f966
TypeScript
aische/ts-typelevel-crap
/src/distribution.ts
3.171875
3
export type Pair1<A,B> = [A] extends any ? [B] extends any ? [A, B] : never : never export type Pair2<A,B> = A extends any ? [B] extends any ? [A, B] : never : never export type Pair3<A,B> = [A] extends any ? B extends any ? [A, B] : never : never export type Pair4<A,B> = A extends any ? B extends any ? [A, B] : never : never type P1 = Pair1<'a' | 'b', 'x' | 'y'> type P2 = Pair2<'a' | 'b', 'x' | 'y'> type P3 = Pair3<'a' | 'b', 'x' | 'y'> type P4 = Pair4<'a' | 'b', 'x' | 'y'>
476ca6fbf71af6b58cf31658289e97a7951cc410
TypeScript
silvioedu/Angular-Practice
/aula-2/declaracaoLet.ts
3.46875
3
let num1:number = 1 function varDeclaration() { let num2:number = 2 if (num2 > num1) { let num3:number = 3 num3++ } while (num1 < num2) { let num4:number = 4; num1++; } console.log("num1: " + num1) console.log("num2: " + num2) console.log("num3: " + num3) //Compile error console.log("num4: " + num4) //Compile error } varDeclaration()
c06d119a9fa477856339e39253e545f02e28b5fb
TypeScript
philipeachille/webapp-v2
/src/services/observables/customOperators.ts
2.828125
3
import { Observable } from 'rxjs'; import { switchMap, filter } from 'rxjs/operators'; export const switchMapIgnoreThrow = <T, Y>(switchMapProm: (data: T) => Promise<Y>) => (source: Observable<T>): Observable<Y> => source.pipe( switchMap((whatever) => switchMapProm(whatever).catch(() => 'DONT THROW' as unknown as Y) ), filter((x) => !(typeof x === 'string' && x === 'DONT THROW')) );
08a0e72ca502667ab0af5b1f8dc3752031b1ef68
TypeScript
kgroat/toodle
/src/types/Mutator.ts
2.796875
3
import { ReadonlyFlatMap } from './FlatMap' import { DeepReadonly } from './DeepReadonly' export interface Mutator<S, O> { mutate: (prev: DeepReadonly<S>, options: O) => DeepReadonly<S> defaultOptions?: O } export interface Mutators<S> extends ReadonlyFlatMap<Mutator<S, any>> {} export interface AsyncMutator<S, O, M extends ReaderMutator<S, any>> { mutate: (mutators: M, options: O) => void defaultOptions?: O } export interface AsyncMutators<S, M extends Mutators<S>> extends ReadonlyFlatMap<AsyncMutator<S, any, ReaderMutator<S, M>>> {} export type ReaderMutator<S, M extends Mutators<S>> = { [P in keyof M]: (opts: M[P]['defaultOptions']) => void } export type ReaderAsyncMutator<S, A extends AsyncMutators<S, M>, M extends Mutators<S>> = { [P in keyof A]: (opts: A[P]['defaultOptions']) => void }
6221d9dbf567664a2c00846a5e1b5d70117b0a08
TypeScript
DimaGashko/security
/src/pages/hill/index.ts
2.609375
3
import chunk from 'lodash/chunk'; import 'normalize.scss/normalize.scss'; import './index.scss'; import { debounce } from 'throttle-debounce'; import { encode, decode } from './scripts/hill'; const $app: HTMLElement = document.querySelector('.app'); const $key: HTMLInputElement = $app.querySelector('.key'); const $msg: HTMLTextAreaElement = $app.querySelector('.msg'); const $encodeMsg: HTMLTextAreaElement = $app.querySelector('.encoded-msg'); const $decodeMsg: HTMLTextAreaElement = $app.querySelector('.decoded-msg'); const $charKey: HTMLTextAreaElement = $app.querySelector('.char-key'); const $numKey: HTMLTextAreaElement = $app.querySelector('.num-key'); const INPUT_DELAY = 200; run(); updateCharKeyNumKey(); initEvents(); function initEvents() { $key.addEventListener('input', debounce(INPUT_DELAY, () => { run(); updateCharKeyNumKey(); })); $msg.addEventListener('input', debounce(INPUT_DELAY, run)); $encodeMsg.addEventListener('input', debounce(INPUT_DELAY, run)); $decodeMsg.addEventListener('input', debounce(INPUT_DELAY, run)); } function run() { const key = $key.value.trim(); const msg = $msg.value.trim(); const encodedMsg = encode(msg, key); const decodedMsg = decode(encodedMsg, key); $encodeMsg.value = encodedMsg; $decodeMsg.value = decodedMsg; } function updateCharKeyNumKey() { const key = $key.value.trim(); const size = Math.sqrt(key.length) ^ 0; const charKey = chunk(key.slice(0, size * size).split(''), size); const numKey = chunk(key.slice(0, size * size).split('') .map(ch => ch.codePointAt(0)), size); $charKey.value = keyToString(charKey); $numKey.value = keyToString(numKey); } function keyToString(key: any[][]) { return key.map(r => r.join('\t')).join('\n'); }
ef6f5c251f3b0835b31eb82e1790084d9b7daaf1
TypeScript
takakoshimizu/wanikani-api
/src/typings/cache.d.ts
2.5625
3
export interface ICache<T> { lastUpdated: number; data: T; } export interface ILevelCache<T> { [key: number]: ICache<T>; }
10a7038aa2725f3aed2495c866de479f2bc76c2e
TypeScript
reidev275/marsrover
/src/filterDsl.ts
3.84375
4
export type Filter<A> = | { kind: "Equals"; field: keyof A; val: A[keyof A] } | { kind: "Greater"; field: keyof A; val: A[keyof A] } | { kind: "Less"; field: keyof A; val: A[keyof A] } | { kind: "And"; a: Filter<A>; b: Filter<A> } | { kind: "Or"; a: Filter<A>; b: Filter<A> }; //core export const equals = <A, K extends keyof A>( field: K, val: A[K] ): Filter<A> => ({ kind: "Equals", field, val }); export const greater = <A, K extends keyof A>( field: K, val: A[K] ): Filter<A> => ({ kind: "Greater", field, val }); export const less = <A, K extends keyof A>(field: K, val: A[K]): Filter<A> => ({ kind: "Less", field, val }); export const and = <A>(a: Filter<A>, b: Filter<A>): Filter<A> => ({ kind: "And", a, b }); export const or = <A>(a: Filter<A>, b: Filter<A>): Filter<A> => ({ kind: "Or", a, b }); /* * Derived operations * These combine core language features to extend the language */ //greater than or equal export const gte = <A, K extends keyof A>(field: K, val: A[K]): Filter<A> => or(greater(field, val), equals(field, val)); //less than or equal export const lte = <A, K extends keyof A>(field: K, val: A[K]): Filter<A> => or(less(field, val), equals(field, val)); //combine 1 to many filters returning true if all are true (and) export const all = <A>(...dsl: Filter<A>[]): Filter<A> => dsl.reduce((p, c) => and(p, c)); //combine 1 to many filters returning true if any are true (or) export const any = <A>(...dsl: Filter<A>[]): Filter<A> => dsl.reduce((p, c) => or(p, c)); //essentially sql's in operator. Given a field and a collection of values //this returns true if any are true. export const oneOf = <A, K extends keyof A>( field: keyof A, ...vals: A[K][] ): Filter<A> => any(...vals.map(x => equals(field, x))); /* * Interpreters */ const interpretToSql = <A>(dsl: Filter<A>): string => { switch (dsl.kind) { case "Equals": return `[${dsl.field}] = '${dsl.val}'`; case "Greater": return `[${dsl.field}] > '${dsl.val}'`; case "Less": return `[${dsl.field}] < '${dsl.val}'`; case "And": return `(${interpretToSql(dsl.a)} and ${interpretToSql(dsl.b)})`; case "Or": return `(${interpretToSql(dsl.a)} or ${interpretToSql(dsl.b)})`; } }; /* * Example */ // a sample data model interface JobPosting { manager: string; salary: number; } //a filter of the data model const query: Filter<JobPosting> = and( equals("manager", "Bob Slydell"), greater("salary", 50000) ); //underlying data representation console.log(query); //sql created by interpreting the data model console.log(interpretToSql(query));
87e35d3f6bef98fa8ff74d88b278d4547bf18027
TypeScript
CrackTheCode016/symbol-cli
/test/models/template.spec.ts
2.765625
3
import { expect } from 'chai' import { Template, TemplateConfig, TemplateDTO, NodeType } from '../../src/models/template' describe('Template Model', () => { it('should create a template from constructor', () => { const config = new TemplateConfig('friendlyNode123', 'bootKey', 'harvesterKey', 0, NodeType.Api) const template = new Template('test-template', false, config) expect(template.name).to.be.equal('test-template') expect(template.bootPrivateKey).to.be.equal('bootKey') expect(template.friendlyName).to.be.equal('friendlyNode123') expect(template.nodeRole).to.be.equal(NodeType.Api) expect(template.harvesterKey).to.be.equal('harvesterKey') expect(template.maxFee).to.be.equal(0) }) it('should create a template from DTO', () => { const templateDTO: TemplateDTO = { name: 'test-template', defaultTemplate: false, config: { friendlyName: 'friendlyNode123', role: NodeType.Dual, bootPrivateKey: 'bootKey', harvesterKey: 'harvesterKey', maxFee: 10, }, } const template = Template.createFromDTO(templateDTO) expect(template.name).to.be.equal('test-template') expect(template.bootPrivateKey).to.be.equal('bootKey') expect(template.friendlyName).to.be.equal('friendlyNode123') expect(templateDTO.config.role).to.be.equal(NodeType.Dual) expect(template.harvesterKey).to.be.equal('harvesterKey') expect(template.maxFee).to.be.equal(10) }) })
864848c73fa1a5cd46002d3085786de8022bcd45
TypeScript
xXD4rkC0d3rXx/freecom
/libs/peer/core/src/lib/peer-client.model.ts
2.75
3
import { ImmutableModel } from './immutable.model' export interface IPeerClient { id?: string label?: string stream: MediaStream } export class PeerClient extends ImmutableModel<IPeerClient, PeerClient> { constructor(data: IPeerClient) { super(PeerClient, data) } get id(): string { return this.data.get('id') } get label(): string { return this.data.get('label') } get stream(): MediaStream { return this.data.get('stream') } setId(val: string): PeerClient { return this.setValue('id', val) } setLabel(val: string): PeerClient { return this.setValue('label', val) } setStream(val: MediaStream): PeerClient { return this.setValue('stream', val) } }
2a0036de70cb8c6b3da3df6f457d33301ff19213
TypeScript
Jumaniyozov/task-mngmnt
/src/auth/auth.service.ts
2.515625
3
import { Inject, Injectable, Logger, UnauthorizedException } from "@nestjs/common"; import { UserRepository } from "./user.repository"; import { AuthCredentialsDto } from "./dto/auth-credentials.dto"; import { JwtService } from "@nestjs/jwt"; @Injectable() export class AuthService { private logger = new Logger(); constructor( @Inject(UserRepository) private userRepository: UserRepository, private jwtService: JwtService ) { } async signUp(authCredentialsDto: AuthCredentialsDto): Promise<void> { return this.userRepository.signUp(authCredentialsDto); } async signIn(authCredentialsDto: AuthCredentialsDto): Promise<{accessToken: string}> { const username = await this.userRepository.validateAuthCredentials(authCredentialsDto); if(!username) { throw new UnauthorizedException('Invalid credentials'); } const payload = {username}; const accessToken = await this.jwtService.sign(payload); return {accessToken}; } }
0d69eaaec67a29320f70eb227fb54b4ab1d0849a
TypeScript
JetBrains/intellij-plugins
/AngularJS/testData/modelStructure/common/i18n/locale_data_api.ts
3
3
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import localeEn from './locale_en'; import {CurrencyIndex, ExtraLocaleDataIndex, LOCALE_DATA, LocaleDataIndex} from './locale_data'; import {CURRENCIES_EN, CurrenciesSymbols} from './currencies'; /** * The different format styles that can be used to represent numbers. * Used by the function {@link getLocaleNumberFormat}. * * @experimental i18n support is experimental. */ export enum NumberFormatStyle { Decimal, Percent, Currency, Scientific } /** @experimental */ export enum Plural { Zero = 0, One = 1, Two = 2, Few = 3, Many = 4, Other = 5, } /** * Some languages use two different forms of strings (standalone and format) depending on the * context. * Typically the standalone version is the nominative form of the word, and the format version is in * the genitive. * See [the CLDR website](http://cldr.unicode.org/translation/date-time) for more information. * * @experimental i18n support is experimental. */ export enum FormStyle { Format, Standalone } /** * Multiple widths are available for translations: narrow (1 character), abbreviated (3 characters), * wide (full length), and short (2 characters, only for days). * * For example the day `Sunday` will be: * - Narrow: `S` * - Short: `Su` * - Abbreviated: `Sun` * - Wide: `Sunday` * * @experimental i18n support is experimental. */ export enum TranslationWidth { Narrow, Abbreviated, Wide, Short } /** * Multiple widths are available for formats: short (minimal amount of data), medium (small amount * of data), long (complete amount of data), full (complete amount of data and extra information). * * For example the date-time formats for the english locale will be: * - `'short'`: `'M/d/yy, h:mm a'` (e.g. `6/15/15, 9:03 AM`) * - `'medium'`: `'MMM d, y, h:mm:ss a'` (e.g. `Jun 15, 2015, 9:03:01 AM`) * - `'long'`: `'MMMM d, y, h:mm:ss a z'` (e.g. `June 15, 2015 at 9:03:01 AM GMT+1`) * - `'full'`: `'EEEE, MMMM d, y, h:mm:ss a zzzz'` (e.g. `Monday, June 15, 2015 at * 9:03:01 AM GMT+01:00`) * * @experimental i18n support is experimental. */ export enum FormatWidth { Short, Medium, Long, Full } /** * Number symbol that can be used to replace placeholders in number patterns. * The placeholders are based on english values: * * | Name | Example for en-US | Meaning | * |------------------------|-------------------|---------------------------------------------| * | decimal | 2,345`.`67 | decimal separator | * | group | 2`,`345.67 | grouping separator, typically for thousands | * | plusSign | `+`23 | the plus sign used with numbers | * | minusSign | `-`23 | the minus sign used with numbers | * | percentSign | 23.4`%` | the percent sign (out of 100) | * | perMille | 234`‰` | the permille sign (out of 1000) | * | exponential | 1.2`E`3 | used in computers for 1.2×10³. | * | superscriptingExponent | 1.2`×`103 | human-readable format of exponential | * | infinity | `∞` | used in +∞ and -∞. | * | nan | `NaN` | "not a number". | * | timeSeparator | 10`:`52 | symbol used between time units | * | currencyDecimal | $2,345`.`67 | decimal separator, fallback to "decimal" | * | currencyGroup | $2`,`345.67 | grouping separator, fallback to "group" | * * @experimental i18n support is experimental. */ export enum NumberSymbol { Decimal, Group, List, PercentSign, PlusSign, MinusSign, Exponential, SuperscriptingExponent, PerMille, Infinity, NaN, TimeSeparator, CurrencyDecimal, CurrencyGroup } /** * The value for each day of the week, based on the en-US locale * * @experimental */ export enum WeekDay { Sunday = 0, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } /** * The locale id for the chosen locale (e.g `en-GB`). * * @experimental i18n support is experimental. */ export function getLocaleId(locale: string): string { return findLocaleData(locale)[LocaleDataIndex.LocaleId]; } /** * Periods of the day (e.g. `[AM, PM]` for en-US). * * @experimental i18n support is experimental. */ export function getLocaleDayPeriods( locale: string, formStyle: FormStyle, width: TranslationWidth): [string, string] { const data = findLocaleData(locale); const amPmData = <[ string, string ][][]>[data[LocaleDataIndex.DayPeriodsFormat], data[LocaleDataIndex.DayPeriodsStandalone]]; const amPm = getLastDefinedValue(amPmData, formStyle); return getLastDefinedValue(amPm, width); } /** * Days of the week for the Gregorian calendar (e.g. `[Sunday, Monday, ... Saturday]` for en-US). * * @experimental i18n support is experimental. */ export function getLocaleDayNames( locale: string, formStyle: FormStyle, width: TranslationWidth): string[] { const data = findLocaleData(locale); const daysData = <string[][][]>[data[LocaleDataIndex.DaysFormat], data[LocaleDataIndex.DaysStandalone]]; const days = getLastDefinedValue(daysData, formStyle); return getLastDefinedValue(days, width); } /** * Months of the year for the Gregorian calendar (e.g. `[January, February, ...]` for en-US). * * @experimental i18n support is experimental. */ export function getLocaleMonthNames( locale: string, formStyle: FormStyle, width: TranslationWidth): string[] { const data = findLocaleData(locale); const monthsData = <string[][][]>[data[LocaleDataIndex.MonthsFormat], data[LocaleDataIndex.MonthsStandalone]]; const months = getLastDefinedValue(monthsData, formStyle); return getLastDefinedValue(months, width); } /** * Eras for the Gregorian calendar (e.g. AD/BC). * * @experimental i18n support is experimental. */ export function getLocaleEraNames(locale: string, width: TranslationWidth): [string, string] { const data = findLocaleData(locale); const erasData = <[string, string][]>data[LocaleDataIndex.Eras]; return getLastDefinedValue(erasData, width); } /** * First day of the week for this locale, based on english days (Sunday = 0, Monday = 1, ...). * For example in french the value would be 1 because the first day of the week is Monday. * * @experimental i18n support is experimental. */ export function getLocaleFirstDayOfWeek(locale: string): WeekDay { const data = findLocaleData(locale); return data[LocaleDataIndex.FirstDayOfWeek]; } /** * Range of days in the week that represent the week-end for this locale, based on english days * (Sunday = 0, Monday = 1, ...). * For example in english the value would be [6,0] for Saturday to Sunday. * * @experimental i18n support is experimental. */ export function getLocaleWeekEndRange(locale: string): [WeekDay, WeekDay] { const data = findLocaleData(locale); return data[LocaleDataIndex.WeekendRange]; } /** * Date format that depends on the locale. * * There are four basic date formats: * - `full` should contain long-weekday (EEEE), year (y), long-month (MMMM), day (d). * * For example, English uses `EEEE, MMMM d, y`, corresponding to a date like * "Tuesday, September 14, 1999". * * - `long` should contain year, long-month, day. * * For example, `MMMM d, y`, corresponding to a date like "September 14, 1999". * * - `medium` should contain year, abbreviated-month (MMM), day. * * For example, `MMM d, y`, corresponding to a date like "Sep 14, 1999". * For languages that do not use abbreviated months, use the numeric month (MM/M). For example, * `y/MM/dd`, corresponding to a date like "1999/09/14". * * - `short` should contain year, numeric-month (MM/M), and day. * * For example, `M/d/yy`, corresponding to a date like "9/14/99". * * @experimental i18n support is experimental. */ export function getLocaleDateFormat(locale: string, width: FormatWidth): string { const data = findLocaleData(locale); return getLastDefinedValue(data[LocaleDataIndex.DateFormat], width); } /** * Time format that depends on the locale. * * The standard formats include four basic time formats: * - `full` should contain hour (h/H), minute (mm), second (ss), and zone (zzzz). * - `long` should contain hour, minute, second, and zone (z) * - `medium` should contain hour, minute, second. * - `short` should contain hour, minute. * * Note: The patterns depend on whether the main country using your language uses 12-hour time or * not: * - For 12-hour time, use a pattern like `hh:mm a` using h to mean a 12-hour clock cycle running * 1 through 12 (midnight plus 1 minute is 12:01), or using K to mean a 12-hour clock cycle * running 0 through 11 (midnight plus 1 minute is 0:01). * - For 24-hour time, use a pattern like `HH:mm` using H to mean a 24-hour clock cycle running 0 * through 23 (midnight plus 1 minute is 0:01), or using k to mean a 24-hour clock cycle running * 1 through 24 (midnight plus 1 minute is 24:01). * * @experimental i18n support is experimental. */ export function getLocaleTimeFormat(locale: string, width: FormatWidth): string { const data = findLocaleData(locale); return getLastDefinedValue(data[LocaleDataIndex.TimeFormat], width); } /** * Date-time format that depends on the locale. * * The date-time pattern shows how to combine separate patterns for date (represented by {1}) * and time (represented by {0}) into a single pattern. It usually doesn't need to be changed. * What you want to pay attention to are: * - possibly removing a space for languages that don't use it, such as many East Asian languages * - possibly adding a comma, other punctuation, or a combining word * * For example: * - English uses `{1} 'at' {0}` or `{1}, {0}` (depending on date style), while Japanese uses * `{1}{0}`. * - An English formatted date-time using the combining pattern `{1}, {0}` could be * `Dec 10, 2010, 3:59:49 PM`. Notice the comma and space between the date portion and the time * portion. * * There are four formats (`full`, `long`, `medium`, `short`); the determination of which to use * is normally based on the date style. For example, if the date has a full month and weekday * name, the full combining pattern will be used to combine that with a time. If the date has * numeric month, the short version of the combining pattern will be used to combine that with a * time. English uses `{1} 'at' {0}` for full and long styles, and `{1}, {0}` for medium and short * styles. * * @experimental i18n support is experimental. */ export function getLocaleDateTimeFormat(locale: string, width: FormatWidth): string { const data = findLocaleData(locale); const dateTimeFormatData = <string[]>data[LocaleDataIndex.DateTimeFormat]; return getLastDefinedValue(dateTimeFormatData, width); } /** * Number symbol that can be used to replace placeholders in number formats. * See {@link NumberSymbol} for more information. * * @experimental i18n support is experimental. */ export function getLocaleNumberSymbol(locale: string, symbol: NumberSymbol): string { const data = findLocaleData(locale); const res = data[LocaleDataIndex.NumberSymbols][symbol]; if (typeof res === 'undefined') { if (symbol === NumberSymbol.CurrencyDecimal) { return data[LocaleDataIndex.NumberSymbols][NumberSymbol.Decimal]; } else if (symbol === NumberSymbol.CurrencyGroup) { return data[LocaleDataIndex.NumberSymbols][NumberSymbol.Group]; } } return res; } /** * Number format that depends on the locale. * * Numbers are formatted using patterns, like `#,###.00`. For example, the pattern `#,###.00` * when used to format the number 12345.678 could result in "12'345,67". That would happen if the * grouping separator for your language is an apostrophe, and the decimal separator is a comma. * * <b>Important:</b> The characters `.` `,` `0` `#` (and others below) are special placeholders; * they stand for the decimal separator, and so on, and are NOT real characters. * You must NOT "translate" the placeholders; for example, don't change `.` to `,` even though in * your language the decimal point is written with a comma. The symbols should be replaced by the * local equivalents, using the Number Symbols for your language. * * Here are the special characters used in number patterns: * * | Symbol | Meaning | * |--------|---------| * | . | Replaced automatically by the character used for the decimal point. | * | , | Replaced by the "grouping" (thousands) separator. | * | 0 | Replaced by a digit (or zero if there aren't enough digits). | * | # | Replaced by a digit (or nothing if there aren't enough). | * | ¤ | This will be replaced by a currency symbol, such as $ or USD. | * | % | This marks a percent format. The % symbol may change position, but must be retained. | * | E | This marks a scientific format. The E symbol may change position, but must be retained. | * | ' | Special characters used as literal characters are quoted with ASCII single quotes. | * * You can find more information * [on the CLDR website](http://cldr.unicode.org/translation/number-patterns) * * @experimental i18n support is experimental. */ export function getLocaleNumberFormat(locale: string, type: NumberFormatStyle): string { const data = findLocaleData(locale); return data[LocaleDataIndex.NumberFormats][type]; } /** * The symbol used to represent the currency for the main country using this locale (e.g. $ for * the locale en-US). * The symbol will be `null` if the main country cannot be determined. * * @experimental i18n support is experimental. */ export function getLocaleCurrencySymbol(locale: string): string|null { const data = findLocaleData(locale); return data[LocaleDataIndex.CurrencySymbol] || null; } /** * The name of the currency for the main country using this locale (e.g. USD for the locale * en-US). * The name will be `null` if the main country cannot be determined. * * @experimental i18n support is experimental. */ export function getLocaleCurrencyName(locale: string): string|null { const data = findLocaleData(locale); return data[LocaleDataIndex.CurrencyName] || null; } /** * Returns the currency values for the locale */ function getLocaleCurrencies(locale: string): {[code: string]: CurrenciesSymbols} { const data = findLocaleData(locale); return data[LocaleDataIndex.Currencies]; } /** * The locale plural function used by ICU expressions to determine the plural case to use. * See {@link NgPlural} for more information. * * @experimental i18n support is experimental. */ export function getLocalePluralCase(locale: string): (value: number) => Plural { const data = findLocaleData(locale); return data[LocaleDataIndex.PluralCase]; } function checkFullData(data: any) { if (!data[LocaleDataIndex.ExtraData]) { throw new Error( `Missing extra locale data for the locale "${data[LocaleDataIndex.LocaleId]}". Use "registerLocaleData" to load new data. See the "I18n guide" on angular.io to know more.`); } } /** * Rules used to determine which day period to use (See `dayPeriods` below). * The rules can either be an array or a single value. If it's an array, consider it as "from" * and "to". If it's a single value then it means that the period is only valid at this exact * value. * There is always the same number of rules as the number of day periods, which means that the * first rule is applied to the first day period and so on. * You should fallback to AM/PM when there are no rules available. * * Note: this is only available if you load the full locale data. * See the ["I18n guide"](guide/i18n#i18n-pipes) to know how to import additional locale * data. * * @experimental i18n support is experimental. */ export function getLocaleExtraDayPeriodRules(locale: string): (Time | [Time, Time])[] { const data = findLocaleData(locale); checkFullData(data); const rules = data[LocaleDataIndex.ExtraData][ExtraLocaleDataIndex.ExtraDayPeriodsRules] || []; return rules.map((rule: string | [string, string]) => { if (typeof rule === 'string') { return extractTime(rule); } return [extractTime(rule[0]), extractTime(rule[1])]; }); } /** * Day Periods indicate roughly how the day is broken up in different languages (e.g. morning, * noon, afternoon, midnight, ...). * You should use the function {@link getLocaleExtraDayPeriodRules} to determine which period to * use. * You should fallback to AM/PM when there are no day periods available. * * Note: this is only available if you load the full locale data. * See the ["I18n guide"](guide/i18n#i18n-pipes) to know how to import additional locale * data. * * @experimental i18n support is experimental. */ export function getLocaleExtraDayPeriods( locale: string, formStyle: FormStyle, width: TranslationWidth): string[] { const data = findLocaleData(locale); checkFullData(data); const dayPeriodsData = <string[][][]>[ data[LocaleDataIndex.ExtraData][ExtraLocaleDataIndex.ExtraDayPeriodFormats], data[LocaleDataIndex.ExtraData][ExtraLocaleDataIndex.ExtraDayPeriodStandalone] ]; const dayPeriods = getLastDefinedValue(dayPeriodsData, formStyle) || []; return getLastDefinedValue(dayPeriods, width) || []; } /** * Returns the first value that is defined in an array, going backwards. * * To avoid repeating the same data (e.g. when "format" and "standalone" are the same) we only * add the first one to the locale data arrays, the other ones are only defined when different. * We use this function to retrieve the first defined value. * * @experimental i18n support is experimental. */ function getLastDefinedValue<T>(data: T[], index: number): T { for (let i = index; i > -1; i--) { if (typeof data[i] !== 'undefined') { return data[i]; } } throw new Error('Locale data API: locale data undefined'); } /** * A representation of the time with hours and minutes * * @experimental i18n support is experimental. */ export type Time = { hours: number, minutes: number }; /** * Extract the hours and minutes from a string like "15:45" */ function extractTime(time: string): Time { const [h, m] = time.split(':'); return {hours: +h, minutes: +m}; } /** * Finds the locale data for a locale id * * @experimental i18n support is experimental. */ export function findLocaleData(locale: string): any { const normalizedLocale = locale.toLowerCase().replace(/_/g, '-'); let match = LOCALE_DATA[normalizedLocale]; if (match) { return match; } // let's try to find a parent locale const parentLocale = normalizedLocale.split('-')[0]; match = LOCALE_DATA[parentLocale]; if (match) { return match; } if (parentLocale === 'en') { return localeEn; } throw new Error(`Missing locale data for the locale "${locale}".`); } /** * Returns the currency symbol for a given currency code, or the code if no symbol available * (e.g.: format narrow = $, format wide = US$, code = USD) * If no locale is provided, it uses the locale "en" by default * * @experimental i18n support is experimental. */ export function getCurrencySymbol(code: string, format: 'wide' | 'narrow', locale = 'en'): string { const currency = getLocaleCurrencies(locale)[code] || CURRENCIES_EN[code] || []; const symbolNarrow = currency[CurrencyIndex.SymbolNarrow]; if (format === 'narrow' && typeof symbolNarrow === 'string') { return symbolNarrow; } return currency[CurrencyIndex.Symbol] || code; } // Most currencies have cents, that's why the default is 2 const DEFAULT_NB_OF_CURRENCY_DIGITS = 2; /** * Returns the number of decimal digits for the given currency. * Its value depends upon the presence of cents in that particular currency. * * @experimental i18n support is experimental. */ export function getNumberOfCurrencyDigits(code: string): number { let digits; const currency = CURRENCIES_EN[code]; if (currency) { digits = currency[CurrencyIndex.NbOfDigits]; } return typeof digits === 'number' ? digits : DEFAULT_NB_OF_CURRENCY_DIGITS; }
906c9740cdf8a2ee420bcf0092dea7761d1a2115
TypeScript
hcigroupkonstanz/STREAM
/stream-server/src/server/modules/plots/plot-utils.ts
2.578125
3
import * as _ from 'lodash'; import { Manager } from '../database'; import { Plot } from './plot'; import { Link } from './link'; export class PlotUtils { public static getConnectedPlots(plots: Manager<Plot>, links: Manager<Link>, startPlotId: number): Plot[] { const startPlot = plots.findLoadedEntry({ id: startPlotId }); if (!startPlot) { return []; } const connectedPlots: Plot[] = [startPlot]; for (let i = 0; i < connectedPlots.length; i++) { const currentPlot = connectedPlots[i]; const upstreamLinks = _.filter(links.loadedEntries, l => l.upstream === currentPlot.id || l.downstream === currentPlot.id); for (const link of upstreamLinks) { const upstreamPlot = plots.findLoadedEntry({ id: link.upstream }); if (upstreamPlot && connectedPlots.indexOf(upstreamPlot) < 0) { connectedPlots.push(upstreamPlot); } const downstreamPlot = plots.findLoadedEntry({ id: link.downstream }); if (downstreamPlot && connectedPlots.indexOf(downstreamPlot) < 0) { connectedPlots.push(downstreamPlot); } } } return connectedPlots; } }
38ef24d330c32849a4ab94bc9f7489f1ba996dbf
TypeScript
ifakejs/page-visibility
/src/PubSub.ts
2.859375
3
export class PubSub { public listenEvent: Record<any, any> constructor() { this.listenEvent = {} } on(key: string, fn: Function): void { if (!this.listenEvent[key]) { this.listenEvent[key] = [] } this.listenEvent[key].push(fn) } trigger(...arg: any[]): void { const fnName = arg[0] const args = arg.splice(1) const fns = this.listenEvent[fnName] if (!fns) { return } for (let i = 0; i < fns.length; i++) { const fnTarget = fns[i] fnTarget.apply(this, args.length > 1 ? [args] : args) } } off(key: string, fn: Function): void { const fns = this.listenEvent[key] if (!fns) { return } if (fns?.length && typeof fn === 'function') { for (let i = 0; i < fns.length; i++) { const _fns = fns[i] if (_fns === fn) { fns.splice(i, 1) } } } } }
da77e2fbb7c68abdd1c689b1d8fc959fdb34026f
TypeScript
lampkraft/recept_angular
/src/app/models/recipe.ts
2.59375
3
export interface IRecipe { id: string, name: string, description: string, images: IRecipeImage[], base64Thumbnail: string, ingredients?: IIngredient[] } export interface IIngredient { id: string, name: string, amount: number, unit: string, order: number } export interface IRecipeForRequest { id?: string, name: string, description: string, ingredients?: any[], base64Thumbnail: string } export interface IRecipeImageCollection { [key: string]: IRecipeImage; } export interface IRecipeImage { id: string; recipeId: string; base64Image: string; }
b386ccdc6ad93533b9f0d57560f63d23c19d5e8d
TypeScript
mbabaei0/nalino
/src/app/components/drop-down/drop-down.component.ts
2.65625
3
import { Component, OnInit, forwardRef, Input, Output } from "@angular/core"; import { ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl } from "@angular/forms"; @Component({ selector: "app-drop-down", templateUrl: "./drop-down.component.html", styleUrls: ["./drop-down.component.scss"], providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: forwardRef(() => DropDownComponent), multi: true } , { provide: NG_VALIDATORS, useExisting: DropDownComponent, multi: true } ] }) export class DropDownComponent implements ControlValueAccessor { @Input() placeholder; @Output() output; disabled = false; // tslint:disable-next-line: member-ordering list = [ { id: 1, title: "tehran" }, { id: 2, title: "zanjan" }, { id: 3, title: "esfa" }, { id: 4, title: "guilan" } ]; open = false; value = {id:1,title:'ostan'}; @Input()set chooseById(id){ this.list.forEach(x =>{ if(id === x.id){ this.value.title = x.title } }) }; constructor() {} // ngOnInit() {} fOut() { setTimeout(() => { this.open = false; }, 500); } chooseOption(item) { // this.value = {...item}; // console.log(item); this.value = item; this.onChange(item.id); this.onTouch(item.id); this.output = {...item}; //console.log(this.value); this.open = false; } validate({ value }: FormControl) { const isNotValid = this.output !== null; return isNotValid && { invalid: true } } // set val(val){ // this value is updated by programmatic changes if( val !== undefined && this.val !== val){ // this.value = val // this.onChange(val) // this.onTouch(val) // } // onChange = (val) => { // console.log(val,'on change') // }; // onTouch = (val) => { // console.log(val,'on change') // }; // writeValue(): void { // this.onChange(this.value); // } // registerOnChange(fn: (val:any) => void): void { // console.log(fn,'dffdd') // this.onChange = fn; // } // registerOnTouched(fn: () => void): void { // this.onTouch = fn; // } // // Allows Angular to disable the input. // setDisabledState(isDisabled: boolean): void { // this.disabled = isDisabled; // } onChange: any = () => {}; onTouch: any = () => {}; get val():any { return this.value.title; } set val(val) { console.log('injaaaaaaaaaaa', val) // this value is updated by programmatic changes if( val !== undefined && this.val !== val){ this.value = val; this.list.forEach(x =>{ if(x.title == val){ this.onChange(x.id); this.onTouch(x.id); } }) } // this method sets the value programmatically writeValue(value: any) { this.value = value; } // upon UI element value changes, this method gets triggered registerOnChange(fn: any) { this.onChange = fn; } // upon touching the element, this method gets triggered registerOnTouched(fn: any) { this.onTouch = fn; } }
48186a2260e4db5981b394ebcb8a19d89c101d81
TypeScript
yayhen/async-race
/src/components/car/index.ts
2.640625
3
import { carSvg } from "../../templates/car-svg"; import { flagSvg } from "../../templates/flag-svg"; import './style.css' class Car { private container: HTMLElement; carInfo: { name: string, color: string, id: number, }; velocity: number = 0; finished: boolean = false; private intervalId: NodeJS.Timer | undefined = undefined; constructor(name: string, color: string, id: number) { this.container = document.createElement('div'); this.container.className = 'car-slot'; this.container.id = id.toString(); this.carInfo = { name, color, id, } } createCar() { let car = document.createElement('div'); car.innerHTML = carSvg(this.carInfo.color); car.className = 'car-slot__car'; car.id = 'car'+this.carInfo.id; car.style.left = '100px'; this.container.append(car); } addFinishLine() { let finishLine = document.createElement('div'); finishLine.className = 'car-slot__finish-line'; finishLine.innerHTML = flagSvg(); this.container.append(finishLine); } addSelectCarButton() { let selectCarButton = document.createElement('button'); selectCarButton.className = 'car-slot__select-car'; selectCarButton.innerText = 'Select'; selectCarButton.onclick = () => { let textField = (document.getElementById('update-text-field') as HTMLInputElement); textField.value = this.carInfo.name; textField.setAttribute('car-id', this.carInfo.id.toString()); let colorPicker = document.getElementById('car-color') as HTMLInputElement; colorPicker.value = this.carInfo.color; } this.container.append(selectCarButton); } addRemoveCarButton() { let removeCarButton = document.createElement('button'); removeCarButton.className = 'car-slot__remove-car'; removeCarButton.innerText = 'Remove'; removeCarButton.onclick = () => { this.removeCar(this.carInfo.id); } this.container.append(removeCarButton); } async removeCar(id: number) { let request = await fetch('http://127.0.0.1:3000/garage/'+id, { method: 'DELETE', headers: {}, }); let carToDelete = document.getElementById(id.toString()); carToDelete?.remove(); let requestToWinners = await fetch('http://127.0.0.1:3000/winners/' + id, { method: 'DELETE', headers: {} }) } addStartEngineButton() { let startEngineButton = document.createElement('button'); startEngineButton.className = 'car-slot__start-engine'; startEngineButton.innerText = 'A'; startEngineButton.onclick = async () => { this.startEngine(); startEngineButton.disabled = true; this.addStopEngineButton(); } this.container.append(startEngineButton); } async startEngine() { let url = new URL('http://127.0.0.1:3000/engine/'); url.searchParams.set('id', this.carInfo.id.toString()); url.searchParams.set('status', 'started'); let response = await fetch(url.toString(), { method: 'GET', headers: {}, }); let info = await response.json(); this.velocity = info.velocity; this.startMovingCar(info.velocity); } async startMovingCar(velocity: number) { let car = document.getElementById('car'+this.carInfo.id); let intervalId = setInterval(() => { if(car) { let currentPosition = parseInt(car.style.left.slice(0, car.style.left.length-2)); currentPosition += velocity/10; car.style.left = `${currentPosition}px`; if(currentPosition >= this.container.clientWidth - 100) { this.finished = true; this.finishMovingCar(intervalId); } } }, 50); this.intervalId = intervalId; let url = new URL('http://127.0.0.1:3000/engine/'); url.searchParams.set('id', this.carInfo.id.toString()); url.searchParams.set('status', 'drive'); try { let response = await fetch(url.toString(), { method: 'GET', headers: {}, }); if(response.status === 200) { } if(response.status === 500) { this.finishMovingCar(intervalId); } } catch (error) { alert('Error with engine response') } } finishMovingCar(timeoutId :NodeJS.Timer) { clearInterval(timeoutId); } addStopEngineButton() { let stopEngineButton = document.createElement('button'); stopEngineButton.className = 'car-slot__stop-engine'; stopEngineButton.innerText = 'B'; stopEngineButton.onclick = () => { this.carMoveToStart(); stopEngineButton.disabled = true; this.addStartEngineButton(); }; this.container.append(stopEngineButton); } async carMoveToStart() { let url = new URL('http://127.0.0.1:3000/engine/'); url.searchParams.set('id', this.carInfo.id.toString()); url.searchParams.set('status', 'stopped'); let car = document.getElementById('car'+this.carInfo.id); let response = await fetch(url.toString(), { method: 'GET', headers: {} }); if(response.ok) { if(car) { if(this.intervalId) { clearInterval(this.intervalId); } car.style.left = '100px'; } } } addCarName() { let carName = document.createElement('p'); carName.className = 'car-slot__car-name'; carName.innerText = this.carInfo.name; this.container.append(carName); } render() { this.addSelectCarButton(); this.addRemoveCarButton(); this.addStartEngineButton(); this.addStopEngineButton(); this.createCar(); this.addFinishLine(); this.addCarName(); return this.container; } } export default Car
235ba3bb4759ddc03057b4772a5b16498ce3594e
TypeScript
bigfu1993/fu-cli
/template/spa3/views/utils/bus.ts
2.78125
3
class Bus { list: any = {} constructor() { // 收集订阅信息,调度中心 this.list = {}; } // 订阅 $on(name: string, fn: any) { this.list[name] = this.list[name] || []; this.list[name].push(fn); } // 发布 $emit(name: string, data: any) { if (this.list[name]) { this.list[name].forEach((fn: any) => { fn(data); }); } } // 取消订阅 $off(name: string) { if (this.list[name]) { delete this.list[name]; } } } class busModel { bus: any constructor() { this.bus = new Bus() } getBus() { return this.bus } } export let bus = new busModel().getBus();
f7f323fd60a2b4a3367e016885ad240d7fa5b96c
TypeScript
mGuv/Advent2018
/src/Collections/__tests__/HashSet.test.ts
3.578125
4
import HashSet from "../HashSet"; interface INestedValue { PropertyC: number; } interface ITestValue { PropertyA: string; PropertyB: INestedValue; } const testValue: ITestValue = {PropertyA: "Test One", PropertyB: {PropertyC: 123}}; const testValueSame: ITestValue = {PropertyA: "Test One", PropertyB: {PropertyC: 123}}; const testValueNested: ITestValue = {PropertyA: "Test One", PropertyB: {PropertyC: 456}}; const set: HashSet<ITestValue> = new HashSet<ITestValue>(); it("Should return false when asking for a non-existent item", () => { expect(set.Contains(testValue)).toBeFalsy(); }); it("Should return false when removing a non-existent item", () => { expect(set.Remove(testValue)).toBeFalsy(); }); it("Should return true when adding a new item", () => { expect(set.Add(testValue)).toBeTruthy(); }); it("Should detect duplicates with same values", () => { expect(set.Contains(testValueSame)).toBeTruthy(); }); it("Should detect differences in nested properties with same values", () => { expect(set.Contains(testValueNested)).toBeFalsy(); }); it("Should report its count correctly", () => { expect(set.Count).toEqual(1); }); it("Should return false when adding an existing item", () => { expect(set.Add(testValue)).toBeFalsy(); }); it("Should return true when asking for an existing item", () => { expect(set.Contains(testValue)).toBeTruthy(); }); it("Should return elements when asked", () => { expect(set.Values).toEqual([testValue]); }); it("Should return true when removing an existing item", () => { expect(set.Remove(testValue)).toBeTruthy(); expect(set.Count).toBe(0); });
1f9bf326866dc95fcfee8a0e566586bfbbcfe1ec
TypeScript
tyrone-sudeium/aethebot
/src/brain/brain.d.ts
2.90625
3
import { EventEmitter } from "events" import StrictEventEmitter from "strict-event-emitter-types" /** * Abstract memory store for the bot. */ /* * AetheBot - A Discord Chatbot * * Created by Tyrone Trevorrow on 03/02/17. * Copyright (c) 2017 Tyrone Trevorrow. All rights reserved. * * This source code is licensed under the permissive MIT license. */ /** * Messages that can be sent over the `systemMessages` event emitter. */ export interface SystemMessages { reconnect: void } export interface Brain { /** System messages events */ readonly systemMessages: StrictEventEmitter<EventEmitter, SystemMessages> /** Forces the Brain to save or persist its data. */ save(): Promise<void> /** Requests the Brain to close any connections. */ close(): Promise<void> /** Sets value for key. */ set(key: string, value: string): Promise<void> /** Returns value for a given key, or null if not found. */ get(key: string): Promise<string | null> /** Removes value for a given key, if any. */ remove(key: string): Promise<void> }
8fc08bd8a706fd6bd938e507f10b1586c2026bb9
TypeScript
ChangJoo-Park/trimmer
/is_alpha.test.ts
3.0625
3
import { assertEquals } from "./deps.ts"; import { isAlpha } from "./is_alpha.ts"; Deno.test("Empty String is alpha", () => { assertEquals(isAlpha(""), true); }); Deno.test("HelloWorld is alpha", () => { assertEquals(isAlpha("HelloWorld"), true); }); Deno.test("12345 is not alpha", () => { assertEquals(isAlpha("12345"), false); }); Deno.test("space is not alpha", () => { assertEquals(isAlpha(" "), false); }); Deno.test("Sentence with space is not alpha", () => { assertEquals(isAlpha("Hello World"), false); }); Deno.test("Lowercase all letters are alpha", () => { assertEquals(isAlpha("abcdefghijklmnopqrstuvwxyz"), true); }); Deno.test("Uppercase all letters are alpha", () => { assertEquals(isAlpha("ABCDEFGHIJKLMNOPQRSTUVWXYZ"), true); });
461225d548b9f2cde1822f7ea8bdb9b187cdba8a
TypeScript
game-OceanPlanet/OceanTribe
/src/com/breeze/game/battle/controller/HeroAttack2Controller.ts
2.828125
3
module qmr { /** * * @author coler * @description 英雄攻击2控制器,技能全部是自动释放 * */ export class HeroAttack2Controller extends BaseMoverActorController { private attackSpeed: number; private lastUseTime: number; public constructor(moverActor: BaseMoverActor) { super(moverActor); this.lastUseTime = 0; } /** * @description 执行此控制器,根据不同技能实现不同效果,这里需要重写 */ public excute(): void { this.attackSpeed = 0; if (this.moverActor) { this.moverActor.onPlayAtk2(); } } /** * @description 取消执行此控制器,需被子类继承 */ public cancelExcute(): void { } /** * @description 清除controller,需要被子类继承 */ public clearController(): void { } } }
2a4aadf979b708b0d36f6459f9949d1833be13f1
TypeScript
ranaDeepanshu/GoogleForm
/scripts/htmlElements/drop_down.ts
2.703125
3
import { dropDownElement } from "../interfaces"; export class dropDown implements dropDownElement { element: HTMLElement; optionList: HTMLSpanElement[]; constructor(list: HTMLSpanElement[]) { this.optionList = list; this.element = this.getBlock(); this.addEventListener(); } getBlock(): HTMLElement { let divElement: HTMLElement = document.createElement("div"); divElement.classList.add("custom-select-wrapper"); let divCustom: HTMLElement = document.createElement("div"); divCustom.classList.add("custom-select"); let divTrigger: HTMLElement = document.createElement("div"); divTrigger.classList.add("custom-select__Trigger"); divTrigger.id = "select-option"; // let arrow: HTMLElement = document.createElement("div"); // arrow.classList.add("arrow"); let customOptions = document.createElement("div"); customOptions.classList.add("custom-options"); customOptions.setAttribute("tabIndex", "0"); customOptions.id = "select-options"; this.optionList.forEach((val) => { val.classList.add("custom-option"); customOptions.appendChild(val); }); customOptions.appendChild(this.optionList[0].cloneNode(true)); // divTrigger.appendChild(arrow); divTrigger.appendChild(this.optionList[0]); divCustom.appendChild(divTrigger); divCustom.appendChild(customOptions); divElement.appendChild(divCustom); return divElement; } addEventListener(): void { let element: HTMLElement = this.element.querySelector("#select-options"); let dropElement: HTMLElement = this.element.querySelector("#select-option"); dropElement.addEventListener("click", (e) => { dropElement.style.visibility = "hidden"; element.style.visibility = "visible"; element.classList.add("dropdown"); element.focus(); }); element.addEventListener("click", (e) => { if ((<HTMLElement>e.target).tagName !== "SPAN") return; if ((<HTMLElement>e.target).classList.contains("custom-option")) { dropElement.replaceChild( (<HTMLElement>e.target).cloneNode(true), dropElement.firstChild ); } else { dropElement.replaceChild( (<HTMLElement>e.target).parentNode.cloneNode(true), dropElement.firstChild ); } element.style.visibility = "hidden"; dropElement.style.visibility = "visible"; }); element.addEventListener("focusout", () => { element.style.visibility = "hidden"; dropElement.style.visibility = "visible"; element.classList.remove("dropdown"); }); } }
0f6e26575778f2cf6d3b9e1882a5bfb89d27f084
TypeScript
Amarillys/genshin-stats
/packages/genshin-api/src/index.ts
2.546875
3
import { APIClientType, WrapWithKey } from '@mihoyo-kit/api/typings'; import { request, RequestOptions } from '@mihoyo-kit/api/lib/request'; import { getServerRegionByUid } from '@mihoyo-kit/genshin-data'; import { GameStats, SpiralAbyssScheduleType, CharacterDetail, Character, SpiralAbyssData } from '../typings'; /** * 获取原神游戏数据总览 * Fetch game record data (what you see in HoYoLab's Game Record, except Spiral Abyss) for given uid. * @param role_id UID */ export function getGenshinGameStats(role_id: number | string, options?: RequestOptions): Promise<GameStats> { const server = getServerRegionByUid(role_id); return request<GameStats>(`https://api-takumi.mihoyo.com/game_record/app/genshin/api/index?server=${server}&role_id=${role_id}`, { ...options, client_type: APIClientType.WEBVIEW, responseType: 'json', resolveBodyOnly: true, ds2: true, }); } /** * 获取原神深境螺旋数据 * Fetch Spiral Abyss statistics data * @param role_id UID * @param schedule_type 本期或上期 (Current or previous) */ export function getSpiralAbyssData(role_id: number | string, schedule_type = SpiralAbyssScheduleType.CURRENT, options?: RequestOptions): Promise<SpiralAbyssData> { const server = getServerRegionByUid(role_id); return request<SpiralAbyssData>(`https://api-takumi.mihoyo.com/game_record/app/genshin/api/spiralAbyss?schedule_type=${schedule_type}&server=${server}&role_id=${role_id}`, { ...options, client_type: APIClientType.WEBVIEW, responseType: 'json', resolveBodyOnly: true, ds2: true, }); } /** * 获取角色装备详情 * Fetch details of a player's characters, including weapon and reliquaries. */ export async function getPlayerCharacterDetails(role_id: number | string, characters: Character[], options?: RequestOptions): Promise<readonly CharacterDetail[]>; export async function getPlayerCharacterDetails(role_id: number | string, character_ids: number[], options?: RequestOptions): Promise<readonly CharacterDetail[]>; export async function getPlayerCharacterDetails(role_id: number | string, data: GameStats, options?: RequestOptions): Promise<readonly CharacterDetail[]>; export async function getPlayerCharacterDetails(role_id: number | string, data: Character[] | number[] | GameStats, options?: RequestOptions): Promise<readonly CharacterDetail[]> { let character_ids: number[]; if (Array.isArray(data)) { if (data.length === 0) { throw new Error('no characters provided'); } character_ids = typeof data[0] === 'number' ? <number[]>data : (<Character[]>data).map(v => v.id); } else { character_ids = data.avatars.map(v => v.id); } const res = await request<WrapWithKey<CharacterDetail[], 'avatars'>>('https://api-takumi.mihoyo.com/game_record/app/genshin/api/character', { ...options, method: 'POST', responseType: 'json', resolveBodyOnly: true, client_type: APIClientType.WEBVIEW, ds2: true, json: { character_ids: character_ids, role_id: '' + role_id, server: getServerRegionByUid(role_id), }, }); return res.avatars; }
aeefde24a2286eeaffe155400ea181562867bb7b
TypeScript
mieshalannair/skuba
/src/cli/configure/processing/javascript.ts
2.671875
3
export const prependImport = (name: string, file?: string) => [`import '${name}';\n`, file] .filter((value) => value !== undefined) .join('\n'); export const stripImports = (names: readonly string[], inputFile: string) => { const searchStrings = names.flatMap((name) => [`'${name}'`, `"${name}"`]); const outputFile = inputFile .split(/\r?\n/) .filter((line) => !searchStrings.some((str) => line.includes(str))) .join('\n') .trim(); return `${outputFile}\n`; };
34049788f3f89d38f2abe2f11f208c0f0502618b
TypeScript
ringcentral/ringcentral-js-widgets
/packages/ringcentral-mock/src/platform/interfaces/ExtensionInfoGrants.ts
2.53125
3
// Extension information export interface ExtensionInfoGrants { /** * Internal identifier of an extension */ id: string; /** * Canonical URI of an extension */ uri: string; /** * Extension short number (usually 3 or 4 digits) */ extensionNumber: string; /** * Name of extension */ name: string; /** * Extension type. Please note that legacy 'Department' extension type corresponds to 'Call Queue' extensions in modern RingCentral product terminology */ type: | 'User' | 'Fax User' | 'VirtualUser' | 'DigitalUser' | 'Department' | 'Announcement' | 'Voicemail' | 'SharedLinesGroup' | 'PagingOnly' | 'IvrMenu' | 'ApplicationExtension' | 'ParkLocation'; }
217e2bfcd75b6d2bcaa433c43cd40c7440185a5e
TypeScript
maximebourdel/carPool-front-office
/src/app/feedback/feedback.ts
2.84375
3
import { Reservation } from '../reservation/reservation'; /** * Objet représentant un retour sur la réservation */ export class Feedback { /** * Constructeur initialisant un Objet Feedback * @param id Identifiant technique unique du Feedback * @param reservation Objet représentant une réservation de voiture de pool * @param kilometres Kilomètres au compteur du véhicule constaté à la fin de la réservation * @param commentaires Commentaire sur la réservation ou le véhicule * @param date_creation Champ technique permettant d'enregistrer la date de d'insertion de la ligne * @param date_der_maj Champ technique permettant d'enregistrer la date de dernière modification de la ligne */ constructor( public id?: number, public reservation?: Reservation, public kilometres?: number, public commentaires?: string, public date_creation?: string, public date_der_maj?: string ) { } }
8b8bc9961bfee81818416bcf4bd5f8ed64c20a3a
TypeScript
royhadad/caregivers-report-server
/src/controllers/reportController.ts
2.546875
3
import {Request, Response} from 'express'; import {QueryResult} from 'pg'; import * as dbUtil from './../utils/dbUtil'; interface Report { year: number, caregivers: { name: string, patients: string[] }[] } export const getReport = async (req: Request, res: Response) => { const {year} = req.params; const sql = ` SELECT caregiver.id AS caregiver_id, array_agg(caregiver.name) AS caregiver_names, array_agg(patient.id) AS patients_ids, array_agg(patient.name) AS patients_names, array_agg(visit.date) AS visit_dates FROM caregiver JOIN visit ON visit.caregiver = caregiver.id JOIN patient ON patient.id = visit.patient WHERE visit.date BETWEEN '$${year}-01-01' AND '$${year}-12-31' GROUP BY caregiver.id `; let result : QueryResult; try { result = await dbUtil.sqlToDB(sql, []); const report: Report = { year: parseInt(year), caregivers: [] }; for ( let row of result.rows) { report.caregivers.push({ name: row.caregiver_names[0], patients: row.patients_names }) } res.status(200).json(report); } catch (error) { throw new Error(error.message); } }
84bbdac4a5e0eb1900b30abc9030c95b7de3d253
TypeScript
game7/sportified
/app/javascript/utils/use-form.ts
2.515625
3
import { FormDataConvertible } from "@inertiajs/inertia"; import { Form, FormItemProps } from "antd"; import _, { get, isPlainObject } from "lodash"; import { humanize } from "./inflector"; import { useErrors } from "./use-errors"; // hook to wrap antd useForm hook and include // model binding helper export function useForm<T extends object>(model?: T) { const [form] = Form.useForm<T>(); const [errorsFor] = useErrors<T>(); function bind(attr: NestedKeyOf<T>): Partial<FormItemProps<T>> { const path = (attr as string).split("."); return { name: path, label: humanize(path.join(" ")), initialValue: getInitialValue<T>(model, attr), ...errorsFor(attr), }; } return { form, bind }; } function getInitialValue<T extends object>( model: T | undefined, attr: NestedKeyOf<T> ) { let value = model && get(model, attr); return value === null ? "" : value; } export function asPayload<TModel extends Record<string, any>>( model: TModel, ...nestedAttributes: string[] ): Record<string, FormDataConvertible> { if (!nestedAttributes.length) { return model as Record<string, FormDataConvertible>; } const attrs = new Set(nestedAttributes); return deepTransformKeys(model, (_obj, key) => { return attrs.has(key) ? `${key}_attributes` : key; }) as Record<string, FormDataConvertible>; } function deepTransformKeys( object: any, callback: (value: any, key: string) => string ): any { if (!isPlainObject(object)) { return object; } return _(object) .mapKeys(callback) .mapValues((value) => deepTransformKeys(value, callback)) .value(); }
29785b5ff5f4844edc6d77e3ff1a7409135173f5
TypeScript
rd-dev-ukraine/rd-url-utils
/src/api.ts
3.375
3
export interface ForceMatch<TParams, TQueryString> { /** Casts result to matched or throws error if URL didn't match. */ asMatched(): Match<TParams, TQueryString>; } export interface NoMatch { isMatched: false; } export interface Match<TParams, TQueryString> { isMatched: true; params: TParams; query?: TQueryString & { [key: string]: string }; } export interface LocationDescriptor { search?: string; pathname: string; } export interface UrlPath<TParams, TQueryString> { urlTemplate: string; paramType: TParams; queryType: TQueryString; /** * Checks if URL matches pattern specified on creating URL and extracts parameters and query if matched. * @param url An URL to check * @param exact If true method would check if pattern matched full URL, if false - only start of URL would be checked. */ match( url: string | LocationDescriptor, exact?: boolean ): (NoMatch | Match<TParams, TQueryString>) & ForceMatch<TParams, TQueryString>; format(params: TParams, query?: any): string; /** * Parses URL and constructs new URL with * updated parameters and query string. * * If given URL doesn't match current UrlPath instance, method returns undefined. */ replace( url: string | LocationDescriptor, params?: Partial<TParams>, query?: Partial<TQueryString> ): string | undefined; /** * Creates a path by adding some url template to parent URL */ createChildPath<TChildParams, TChildQueryString>( urlTemplate: string ): UrlPath<TParams & TChildParams, TQueryString & TChildQueryString>; }
f4a8b68cb9691b55ae54b128f94eaa37531dd568
TypeScript
hachimitu22/countdown
/test/ratio-record.test.ts
2.859375
3
import * as chai from 'chai'; import RatioRecord from '../src/frontend/ratio/ratio-record'; describe('RatioRecord', () => { it('stringを値に持つレコードが作成される', async () => { const record = new RatioRecord<string>('record', 100); chai.expect(record.value).to.equal('record'); chai.expect(record.ratio).to.equal(100); }); it('numberを値に持つレコードが作成される', async () => { const record = new RatioRecord<number>(1, 100); chai.expect(record.value).to.equal(1); chai.expect(record.ratio).to.equal(100); }); it('booleanを値に持つレコードが作成される', async () => { const record = new RatioRecord<boolean>(true, 100); chai.expect(record.value).to.equal(true); chai.expect(record.ratio).to.equal(100); }); it('{ [key: string]: string }のobjectを持つレコードが作成される', async () => { const record = new RatioRecord<{ [key: string]: string }>({ 'key': 'value' }, 100); chai.expect(record.value).to.deep.equal({ 'key': 'value' }); chai.expect(record.ratio).to.equal(100); }); });
c2ee9d976b94e97e1f20c9b8be289e749ae278be
TypeScript
CityOfZion/neon-js
/packages/neon-core/src/u/HexString.ts
3.71875
4
import { base642hex, hex2base64, ensureHex, reverseHex } from "./basic"; import { hexXor } from "./misc"; import { str2hexstring, hexstring2ab, ab2hexstring, hexstring2str, } from "./convert"; export class HexString { /** * Will store value in big endian */ #value: string; public get length(): number { return this.#value.length; } public get byteLength(): number { return this.#value.length / 2; } public assert(value: string): void { ensureHex(value); } /** * Initiate a HexString * @param value - a string that contains only [1-9a-f]. Can be prefixed with 0x. * @param littleEndian - indicate whether value is little endian or not. default to be false. */ protected constructor(value: string, littleEndian = false) { if (value.startsWith("0x")) { value = value.slice(2); } this.assert(value); this.#value = littleEndian ? reverseHex(value) : value; } public toString(): string { return this.#value; } /** * Export as big endian string */ public toBigEndian(): string { return this.#value; } /** * Export as little endian string */ public toLittleEndian(): string { return reverseHex(this.#value); } /** * Returns a new HexString with internal value reversed hex. */ public reversed(): HexString { return new HexString(reverseHex(this.#value)); } /** * Judge if 2 HexString are equal */ public equals(other: HexString | string): boolean { if (typeof other === "string") { return this.toBigEndian() === HexString.fromHex(other).toBigEndian(); } return this.toBigEndian() === other.toBigEndian(); } /** * XOR with another HexString to get a new one. */ public xor(other: HexString): HexString { return HexString.fromHex(hexXor(this.toBigEndian(), other.toBigEndian())); } /** * Export as ASCII string */ public toAscii(): string { return hexstring2str(this.toBigEndian()); } /** * Export as number * @param asLittleEndian - whether export as little endian number, default to be false */ public toNumber(asLittleEndian = false): number { return parseInt( asLittleEndian ? this.toLittleEndian() : this.toBigEndian(), 16 ); } /** * Export to ArrayBuffer in Uint8Array * @param asLittleEndian - whether export as little endian array, default to be false */ public toArrayBuffer(asLittleEndian = false): Uint8Array { return hexstring2ab( asLittleEndian ? this.toLittleEndian() : this.toBigEndian() ); } /** * Export as a base64-encoded string. * @param asLittleEndian - whether to encode as little endian, default to be false */ public toBase64(asLittleEndian = false): string { return hex2base64( asLittleEndian ? this.toLittleEndian() : this.toBigEndian() ); } /** * Get HexString instance from a hex string * @param str - hexstring * @param littleEndian - whether `str` is little endian */ public static fromHex(str: string, littleEndian: boolean): HexString; public static fromHex(str: string | HexString): HexString; public static fromHex( str: string | HexString, littleEndian = false ): HexString { if (typeof str === "object" && str instanceof HexString) { return new HexString(str.toBigEndian()); } return new HexString(str, littleEndian); } /** * Get HexString instance from a ASCII string */ public static fromAscii(str: string): HexString { const hex = str2hexstring(str); return new HexString(hex); } /** * Get HexString instance from a number * @param littleEndian - whether `num` is little endian */ public static fromNumber(num: number): HexString { const rawHex = num.toString(16); if (rawHex.length % 2 !== 0) { return new HexString("0" + rawHex); } return new HexString(rawHex); } /** * Get HexString instance from array buffer * @param littleEndian - whether `arr` is little endian */ public static fromArrayBuffer( arr: ArrayBuffer | ArrayLike<number>, littleEndian = false ): HexString { return new HexString(ab2hexstring(arr), littleEndian); } /** * Get HexString instance from a Base64-encoded string * @param littleEndian - whether the decoded hexstring is little endian */ public static fromBase64( encodedString: string, littleEndian = false ): HexString { return new HexString(base642hex(encodedString), littleEndian); } }
0c41a9ed53059c164ecab92238ffbf6756fd7e35
TypeScript
travetto/travetto
/module/model/src/internal/service/bulk.ts
2.625
3
import { Class } from '@travetto/base'; import { BulkOp } from '../../service/bulk'; import { ModelType } from '../../types/model'; import { ModelCrudProvider, ModelCrudUtil } from './crud'; export type BulkPreStore<T extends ModelType> = { insertedIds: Map<number, string>; upsertedIds: Map<number, string>; updatedIds: Map<number, string>; existingUpsertedIds: Map<number, string>; operations: BulkOp<T>[]; }; export class ModelBulkUtil { /** * Prepares bulk ops for storage * @param cls * @param operations * @param provider */ static async preStore<T extends ModelType>(cls: Class<T>, operations: BulkOp<T>[], provider: ModelCrudProvider): Promise<BulkPreStore<T>> { const insertedIds = new Map<number, string>(); const upsertedIds = new Map<number, string>(); const updatedIds = new Map<number, string>(); const existingUpsertedIds = new Map<number, string>(); // Pre store let i = 0; for (const op of operations) { if ('insert' in op && op.insert) { op.insert = await ModelCrudUtil.preStore(cls, op.insert, provider); insertedIds.set(i, op.insert.id!); } else if ('update' in op && op.update) { op.update = await ModelCrudUtil.preStore(cls, op.update, provider); updatedIds.set(i, op.update.id); } else if ('upsert' in op && op.upsert) { const isNew = !op.upsert.id; op.upsert = await ModelCrudUtil.preStore(cls, op.upsert, provider); if (isNew) { upsertedIds.set(i, op.upsert.id!); } else { existingUpsertedIds.set(i, op.upsert.id!); } } i += 1; } return { insertedIds, upsertedIds, updatedIds, existingUpsertedIds, operations }; } }
1995abc828c81a1c8c9edf3898fe34db81c48039
TypeScript
cHolzberger/pricey-typescript
/src/TaxDecorator.ts
2.75
3
import {PriceDecorator, Price} from "./Price"; import {Currency} from "./currency"; import {_internalToAmount,_amountToInternal} from "./helper"; //fixme move common code here export abstract class PriceWithTaxDecorator extends PriceDecorator { _price: Price; _tax: number; constructor(p: Price, c: { tax: number }) { super(); this._price = p; this._tax = c.tax; } get currency(): Currency { return this._price.currency; } get amount(): number { return _internalToAmount(this.currency, this._internalAmmount); } toString(): string { return `${this.amount.toFixed(this.currency.decimal_digits)}`; } _internalTax: number; _internalAmmount: number; get tax(): number { return _internalToAmount(this.currency, this._internalTax); } get taxRate(): number { return this._tax; } get annotation(): string { return `including ${this.tax.toFixed(this.currency.decimal_digits)} (${this.taxRate}%) Tax`; } } export class PriceWithAddTaxDecorator extends PriceWithTaxDecorator { get _internalTax(): number { return (this._price._internalAmmount * this._tax) / 100; } get _internalAmmount(): number { return (this._price._internalAmmount + this._internalTax); } } export class PriceIncludingTaxDecorator extends PriceWithTaxDecorator { get _internalAmmount(): number { return (this._price._internalAmmount); } get _internalTax(): number { // FIXME: right formular return this._price._internalAmmount - (this._price._internalAmmount / ((100 + this._tax) / 100)); } }
07a792c8bf3e813e10d296a6123b15aac3180c85
TypeScript
heartpoints/heartpoints.org
/src/restguru/restguru.test.ts
2.6875
3
import * as _ from "lodash"; import { then } from "../testing/then"; import { whenValues } from "../testing/whenValues"; import { theInternet } from "../restguru/theInternet"; import { expect } from "chai"; import { HttpMethod } from "../restguru/HttpMethod"; import { RestClient } from "./RestClient"; describe("restful-json", () => { describe("theInternet", () => { const simpleResourceTest = ({url,contentType,expectedValue}) => whenValues({url, contentType}, () => { const result = () => theInternet({url, contentType}) then(result).shouldMeetExpectations(maybeRepresentation => { expect(maybeRepresentation.value).to.deep.equal(expectedValue); }); }); simpleResourceTest({ url: "http://names/Tommy", contentType: "ifdjhsidufh", expectedValue:"Tommy" }) simpleResourceTest({ url: "http://colors/red", contentType: "ifdjhsidufh", expectedValue:"red" }) simpleResourceTest({ url: "http://colors/red", contentType: "text/html", expectedValue:"<html><body><h1>red</h1><p>red is a color</body></html>" }) simpleResourceTest({ url: "http://people", contentType: "http://rest.guru/rgson/primitive", expectedValue: [ "http://people/1", "http://people/2", ] }) simpleResourceTest({ url: "http://people", contentType: "http://rest.guru/rgson/completeProjection", expectedValue: [ { "id": 1, "name": "Tommy", "favoriteColors": ["red","green","blue"] }, { "id": 2, "name": "Mike", "favoriteColors": ["pink","purple"] } ] }) }); describe("via actual web server", () => { whenValues({restClient: RestClient()}, ({restClient}) => { whenValues({url: "http://rest.guru", method: HttpMethod.OPTIONS, accept: ["http://rest.guru/contentTypes/http/optionsResponse"]}, ({url, method, accept}) => { then(() => restClient.request({url, method, accept})).shouldEventually((httpResponse) => { expect(httpResponse).to.exist; }) }) }); }) });
fba536b66b5dcfb510c4dce9e954808355fc1c69
TypeScript
training4developers/angular_01082018
/demos/app.component.7.ts
2.515625
3
import { Component, InjectionToken, Inject, Injectable } from '@angular/core'; import { HttpClient, HttpInterceptor, HttpRequest, HttpHandler, HTTP_INTERCEPTORS } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { WebSocketDemoService } from './services/web-socket-demo.service'; interface Color { id: number; name: string; hexCode: string; } @Injectable() export class AuthorizationTokenInterceptor implements HttpInterceptor { public intercept(request: HttpRequest<any>, next: HttpHandler) { request = request.clone({ setHeaders: { Authorization: 'some token', } }); return next.handle(request); } } const DataServiceToken = new InjectionToken<DataService>('data service'); interface DataService { all(); } @Injectable() class ColorsService implements DataService { constructor(private httpClient: HttpClient) { } all() { return this.httpClient.get<Color[]>('http://localhost:3010/colors').toPromise(); } } const colorsServiceFactory = (httpClient: HttpClient) => { return new ColorsService(httpClient); }; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], providers: [ // { provide: DataServiceToken, useFactory: colorsServiceFactory, deps: [ HttpClient ] } ColorsService, ], }) export class AppComponent { public coolNums: Observable<number>; // constructor(@Inject(DataServiceToken) private dataSvc: DataService) { constructor(private dataSvc: ColorsService, private webSocketDemo: WebSocketDemoService) { this.coolNums = webSocketDemo.all(); if (dataSvc) { dataSvc.all().then( (colors: Color[]) => console.log(colors)); } } }
03470121bbf70a5967f09c05787c3456788d5c47
TypeScript
bradrivenburgh/jotto-ts
/src/reducers/successReducer.test.ts
2.703125
3
import { actionTypes } from '../actions'; import successReducer from './successReducer'; test('when previous state is undefined, return false', () => { const newState = successReducer(undefined, { type: '' }); expect(newState).toBe(false); }); test('return previous state when unknown action type', () => { const newState = successReducer(false, { type: 'unknown' }); expect(newState).toBe(false); }); test('return "true" for action type CORRECT_GUESS', () => { const newState = successReducer(false, { type: actionTypes.CORRECT_GUESS }); expect(newState).toBe(true); });
558228aed881e0f7f8f27c444c7ab7aca3fd4e5e
TypeScript
AmandaVP23/nestjs-twitter-copy
/src/follow/follow.repository.ts
2.71875
3
import { EntityRepository, Repository } from 'typeorm'; import { Follow } from '../users/entities/follow.entity'; import { User } from '../users/entities/user.entity'; import { InternalServerErrorException } from '@nestjs/common'; import { IPaginationOptions, paginate } from 'nestjs-typeorm-paginate'; @EntityRepository(Follow) export class FollowRepository extends Repository<Follow> { async createNewFollow(user: User, followerUser: User) { const existingFollow = await this.findFollow(user, followerUser) if (existingFollow) { try { await existingFollow.remove(); // await followerUser.decrementFollowing(); // await user.decrementFollowers(); return true; } catch (e) { throw new InternalServerErrorException(); } } const follow = new Follow(); follow.user = followerUser; // user that is followed follow.follower = user; // user that follows try { await follow.save(); // await followerUser.incrementFollowing(); // await user.incrementFollowers(); return true; } catch (e) { throw new InternalServerErrorException(); } } async findFollow(user: User, followerUser: User) { const query = this.createQueryBuilder('follow'); query.where('user = :username', { username: user.username }); query.andWhere('follower = :followerUsername', { followerUsername: followerUser.username }); try { return await query.getOne(); } catch (e) { throw new InternalServerErrorException(); } } async getUserFollowers(username: string, options: IPaginationOptions<Follow>) { // const user = await this.find({ where: { user: user.username } }) const query = this.createQueryBuilder('follow'); query.innerJoinAndSelect('follow.follower', 'follower') query.where('user = :username', { username }); try { // return await this.find({ where: { user: user.username } }) return paginate(query, options); // return await query.getMany(); } catch (e) { throw new InternalServerErrorException(); } } async getUserFollowing(username: string, options: IPaginationOptions<Follow>) { const query = this.createQueryBuilder('follow'); query.innerJoinAndSelect('follow.user', 'follower') query.where('follower = :username', { username }); try { return paginate(query, options); // return await query.getMany(); } catch (e) { throw new InternalServerErrorException(); } } }
fccb55a6093825d945744745d524ada8189f963b
TypeScript
Nergal2/Shoping-Center-Front
/src/app/orders-list/cart.model.ts
2.546875
3
import {Recipe} from '../recipies/recipe.model'; export class Cart { public name: string; public email: string; public sex: string; public cart: {numb: number, rec: Recipe}[]; public price: number; public orderId: string; constructor(name: string, email: string, sex: string, cart: {numb: number, rec: Recipe}[], price: number, orderId: string) { this.name = name; this.email = email; this.sex = sex; this.cart = cart; this.price = price; this.orderId = orderId; } }
c6b450f6268e2bb25fc60175058dabc064cad5f0
TypeScript
paullessing/home-comms-server
/entities/Channel.ts
2.6875
3
///<reference path='_all.ts' /> import * as Promise from 'bluebird'; import { Document, Schema, Model, model, Query } from 'mongoose'; var Types = Schema.Types; //#################// // Action // //#################// export interface Action { name: string, seqId?: number, timestamp: Date, data?: any } interface ActionDocument extends Action, Document { name: string; seqId: number; //id: Types.ObjectId; timestamp: Date; data: any; } var ActionSchema = new Schema({ name: { type: Types.String, required: true }, seqId: { type: Number, required: true }, timestamp: { type: Date, 'default': Date.now, required: true }, data: { type: Types.Mixed, required: false } }); var ActionModel = model<ActionDocument>("Action", ActionSchema); //#################// // Channel // //#################// var ChannelSchema = new Schema({ name: { type: String, required: true }, actions: [ActionSchema] }); interface ChannelDocument extends Document { name: string; actions: Action[]; } var ChannelModel = model<ChannelDocument>("Channel", ChannelSchema); export class Channel { constructor(private mChannel: ChannelDocument) { this._lastUpdateId = mChannel.actions.length ? mChannel.actions[mChannel.actions.length - 1].seqId : 0; } public get name(): string { return name; } private _lastUpdateId: number = 0; public get lastUpdateId(): number { return this._lastUpdateId; } public addAction(action: Action): Promise<Action> { action.seqId = ++this._lastUpdateId; var mAction = new ActionModel(action); this.mChannel.actions.push(mAction); return Promise.resolve(this.mChannel.save()).then(() => mAction); } public get lastAction(): Action { if (this.mChannel.actions.length === 0) { return null; } else { return this.mChannel.actions[this.mChannel.actions.length - 1]; } } public get actions(): Action[] { return this.mChannel.actions.slice(); } public static create(name: string): Promise<Channel> { return Promise.resolve(new ChannelModel({ name: name, actions: [] }).save()) .then((mChannel: ChannelDocument) => { return new Channel(mChannel); }); } public static fetch(name: string): Promise<Channel> { console.log("Fetching"); return Promise.resolve(ChannelModel.findOne({ name: name })) .then((mChannel: ChannelDocument) => { console.log(mChannel); return Promise.resolve(new Channel(mChannel)) }) .catch(err => { console.log(err); return Promise.reject(err); }); } public static exists(name: string): Promise<boolean> { console.log("Checking existence", name); return Channel.fetch(name).then(() => { console.log("Exists"); return Promise.resolve(true); }).catch(err => { console.log("No Exists", err); return Promise.resolve(false); }); } }
7892cd6677c2d089e2c7f9a587c18f73c5d0bc88
TypeScript
scottyboi30/Task-Management
/src/app/core/services/state.service.ts
2.515625
3
import { Injectable } from '@angular/core'; import { State } from '../../shared/enums/state'; @Injectable({ providedIn: 'root' }) export class StateService { getStateOptions() { let states: any[] = []; for (let value in State) { if (isNaN(Number(value))) { states.push({ name: value, value: State[value] }) } } return states; } getAllStatesBit() { return State.ToDo | State.Started | State.Completed | State.Cancelled | State.Deleted; } }
f70fe800931eb39968558326c274c8e65cae7d04
TypeScript
vinbustamante/pokemonquery
/test/common/services/ReflectionService.spec.ts
3.234375
3
import * as expect from "expect"; import { ReflectionService } from "../../../src/common/services/implementation/ReflectionService"; describe("ReflectionService", () => { let _reflectionService; beforeEach(() => { _reflectionService = new ReflectionService(); }); describe("isArray()", () => { it("should check string type", () => { expect(_reflectionService.isArray([])).toBe(true); expect(_reflectionService.isArray([1, 2, 3])).toBe(true); expect(_reflectionService.isArray()).toBe(false); expect(_reflectionService.isArray(1)).toBe(false); expect(_reflectionService.isArray("eee")).toBe(false); }); }); describe("isObject()", () => { it("should check type object", () => { expect(_reflectionService.isObject([])).toBe(true); expect(_reflectionService.isObject({})).toBe(true); expect(_reflectionService.isObject("eee")).toBe(false); }); }); describe("createObjectFrom", () => { it("it should create an object base on class", () => { const cust = _reflectionService.createObjectFrom(Customer, { name: "marvin" }); expect(cust.name).toBe("marvin"); }); }); describe("objectToConstructor()", () => { it("should determing the constructor function properly", () => { expect(_reflectionService.objectToConstructor(Customer)).toBe(Customer); expect(_reflectionService.objectToConstructor(new Customer())).toBe( Customer ); }); }); describe("readObjectValue()", () => { it("should be able to read property and subproperty", () => { const config = { name: { firstname: "marvin", lastname: "bustamante" }, address: "sigbapore" }; expect(_reflectionService.readObjectValue(config, "address")).toBe( config.address ); expect(_reflectionService.readObjectValue(config, "name.firstname")).toBe( config.name.firstname ); }); }); describe("toObject()", () => { it("should convert string to object", () => { const customer = { name: "marvin" }; const json = JSON.stringify(customer); const result = _reflectionService.toObject(json); expect(JSON.stringify(result)).toBe(json); }); it("should default to empty object if there was an error parsing", () => { expect(Object.keys(_reflectionService.toObject("xxx")).length).toBe(0); }); it("should return the value if not string", () => { expect(_reflectionService.toObject(1)).toBe(1); expect(_reflectionService.toObject(false)).toBe(false); }); }); describe("toJson()", () => { it("should return the value if not an object", () => { expect(_reflectionService.toJson(1)).toBe(1); expect(_reflectionService.toJson(false)).toBe(false); }); it("should be able to convert an object to string", () => { const cust = { name: "marvin" }; const json = JSON.stringify(cust); expect(_reflectionService.toJson(cust)).toBe(json); }); }); }); class Customer {}
1e5596f5d12599dff19b0572c2b7f7caa6cf872f
TypeScript
aduserviewer/aduserviewer
/user-viewer/src/model/sort-options.ts
3.25
3
/** * Represents sorting behavior to be applied to a dataset. 'attribute' * 'specifies' the attribute to sort on, and 'direction' specifies * whether to sort ascending or descending on the dataset. */ export interface SortOptions { attribute: string; direction: "asc" | "desc"; }
21cb1e76e81d3f04024cf0b2bc7343731018c087
TypeScript
vlad2497/tango
/src/store/modules/lessonAnnounces/reducer.ts
2.859375
3
import { SET_LESSON_ANNOUNCES_LIST, SET_LESSON_ANNOUNCES_LOADING, SET_LESSON_ANNOUNCES_ERROR, } from "./selectors"; import { ILessonAnnounce } from "./../../../interfaces/ILessonAnnounce"; export interface IState { list: ILessonAnnounce[] | null; loading: boolean; error: string | null; } type ActionType = | { type: typeof SET_LESSON_ANNOUNCES_LIST; payload: IState["list"]; } | { type: typeof SET_LESSON_ANNOUNCES_LOADING; payload: IState["loading"]; } | { type: typeof SET_LESSON_ANNOUNCES_ERROR; payload: IState["error"]; }; const initialState: IState = { list: null, error: null, loading: false, }; const authReducer = (state = initialState, action: ActionType): IState => { switch (action.type) { case SET_LESSON_ANNOUNCES_LIST: { return { ...state, list: action.payload }; } case SET_LESSON_ANNOUNCES_LOADING: { return { ...state, loading: action.payload }; } case SET_LESSON_ANNOUNCES_ERROR: { return { ...state, error: action.payload }; } default: return state; } }; export default authReducer;
a1b8a5608dc9f9a1231f5f20f7d771006ffabe86
TypeScript
zachabney/atem-stream-deck
/src/auth/numeric-button.ts
2.921875
3
import { ImageSize, UIImage, UIScreen, Component } from 'tile-ui' import { RED, BLUE } from '../colors' export type NumericButtonListener = (button: NumericButton) => void type ButtonState = { isPressed: boolean hasError: boolean } export default class NumericButton extends Component<ButtonState> { readonly number: number private onPressListener?: NumericButtonListener private onReleaseListener?: NumericButtonListener private initialButtonImage!: UIImage private pressedButtonImage!: UIImage private errorButtonImage!: UIImage private errorTimeout?: NodeJS.Timeout constructor( screen: UIScreen, number: number, onPressListener?: NumericButtonListener, onReleaseListener?: NumericButtonListener ) { super(screen, { isPressed: false, hasError: false }) this.number = number this.onPressListener = onPressListener this.onReleaseListener = onReleaseListener } async preload(size: ImageSize) { const path = `assets/Numeric/${this.number}.png` this.initialButtonImage = await this.imageLoader.get(path, size) this.pressedButtonImage = await this.imageLoader.get(path, size, BLUE) this.errorButtonImage = await this.imageLoader.get(path, size, RED) } private isDisabled() { return this.state.hasError } onPress() { if (this.isDisabled()) { return } this.setState(prevState => { return { ...prevState, isPressed: true } }) if (this.onPressListener) { this.onPressListener(this) } } onRelease() { this.setState(prevState => { return { ...prevState, isPressed: false } }) if (!this.isDisabled() && this.onReleaseListener) { this.onReleaseListener(this) } } showError(duration: number) { if (this.state && !this.state.hasError) { this.setState(prevState => { return { ...prevState, hasError: true } }) } this.cancelErrorTimeout() this.errorTimeout = setTimeout(() => { this.errorTimeout = undefined this.setState(prevState => { return { ...prevState, hasError: false } }) }, duration) } onDestroy() { this.cancelErrorTimeout() } cancelErrorTimeout() { if (this.errorTimeout) { clearTimeout(this.errorTimeout) this.errorTimeout = undefined } } render(): UIImage { if (this.state.isPressed) { return this.pressedButtonImage } if (this.state.hasError) { return this.errorButtonImage } return this.initialButtonImage } }
82e72e0c37626acc4d8ae323fed96c82716eae05
TypeScript
Prasannakumar124/Angular-Concepts
/Pipes/src/app/shorten.pipe.ts
2.515625
3
import { PipeTransform, Pipe } from "@angular/core"; @Pipe({ name:'short' }) export class ShortenPipes implements PipeTransform{ // transform(value:any){ // if(value.length>10){ // return value.substr(0,10) + '...'; // } // return value; // } transform(value:any,limit:number){ if(value.length>limit){ return value.substr(0,limit) + '...'; } return value; } }
6dca9ed1e9fbaee9f7c4de16fb9681d1ae0c4723
TypeScript
choyg/wwwwwwwww
/functions/service/extractor.ts
2.65625
3
import * as ytdl from 'ytdl-core'; import { AudioQuality, ContentDownloadable, ContentFormat, ContentInfo } from '../util/types'; // TODO ytdl.videoInfo typings are incorrect // Using any for now cuz too lazy to fix export function getBestM4a(info: any): ContentFormat | null { const streamingData = info.player_response.streamingData; const formats = streamingData.formats.concat(streamingData.adaptiveFormats); if (!formats.length) { return null; } const [content] = formats .filter(f => f.itag >= AudioQuality.LOW && f.itag <= AudioQuality.HIGH) // All m4as .sort((a, b) => b.itag - a.itag) // Filter descending by audio quality let quality: string; for (var enumMember in AudioQuality) { if (AudioQuality[enumMember]) { quality = enumMember; break; } } return { url: content.url, length: content.approxDurationMs, quality: quality || content.itag, size: content.contentLength } } export function getDownloadable(info: ytdl.videoInfo): ContentDownloadable | null { const contentInfo: ContentInfo = { author: info.author.name, title: info.title, }; const bestFormat = getBestM4a(info); if (!bestFormat) return null; return { ...bestFormat, ...contentInfo } }
7ff96c8cdcfe5d970571f6868fd040812d3b622b
TypeScript
fabasoad/algorithm-tasks
/typescript/leetcode/easy/Solution_MostCommonWord.ts
3.421875
3
{ // https://leetcode.com/problems/most-common-word/ function mostCommonWord(paragraph: string, banned: string[]): string { const map: Map<string, number> = new Map<string, number>(); const words: string[] = paragraph.match(/[a-zA-Z0-9]+/g) as Array<string>; let max: number = 0; let maxWord: string = ''; for (let i = 0; i < words.length; i++) { const w: string = words[i].toLowerCase(); if (!banned.includes(w)) { const val: number = (map.get(w) || 0) + 1; map.set(w, val); if (val > max) { max = val; maxWord = w; } } } return maxWord; } const res: string = mostCommonWord('Bob hit a ball, the hit BALL flew far after it was hit.', ['hit']); console.log(res); }
f7026bac4b906e503412c8c0402b1c2667caf4aa
TypeScript
darlanhms/new-world-guild-discord-bot
/src/handlers/invite/subcommands/deny.ts
2.625
3
import { Message } from 'discord.js'; import BaseHandler from '../../../shared/logic/BaseHandler'; import Handler from '../../../shared/logic/Handler'; import DenyGuildInviteUseCase from '../../../useCases/invites/denyGuildInvite/denyGuildInviteUseCase'; export default class DenyInviteHandler extends BaseHandler implements Handler { name = 'deny'; constructor(private denyGuildInvite: DenyGuildInviteUseCase) { super(); } public async handle(message: Message): Promise<Message> { const guildName = this.getCommandPayload(message, 'invite'); const response = await this.denyGuildInvite.execute({ guildName, userId: message.author.id, }); if (response.isLeft()) { return message.reply(response.value); } return message.channel.send( `O guerreiro <@${message.author.id}> recusou o convite da guilda ${guildName}`, ); } }
354005f4ece39b2608b0af13493c99fbc218cbe5
TypeScript
MaxKim-J/tweet-bot-client
/src/utils/flattenHelper.ts
2.78125
3
export const flattenPrevTweetList = (tweetList:any) => tweetList.map((tweet:any) => { const { id, uploadedAt, precedent: { name } } = tweet return { id, name, uploadedAt: uploadedAt.slice(0, 10) } }) export type TweetListType = ReturnType<typeof flattenPrevTweetList> export const flattenPrecedentDetail = (precedent:any, tweet:any) => { const { precedent: { content, url, type, name, }, } = precedent const { tweet: { id, content: tweetContent } } = tweet return { id, name, type, content, tweetContent, url, } } export type precedentDetailType = ReturnType<typeof flattenPrecedentDetail>
52c0507de32808cf657872981a73f8171f9c2eb5
TypeScript
BarkSanson/sort-algorithms-animation
/ts/Node.ts
3.09375
3
import * as Animator from "./animator.js"; import * as Sort from "./sortAlgorithms.js"; import Err from "./errors.js"; const addInput = document.querySelector(".add-input") as HTMLInputElement; const removeInput = document.querySelector(".remove-input") as HTMLInputElement; const elements = document.querySelector(".elements"); export default class Node { private static nextPosition: number = 0; private static _nodes: Node[] = []; private static _selectedSortAlgorithm: Sort.SortAlgorithm = Sort.SortAlgorithm.DirectSelection; private _num: number; private _position: number; private _box?: HTMLDivElement; constructor(num: number) { this._num = num; this._position = Node.nextPosition++; Node._nodes.push(this); } public static sort() { switch(Node.selectedSortAlgorithm) { case Sort.SortAlgorithm.DirectSelection: Sort.directSelection(Node.nodes); break; case Sort.SortAlgorithm.DirectInsertion: Sort.directInsertion(Node.nodes); break; case Sort.SortAlgorithm.BubbleSort: Sort.bubbleSort(Node.nodes); break; case Sort.SortAlgorithm.CocktailSort: Sort.cocktailSort(Node.nodes); break; case Sort.SortAlgorithm.ShellSort: Sort.shellSort(Node.nodes); break; } console.log(Node.nodes); } public static renderNode(node: Node): void { if (node.num || node.num === 0) { // Create the box that contains the data the user inserted const box = document.createElement("div"); box.setAttribute("id", node.position.toString()); box.classList.add("element"); box.innerText = node._num.toString(); node.box = box; // Append the box to the "elements" element in HTML elements!.appendChild(box); } } public static removeNode(num?: number, index?: number) { let nodesToRemove: Node[] = []; if(num && !index) { nodesToRemove = Node._nodes.filter((node) => { return node._num === num; }); Node._nodes = Node._nodes.filter((node) => { return node._num !== num; }); } else if(!num && index) { nodesToRemove.push(Node._nodes.splice(index, 1)[0]); } if(nodesToRemove.length > 0) { Err.cleanErrors(); nodesToRemove.forEach((node) => Animator.removeNode(node)); setTimeout(() => { Node.removeAll(); Node.renderAll(); }, 1500); removeInput.value = ""; } else { new Err("The element you want to remove hasn't been created yet!").render(); } } public static renderAll(): void { Node._nodes.forEach((node) => { Node.renderNode(node); }); } public static removeAll(): void { while (elements?.firstChild) { elements.removeChild(elements.firstChild); } } public static get selectedSortAlgorithm() { return Node._selectedSortAlgorithm; } public static set selectedSortAlgorithm(sortAlgorithm: Sort.SortAlgorithm) { Node._selectedSortAlgorithm = sortAlgorithm; } public static get nodes() { return Node._nodes; } public get num() { return this._num; } public get position() { return this._position; } public get box() { if(!this._box) throw new Error("Node has no attribute 'box' assigned"); return this._box; } public set box(box: HTMLDivElement) { this._box = box; } public set num(num: number) { this._num = num; } }
81fe7c64b272da2845f928147daa2f0c4320173a
TypeScript
dljsbook/data
/src/Stripes/generator.ts
2.9375
3
import getAtStep from '../utils/getAtStep'; import squish from '../utils/squish'; import { IRange, IGeneratorFn, IPoint, IGetX, } from '../NonLinear'; const getDividedDistribution = (num: number) => { const n = num; if (n <= 3) { return [n]; } else if (n === 4) { return [2, 2]; } const div = n / 3; if (n % 3 === 2) { return [Math.ceil(div), Math.floor(div), Math.ceil(div)]; } else if (n % 3 === 0) { return [div, div, div]; } return [Math.floor(div), Math.ceil(div), Math.floor(div)]; }; const getDistributions = (dist: number[]) => { if (dist.length === 1) { return Array(dist[0]).fill(DISTRIBUTION.CENTER); } else if (dist.length === 2) { return [ ...Array(dist[0]).fill(DISTRIBUTION.TOP), ...Array(dist[1]).fill(DISTRIBUTION.BOTTOM), ]; } return [ ...Array(dist[0]).fill(DISTRIBUTION.TOP), ...Array(dist[1]).fill(DISTRIBUTION.CENTER), ...Array(dist[2]).fill(DISTRIBUTION.BOTTOM), ]; } const getXForDistribution = (step: number, num: number, dist: DISTRIBUTION, range: IRange) => { let x; if (dist === DISTRIBUTION.TOP) { x = getAtStep(step, num, range[0] / 2, range[1]); return squish(x, [-0.5, -.25], [-.5, 0]); } if (dist === DISTRIBUTION.BOTTOM) { x = getAtStep(step, num, range[0], range[1] / 2); return squish(x, [0.25, .5], [0, .5]); } x = getAtStep(step, num, range[0], range[1]); return squish(x, [-0.33333333, .333333333], [-0.5, 0.5]); }; const getYForDistribution = (step: number, num: number, dist: DISTRIBUTION, range: IRange) => { let y; if (dist === DISTRIBUTION.TOP) { y = getAtStep(step, num, range[0] / 2, range[1]); return squish(y, [-0.5, -.25], [0, .5]); } if (dist === DISTRIBUTION.BOTTOM) { y = getAtStep(step, num, range[0], range[1] / 2); return squish(y, [.25, .5], [-.5, 0]); } y = getAtStep(step, num, range[0], range[1]); return squish(y, [-.333333, .333333333], [-0.5, 0.5]); }; enum DISTRIBUTION { TOP, CENTER, BOTTOM, } const X_PADDING = 0.0; const Y_PADDING = 0.6; const getPadding = (start: number, end: number): [number, number] => [start + X_PADDING, end - Y_PADDING]; const getRangeForCluster = (x: number, y: number, cluster: number) => { if (cluster === 0) { return { x: squish(x, [-0.5, .5], getPadding(-1, 0)), y: squish(y, [-0.5, .5], getPadding(0, 1)), }; } return { x: squish(x, [-0.5, .5], getPadding(0, 1)), y: squish(y, [-0.5, .5], getPadding(-1, 0)), }; }; type IGetY = (y: number) => number; type IGetPointProps = { noise: number; range: IRange; getX: IGetX; getY: IGetY; num: number; step: number; }; type IGetPoint = (props: IGetPointProps) => IPoint; const getPoint: IGetPoint = ({ noise, range, getX, getY, num, step, }) => { const actualNum = num / 2; const cluster = Math.floor(step / actualNum); step = step - (cluster * actualNum); const dividedDistributions = getDividedDistribution(actualNum); const distributions = getDistributions(dividedDistributions); const distribution = distributions[step]; let _x = getXForDistribution(step, actualNum, distribution, range); let _y = getYForDistribution(step, actualNum, distribution, range); const { x, y, } = getRangeForCluster(_x, _y, cluster); return { x, y: getY(y), }; } const defaultRange: IRange = [-1, 1]; export const positiveGenerator: IGeneratorFn = (range = defaultRange, { noise, getX, num, step, }) => getPoint({ range, getY: y => y, noise, getX, num, step, }); export const negativeGenerator: IGeneratorFn = (range = defaultRange, { noise, getX, num, step, }) => getPoint({ range, getY: (y: number) => -1 * y - Y_PADDING, noise, getX, num, step, });
2d6dfa3179dddc585d5698cb2014d2769adff33c
TypeScript
next-cd/nest-learn
/src/dog/dog.controller.ts
2.84375
3
import { Controller, Get, HttpException, HttpStatus, UseFilters } from '@nestjs/common'; import { AppService } from './dog.service'; import { HttpExceptionFilter } from '../common/filters/http-exception.filter'; // import { CatsService } from '../cats/cats.service'; @Controller('dog') @UseFilters(HttpExceptionFilter) export class AppController { constructor( // 这是一种ts的语法 定义和 声明一起 private readonly appService: AppService, // private readonly catsService: CatsService ) {} @Get('/') @UseFilters(HttpExceptionFilter) getHello(): string { console.log(HttpStatus.FORBIDDEN); // throw new HttpException('Forbidden', HttpStatus.FORBIDDEN); return this.appService.getHello(); } } // aop 是一种非常好的思想 装饰器 就是使用aop的一种方式 纵切面思想 是非常不错的一种思想 // mobx 也是aop的一宗思想 ts 更是了 类集合 // 函数签名 签名就是告诉你做什么 和怎么 索引签名 是非常不错的 // 一个模块有很多控制器 还有其他
69744043af18a2e692fc09ba71fba4e5373f932a
TypeScript
helenmenge/cs445-lab-3
/lab3b/q1/q1.ts
3.1875
3
class University { name: string; dept: string; constructor(name: string, dept: string) { this.name = name; this.dept = dept; } graduation(year: number) { console.log(`Graduating ${this.dept} ${year} students`); } } let miu = new University("MIU", "MSD"); miu.graduation(2021);
1b1a97b2032f53f79b4cf7e6263b055fd51b99c6
TypeScript
junkerm/specmate
/web/src/app/modules/views/side/modules/log-list/services/logging.service.ts
2.625
3
import { Injectable } from '@angular/core'; import { BehaviorSubject } from 'rxjs/BehaviorSubject'; import { Observable } from 'rxjs/Observable'; import { Config } from '../../../../../../config/config'; import { ELogSeverity } from './e-log-severity'; import { LogElement } from './log-element'; @Injectable() export class LoggingService { private logHistory: LogElement[] = []; private logSubject: BehaviorSubject<LogElement>; public logObservable: Observable<LogElement>; constructor() { this.logSubject = new BehaviorSubject<LogElement>(new LogElement(Config.LOG_START_MESSAGE, ELogSeverity.INFO, new Date())); this.logObservable = this.logSubject.asObservable(); } public get logs(): LogElement[] { return this.logHistory; } public debug(message: string, url?: string): void { this.log(message, ELogSeverity.DEBUG, url); } public info(message: string, url?: string): void { this.log(message, ELogSeverity.INFO, url); } public warn(message: string, url?: string): void { this.log(message, ELogSeverity.WARN, url); } public error(message: string, url?: string): void { this.log(message, ELogSeverity.ERROR, url); } private log(message: string, severity: ELogSeverity, url?: string): void { let logElement: LogElement = new LogElement(message, severity, new Date(), url); this.logHistory.unshift(logElement); if (this.logHistory.length > Config.LOG_LENGTH) { this.logHistory = this.logHistory.slice(0, Config.LOG_LENGTH); } this.logSubject.next(logElement); } }
47c04c9960272dc95466e0bf61385430dafb2302
TypeScript
1kriva1/sfc-components
/projects/sfc-components/src/lib/common/interfaces/sfc-toggle/IToggleConfig.ts
2.59375
3
export interface IToggleConfigItem { label: string; icon?: string; } export interface IToggleConfig { checkedItem: IToggleConfigItem; uncheckedItem: IToggleConfigItem; }
5e828b72ae0c394a5ec33bac9def088d373b132f
TypeScript
Reamd7/react-recontext
/src/types.ts
3.015625
3
export interface ObjectWithKey { [key: string]: any; } export interface StoreState { [key: string]: any; } export interface Actions { [actionType: string]: (state: StoreState, params?: any) => StoreState; } export type VoidFunction = () => void; export type ListenerFunction = (newStoreState: StoreState) => void; export interface Store { getState: () => StoreState; subscribe: (callback: ListenerFunction) => VoidFunction; dispatch: (actionType: string, params?: any) => void; }