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
34b43a5e997033e2831159a02892cd44c4062c6e
TypeScript
WindSpiritSR/casdoor-js-sdk
/src/sdk.ts
2.59375
3
export interface sdkConfig { serverUrl: string, // your Casdoor URL, like the official one: https://door.casbin.com clientId: string, // your Casdoor OAuth Client ID appName: string, // your Casdoor application name, like: "app-built-in" organizationName: string // your Casdoor organization name, like: "built-in" } // reference: https://github.com/casdoor/casdoor-go-sdk/blob/90fcd5646ec63d733472c5e7ce526f3447f99f1f/auth/jwt.go#L19-L32 export interface accountSession { organization: string, username: string, type: string, name: string, avatar: string, email: string, phone: string, affiliation: string, tag: string, language: string, score: number, isAdmin: boolean, accessToken: string } class Sdk { private config: sdkConfig constructor(config: sdkConfig) { this.config = config } public getSignupUrl() { return `${this.config.serverUrl.trim()}/signup/${this.config.appName}`; } public getSigninUrl(redirectUri: string = `${window.location.origin}/callback`): string { const scope = "read"; const state = this.config.appName; return `${this.config.serverUrl.trim()}/login/oauth/authorize?client_id=${this.config.clientId}&response_type=code&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${scope}&state=${state}`; } public getUserProfileUrl(userName: string, account: accountSession) { let param = ""; if (account !== undefined && account !== null) { param = `?access_token=${account.accessToken}`; } return `${this.config.serverUrl.trim()}/users/${this.config.organizationName}/${userName}${param}`; } public getMyProfileUrl(account: accountSession) { let param = ""; if (account !== undefined && account !== null) { param = `?access_token=${account.accessToken}`; } return `${this.config.serverUrl.trim()}/account${param}`; } } export default Sdk;
3d048ec5f8e8f0112d97eb312a814585ed7ff562
TypeScript
mircearoata/SMRVersionVerifier
/src/virustotal.ts
2.65625
3
import got, { Response } from 'got'; import FormData from 'form-data'; import { VTAuthorization } from '../config.json'; import { sleep, setIntervalImmediate } from './util'; import { logger } from './logging'; export interface VTRequest { endpoint: string; method?: 'GET' | 'POST'; body?: string | Buffer | FormData } const VT_API_URL = 'https://www.virustotal.com/api/v3'; const RATE_LIMIT = 240; const RATE_LIMIT_PERIOD = 60 * 60; // seconds interface VTRequestQueueEntry<T> { request: VTRequest; resolve: (value?: { data: T; } | PromiseLike<{ data: T; }> | undefined) => void; reject: (error: Error | string) => void; } const requestQueue: VTRequestQueueEntry<never>[] = []; async function sendRequest(request: VTRequest): Promise<Response<string>> { let url = ''; if (request.endpoint.includes('virustotal.com')) { url = request.endpoint; } else { url = `${VT_API_URL}${request.endpoint}`; } return got(url, { method: request.method || 'GET', body: request.body, headers: { 'x-apikey': VTAuthorization, }, }); } async function executeRequest(request: VTRequestQueueEntry<never>): Promise<void> { logger.debug(`Processing VT request ${request.request.endpoint}`); try { const response = await sendRequest(request.request); request.resolve(JSON.parse(response.body)); } catch (e) { logger.error(e); if (e.name === 'HTTPError') { logger.error(e.response.body); } request.reject(e); } } async function processRequests() { logger.debug('Processing batch of VT requests'); let run = true; setTimeout(() => { if (run) { run = false; logger.debug('Batch of VT requests timed out'); } }, RATE_LIMIT_PERIOD * 1000); for (let i = 0; i < RATE_LIMIT && run; i += 1) { let request = requestQueue.shift(); while (run && !request) { request = requestQueue.shift(); await sleep(0.000001); } if (request) { executeRequest(request); } } run = false; logger.debug('Finished processing batch of VT requests'); } export async function queueRequest<T>(request: VTRequest): Promise<{data: T}> { logger.debug(`Queuing VT request ${request.endpoint}`); return new Promise((resolve, reject) => { requestQueue.push({ request, resolve, reject, }); }); } setIntervalImmediate(processRequests, RATE_LIMIT_PERIOD * 1000);
15b8e1116516e0d50fa6fadaf0183b19bcad44a9
TypeScript
clokken/gaf-converter
/src/frameWriter.ts
2.75
3
import { PNG } from "pngjs"; import { Palette } from "./palette"; export const FrameWriter = { makePNG(frame: Buffer, width: number, height: number, palette: Palette = null) { let png = new PNG({ filterType: -1, width: width, height: height, }); let read = 0; for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { let idx = (width * y + x) << 2; let pixel = frame[read++]; let [red, green, blue, alpha] = palette ? [ palette.getRed(pixel), palette.getGreen(pixel), palette.getBlue(pixel), palette.getAlpha(pixel), ] : [ pixel, pixel, pixel, pixel, ]; png.data[idx + 0] = red; png.data[idx + 1] = green; png.data[idx + 2] = blue; png.data[idx + 3] = alpha; } } return PNG.sync.write(png); } };
7fc56540c5c118e24499dba1b94ef39d0c4838f1
TypeScript
SocialGouv/code-du-travail-numerique
/packages/code-du-travail-modeles/src/modeles/conventions/2596_coiffure/salary.ts
2.703125
3
import { ReferenceSalaryLegal } from "../../base"; import type { IReferenceSalary, ReferenceSalaryProps, SalaryPeriods, SupportedCcIndemniteLicenciement, } from "../../common"; import { nonNullable, rankByMonthArrayDescFrench, sum } from "../../common"; export enum CatPro2596 { agentsMaitrise = "Agents de maîtrise", cadres = "Cadres", coiffeur = "Emplois techniques et de coiffeurs", esthetique = "Emplois de l'esthétique-cosmétique", nonTechnique = "Emplois non techniques", } export type CC2596ReferenceSalaryProps = { salaires: SalaryPeriods[]; catPro: CatPro2596; salairesPendantPreavis: SalaryPeriods[]; }; export class ReferenceSalary2596 implements IReferenceSalary<SupportedCcIndemniteLicenciement.IDCC2596> { computeReferenceSalary({ salaires = [], salairesPendantPreavis = [], catPro, }: ReferenceSalaryProps<SupportedCcIndemniteLicenciement.IDCC2596>): number { if ( catPro === CatPro2596.coiffeur || catPro === CatPro2596.esthetique || catPro === CatPro2596.nonTechnique ) { return new ReferenceSalaryLegal().computeReferenceSalary({ salaires }); } else { const rankedSalaires = rankByMonthArrayDescFrench(salaires); const rankedSalairesPendantPreavis = rankByMonthArrayDescFrench( salairesPendantPreavis ); const salaryValues = rankedSalaires .map((a) => a.value) .filter(nonNullable); const totalSalaryValues = [ ...rankedSalairesPendantPreavis.map((a) => a.value).filter(nonNullable), ...salaryValues, ].slice(0, 12); const primesPendantPreavis = rankedSalairesPendantPreavis .map((v) => v.prime) .filter(nonNullable); return ( (sum(totalSalaryValues) + sum(primesPendantPreavis)) / totalSalaryValues.length ); } } }
251ef26e556835a15d0a86d23379512c2d5fd930
TypeScript
kuma-research/typescript
/pro-typescript/chap01/listing0160_generic_interface.ts
3.234375
3
class CustomerId { constructor (public customerIdValue: number) {} get value() { return this.customerIdValue; } } class Customer { constructor (public id: CustomerId, public name: string) { } } interface Repository<T, TId> { getById(id: TId): T; persist(model: T): TId; } class CustomerRepository implements Repository<Customer, CustomerId> { constructor (private customers: Customer[]) {} getById(customerId: CustomerId) { return this.customers[customerId.value]; } persist(customer: Customer) { this.customers[customer.id.value] = customer; return customer.id; } }
34e68556e225ac954b43214b4c0b7b5da0744768
TypeScript
unkindypie/graphqltodo
/server/src/entities/Task.ts
2.6875
3
import { Entity, ManyToOne, Column, PrimaryGeneratedColumn, AfterUpdate, } from 'typeorm'; import {ObjectType, Field, Int} from 'type-graphql'; import {TaskKind} from './TaskKind'; import {User} from './User'; import {IdType} from '../modules/core/types/CommonEntityTypes'; @ObjectType() @Entity() export class Task { @Field(() => Int) @PrimaryGeneratedColumn() id!: IdType; @Field(() => String) @Column({type: 'timestamptz'}) createdAt = new Date(); @Field(() => String) @Column({ type: 'timestamptz', }) updatedAt = new Date(); @Field() @Column({type: 'text'}) title!: string; @Field() @Column({type: 'text'}) description!: string; @Field() @ManyToOne(() => TaskKind) kind!: TaskKind; @Field(() => User) @ManyToOne(() => User, user => user.tasks, {onDelete: 'CASCADE'}) user!: User; @Field(() => String) @Column({type: 'timestamptz'}) dateTime!: Date; @Field() @Column({type: 'boolean', default: false}) completed!: boolean; @AfterUpdate() updateUpdatedAt() { this.updatedAt = new Date(); } }
676058563d026cd6b81df4d7c52118fa10b37c2c
TypeScript
krotscheck/cv
/src/app/model/career-event.ts
3.078125
3
/** * Basic event type. */ export interface CareerEvent { date: string | { begin: string, end: string }; type: string; title: string; institution?: string; event?: string; description: string; duration: { begin: string, end: string | 'current' }; location: { city: string; region: string; country: string; }; tags: string[]; employer: string; } /** * A successful project. */ export interface ProjectCareerEvent extends CareerEvent { type: 'project'; url?: string; } /** * A job change. */ export interface JobChangeCareerEvent extends CareerEvent { type: 'job_change'; reason: 'hired' | 'dismissed' | 'laid-off' | 'departed' | 'acquisition' | 'promotion'; } /** * A formal presentation. */ export interface PresentationCareerEvent extends CareerEvent { type: 'presentation'; event: 'string'; url?: string; } /** * Education. */ export interface EducationCareerEvent extends CareerEvent { type: 'presentation'; institution: 'string'; school: 'string'; url?: string; } /** * An award. */ export interface AwardCareerEvent extends CareerEvent { type: 'award'; institution: 'string'; url?: string; }
4fe408fd3a0e1e61b20167e04b06039658608f4b
TypeScript
jaimetellezb/typescript-basico
/src/server/server.ts
3.078125
3
/** * para usar express con typeScript * debemos tener instalado typeScript (sudo npm i -g typescript) * también npm install @types/express --save-dev (express para typescript en desarrollo) */ import express = require("express"); // también se puede //import express from "express"; import path = require("path"); // export para que la clase se pueda usar en otros archivos // default la clase Server es la que se va importar por defecto export default class Server { // es se puede reducir // public app: express.Application; // public port: number; // constructor(port: number) { // this.port = port; // this.app = express(); // } // esto es igual a lo que hay en las líneas comentadas // este puede ir en el constructor pero por el momento no lo necesitamos public app: express.Application; constructor(public port: number) { // iniciar la apliación this.app = express(); } // este es el método que se va llamar para disparar el constructor e inicializar todo // para solo tener una sola instancia de express static init(port: number) { return new Server(port); } /** * función que se encarga de */ private publicFolder() { // definir el path de la carpeta "public" // donde estará el frontend para este ejercicio const publicPath = path.resolve(__dirname, "../public"); this.app.use(express.static(publicPath)); } // iniciar el express con el puerto que se desea start(callback: Function) { this.app.listen(this.port, callback()); this.publicFolder(); } } // VERSION JS // const express = require('express'); // const path = require('path'); // const app = express(); // const publicPath = path.resolve(__dirname, '../public'); // const port = process.env.PORT || 3000; // app.use(express.static(publicPath)); // app.listen(port, (err) => { // if (err) throw new Error(err); // console.log(`Servidor corriendo en puerto ${ port }`); // });
c8ff43af2e2c8c44ba4c2aae2891270b23ef2f50
TypeScript
manuel-woelker/topd
/ui/src/app/reducers.ts
2.703125
3
import {LocationState} from "redux-first-router"; const HISTORY_SIZE = 30; export type DataSeries = number[]; export interface DiskHistory { _max: number, disks: { [key: string]: any }, } export interface CpuUsage { system: number, user: number, other: number, } export interface DiskUsage { [key: string]: number; } export interface LoadAvg { load_avg_1_min?: number; load_avg_5_min?: number; load_avg_10_min?: number; color?: string; } export interface MemoryUsage { used: number; buffers: number; cache: number; swap: number; } export interface NetUsage { send: number; recv: number; } export interface Process { cpu: number; pid: number; cmd: string; cmdline: string; rss: number; } export interface State { location?: LocationState; systemMetrics: { loadavg?: LoadAvg; cpu_usage: CpuUsage; net_usage: NetUsage; disk_usage?: DiskUsage; memory_usage: MemoryUsage; processes?: Process[]; }, loadHistory: DataSeries; cpuHistory: { [P in keyof CpuUsage]: DataSeries; }; memoryHistory: { [P in keyof MemoryUsage]: DataSeries; }; netHistory: { send: DataSeries; recv: DataSeries; max: number; }; diskHistory: DiskHistory; systemInfo: any; cmdlines: any; } let initialState: State = { systemMetrics: { loadavg: {}, cpu_usage: { system: NaN, user: NaN, other: NaN, }, memory_usage: { buffers: NaN, cache: NaN, swap: NaN, used: NaN, }, net_usage: { send: NaN, recv: NaN, }, }, loadHistory: new Array(30), cpuHistory: { system: new Array(30), user: new Array(30), other: new Array(30) }, memoryHistory: { used: new Array(HISTORY_SIZE), buffers: new Array(HISTORY_SIZE), cache: new Array(HISTORY_SIZE), swap: new Array(HISTORY_SIZE) }, netHistory: { send: new Array(HISTORY_SIZE), recv: new Array(HISTORY_SIZE), max: 10 }, diskHistory: { _max: 10, disks: {} }, systemInfo: {}, cmdlines: {} }; initialState.loadHistory.fill(0); initialState.cpuHistory.user.fill(0); initialState.cpuHistory.system.fill(0); initialState.cpuHistory.other.fill(0); initialState.memoryHistory.used.fill(0); initialState.memoryHistory.buffers.fill(0); initialState.memoryHistory.cache.fill(0); initialState.memoryHistory.swap.fill(0); initialState.netHistory.send.fill(0); initialState.netHistory.recv.fill(0); function receiveSystemMetrics(state: State, action: any) { var cpuUsage = action.systemMetrics.cpu_usage; var memoryUsage = action.systemMetrics.memory_usage; cpuUsage.other = Math.max(0, 1 - cpuUsage.system - cpuUsage.user - cpuUsage.idle); let cpuHistory = { user: state.cpuHistory.user.concat([cpuUsage.user]).slice(-HISTORY_SIZE), system: state.cpuHistory.system.concat([cpuUsage.system]).slice(-HISTORY_SIZE), other: state.cpuHistory.other.concat([cpuUsage.other]).slice(-HISTORY_SIZE) }; let memoryHistory = { used: state.memoryHistory.used.concat([memoryUsage.used]).slice(-HISTORY_SIZE), buffers: state.memoryHistory.buffers.concat([memoryUsage.buffers]).slice(-HISTORY_SIZE), cache: state.memoryHistory.cache.concat([memoryUsage.cache]).slice(-HISTORY_SIZE), swap: state.memoryHistory.swap.concat([memoryUsage.swap]).slice(-HISTORY_SIZE) }; var netUsage = action.systemMetrics.net_usage; var netHistory = state.netHistory; if (netUsage) { let netMaxValue = Math.max(state.netHistory.max, Math.max(netUsage.send, netUsage.recv)); netHistory = { send: state.netHistory.send.concat([netUsage.send]).slice(-HISTORY_SIZE), recv: state.netHistory.recv.concat([netUsage.recv]).slice(-HISTORY_SIZE), max: netMaxValue }; } var diskUsage = action.systemMetrics.disk_usage || {}; var oldDiskHistory = state.diskHistory; let netMaxValue = oldDiskHistory._max; for (var disk in diskUsage) { let value = diskUsage[disk]; netMaxValue = Math.max(netMaxValue, value); } let diskHistory: DiskHistory = { _max: netMaxValue, disks: {} }; for (var disk in diskUsage) { let value = diskUsage[disk]; var history = oldDiskHistory.disks[disk]; if (!history) { history = new Array(HISTORY_SIZE); } diskHistory.disks[disk] = history.concat([value]).slice(-HISTORY_SIZE); } let loadHistory = state.loadHistory.concat([Math.min(1, action.systemMetrics.loadavg.load_avg_1_min / 10)]).slice(-HISTORY_SIZE); action.systemMetrics.loadavg.color = action.systemMetrics.loadavg.load_avg_1_min < 10 ? "#0d551c" : "#a00000"; if (!action.systemMetrics.processes) { action.systemMetrics.processes = state.systemMetrics.processes; } let processes = action.systemMetrics.processes; let cmdlines = state.cmdlines; for (var i in processes) { let process = processes[i]; if (process.cmdline) { cmdlines[process.pid] = process.cmdline; } else { process.cmdline = cmdlines[process.pid] || "?"; } } return Object.assign({}, state, { systemMetrics: action.systemMetrics, cmdlines, cpuHistory: cpuHistory, loadHistory, memoryHistory, netHistory, diskHistory }); } function receiveSystemInfo(state: State, action: any) { let newState = Object.assign({}, state, {systemInfo: action.systemInfo}); newState.systemInfo.bootDate = Date.now() - (newState.systemInfo.uptime * 1000); return newState; } function reducer(state: State = initialState, action: any = {}) { switch (action.type) { case "RECEIVE_SYSTEM_METRICS": return receiveSystemMetrics(state, action); case "RECEIVE_SYSTEM_INFO": return receiveSystemInfo(state, action); default: return state; } } export default reducer;
f7f5092beeb11ed7a4e6ea2c61483680bfeb7bd4
TypeScript
cloudfoundry/stratos
/src/frontend/packages/cloud-foundry/src/shared/q-param.ts
3.21875
3
export enum QParamJoiners { greaterThanOrEqual = '>=', lessThanOrEqual = '<=', lessThan = '<', greaterThan = '>', in = ' IN ', colon = ':', equal = '=' } export class QParam { static fromString(qString: string) { const qParamComponents = Object.values(QParamJoiners).reduce((split, joiner) => { if (split) { return split; } const testSplit = qString.split(joiner); if (testSplit.length === 2) { return [testSplit[0], testSplit[1], joiner]; } }, null as []); if (qParamComponents && qParamComponents.length === 3) { const legitJoiner = Object.values(QParamJoiners).find(joiner => joiner === qParamComponents[2]); if (legitJoiner) { return new QParam( qParamComponents[0], qParamComponents[1], legitJoiner ); } } return null; } static fromStrings(qStrings: string[]) { return qStrings.map(qString => QParam.fromString(qString)).filter(qObject => !!qObject); } static keyFromString(qParamString: string): string { const match = qParamString.match(/(>=|<=|<|>| IN |,|:|=)/); return match.index >= 0 ? qParamString.substring(0, match.index) : null; } constructor( public key: string, public value: string | string[], public joiner: QParamJoiners = QParamJoiners.equal ) { } public toString() { return `${this.key}${this.joiner}${(this.value as string[]).join ? (this.value as string[]).join(',') : this.value}`; } }
8c7ab1e1c52ef7ca66f94896efc2a51af1f59349
TypeScript
gradebook/utils
/packages/release-utils/src/util/require-env-variables.ts
2.53125
3
import {env, exit} from 'process'; export function requireEnvVariables(requiredVariables: Readonly<string[]>) { for (const key of requiredVariables) { if (!(key in env)) { console.error(`Missing environment variable: ${key}. Recipe failed`); exit(1); } } }
272db798aad16886cb9a1045665a69ab1df89327
TypeScript
mrfsrf/node-rcs-core
/lib/allWarnings.ts
3.03125
3
export interface Source { line: number; file: string; text: string; } export class Warnings { ranOnMinifiedFiles = false; warningArray: { [s: string]: Source[] } = {}; constructor() { this.reset(); } summary(text: string): string { if (text.length > 120) { this.ranOnMinifiedFiles = this.ranOnMinifiedFiles || text.length > 500; return `${text.slice(0, 120)}...`; } return text; } reset(): void { this.warningArray = {}; this.ranOnMinifiedFiles = false; } append(value: string, source: Source | undefined): void { if (value in this.warningArray) { if ( source && ( this.warningArray[value].findIndex((e) => (( e.file === source.file && e.line === source.line) )) === -1 ) ) { this.warningArray[value].push(source); } } else { this.warningArray[value] = source ? [source] : []; } } warn(): void { const keys = Object.keys(this.warningArray); if (!keys.length) return; // eslint-disable-next-line no-console console.warn('WARNING: The following selectors were not found in the rename table, but ' + 'appears in the compressed map. In order to avoid that some other selectors ' + 'are used instead, they were appended with \'_conflict\'. You need to fix this ' + 'either by:\n'); // eslint-disable-next-line no-console console.warn('- Creating a CSS rule with the selector name and re-run the process, or'); // eslint-disable-next-line no-console console.warn('- Excluding the selectors so it\'s not renamed, or'); // eslint-disable-next-line no-console console.warn('- Adding the value to the reserved selectors table so it\'s not used as a possible short name\n\n'); // eslint-disable-next-line no-console console.warn('The failing selector are:'); keys.forEach((key) => { const line = this.warningArray[key]; if (line.length) { // eslint-disable-next-line no-console console.warn(` - '${key}' found in: `); // eslint-disable-next-line no-console line.forEach((e) => console.warn(` ${e.file}(${e.line}): ${this.summary(e.text)}`)); } else { // eslint-disable-next-line no-console console.warn(` - '${key}'`); } }); if (this.ranOnMinifiedFiles) { // eslint-disable-next-line no-console console.warn('WARNING: You shouldn\'t run this software on minified files as it\'ll be ' + 'hard to debug errors whenever they happens.\n'); } } } export default new Warnings();
7b047a5863f08ccaa287ca5f38c6140f09e2a5ee
TypeScript
jcpachecoh/waes-todo-app
/src/Containers/LoginContainer.ts
2.609375
3
import { connect, Dispatch } from 'react-redux'; import { StoreState } from '../Models/StoreState'; import { LoginProps, Login } from '../Components/Login'; import { userActions, handleUsername, handlePassword, setUserId } from '../actions/userActions'; export function mapStateToProps(state: StoreState) { return { user: state.userReducer.user }; } type ConnectedDispatchProps = Pick<LoginProps, 'handleUsername' | 'handlePassword' | 'setUserId'>; export function mapDispatchToProps(dispatch: Dispatch<userActions>): ConnectedDispatchProps { return { handleUsername: (username: string) => dispatch(handleUsername(username)), handlePassword: (password: string) => dispatch(handlePassword(password)), setUserId: (userId: string) => dispatch(setUserId(userId)) }; } export default connect(mapStateToProps, mapDispatchToProps)(Login);
14954f7a6feec795144ba4fca30484b94054e17f
TypeScript
bngesp/typescript
/tp/tp3/personne.ts
2.703125
3
import {Adresse} from "./adresse"; export class Personne { private _nom: string; private _sexe: string; private _adresses: Adresse[]; constructor(nom: string, sexe: string, adresses: Adresse[]) { this._nom = nom; this._sexe = sexe; this._adresses = adresses; } get nom(): string { return this._nom; } set nom(value: string) { this._nom = value; } get sexe(): string { return this._sexe; } set sexe(value: string) { this._sexe = value; } get adresses(): Adresse[] { return this._adresses; } set adresses(value: Adresse[]) { this._adresses = value; } }
c56bb12a72131e9c21c306a02f4261358144a370
TypeScript
fatihky/vald
/test/extend.spec.ts
2.78125
3
import * as assert from 'assert' import {Map} from 'immutable' import {isValid, notValid} from '../src/test-utils' import vald, {SchemaBase, IValidator, ValidatorInsertType, ValidationStepResultOp} from '../src' describe('extend', () => { it('basic', () => { const NUMBER_LIST_REGEX = /^(\d+)(,\d+)*$/ const exendStringMethods = new SchemaBase(Map<string, IValidator>()) .set('numberList', { insertType: ValidatorInsertType.TAIL, func: (value: string, param) => { if (NUMBER_LIST_REGEX.test(value)) { return { op: ValidationStepResultOp.CONTINUE, value: value.split(','), error: null, } } return { op: ValidationStepResultOp.CONTINUE, value, error: new Error('invalid number list format'), } }, }) const schema = vald .extend('string', exendStringMethods) .base('string') .step('numberList') const result = schema.validate('1,2,3') isValid(result) assert.deepEqual(result.value, [1, 2, 3]) notValid(schema.validate('1-2-3')) }) })
6f2622b9748f3d356480fc2c17e1576992dd4c17
TypeScript
Assylkhan/ecommerce-app
/src/app/services/user.service.ts
2.53125
3
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; import { User } from '@app/models'; import { tap } from 'rxjs/operators'; import { ViewOptions } from '@app/helpers/view-options'; @Injectable({ providedIn: 'root' }) export class UserService { rootURL = '/api' users: Observable<User[]> constructor(private http: HttpClient) { } create(user: any): Observable<any> { return this.http.post(this.rootURL+'/users', user); } update(user: any): Observable<any> { return this.http.put(`${this.rootURL}/users/${user._id}`, user); } findByEmail(email: any): Observable<any> { return this.http.get<User>(`${this.rootURL}/users?email=${email}`); } findById(id: any): Observable<any> { return this.http.get<User>(`${this.rootURL}/users/${id}`); } fetchAllWithOptions(options: ViewOptions): Observable<User[]> { if (this.users) { return this.users.pipe( tap(users => { users = users.sort((a, b) => { const sortOrder = options.sortDirection === 'asc' ? -1 : 1; const valueA = a[options.sortField]; const valueB = b[options.sortField]; var result = (valueA < valueB) ? -1 : (valueA > valueB) ? 1 : 0; return result * sortOrder; }) }), tap(users => { const start = options.page * options.pageSize; const end = start + options.pageSize; users = users.slice(start, end) })) } else { this.users = this.http.get<User[]>(`${this.rootURL}/users`).pipe( tap(users => { users = users.sort((a, b) => { const sortOrder = options.sortDirection === 'asc' ? -1 : 1; const valueA = a[options.sortField]; const valueB = b[options.sortField]; var result = (valueA < valueB) ? -1 : (valueA > valueB) ? 1 : 0; return result * sortOrder; }) }), tap(users => { const start = options.page * options.pageSize; const end = start + options.pageSize; users = users.slice(start, end) })) return this.users } } fetchAll(): Observable<any[]> { return this.http.get<User[]>(`${this.rootURL}/users`); } }
c3d27a6ac3927ac1e68d2bbfc8d2b18ad3f90bf6
TypeScript
green-fox-academy/kkovax25
/week-01/day-4/16-i-wont-cheat-on-the-exams.ts
3.296875
3
'use strict'; // Create a program that writes this line 100 times: // "I won't cheat on the exam!" let a: number = 0; let cheatLine: string = "I won't cheat on the exam!" while (a <= 100) { console.log(cheatLine); a++; }
61aa2011c557eb3a01b243f4aa09d6e7cc1894db
TypeScript
sindresorhus/type-fest
/test-d/delimiter-cased-properties-deep.ts
2.9375
3
import {expectType} from 'tsd'; import type {DelimiterCasedPropertiesDeep} from '../index'; declare const foo: DelimiterCasedPropertiesDeep<{helloWorld: {fooBar: string}}, '/'>; expectType<{'hello/world': {'foo/bar': string}}>(foo); declare const fooBar: DelimiterCasedPropertiesDeep<() => {a: string}, '/'>; expectType<() => {a: string}>(fooBar); declare const bar: DelimiterCasedPropertiesDeep<Set<{fooBar: string}>, '-'>; expectType<Set<{'foo-bar': string}>>(bar); // Verify example type User = { userId: number; userName: string; date: Date; regExp: RegExp; }; type UserWithFriends = { userInfo: User; userFriends: User[]; }; const result: DelimiterCasedPropertiesDeep<UserWithFriends, '-'> = { 'user-info': { 'user-id': 1, 'user-name': 'Tom', date: new Date(), 'reg-exp': /.*/, }, 'user-friends': [ { 'user-id': 2, 'user-name': 'Jerry', date: new Date(), 'reg-exp': /.*/, }, { 'user-id': 3, 'user-name': 'Spike', date: new Date(), 'reg-exp': /.*/, }, ], }; expectType<DelimiterCasedPropertiesDeep<UserWithFriends, '-'>>(result);
2c97e222093d1e49ce83314b1a224d51406fb743
TypeScript
figuevigo/angular-escalable-vitae-febrero
/libs/data/src/lib/services/xtore.service.ts
2.875
3
import { queueScheduler } from 'rxjs'; import { distinctUntilChanged, map } from 'rxjs/operators'; import { StoreService } from './store.service'; // ToDo: define Action with payload type Action<StateType> = (state: StateType) => StateType; export class XtoreService<StateType> extends StoreService<StateType> { constructor(initialState: StateType, needsDeepClone = true) { super(initialState, needsDeepClone); } public dispatch(action: Action<StateType>) { const state = this.state; queueScheduler.schedule(() => this.executeAction(action, state)); } private executeAction(action: Action<StateType>, state: StateType) { const newState = action(state); // ToDo: write to an instumental log like ReduxWebTools this.state = newState; } public select$<SelectionType>(selector: (state: StateType) => SelectionType) { return this.state$.pipe( map<StateType, SelectionType>(selector), distinctUntilChanged(this.areEqual.bind(this)) ); } private areEqual<SelectionType>(a: SelectionType, b: SelectionType) { if (super.needsDeepClone) { const aJson = JSON.stringify(a); const bJson = JSON.stringify(b); return aJson === bJson; } else { return a === b; } } }
3a809e212d0721b4a32c865e1038c082477ec4c4
TypeScript
dvens/atomify
/packages/kit/src/utilities/store/store.ts
2.84375
3
import { isServer } from '@atomify/shared'; import { defaultObject, Observers, Store, StoreSettings } from './store.types'; let proxyContainer: any = null; export function createStore<State>(settings: StoreSettings<State>): Store<State> { const actionsHolder = settings.actions || {}; const observers: Observers = []; let prevState: State = settings.initialState; const validator = { set(state: State, key: any, value: any) { if (valueHasChanged(state[key as keyof typeof state], value)) { state[key as keyof typeof state] = value; callObservers(state, key); } return true; }, }; let state: any = getProxyConatiner(settings.initialState || {}, validator); function subscribe(observer: (data: State) => void, keys?: undefined | string[]) { if (typeof observer !== 'function') new Error('You can only subscribe to Store changes with a valid function!'); observers.push({ callback: observer, keys, }); return true; } function unsubscribe(observer: (data: State) => void) { if (typeof observer !== 'function') new Error('You can only subscribe to Store changes with a valid function!'); const match = observers.find(({ callback }) => callback === observer); if (match) { observers.splice(observers.indexOf(match), 1); } } async function dispatch(actionKey: string, payload: any) { const action = actionsHolder[actionKey]; if (typeof action !== 'function') new Error(`Action "${actionKey}" doesn't exist.`); prevState = Object.assign({}, state); const newState = await action(state, payload); state = newState; return true; } function callObservers(data: State, key: any) { observers.forEach(({ keys, callback }) => { if (!keys) { callback(data); } else if (Array.isArray(keys) && keys.indexOf(key) > -1) { callback(data); } }); } return { subscribe, unsubscribe, dispatch, getState: () => state, getPrevState: () => prevState, }; } export const setProxyContainer = (proxy: () => void) => { proxyContainer = proxy; }; function getProxyConatiner(services = {}, handler: defaultObject = {}) { if (!isServer && !window.Proxy) { return new proxyContainer(services, handler); } return new Proxy(services, handler); } function valueHasChanged(value: unknown, old: unknown): boolean { // This ensures (old==NaN, value==NaN) always returns false return old !== value && (old === old || value === value); }
30852d22a92064f2888becf094af8e7520155326
TypeScript
totofish/XSS
/src/extension/utility/importFormatHelper.ts
2.53125
3
import { IScriptItem } from '../../types'; export default function importFormatHelper(data: Array<IScriptItem>): Array<IScriptItem> { if (!Array.isArray(data)) return []; let savelist: Array<IScriptItem> = [...data]; savelist = savelist.filter((item) => ( Object.prototype.hasOwnProperty.call(item, 'title') && Object.prototype.hasOwnProperty.call(item, 'code') )); savelist = savelist.map((item) => ({ autoExecute: !!item.autoExecute, title: item.title, code: item.code, })); return savelist; }
f74f4f7ed886e327af9062446fabf3a8f7b272f7
TypeScript
amruta8712/Assignments
/UI Framework/TYPESCRIPT/A1Que3.ts
2.875
3
const order={ id:10, title:"Pizza", price:200, printOrder(){ console.log(this.title); }, getPrice(){ console.log(this.price); } }; const NewOrder=Object.assign(order); console.log(order); console.log(NewOrder); NewOrder.getPrice(); NewOrder.printOrder();
54188d088b177542abdd532984d95ea27f525370
TypeScript
dwook/mini-link-ts
/front/feature/Home/saga.ts
2.5625
3
import axios from 'axios'; import { call, put, takeLatest } from 'redux-saga/effects'; import { homeAction } from './slice'; import { HomeInfo } from './types'; async function getHomeAPI(username: string) { const response = await axios.get<HomeInfo>(`/home/${username}`); return response.data; } function* getHome(action: ReturnType<typeof homeAction.getHomeRequest>) { try { console.log('호출', homeAction.getHomeRequest()); const result:HomeInfo = yield call(getHomeAPI, action.payload); console.log('결과', result, action.payload); yield put(homeAction.getHomeSuccess(result)); } catch (error) { console.error(error); yield put(homeAction.getHomeFailure(error.message)); } } export function* watchGetHome() { yield takeLatest(homeAction.getHomeRequest, getHome); } async function editHomeAPI(data:FormData) { console.log('데이터', data); const response = await axios.patch<HomeInfo>(`/home/${data.get('userId')}`, data); return response.data; } function* editHome(action: ReturnType<typeof homeAction.editHomeRequest>) { try { const result:HomeInfo = yield call(editHomeAPI, action.payload); console.log('수정결과', result); yield put(homeAction.editHomeSuccess(result)); } catch (error) { console.error(error); yield put(homeAction.editHomeFailure(error)); } } export function* watchEditHome() { yield takeLatest(homeAction.editHomeRequest, editHome); }
aac9c1b4f3ed3a5b5c37b8a35078bc253be54f13
TypeScript
UniBitProject/wallet
/app/lib/commands/CreateRawTransaction.ts
2.765625
3
import { RpcRequest } from '../RpcRequest' import { RpcResponse } from '../RpcResponse' /** * JSON-RPC request for the *createrawtransaction* command. */ export interface CreateRawTransactionRequest extends RpcRequest { readonly method: 'createrawtransaction' readonly params?: any[] } /** * JSON-RPC response for the *createrawtransaction* command. */ export interface CreateRawTransactionResponse extends RpcResponse { readonly result: CreateRawTransactionResult | null } /** * Result of the *createrawtransaction* command. */ export type CreateRawTransactionResult = any export function CreateRawTransaction(...params: any[]): CreateRawTransactionRequest { return params.length === 0 ? { method: 'createrawtransaction' } : { method: 'createrawtransaction', params } }
84cbe409574879be827eb7fc93f64d358708b4bc
TypeScript
nullnull/apollo-server-sample
/src/prototype.ts
2.921875
3
export function defineProperty(target: any, name: string, f: any) { if (target[name]) return Object.defineProperty(target, name, { enumerable: false, configurable: false, writable: false, value: f, }) } const unique = function (this: Array<any>) { return Array.from(new Set(this)) } defineProperty(Array.prototype, 'unique', unique)
8fda1aaec99ed1e4d44aa006a73790547668a1d4
TypeScript
rossng/transcriptor
/packages/util/src/lib/convert-words-to-text/index.ts
2.859375
3
import { TranscriptWord } from 'types/slate'; /** * Helper function * @param {array} words - dpe word object, with at list text attribute to be able to convert to string of text */ export function convertWordsToText(words: TranscriptWord[]): string { return words .map((word) => { return word.text ? word.text.trim() : ''; }) .join(' '); }
137852bb741388cec25c0df61043d5ef35e7a1fa
TypeScript
artem-linenko/game-of-life
/src/hooks/useFieldDataGeneration.ts
2.84375
3
import { isEqual } from 'lodash'; import { useEffect, useRef, useState } from 'react'; import { FieldData } from '../types'; import { calculateNextTickFieldData, initialFieldData } from '../utils'; export const useFieldDataGeneration = ({ rowsNum, columnsNum, }: { rowsNum?: number; columnsNum?: number; }) => { const fieldDataRef = useRef<FieldData>(initialFieldData(rowsNum, columnsNum)); const [tick, setTick] = useState(0); const [finished, setFinished] = useState<boolean>(); useEffect(() => { if (!finished) { setTimeout(() => { setTick((t) => t + 1); }, 400); } if (tick === 0) { // initial field data is already set return; } const fieldData = fieldDataRef.current; const newFieldData = calculateNextTickFieldData(fieldData); if (tick % 5 === 0 && isEqual(fieldData, newFieldData)) { setFinished(true); } else { fieldDataRef.current = newFieldData; } }, [tick, finished]); useEffect(() => { if (finished) { window.alert("The game is over ;)"); } }, [finished]); return { fieldData: fieldDataRef.current, }; };
12ae3f9e5d406bd4c0fdaeb68a425dfde3a9fd7d
TypeScript
lukasgeiter/gettext-extractor
/src/js/utils.ts
3.0625
3
import * as ts from 'typescript'; export abstract class JsUtils { public static segmentsMatchPropertyExpression(segments: string[], propertyAccessExpression: ts.PropertyAccessExpression): boolean { segments = segments.slice(); if (!(segments.pop() === propertyAccessExpression.name.text)) { return false; } let segment: string | undefined; switch (propertyAccessExpression.expression.kind) { case ts.SyntaxKind.Identifier: segment = segments.pop(); return (segments.length === 0 || segments.length === 1 && segments[0] === '[this]') && segment === (<ts.Identifier>propertyAccessExpression.expression).text; case ts.SyntaxKind.ThisKeyword: segment = segments.pop(); return segments.length === 0 && (segment === 'this' || segment === '[this]'); case ts.SyntaxKind.PropertyAccessExpression: return this.segmentsMatchPropertyExpression(segments, <ts.PropertyAccessExpression>propertyAccessExpression.expression); } return false; } public static calleeNameMatchesCallExpression(calleeName: string, callExpression: ts.CallExpression): boolean { let segments = calleeName.split('.'); switch (segments.length) { case 0: return false; case 1: return callExpression.expression.kind === ts.SyntaxKind.Identifier && (<ts.Identifier>callExpression.expression).text === segments[0]; default: return callExpression.expression.kind === ts.SyntaxKind.PropertyAccessExpression && this.segmentsMatchPropertyExpression(segments, <ts.PropertyAccessExpression>callExpression.expression); } } }
380ed53e9d4f5bf709f639ac032d7569ee148e9b
TypeScript
luangregori/express-typescript
/src/controllers/order.controller.ts
2.546875
3
import { Get, Route, Tags, Post, Body, Path } from "tsoa"; import * as Yup from 'yup'; import { Product, Order } from '../models' import { getOnlyProductbyId, getOnlyPriceByMarket } from '../repositories/product.repository'; import { getOnlyMarketbyId } from '../repositories/market.repository'; import { getOnlyAddressbyId } from '../repositories/address.repository'; import { createOrder, getOrderbyUser } from '../repositories/order.repository'; import { badRequestError } from '../helpers/httpHelper' import { IOrderPayload } from '../interface/order.interface'; @Route("order") @Tags("Order") export default class OrderController { @Get("/:id") public async getOrders(id: number): Promise<Array<Order>> { return getOrderbyUser(id) } @Post("/") public async createOrder(@Body() body: IOrderPayload): Promise<Order> { const schema = Yup.object().shape({ productsIds: Yup.array().required(), marketId: Yup.number().required(), addressId: Yup.number().required() }); if (!(await schema.isValid(body))) { return badRequestError('Invalid argument') } const market = await getOnlyMarketbyId(body.marketId); const address = await getOnlyAddressbyId(body.addressId); let total_value: number = 0; const products: Array<Product> = await Promise.all( body.productsIds.map(async el =>{ const product = await getOnlyProductbyId(el); const productPrice = await getOnlyPriceByMarket(el, body.marketId); total_value += productPrice return product }) ) const newOrder = { products, total_value, market, address, user: body.user, status: 'created' } const order = await createOrder(newOrder) return order } }
47203de9225943e77d53c2ea54eb93e5c3d7f067
TypeScript
zhuoqi-chen/algorithm_course
/Heap/utils.ts
2.8125
3
export function getRadomNumberArray(size: number = 10) { return [ ...new Set( Array.from({ length: size }, (item) => Math.floor(Math.random() * size)) ), ]; }
9399933af0b10d731a24116c3e13371ba1c3c13b
TypeScript
JimmySorza/sentry-importer
/src/helpers/SentryClient.ts
2.625
3
import { AxiosInstance } from "axios"; import axios from "./axios"; import { MAX_RETRY_COUNT } from "./config"; /** * @class Sentry API Manager */ class SentryClient { static _instance: SentryClient; /** * Create SentryClient Instance * * @param token * @returns */ static create = (): SentryClient => { if (!SentryClient._instance) { SentryClient._instance = new SentryClient(); } return SentryClient._instance; }; /** * Create Axios Instance * * @param token */ setToken = (token: string) => { this.axiosIns = axios(token); }; retryCount = 0; axiosIns: AxiosInstance; constructor() {} /** * When authentication failed * * @param callBack * @returns */ auth = async (reAuth = false, callBack: () => any = () => {}) => { if (this.axiosIns && !reAuth) { return; } let options = {}; if (!reAuth) { options = { useCachedRetry: true, reAuth: false }; } const authData = await aha.auth("sentry", options); this.setToken(authData.token); return await callBack(); }; /** * Get Organizations from Sentry * * @returns */ getOrganizations = async (): Promise<IOrganization[]> => { try { const { data } = await this.axiosIns.get("/organizations/"); return data; } catch (error) { this.log("Could not get Organizations", error); if (!this.checkRetry(error)) { return; } this.retryCount++; return await this.auth(true, async () => await this.getOrganizations()); } }; /** * Get Projects from Sentry * * @param options * @returns */ getProjects = async (options: IGetProjectOptions): Promise<IProject[]> => { try { if (!options.org_slug) { return []; } const { data } = await this.axiosIns.get(`/organizations/${options.org_slug}/projects/`); return data; } catch (error) { this.log("Could not get Projects", error); if (!this.checkRetry(error)) { return; } return await this.auth(true, async () => await this.getProjects(options)); } }; /** * Get Issues from Sentry * * @param options * @returns */ getIssues = async (options: IGetIssuesOptions): Promise<{ data: IIssue[]; next_page: string | null }> => { try { if (!options?.org_slug || !options?.project_slug) { return { data: [], next_page: null }; } const { data } = await this.axiosIns.get(`/projects/${options.org_slug}/${options.project_slug}/issues/`, { params: { cursor: options.cursor }, }); return { data: data, next_page: "" }; } catch (error) { this.log("Could not get Issues", error); if (!this.checkRetry(error)) { return; } return await this.auth(true, async () => await this.getIssues(options)); } }; /** * Get a Issue from Sentry * * @param options * @returns */ getIssue = async (issueId: string): Promise<IIssue> => { try { const { data } = await this.axiosIns.get(`/issues/${issueId}/`); return data; } catch (error) { this.log("Could not get an issue", error.message); if (!this.checkRetry(error)) { return; } return await this.auth(true, async () => await this.getIssue(issueId)); } }; /** * Get Latest Event from Sentry * * @param options * @returns */ getLatestEvent = async (options: IGetEventOptions): Promise<IEvent> => { try { if (!options?.issue_id) { return null; } const axiosIns = this.axiosIns; const { data } = await axiosIns.get(`/issues/${options.issue_id}/events/latest/`); return data; } catch (error) { this.log("Could not get Latest Event", error); if (!this.checkRetry(error)) { return; } return await this.auth(true, async () => await this.getLatestEvent(options)); } }; /** * Error Log * * @param msg * @param error */ log = (msg, error) => { console.log(`[Error in Sentry API Call] => `, msg, error); }; /** * Auth Retry * * @returns */ checkRetry = (err: any) => { if (this.retryCount >= MAX_RETRY_COUNT || err?.response?.status !== 401) { this.retryCount === 0; return false; } this.retryCount++; return true; }; } export default SentryClient.create();
2f3e517dabb6a0f215dbe680c9398dea97dd6c1c
TypeScript
EventRegistry/event-registry-node-js
/src/returnInfo.ts
2.890625
3
import * as _ from "lodash"; import { EventRegistryStatic } from "./types"; import * as fs from "fs"; export abstract class ReturnInfoFlagsBase<T extends {}> { protected type: string; private data = {}; public setFlag(key: string, value: boolean, defaultValue?: boolean) { this.setProperty("Include" + this.type + _.upperFirst(key), value, defaultValue); } public setValue(key: string, value: any, defaultValue?: any, skipKeyMod = false) { const constructedKey = skipKeyMod ? _.upperFirst(key) : this.type + _.upperFirst(key); this.setProperty(constructedKey, value, defaultValue); } public getProperties(prefix = "") { return _.mapKeys(this.data, (value, key) => { if (_.startsWith(_.toLower(key), _.toLower(prefix))) { return _.camelCase(key); } else { return _.camelCase(prefix + key); } }); } public addProperties(properties: object) { if (properties instanceof Object) { for (const name in properties) { if (properties.hasOwnProperty(name)) { const value = properties[name]; if (typeof value === "boolean") { this.setFlag(name, value, !value); } else { this.setValue(name, value); } } } } } private setProperty(key, value, defaultValue?) { if (value !== defaultValue) { _.set(this.data, key, value); } } } export class ReturnInfo { private articleInfo: ArticleInfoFlags; private eventInfo: EventInfoFlags; private sourceInfo: SourceInfoFlags; private categoryInfo: CategoryInfoFlags; private conceptInfo: ConceptInfoFlags; private locationInfo: LocationInfoFlags; private storyInfo: StoryInfoFlags; private conceptClassInfo: ConceptClassInfoFlags; private conceptFolderInfo: ConceptFolderInfoFlags; // Accepts all InfoFlags constructor({ articleInfo = new ArticleInfoFlags(), eventInfo = new EventInfoFlags(), sourceInfo = new SourceInfoFlags(), categoryInfo = new CategoryInfoFlags(), conceptInfo = new ConceptInfoFlags(), locationInfo = new LocationInfoFlags(), storyInfo = new StoryInfoFlags(), conceptClassInfo = new ConceptClassInfoFlags(), conceptFolderInfo = new ConceptFolderInfoFlags(), ...unsupported } = {}) { if (!_.isEmpty(unsupported)) { console.warn(`ReturnInfo: Unsupported parameters detected: ${JSON.stringify(unsupported)}. Please check the documentation.`); } this.articleInfo = articleInfo; this.eventInfo = eventInfo; this.sourceInfo = sourceInfo; this.categoryInfo = categoryInfo; this.conceptInfo = conceptInfo; this.locationInfo = locationInfo; this.storyInfo = storyInfo; this.conceptClassInfo = conceptClassInfo; this.conceptFolderInfo = conceptFolderInfo; } public getParams(prefix?: string) { return _.extend( {}, this.articleInfo.getProperties(prefix), this.eventInfo.getProperties(prefix), this.sourceInfo.getProperties(prefix), this.categoryInfo.getProperties(prefix), this.conceptInfo.getProperties(prefix), this.locationInfo.getProperties(prefix), this.storyInfo.getProperties(prefix), this.conceptClassInfo.getProperties(prefix), this.conceptFolderInfo.getProperties(prefix), ); } /** * load the configuration for the ReturnInfo from a filename * @param filename filename that contains the json configuration to use in the ReturnInfo */ public static loadFromFile(filename: string): ReturnInfo { if (!(fs && fs.existsSync(filename))) { throw new Error(`File ${filename} does not exist`); } const conf = JSON.parse(fs.readFileSync(filename, "utf8")); return new ReturnInfo({ articleInfo: new ArticleInfoFlags(_.get(conf, "articleInfo", {})), eventInfo: new EventInfoFlags(_.get(conf, "eventInfo", {})), sourceInfo: new SourceInfoFlags(_.get(conf, "sourceInfo", {})), categoryInfo: new CategoryInfoFlags(_.get(conf, "categoryInfo", {})), conceptInfo: new ConceptInfoFlags(_.get(conf, "conceptInfo", {})), locationInfo: new LocationInfoFlags(_.get(conf, "locationInfo", {})), storyInfo: new StoryInfoFlags(_.get(conf, "storyInfo", {})), conceptClassInfo: new ConceptClassInfoFlags(_.get(conf, "conceptClassInfo", {})), conceptFolderInfo: new ConceptFolderInfoFlags(_.get(conf, "conceptFolderInfo", {})), }); } } export class ArticleInfoFlags extends ReturnInfoFlagsBase<EventRegistryStatic.ReturnInfo.ArticleInfoFlags> { constructor(params: EventRegistryStatic.ReturnInfo.ArticleInfo = {}) { super(); this.type = "Article"; const { bodyLen = -1, basicInfo = true, title = true, body = true, url = true, eventUri = true, authors = true, concepts = false, categories = false, links = false, videos = false, image = true, socialScore = false, sentiment = true, location = false, extractedDates = false, originalArticle = false, storyUri = false, ...properties } = params; this.setValue("bodyLen", bodyLen); this.setFlag("basicInfo", basicInfo); this.setFlag("title", title); this.setFlag("body", body); this.setFlag("url", url); this.setFlag("eventUri", eventUri); this.setFlag("authors", authors); this.setFlag("concepts", concepts); this.setFlag("categories", categories); this.setFlag("links", links); this.setFlag("videos", videos); this.setFlag("image", image); this.setFlag("socialScore", socialScore); this.setFlag("sentiment", sentiment); this.setFlag("location", location); this.setFlag("extractedDates", extractedDates); this.setFlag("originalArticle", originalArticle); this.setFlag("storyUri", storyUri); this.addProperties(properties); } } export class StoryInfoFlags extends ReturnInfoFlagsBase<EventRegistryStatic.ReturnInfo.StoryInfoFlags> { constructor(params: EventRegistryStatic.ReturnInfo.StoryInfo = {}) { super(); this.type = "Story"; const { basicStats = true, location = true, date = false, title = false, summary = false, concepts = false, categories = false, medoidArticle = false, infoArticle = false, commonDates = false, socialScore = false, imageCount = 0, ...properties } = params; this.setFlag("basicStats", basicStats); this.setFlag("location", location); this.setFlag("date", date); this.setFlag("title", title); this.setFlag("summary", summary); this.setFlag("concepts", concepts); this.setFlag("categories", categories); this.setFlag("medoidArticle", medoidArticle); this.setFlag("infoArticle", infoArticle); this.setFlag("commonDates", commonDates); this.setFlag("socialScore", socialScore); this.setValue("imageCount", imageCount); this.addProperties(properties); } } export class EventInfoFlags extends ReturnInfoFlagsBase<EventRegistryStatic.ReturnInfo.EventInfoFlags> { constructor(params: EventRegistryStatic.ReturnInfo.EventInfo = {}) { super(); this.type = "Event"; const { title = true, summary = true, articleCounts = true, concepts = true, categories = true, date = true, commonDates = false, infoArticle = false, stories = false, socialScore = false, imageCount = 0, ...properties } = params; this.setFlag("title", title); this.setFlag("summary", summary); this.setFlag("articleCounts", articleCounts); this.setFlag("concepts", concepts); this.setFlag("categories", categories); this.setFlag("date", date); this.setFlag("commonDates", commonDates); this.setFlag("infoArticle", infoArticle as boolean); this.setFlag("stories", stories); this.setFlag("socialScore", socialScore); this.setValue("imageCount", imageCount); this.addProperties(properties); } } export class SourceInfoFlags extends ReturnInfoFlagsBase<EventRegistryStatic.ReturnInfo.SourceInfoFlags> { constructor(params: EventRegistryStatic.ReturnInfo.SourceInfo = {}) { super(); const { title = true, description = false, location = false, ranking = false, image = false, socialMedia = false, ...properties } = params; this.type = "Source"; this.setFlag("title", title); this.setFlag("description", description); this.setFlag("location", location); this.setFlag("ranking", ranking); this.setFlag("image", image); this.setFlag("socialMedia", socialMedia); this.addProperties(properties); } } export class CategoryInfoFlags extends ReturnInfoFlagsBase<EventRegistryStatic.ReturnInfo.CategoryInfoFlags> { constructor(params: EventRegistryStatic.ReturnInfo.CategoryInfo = {}) { super(); this.type = "Category"; const { trendingScore = true, ...properties } = params; this.setFlag("trendingScore", trendingScore); this.addProperties(properties); } } export class ConceptInfoFlags extends ReturnInfoFlagsBase<EventRegistryStatic.ReturnInfo.ConceptInfoFlags> { constructor(params: EventRegistryStatic.ReturnInfo.ConceptInfo = {}) { super(); this.type = "Concept"; const { type = "concepts", lang = "eng", label = true, synonyms = false, image = false, description = false, trendingScore = false, maxConceptsPerType = 20, ...properties } = params; this.setValue("type", type); this.setValue("lang", lang); this.setFlag("label", label); this.setFlag("synonyms", synonyms); this.setFlag("image", image); this.setFlag("description", description); this.setFlag("trendingScore", trendingScore); this.setValue("maxConceptsPerType", maxConceptsPerType, 20, true); this.addProperties(properties); } } export class LocationInfoFlags extends ReturnInfoFlagsBase<EventRegistryStatic.ReturnInfo.LocationInfoFlags> { constructor(params: EventRegistryStatic.ReturnInfo.LocationInfo = {}) { super(); this.type = "Location"; const { label = true, wikiUri = false, geoNamesId = false, population = false, geoLocation = false, countryArea = false, countryDetails = false, countryContinent = false, placeFeatureCode = false, placeCountry = true, ...properties } = params; this.setFlag("label", label); this.setFlag("wikiUri", wikiUri); this.setFlag("geoNamesId", geoNamesId); this.setFlag("population", population); this.setFlag("geoLocation", geoLocation); this.setFlag("countryArea", countryArea); this.setFlag("countryDetails", countryDetails); this.setFlag("countryContinent", countryContinent); this.setFlag("placeFeatureCode", placeFeatureCode); this.setFlag("placeCountry", placeCountry); this.addProperties(properties); } } export class ConceptClassInfoFlags extends ReturnInfoFlagsBase<EventRegistryStatic.ReturnInfo.ConceptClassInfoFlags> { constructor(params: EventRegistryStatic.ReturnInfo.ConceptClassInfo = {}) { super(); this.type = "ConceptClass"; const { parentLabels = true, concepts = false, ...properties } = params; this.setFlag("parentLabels", parentLabels); this.setFlag("concepts", concepts); this.addProperties(properties); } } export class ConceptFolderInfoFlags extends ReturnInfoFlagsBase<EventRegistryStatic.ReturnInfo.ConceptFolderInfoFlags> { constructor(params: EventRegistryStatic.ReturnInfo.ConceptFolderInfo = {}) { super(); this.type = "ConceptFolder"; const { definition = true, owner = false, ...properties } = params; this.setFlag("owner", definition); this.setFlag("owner", owner); this.addProperties(properties); } }
d80115cb624c13722072074e8fd36f68b2914930
TypeScript
amalpsy101/psykhe
/types/analytics/events.ts
2.546875
3
export enum AnalyticsEvent { PAGEVIEW = 'pageview', HOME_EVENT = 'home_event', TRANSACTION = 'transaction', BROWSE_EVENT = 'browse_event', PROFILE_EVENT = 'profile_event' } export type AnalyticsMessage = | PageViewMessage | TransactionMessage | HomeEventMessage | BrowseEventMessage | ProfileEventMessage; // Pageview events export interface PageViewMessage { type: AnalyticsEvent.PAGEVIEW; data: { page: string; }; } // Clickthrough events export interface TransactionMessage { type: AnalyticsEvent.TRANSACTION; data: { id: string; price?: number; partner?: string; product: { name?: string; price?: number; category?: string; identifier?: number; }; }; } // Homepage events export enum HomeAction { REGISTRATION_STARTED = 'registration_started', REGISTRATION_COMPLETED = 'registration_completed' } export interface HomeEventMessage { type: AnalyticsEvent.HOME_EVENT; data: { action: HomeAction; context: { page: string; }; }; } // Browse events export enum BrowseAction { VIEW = 'view', LIKE = 'like', SAVE = 'save', UNSAVE = 'unsave', DISLIKE = 'dislike', MERCHANT = 'merchant', CLICKTHROUGH = 'clickthrough' } export interface BrowseEventMessage { type: AnalyticsEvent.BROWSE_EVENT; data: { user?: string; product?: number; action: BrowseAction; context?: { page: string; page_position?: number; recommendation?: string; result_position?: number; ymal_seed_product?: number; }; }; } // Profile events export enum ProfileAction { REFERRED = 'referred' } export interface ProfileEventMessage { type: AnalyticsEvent.PROFILE_EVENT; data: { user: string; action: ProfileAction; context: { page: string; }; }; }
8c619d09ecaad891fd37280d85e03ccaef38257f
TypeScript
DaniFernandezCal/codetest2_seedtag
/tests/builders/ScanBuilder.ts
3.125
3
import { Coordinates } from '../../src/radar/models/Coordinates'; import { Enemy } from '../../src/radar/models/Enemy'; import { Scan } from '../../src/radar/models/Scan'; const getRandomInteger = () => { return Math.floor(Math.random() * 100); }; const getRandomEnemyType = (): 'mech' | 'soldier' => { return Math.floor(Math.random() * enemyTypes.length) === 0 ? 'mech' : 'soldier'; }; const enemyTypes = ['mech', 'soldier']; export class ScanBuilder { private coordinates: Coordinates; private enemies: Enemy; private allies?: number; public constructor() { this.coordinates = { x: getRandomInteger(), y: getRandomInteger(), }; this.enemies = { type: getRandomEnemyType(), number: getRandomInteger(), }; } public withSoldierEnemy() { this.enemies = { type: 'soldier', number: getRandomInteger(), }; return this; } public withRandomAttrs() { this.enemies = { type: getRandomEnemyType(), number: getRandomInteger(), }; this.allies = getRandomInteger(); return this; } public withMechEnemy() { this.enemies = { type: 'mech', number: getRandomInteger(), }; return this; } public withRandomEnemy() { this.enemies = { type: getRandomEnemyType(), number: getRandomInteger(), }; return this; } public withAlly(allies: number) { this.allies = allies; return this; } public build(): Scan { return { coordinates: this.coordinates, enemies: this.enemies, allies: this.allies, }; } }
b21112b176c9387d05849eb18d7e3cc2269c4ea2
TypeScript
globalbrain/sefirot
/lib/validation/validators/maxFileSize.ts
2.78125
3
export function maxFileSize(file: File, size: string): boolean { const factor = /gb/i.test(size) ? 1e9 : /mb/i.test(size) ? 1e6 : /kb/i.test(size) ? 1e3 : 1 return file.size <= factor * +size.replace(/[^\d\.]/g, '') }
c56a0e42f6b2415ce22b551e51f2d5e6c2a91ba3
TypeScript
RennanD/api-app-memoria
/src/modules/user/services/DeleteImportantDateService.ts
2.53125
3
import { getRepository } from 'typeorm'; import ImportantDate from '../models/ImportantDate'; import AppError from '../../../errors/AppError'; interface Request { date_id: string; user_id: string; } class DeleteImportantDateService { public async execute({ date_id, user_id }: Request): Promise<void> { const dateRepository = getRepository(ImportantDate); const date = await dateRepository.findOne({ where: { id: date_id, }, }); if (!date) { throw new AppError('Registro não encontrado'); } if (date.user_id !== user_id) { throw new AppError('Você não tem autorização para isso.'); } date.deleted_at = new Date(); await dateRepository.save(date); } } export default DeleteImportantDateService;
e9c6dc08179e9025b3aaffda19b92810a2620ee1
TypeScript
shlomiassaf/tdm
/libs/data/src/lib/metadata/meta-types/action.ts
2.890625
3
import { isFunction, isString, DecoratorInfo, BaseMetadata } from '@tdm/core/tdm'; import { ExecuteResponse, ActionOptions, ValidationSchedule, AdapterStatic } from '../../fw'; import { ExecuteContext } from '../../core'; export enum ActionMethodType { /** * Used to mark a method as local to the implementing adapter. */ LOCAL, READ, CREATE, REPLACE, UPDATE, DELETE } export type PreActionHandler = ( ctx: ExecuteContext<any>, ...args: any[] ) => any; /** * The */ export type PostActionHandler = ( response: ExecuteResponse, options: ActionOptions ) => void; export type PostActionMetadata = { handler: PostActionHandler; /** * Override mode. * * When set to true the action, when invoked, will not return the instance of the model, instead it will return a * promise to the return value of the handler. * * When setting returns to true the incoming data is not managed by the library (no deserialization). * When called on an ActiveRecord instance the instance is cloned and the action will work on the clone and not the * original instance this is why you SHOULD NOT return the instance when setting returns to true. * * This mode is useful for custom methods that does not return the instance itself but a different value, for example * an action operation with an indicator (true/false) * * @default false */ returns?: boolean; }; export interface ActionMetadataArgs<T = any> { method: T; /** * Specify if the response is an array. * A collection can only be set on static level actions. * @optional * @default false */ isCollection?: boolean; /** * If set to true, the action is also set on the ActiveRecordCollection instance. * Valid on if isCollection is true; */ collInstance?: boolean; /** * A hook to update data and return the options. * If not set the options is taken from the 1st arg. */ pre?: PreActionHandler; /** * A hook that allow control over the response. * * The hook's handler signature is [[PostActionHandler]]. * * > Note that the context (this) of the handler is the instance of the model. * * The hook has 2 modes: PASSIVE and ACTIVE * * >The default mode is PASSIVE. * * PASSIVE MODE: * Hook used to manipulate values in the response but does not control the structure. * This mode allows updating the instance of the model before it is sent back to the user. * * The instance is created by the library which (optionally) deserialize the response and then the hooks can update * the instance before it is serialized and sent to the user. * * > Optionally deserialize because the action might instruct not to, use ExecuteResponse.skipDeserialize to detect * this. * * ACTIVE MODE: * Hook used to change the response returned from the execution of the action. * * An execution returns one of 2: The instance of the model it "executes on" OR a promise of... * * When using ACTIVE mode, the execution will (always) return a promise of the value returned by the post handler. * * ACTIVE mode allows execution of operations/actions that does not return a response matching the structure of * the model attached to it. * * For example, In a virtual machines ,management application we have a `VirtualMachine` record which we store in a * database but we can also use to invoke operations (RPC). The `stop()` method is an operation/action we want to * define but it returns an object with some keys that is not related to the `VirtualMachine` and used to keep track * of the shutdown. For that we need to use an ACTIVE post action handler so we return this object instead of the * library thinking this object represents the `VierualMachine` model. */ post?: PostActionHandler | PostActionMetadata; validation?: ValidationSchedule; /** * An alias (or alias list) for methods names that reference this action. * * > The library will create a reference to the action methods for each alias in the list. */ alias?: string | string[]; /** * Declare the number of parameters that the action accepts. * When set, if the number of params is less then the hint an empty option object is added at the * hint location. * * The library assumes that the last parameter in an action method signature is the option object. * * > The value is the length, not last index. * * * > This will eliminate the need to validate the options object on actions where options object is optional. * * If you are using other optional parameters or union types you will need to verify the options manually and do not * define a hint. In such cases it is probably better to reconsider the implementation, remove parameters from the * signature and put them in the options object. */ paramHint?: number; } export abstract class ActionMetadata extends BaseMetadata { method: ActionMethodType; isCollection: boolean | undefined; collInstance: boolean | undefined; pre?: PreActionHandler; post?: PostActionMetadata; validation: ValidationSchedule; alias?: string[]; paramHint: number; constructor( public readonly metaArgs: ActionMetadataArgs<any>, info: DecoratorInfo ) { super(info); Object.assign(this, metaArgs); if (metaArgs.post) { if (isFunction(metaArgs.post)) { this.post = { handler: metaArgs.post }; } else if (metaArgs.post && isFunction(metaArgs.post.handler)) { this.post = metaArgs.post; } } if (isString(metaArgs.alias)) { this.alias = [metaArgs.alias]; } this.paramHint = metaArgs.paramHint || 0; } /** * The adapter class this action represents */ static adapterClass: AdapterStatic<any, any>; }
55e4b58521328d57aab2d8a72f25ad5e79af3f32
TypeScript
ethisscam/keep-subgraph
/src/utils.ts
2.5625
3
import { ethereum } from "@graphprotocol/graph-ts"; /** * If nothing better is available, this generates a unique id from the trransaction hash + log index. */ export function getIDFromEvent(event: ethereum.Event): string { return event.transaction.hash.toHex() + "-" + event.logIndex.toString() }
a06b76785cf0aaacb9727ba2df73ff3ac7311cf6
TypeScript
sky7th/lotto
/src/domain/LottoPrize.ts
3.359375
3
export class LottoPrize { static readonly READY = new LottoPrize('결과 발표 전', 0, 0); static readonly LOSE = new LottoPrize('꽝', 0, 0); static readonly FIFTH = new LottoPrize('5등', 3, 5000); static readonly FOURTH = new LottoPrize('4등', 4, 50000); static readonly THIRD = new LottoPrize('3등', 5, 2000000); static readonly SECOND = new LottoPrize('2등', 6, 50000000, true); static readonly FIRST = new LottoPrize('1등', 6, 2000000000); private constructor( public readonly rank: string, public readonly winNumberCount: number, public readonly reward: number, public readonly matchedBonus: boolean = false ) {} static valueOf(winNumberCount: number, matchedBonus: boolean) { if (winNumberCount < LottoPrize.FIFTH.winNumberCount) { return LottoPrize.LOSE; } return this.values().filter(value => value.winNumberCount === winNumberCount) .filter(value => value.matchedBonus === matchedBonus)[0]; } static values() { return [LottoPrize.LOSE, LottoPrize.FIFTH, LottoPrize.FOURTH, LottoPrize.THIRD, LottoPrize.SECOND, LottoPrize.FIRST] } }
876cc6a0671711fc0e65f55c4fc133173dabbbf9
TypeScript
sirian/js
/scripts/prebuild.ts
2.609375
3
import * as fs from "node:fs"; import {PackageJson} from "type-fest"; import {debug, getPackageDir, packagesDir, readPackageJSON, rootDir, validate, writeJSON} from "./util"; const VALIDATE = process.argv.includes("--validate"); const getReferences = (pkg: PackageJson) => Object.keys({...pkg.dependencies, ...pkg.devDependencies}) .map((dep) => /^@sirian\/([^/]+)$/.exec(dep)?.[1]) .filter(Boolean) .map((depName) => "../" + depName); const prebuild = async () => { const packages = fs .readdirSync(packagesDir, {withFileTypes: true}) .sort() .filter((dir) => dir.isDirectory()) .map((dir) => ({ name: dir.name, pkg: readPackageJSON(dir.name), })) ; // .filter((name) => fs.existsSync(getPackageDir(name) + "/package.json")); if (VALIDATE) { await validate(packages.map(({pkg}) => pkg)); } const publicAccess = []; debug("Prebuild"); for (const [i, {name, pkg}] of packages.entries()) { debug("[%o/%o] %o ", i + 1, packages.length, name); if (!pkg.name || !pkg.version) { continue; } if (!pkg.private) { publicAccess.push(name); } prebuildType(pkg, name, "cjs", "CommonJS"); prebuildType(pkg, name, "esm", "ESNext"); } }; const prebuildType = (pkg: any, pkgName: string, type: string, tsModule: "ESNext" | "CommonJS") => { const references = getReferences(pkg); const tmpDir = rootDir + "/tmp"; const cfg = { extends: "./tsconfig.json", include: ["src"], compilerOptions: { noEmit: false, module: tsModule, rootDir: "src", outDir: `build/${type}`, declarationDir: "build/types", tsBuildInfoFile: `${tmpDir}/${pkgName}.${type}.tsbuildinfo`, }, references: references.map((p) => ({path: `${p}/tsconfig.${type}.json`})), }; writeJSON(getPackageDir(pkgName) + `/tsconfig.${type}.json`, cfg); }; prebuild().catch(console.error);
9ddd10d2a62125908159b824e15c2dd5def99f14
TypeScript
huixiong123/todolist
/src/model/ProjectDetail.ts
2.5625
3
export class ProjectDetail { id: number; name: string; createDate: string; constructor(id: number, name: string, createDate: string) { this.id = id; this.name = name; this.createDate = createDate; } }
4c467d3d1736c2911cea8401d9d7f9b9269d0dca
TypeScript
sorokinvld/database-viewer
/types/src/generated.ts
2.71875
3
import { useMutation, UseMutationOptions, useQuery, UseQueryOptions } from 'react-query'; export type Maybe<T> = T | null; export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] }; export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> }; export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> }; function fetcher<TData, TVariables>(endpoint: string, requestInit: RequestInit, query: string, variables?: TVariables) { return async (): Promise<TData> => { const res = await fetch(endpoint, { method: 'POST', ...requestInit, body: JSON.stringify({ query, variables }), }); const json = await res.json(); if (json.errors) { const { message } = json.errors[0]; throw new Error(message); } return json.data; } } /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; }; export type Column = { __typename?: 'Column'; schemaName: Scalars['String']; tableName: Scalars['String']; name: Scalars['String']; type: Scalars['String']; default?: Maybe<Scalars['String']>; isNullable: Scalars['Boolean']; }; export type Constraint = { __typename?: 'Constraint'; schemaName: Scalars['String']; tableName: Scalars['String']; name: Scalars['String']; type: ConstraintType; columnNames: Array<Scalars['String']>; }; export enum ConstraintType { PrimaryKey = 'PrimaryKey', Unique = 'Unique', Check = 'Check', Exclude = 'Exclude' } export type Database = { __typename?: 'Database'; url: Scalars['String']; name: Scalars['String']; schemas: Array<Schema>; }; export type Field = { __typename?: 'Field'; name: Scalars['String']; type: Scalars['String']; }; export type ForeignKey = { __typename?: 'ForeignKey'; schemaName: Scalars['String']; tableName: Scalars['String']; foreignTableSchemaName: Scalars['String']; foreignTableName: Scalars['String']; name: Scalars['String']; columnNames: Array<Scalars['String']>; foreignColumnNames: Array<Scalars['String']>; }; export type Index = { __typename?: 'Index'; schemaName: Scalars['String']; tableName: Scalars['String']; columnNames: Array<Scalars['String']>; name: Scalars['String']; isUnique: Scalars['Boolean']; isPrimary: Scalars['Boolean']; }; export type Mutation = { __typename?: 'Mutation'; checkConnection: Scalars['Boolean']; }; export type MutationCheckConnectionArgs = { url: Scalars['String']; }; export type Procedure = { __typename?: 'Procedure'; schemaName: Scalars['String']; name: Scalars['String']; returnSet: Scalars['Boolean']; returnType: Scalars['String']; kind: Scalars['String']; isTrigger: Scalars['Boolean']; argTypes: Array<Scalars['String']>; argModes: Array<Scalars['String']>; argNames?: Maybe<Array<Scalars['String']>>; }; export type Query = { __typename?: 'Query'; server: Server; executeQuery: QueryResult; }; export type QueryServerArgs = { url: Scalars['String']; }; export type QueryExecuteQueryArgs = { url: Scalars['String']; query: Scalars['String']; }; export type QueryResult = { __typename?: 'QueryResult'; fields: Array<Field>; rows: Array<Array<Maybe<Scalars['String']>>>; }; export type Schema = { __typename?: 'Schema'; url: Scalars['String']; name: Scalars['String']; tables: Array<Table>; views: Array<View>; procedures: Array<Procedure>; }; export type Server = { __typename?: 'Server'; url: Scalars['String']; databases: Array<Database>; }; export type ServerDatabasesArgs = { name?: Maybe<Scalars['String']>; }; export type Table = { __typename?: 'Table'; url: Scalars['String']; schemaName: Scalars['String']; name: Scalars['String']; columns: Array<Column>; indices: Array<Index>; foreignKeys: Array<ForeignKey>; constraints: Array<Constraint>; triggers: Array<Trigger>; }; export type Trigger = { __typename?: 'Trigger'; schemaName: Scalars['String']; tableName: Scalars['String']; triggerSchema: Scalars['String']; name: Scalars['String']; events: Array<Scalars['String']>; activation: Scalars['String']; condition?: Maybe<Scalars['String']>; definition: Scalars['String']; }; export type View = { __typename?: 'View'; url: Scalars['String']; schemaName: Scalars['String']; name: Scalars['String']; columns: Array<Column>; }; export type CheckConnectionMutationVariables = Exact<{ url: Scalars['String']; }>; export type CheckConnectionMutation = ( { __typename?: 'Mutation' } & Pick<Mutation, 'checkConnection'> ); export type GetDataTreeQueryVariables = Exact<{ url: Scalars['String']; }>; export type GetDataTreeQuery = ( { __typename?: 'Query' } & { server: ( { __typename?: 'Server' } & Pick<Server, 'url'> & { databases: Array<( { __typename?: 'Database' } & Pick<Database, 'name'> & { schemas: Array<( { __typename?: 'Schema' } & Pick<Schema, 'name'> & { tables: Array<( { __typename?: 'Table' } & Pick<Table, 'name'> & { columns: Array<( { __typename?: 'Column' } & Pick<Column, 'name' | 'type' | 'default' | 'isNullable'> )>, indices: Array<( { __typename?: 'Index' } & Pick<Index, 'columnNames' | 'name' | 'isUnique' | 'isPrimary'> )>, foreignKeys: Array<( { __typename?: 'ForeignKey' } & Pick<ForeignKey, 'foreignTableSchemaName' | 'foreignTableName' | 'name' | 'columnNames' | 'foreignColumnNames'> )>, constraints: Array<( { __typename?: 'Constraint' } & Pick<Constraint, 'schemaName' | 'tableName' | 'name' | 'type' | 'columnNames'> )>, triggers: Array<( { __typename?: 'Trigger' } & Pick<Trigger, 'triggerSchema' | 'name' | 'events' | 'activation' | 'condition' | 'definition'> )> } )>, views: Array<( { __typename?: 'View' } & Pick<View, 'name'> & { columns: Array<( { __typename?: 'Column' } & Pick<Column, 'name' | 'type' | 'isNullable'> )> } )>, procedures: Array<( { __typename?: 'Procedure' } & Pick<Procedure, 'schemaName' | 'name' | 'returnSet' | 'returnType' | 'kind' | 'isTrigger' | 'argTypes' | 'argModes' | 'argNames'> )> } )> } )> } ) } ); export type QueryFieldsAndRowsQueryVariables = Exact<{ url: Scalars['String']; query: Scalars['String']; }>; export type QueryFieldsAndRowsQuery = ( { __typename?: 'Query' } & { executeQuery: ( { __typename?: 'QueryResult' } & Pick<QueryResult, 'rows'> & { fields: Array<( { __typename?: 'Field' } & Pick<Field, 'name' | 'type'> )> } ) } ); export type QueryRowsQueryVariables = Exact<{ url: Scalars['String']; query: Scalars['String']; }>; export type QueryRowsQuery = ( { __typename?: 'Query' } & { executeQuery: ( { __typename?: 'QueryResult' } & Pick<QueryResult, 'rows'> ) } ); export const CheckConnectionDocument = ` mutation CheckConnection($url: String!) { checkConnection(url: $url) } `; export const useCheckConnectionMutation = < TError = unknown, TContext = unknown >( dataSource: { endpoint: string, fetchParams?: RequestInit }, options?: UseMutationOptions<CheckConnectionMutation, TError, CheckConnectionMutationVariables, TContext> ) => useMutation<CheckConnectionMutation, TError, CheckConnectionMutationVariables, TContext>( (variables?: CheckConnectionMutationVariables) => fetcher<CheckConnectionMutation, CheckConnectionMutationVariables>(dataSource.endpoint, dataSource.fetchParams || {}, CheckConnectionDocument, variables)(), options ); export const GetDataTreeDocument = ` query GetDataTree($url: String!) { server(url: $url) { url databases { name schemas { name tables { name columns { name type default isNullable } indices { columnNames name isUnique isPrimary } foreignKeys { foreignTableSchemaName foreignTableName name columnNames foreignColumnNames } constraints { schemaName tableName name type columnNames } triggers { triggerSchema name events activation condition definition } } views { name columns { name type isNullable } } procedures { schemaName name returnSet returnType kind isTrigger argTypes argModes argNames } } } } } `; export const useGetDataTreeQuery = < TData = GetDataTreeQuery, TError = unknown >( dataSource: { endpoint: string, fetchParams?: RequestInit }, variables: GetDataTreeQueryVariables, options?: UseQueryOptions<GetDataTreeQuery, TError, TData> ) => useQuery<GetDataTreeQuery, TError, TData>( ['GetDataTree', variables], fetcher<GetDataTreeQuery, GetDataTreeQueryVariables>(dataSource.endpoint, dataSource.fetchParams || {}, GetDataTreeDocument, variables), options ); useGetDataTreeQuery.document = GetDataTreeDocument; useGetDataTreeQuery.getKey = (variables: GetDataTreeQueryVariables) => ['GetDataTree', variables]; useGetDataTreeQuery.fetcher = (dataSource: { endpoint: string, fetchParams?: RequestInit }, variables: GetDataTreeQueryVariables) => fetcher<GetDataTreeQuery, GetDataTreeQueryVariables>(dataSource.endpoint, dataSource.fetchParams || {}, GetDataTreeDocument, variables); export const QueryFieldsAndRowsDocument = ` query QueryFieldsAndRows($url: String!, $query: String!) { executeQuery(url: $url, query: $query) { fields { name type } rows } } `; export const useQueryFieldsAndRowsQuery = < TData = QueryFieldsAndRowsQuery, TError = unknown >( dataSource: { endpoint: string, fetchParams?: RequestInit }, variables: QueryFieldsAndRowsQueryVariables, options?: UseQueryOptions<QueryFieldsAndRowsQuery, TError, TData> ) => useQuery<QueryFieldsAndRowsQuery, TError, TData>( ['QueryFieldsAndRows', variables], fetcher<QueryFieldsAndRowsQuery, QueryFieldsAndRowsQueryVariables>(dataSource.endpoint, dataSource.fetchParams || {}, QueryFieldsAndRowsDocument, variables), options ); useQueryFieldsAndRowsQuery.document = QueryFieldsAndRowsDocument; useQueryFieldsAndRowsQuery.getKey = (variables: QueryFieldsAndRowsQueryVariables) => ['QueryFieldsAndRows', variables]; useQueryFieldsAndRowsQuery.fetcher = (dataSource: { endpoint: string, fetchParams?: RequestInit }, variables: QueryFieldsAndRowsQueryVariables) => fetcher<QueryFieldsAndRowsQuery, QueryFieldsAndRowsQueryVariables>(dataSource.endpoint, dataSource.fetchParams || {}, QueryFieldsAndRowsDocument, variables); export const QueryRowsDocument = ` query QueryRows($url: String!, $query: String!) { executeQuery(url: $url, query: $query) { rows } } `; export const useQueryRowsQuery = < TData = QueryRowsQuery, TError = unknown >( dataSource: { endpoint: string, fetchParams?: RequestInit }, variables: QueryRowsQueryVariables, options?: UseQueryOptions<QueryRowsQuery, TError, TData> ) => useQuery<QueryRowsQuery, TError, TData>( ['QueryRows', variables], fetcher<QueryRowsQuery, QueryRowsQueryVariables>(dataSource.endpoint, dataSource.fetchParams || {}, QueryRowsDocument, variables), options ); useQueryRowsQuery.document = QueryRowsDocument; useQueryRowsQuery.getKey = (variables: QueryRowsQueryVariables) => ['QueryRows', variables]; useQueryRowsQuery.fetcher = (dataSource: { endpoint: string, fetchParams?: RequestInit }, variables: QueryRowsQueryVariables) => fetcher<QueryRowsQuery, QueryRowsQueryVariables>(dataSource.endpoint, dataSource.fetchParams || {}, QueryRowsDocument, variables);
f63510e2fdc723cc6194f247378c6c818fb02bae
TypeScript
hd-code/hd-neural-net
/src/helper/random.ts
3.296875
3
/*! random v0.1.0 | MIT | © Hannes Dröse https://github.com/hd-code/js-snippets */ /** * @file * The JavaScript Math.random() function is not seedable. This package provides * an implementation of the Lehmer random number generator. The generator is * seedable, but will use a random seed when none was set. * * Make sure to set the seed only once in your application, ideally on startup. */ // ----------------------------------------------------------------------------- /** Returns a random number between 0 and 1 (both included). */ export function getFloat(): number; /** Returns a random number between 0 and `max` (both included). */ export function getFloat(max: number): number; /** Returns a random number between `min` and `max` (both included). */ export function getFloat(min: number, max: number): number; export function getFloat(arg1?: number, arg2?: number): number { let min = 0, max = 1; if (arg2 === undefined) { max = arg1 || max; } else { max = arg2; min = arg1 || min; } const diff = max - min; const rand = (getNext() - 1) / (mod - 2); return rand * diff + min; } // ----------------------------------------------------------------------------- /** The maximum integer that is returned by the `getInt()` function. */ export const MAX_INT = 2147483647 - 1; // ----------------------------------------------------------------------------- /** Returns an integer between 0 and `MAX_INT` (both included). */ export function getInt(): number; /** Returns an integer between 0 and `max` (both included). * * _Note:_ Decimals will be ignored. */ export function getInt(max: number): number; /** Returns an integer between `min` and `max` (both included). * * _Note:_ Decimals will be ignored. */ export function getInt(min: number, max: number): number; export function getInt(arg1?: number, arg2?: number): number { const rand = getNext() - 1; let min = 0, max = 0; if (arg1 === undefined) { if (arg2 === undefined) { return rand; } max = toInt(arg2); } else { if (arg2 === undefined) { max = toInt(arg1); } else { min = toInt(arg1); max = toInt(arg2); } } const diff = max - min; const mod = Math.abs(diff) + 1; const result = rand % mod; return (diff > 0 ? 1 : -1) * result + min; } // ----------------------------------------------------------------------------- /** Sets the seed for the random number generator to 0. */ export function setSeed(): void; /** Sets the seed for the random number generator. * * _Note:_ Decimals will be ignored. */ export function setSeed(seed: number): void; export function setSeed(seed?: number): void { if (!seed) { val = mod; return; } val = Math.ceil(Math.abs(seed)) % mod; } // ----------------------------------------------------------------------------- function toInt(number: number): number { return number > 0 ? Math.floor(number) : Math.ceil(number); } // ----------------------------------------------------------------------------- // Lehmer random number generator // ----------------------------------------------------------------------------- const mod = 2147483647; // mersenne prime number: 2^31 − 1 -> 7FFF FFFF in hex const mul = 16807; // 7^5 // use random seed by default const defaultSeed = Math.floor(Math.random() * mod) + 1; let val = defaultSeed; /** Returns an int between 1 and mod - 1 (both included) */ function getNext(): number { return (val = (val * mul) % mod); }
862af62ee8dca81ef4d2e89dfe0c4937a27d0f88
TypeScript
JetBrains/intellij-plugins
/AngularJS/testData/inspections/expressionType/genericDirectiveReference.ts
2.65625
3
/* tslint:disable */ import { Component } from '@angular/core'; import {FormControl, ReactiveFormsModule} from '@angular/forms'; import {MatDatepicker, MatDatepickerModule} from '@angular/material/datepicker'; import {MatInputModule} from "@angular/material/input"; export interface Moment extends Object { month(): number; year(): number; } // noinspection JSUnusedLocalSymbols function moment(input?: string, strict?: boolean): Moment { return { month(): number { return 0; }, year(): number { return 0; } } } /** @title Datepicker emulating a Year and month picker */ @Component({ standalone: true, selector: 'datepicker-views-selection-example', template: ` <mat-form-field> <input matInput [matDatepicker]="dp" placeholder="Month and Year" [formControl]="date" [max]="my" /> <mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle> <mat-datepicker #dp startView="multi-year" (monthSelected)="setMonthAndYear($event, dp)" (yearSelected)="acceptBoolean(<error descr="Argument type MatDatepicker<any> is not assignable to parameter type boolean ">dp</error>)" panelClass="example-month-picker" > </mat-datepicker> </mat-form-field> <mat-datepicker #dp2 [startAt]="12" startView="multi-year" (monthSelected)="setMonthAndYear(<error descr="Argument type number is not assignable to parameter type Moment ">$event</error>, <error descr="Argument type MatDatepicker<number> is not assignable to parameter type MatDatepicker<Moment> ... Type (date: number) => void is not assignable to type (date: Moment) => void Type Moment is not assignable to type number ">dp2</error>)" (yearSelected)="acceptBoolean(<error descr="Argument type MatDatepicker<number> is not assignable to parameter type boolean ">dp2</error>)" panelClass="example-month-picker" /> `, imports: [ MatDatepickerModule, MatInputModule, ReactiveFormsModule ] }) export class DatepickerViewsSelectionExample { validFrom = '2022-06-17T09:08:15.382+00:00'; date = new FormControl(moment(this.validFrom)); my = moment(); setMonthAndYear( normalizedMonthAndYear: Moment, datepicker: MatDatepicker<Moment> ) { const ctrlValue = this.date.value!; this.date.setValue(ctrlValue); datepicker.close(); } acceptBoolean(_arg: boolean){ } }
b60cbf2f41169d52aef6aab6df6f0a98fe05f229
TypeScript
dotrey/cursed-kanji
/src/app/ui/views/game/RomajiBoardView.ts
2.609375
3
import m from "../../Mithril.js"; const RomajiBoardView : any = { orientation : "", layout : "aiueo", layouts : { "aiueo" : { // vocal and consonants in order how they appear in hiragana alphabet // exception: two y since it is often used in conjunction with the other chars vocal : "aiueo", consonant : "kshtcnfmyrwgzjdbpy" }, "aiueo-bz" : { // vocal in hiragana order, consonant in roman alphabet order // exception: two y since it is often used in conjunction with the other chars vocal : "aiueo", consonant : "bcdfghjkmynprstwyz", }, "a-z" : { // vocal and consonant in roman alphabet order // exception: two y since it is often used in conjunction with the other chars vocal : "aeiou", consonant : "bcdfghjkmynprstwyz" } }, oncreate(vnode : any) { vnode.attrs.game.input.registerRomajiBoard("game-romajiboard"); this.layout = vnode.attrs.settings.romajiBoardLayout; this.orientation = vnode.attrs.settings.romajiBoardOrientation; }, view() { return m(".romajiboard" + (this.orientation ? "." : "") + this.orientation , { "id" : "game-romajiboard" },[ this.buildVocalPanel(), this.buildConsonantPanel() ]); }, buildVocalPanel() { const keys : string[] = this.getVocals(); return m(".romajiboard-scrollrow", m(".romajiboard-panel", { }, keys.map((k) => { return this.buildKey(k); }) ) ); }, buildConsonantPanel() { const panels : string[][] = this.getConsonants(); return m(".romajiboard-scrollrow", { "data-scrollable" : "1", "style" : "top: var(--panel-height);" },[ panels.map((keys, i) => { return m(".romajiboard-panel", { "style" : "left: " + (i * 100) + "vw;" }, keys.map((key) => { return this.buildKey(key); }) ); }) ] ); }, buildKey(key : string) { return m(".romajiboard-key", { "data-key" : key }, key); }, getVocals() : string[] { return this.layouts[this.layout].vocal.split(""); }, getConsonants() : string[][] { let r : string[][] = []; let remaining : string = this.layouts[this.layout].consonant; while (remaining.length > 0) { let part = remaining.substr(0, Math.min(5, remaining.length)); remaining = remaining.substr(part.length); let tmp = part.split(""); while (tmp.length < 5) { tmp.push(""); } r.push(tmp); } return r; } } export default RomajiBoardView;
99294d49bf62abb9d6e4658cb4814a5badebcd94
TypeScript
pras75299/typescript-master
/src/baisc.ts
3.453125
3
function addBasic(n1: number, n2: number, showResult: boolean, pharse: string) { const result = n1 + n2; if (showResult) { console.log(pharse + result); } else { return result; } } const number1 = 5; const number2 = 3.8; const printResul = true; const resultPharse = "Result is: "; addBasic(number1, number2, printResul, resultPharse);
0ac12b72c036a80ed4c89b7f5fcaf1b322609a28
TypeScript
anthcny/pdns-admin
/server/src/auth/dto/sign-up.dto.ts
2.5625
3
import {IsBoolean, IsOptional, IsInt, IsString, IsEmail, IsMobilePhone} from 'class-validator'; class SignUpHeaders { @IsOptional() @IsString() token?: string; @IsOptional() @IsInt() username?: number; @IsOptional() @IsBoolean() update?: boolean; } export class SignUpDto { // mobile @IsOptional() @IsBoolean() isMobile?: boolean; @IsOptional() @IsInt() confirmCode?: number; @IsOptional() @IsString() phone?: string; @IsOptional() @IsString() deviceId?: string; // web @IsOptional() @IsString() email?: string; @IsOptional() @IsString() username?: string; @IsOptional() @IsString() password?: string; @IsOptional() @IsString() role?: string; //fast and bad @IsOptional() headers?: SignUpHeaders; }
e88cd9724fe6acb7f64a259c82b41e9aa3f54b32
TypeScript
VitaminCtea/ts-canvas
/src/colorPicker/index.ts
2.640625
3
window.onload = () => { const $ = (selector: string) => document.getElementById(selector) as HTMLElement const colorPickerPanelCanvas: HTMLCanvasElement = $('color-picker__panel') as HTMLCanvasElement const colorPickerBarCanvas: HTMLCanvasElement = $('color-picker__bar') as HTMLCanvasElement const colorSvpanelCursor: HTMLDivElement = $('color-svpanel__cursor') as HTMLDivElement const colorHueSliderThumb: HTMLDivElement = $('color-thumb') as HTMLDivElement const color: HTMLDivElement = $('color') as HTMLDivElement const colorPickerContent: HTMLDivElement = $('colorPickerContent') as HTMLDivElement const colorPickerBarContext: CanvasRenderingContext2D = colorPickerBarCanvas.getContext('2d') as CanvasRenderingContext2D const colorPickerPanelContext: CanvasRenderingContext2D = colorPickerPanelCanvas.getContext('2d') as CanvasRenderingContext2D colorPickerBarCanvas.width = 12 colorPickerBarCanvas.height = colorPickerContent.clientHeight colorPickerPanelCanvas.width = 282 colorPickerPanelCanvas.height = 214 const { clientWidth: colorSvpanelCursorWidth, clientHeight: colorSvpanelCursorHeight } = colorSvpanelCursor enum Coordinate { TO_RIGHT, TO_TOP, } const colors = { defaultColor: '#f00', barColors: ['#f00', '#ff0', '#0f0', '#0ff', '#00f', '#f0f', '#f00'], toRightColors(toColor: string) { return ['#fff', toColor] }, toTopColors: ['rgba(0, 0, 0, 0)', 'rgba(0, 0, 0, 1)'], } type Options = { colors: string[] fillRect: [number, number, number, number] direction: Coordinate offsets?: number[] } const createLinearGradient = (context: CanvasRenderingContext2D, { offsets = [0, 1], colors, fillRect, direction }: Options) => { let startX: number = 0 let startY: number = 0 let endX: number = 0 let endY: number = 0 if (direction === Coordinate.TO_RIGHT) { endX = context.canvas.width } else { endY = context.canvas.height } const linearGradient: CanvasGradient = context.createLinearGradient(startX, startY, endX, endY) offsets.forEach((offset, index) => linearGradient.addColorStop(offset, colors[index])) context.fillStyle = linearGradient context.fillRect.apply(context, fillRect) } const initColorPickerBar = () => { // -> 创建颜色条 createLinearGradient(colorPickerBarContext, { offsets: [0, 0.17, 0.33, 0.5, 0.67, 0.83, 1], colors: colors.barColors, fillRect: [0, 0, colorPickerBarCanvas.width, colorPickerBarCanvas.height], direction: Coordinate.TO_TOP, }) } const initColorPickerPanel = (toColor: string = colors.defaultColor) => { // => 创建从左到右的线性渐变(白色 -> COLOR_PICKER_PANEL_DEFAULT_COLOR) createLinearGradient(colorPickerPanelContext, { colors: colors.toRightColors(toColor), fillRect: [0, 0, colorPickerPanelCanvas.width, colorPickerPanelCanvas.height], direction: Coordinate.TO_RIGHT, }) // ?> 创建从下到上的线性渐变(黑色的透明度 -> 黑色的透明度) createLinearGradient(colorPickerPanelContext, { colors: colors.toTopColors, fillRect: [0, 0, colorPickerPanelCanvas.width, colorPickerPanelCanvas.height], direction: Coordinate.TO_TOP }) } const updateColorPickerPanel = (toString: string) => initColorPickerPanel(toString) const windowToCanvas = (canvasEl: HTMLCanvasElement, event: MouseEvent): { x: number; y: number } => { const rect: DOMRect = canvasEl.getBoundingClientRect() const x: number = event.clientX - rect.left const y: number = event.clientY - rect.top return { x, y, } } const setColor = (canvasEl: HTMLCanvasElement, context: CanvasRenderingContext2D, event: MouseEvent) => { const { x, y } = windowToCanvas(canvasEl, event) const { newX, newY } = boundaryTreatment(canvasEl, x, y) colorSvpanelCursor.style.left = `${ newX }px` colorSvpanelCursor.style.top = `${ newY }px` const [ red, green, blue, alpha ] = getColor(newX, newY, canvasEl, context) color.style.backgroundColor = `rgba(${ red }, ${ green }, ${ blue }, ${ alpha })` } const getColor = (x: number, y: number, canvasEl: HTMLCanvasElement, context: CanvasRenderingContext2D) => { const { width, height } = getCanvasRect(canvasEl) const imageData: ImageData = context.getImageData(0, 0, width, height) const data: Uint8ClampedArray = imageData.data const redIndex: number = y * (width * 4) + x * 4 const alpha: number = data[redIndex + 3] return [data[redIndex], data[redIndex + 1], data[redIndex + 2], alpha === 0 ? 1 : alpha / 255] } const getCanvasRect = (canvasEl: HTMLCanvasElement) => ({ width: canvasEl.clientWidth, height: canvasEl.clientHeight }) const boundaryTreatment = (canvasEl: HTMLCanvasElement, x: number, y: number): { newX: number, newY: number } => { const { width, height } = getCanvasRect(canvasEl) x = Math.max(Math.min(x, width - 1), 0) y = Math.max(Math.min(y, height), 0) return { newX: x, newY: y } } const moveThumb = (canvasEl: HTMLCanvasElement, context: CanvasRenderingContext2D, event: MouseEvent) => { let { x, y } = windowToCanvas(canvasEl, event) if (y >= 0 && y <= canvasEl.clientHeight) { const { newY } = boundaryTreatment(canvasEl, x, y) try { const [ red, green, blue, alpha ] = getColor(0, newY, canvasEl, context) const rgb = `rgba(${ red }, ${ green }, ${ blue }, ${ alpha })` updateColorPickerPanel(rgb) colorHueSliderThumb.style.top = `${ newY }px` color.style.backgroundColor = rgb } catch (e) { /** * $ Will report a mistake * = DOMException: Failed to execute 'addColorStop' on 'CanvasGradient': * =The value provided ('rgba(undefined, undefined, undefined, NaN)') could not be parsed as a color. * */ } } } const registerEvent = (el: HTMLElement, callback: (...args: any[]) => void) => { el.addEventListener('mousedown', (event: MouseEvent) => { callback(event) document.onmousemove = callback document.onmouseup = () => (document.onmouseup = document.onmousemove = null) }) } registerEvent(colorPickerPanelCanvas, setColor.bind(null, colorPickerPanelCanvas, colorPickerPanelContext)) registerEvent(colorPickerBarCanvas, moveThumb.bind(null, colorPickerBarCanvas, colorPickerBarContext)) initColorPickerBar() initColorPickerPanel() }
c7114f4d2e8842ce9c2a305d89a3ae0411ad1eb2
TypeScript
daniilshustov10/Netcracker
/other/typescript/src/types.ts
4.09375
4
// boolean let isLoading: boolean = true; const isWaiting: boolean = false; // number const num: number = 10; const float: number = 3.5; // string const str: string = 'I am str'; const word: string = "TypeScript"; // Array const arr: number[] = [1, 2, 3]; const arrayOfWords: Array<string> = ['TS', 'JS']; // Tuple const x: [string, number] = ['str', 10]; // Enum enum Citrus { Lemon = 0, Orange = 10, Lime = 11 } enum Words { A = 'adadad', B = 'sfsfsf' } const obj = {} let value: number = Citrus.Lemon; let identificator: string = Citrus[10]; // identificator = Orange // Unknown let notSure: unknown = 4; // let num: number = notSure notSure = 'str'; // Any let valueAny: any; valueAny = 5; valueAny = 'new string'; valueAny.fixed() let myNum: number = valueAny; console.log(`My num - ${myNum}`); // Void function sayHello(): void { console.log('hello'); } // Null and Undefined let u: undefined = undefined; let n: null = null; // never function infiniteLoop(): never { while (true) { } } function getError(): never { throw new Error('error'); } // Object declare function create(o: object | null): void; // OK create({ prop: 0 }); create(null); // Type assertions let someValue: unknown = "this is a string"; let strLength: number = (someValue as string).length; // let strLength: number = (<string>someValue).length;
72e0a4c94c78bcd8f83e13df5177edc597ae49bc
TypeScript
kagan1/GraphicalPeercoinAddress
/lib/Peercoin.ts
3.15625
3
import BigInteger=require("../lib/BigInteger"); import Base58=require("../lib/Base58"); //module Peercoin { ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// export class Crypto { static base64map = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; // Bit-wise rotate left static rotl(n, b) { return (n << b) | (n >>> (32 - b)); } // Bit-wise rotate right static rotr(n, b) { return (n << (32 - b)) | (n >>> b); } // Swap big-endian to little-endian and vice versa static endian (n) { // If number given, swap endian if (n.constructor == Number) { return Crypto.rotl(n, 8) & 0x00FF00FF | Crypto.rotl(n, 24) & 0xFF00FF00; } // Else, assume array and swap all items for (var i = 0; i < n.length; i++) n[i] = Crypto.endian(n[i]); return n; } // Generate an array of any length of random bytes static randomBytes (bytes:number[]) : number[] { for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) words[b >>> 5] |= (bytes[i] & 0xFF) << (24 - b % 32); return words; } // Convert a byte array to big-endian 32-bit words static bytesToWords(bytes:number[]) : number[] { for (var words = [], i = 0, b = 0; i < bytes.length; i++, b += 8) words[b >>> 5] |= (bytes[i] & 0xFF) << (24 - b % 32); return words; } // Convert big-endian 32-bit words to a byte array static wordsToBytes (words:number[]) : number[] { for (var bytes = [], b = 0; b < words.length * 32; b += 8) bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF); return bytes; } // Convert a byte array to a hex string static bytesToHex (bytes:number[]) : string { for (var hex = [], i = 0; i < bytes.length; i++) { hex.push((bytes[i] >>> 4).toString(16)); hex.push((bytes[i] & 0xF).toString(16)); } return hex.join(""); } // Convert a hex string to a byte array static hexToBytes (hex:string) :number[] { for (var bytes = [], c = 0; c < hex.length; c += 2) bytes.push(parseInt(hex.substr(c, 2), 16)); return bytes; } // Convert a byte array to a base-64 string static bytesToBase64 (bytes:number[]) :string{ for (var base64 = [], i = 0; i < bytes.length; i += 3) { var triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]; for (var j = 0; j < 4; j++) { if (i * 8 + j * 6 <= bytes.length * 8) base64.push(Crypto.base64map.charAt((triplet >>> 6 * (3 - j)) & 0x3F)); else base64.push("="); } } return base64.join(""); } // Convert a base-64 string to a byte array static base64ToBytes (base64:string) :number[] { // Remove non-base-64 characters base64 = base64.replace(/[^A-Z0-9+\/]/ig, ""); for (var bytes = [], i = 0, imod4 = 0; i < base64.length; imod4 = ++i % 4) { if (imod4 == 0) continue; bytes.push(((Crypto.base64map.indexOf(base64.charAt(i - 1)) & (Math.pow(2, -2 * imod4 + 8) - 1)) << (imod4 * 2)) | (Crypto.base64map.indexOf(base64.charAt(i)) >>> (6 - imod4 * 2))); } return bytes; } // Convert a byte array to little-endian 32-bit words static bytesToLWords (bytes:number[]) :number[] { var output = Array(bytes.length >> 2); for (var i = 0; i < output.length; i++) output[i] = 0; for (var i = 0; i < bytes.length * 8; i += 8) output[i >> 5] |= (bytes[i / 8] & 0xFF) << (i % 32); return output; } // Convert little-endian 32-bit words to a byte array static lWordsToBytes (words:number[]) :number[] { var output = []; for (var i = 0; i < words.length * 32; i += 8) output.push((words[i >> 5] >>> (i % 32)) & 0xff); return output; } static integerToBytes(e: BigInteger, t:number):number[] { var n = e.toByteArrayUnsigned(); if (t < n.length) n = n.slice(n.length - t); else while (t > n.length) n.unshift(0); return n } static charenc = { Binary: { // Convert a string to a byte array stringToBytes : function (str:string):number[] { for (var bytes = [], i = 0; i < str.length; i++) bytes.push(str.charCodeAt(i) & 0xFF); return bytes; }, // Convert a byte array to a string bytesToString : function (bytes:number[]) :string { for (var str = [], i = 0; i < bytes.length; i++) str.push(String.fromCharCode(bytes[i])); return str.join(""); } }, UTF8 : { // Convert a string to a byte array stringToBytes : function (str:string) { return Crypto.charenc.Binary.stringToBytes(decodeURIComponent(encodeURIComponent(str))); }, // Convert a byte array to a string bytesToString : function (bytes) { return decodeURIComponent(encodeURIComponent(Crypto.charenc.Binary.bytesToString(bytes))); } } } static UTF8 = Crypto.charenc.UTF8; private static safe_add(x:number, y:number) :number { var lsw = (x & 0xFFFF) + (y & 0xFFFF); var msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ private static bit_rol(num:number, cnt:number) :number { return (num << cnt) | (num >>> (32 - cnt)); } private static rmd160_f(j:number, x:number, y:number, z:number) :number { if (j>=80) throw("rmd160_f: j out of range"); return (0 <= j && j <= 15) ? (x^y^z) : (16 <= j && j <= 31) ? (x & y) | (~x & z) : (32 <= j && j <= 47) ? (x | ~y)^z : (48 <= j && j <= 63) ? (x & z) | (y & ~z) : x^(y | ~z) ; } private static rmd160_K1(j:number):number { if (j>=80) throw("rmd160_K1: j out of range"); return (0 <= j && j <= 15) ? 0x00000000 : (16 <= j && j <= 31) ? 0x5a827999 : (32 <= j && j <= 47) ? 0x6ed9eba1 : (48 <= j && j <= 63) ? 0x8f1bbcdc : 0xa953fd4e; } private static rmd160_K2(j:number) :number { if (j>=80) throw("rmd160_K2: j out of range"); return (0 <= j && j <= 15) ? 0x50a28be6 : (16 <= j && j <= 31) ? 0x5c4dd124 : (32 <= j && j <= 47) ? 0x6d703ef3 : (48 <= j && j <= 63) ? 0x7a6d76e9 : 0x00000000 ; } private static rmd160_r1 = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 ] private static rmd160_r2 = [ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 ] private static rmd160_s1 = [ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ] private static rmd160_s2 = [ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ] private static _rmd160 (message) :number[]{ // Convert to byte array if (message.constructor == String) message = Crypto.UTF8.stringToBytes(message); var x = Crypto.bytesToLWords(message), len = message.length * 8; /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var h0 = 0x67452301; var h1 = 0xefcdab89; var h2 = 0x98badcfe; var h3 = 0x10325476; var h4 = 0xc3d2e1f0; var safe_add=Crypto.safe_add; var bit_rol=Crypto.bit_rol; var rmd160_f=Crypto.rmd160_f; var rmd160_K1=Crypto.rmd160_K1; var rmd160_K2=Crypto.rmd160_K2; for (var i = 0, xlh=x.length; i < xlh; i += 16) { var T; var A1 = h0, B1 = h1, C1 = h2, D1 = h3, E1 = h4; var A2 = h0, B2 = h1, C2 = h2, D2 = h3, E2 = h4; for (var j = 0; j <= 79; ++j) { T = safe_add(A1, rmd160_f(j, B1, C1, D1)); T = safe_add(T, x[i + Crypto.rmd160_r1[j]]); T = safe_add(T, rmd160_K1(j)); T = safe_add(bit_rol(T, Crypto.rmd160_s1[j]), E1); A1 = E1; E1 = D1; D1 = bit_rol(C1, 10); C1 = B1; B1 = T; T = safe_add(A2, rmd160_f(79 - j, B2, C2, D2)); T = safe_add(T, x[i + Crypto.rmd160_r2[j]]); T = safe_add(T, rmd160_K2(j)); T = safe_add(bit_rol(T, Crypto.rmd160_s2[j]), E2); A2 = E2; E2 = D2; D2 = bit_rol(C2, 10); C2 = B2; B2 = T; } T = safe_add(h1, safe_add(C1, D2)); h1 = safe_add(h2, safe_add(D1, E2)); h2 = safe_add(h3, safe_add(E1, A2)); h3 = safe_add(h4, safe_add(A1, B2)); h4 = safe_add(h0, safe_add(B1, C2)); h0 = T; } return [h0, h1, h2, h3, h4]; } // Constants private static K:number[] = [0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2] private static _sha256 (message) :number[] { // Convert to byte array if (message.constructor == String) message = Crypto.UTF8.stringToBytes(message); /* else, assume byte array already */ var m = Crypto.bytesToWords(message), l = message.length * 8, H = [0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19], w = [], a, b, c, d, e, f, g, h, t1, t2; // Padding m[l >> 5] |= 0x80 << (24 - l % 32); m[((l + 64 >> 9) << 4) + 15] = l; for (var i = 0, ml=m.length; i < ml; i += 16) { a = H[0]; b = H[1]; c = H[2]; d = H[3]; e = H[4]; f = H[5]; g = H[6]; h = H[7]; for (var j = 0; j < 64; j++) { if (j < 16) w[j] = m[j + i]; else { var gamma0x = w[j - 15], gamma1x = w[j - 2], gamma0 = ((gamma0x << 25) | (gamma0x >>> 7))^ ((gamma0x << 14) | (gamma0x >>> 18))^ (gamma0x >>> 3), gamma1 = ((gamma1x << 15) | (gamma1x >>> 17))^ ((gamma1x << 13) | (gamma1x >>> 19))^ (gamma1x >>> 10); w[j] = gamma0 + (w[j - 7] >>> 0) + gamma1 + (w[j - 16] >>> 0); } var ch = e & f^~e & g, maj = a & b^a & c^b & c, sigma0 = ((a << 30) | (a >>> 2))^ ((a << 19) | (a >>> 13))^ ((a << 10) | (a >>> 22)), sigma1 = ((e << 26) | (e >>> 6))^ ((e << 21) | (e >>> 11))^ ((e << 7) | (e >>> 25)); t1 = (h >>> 0) + sigma1 + ch + (Crypto.K[j]) + (w[j] >>> 0); t2 = sigma0 + maj; h = g; g = f; f = e; e = (d + t1) >>> 0; d = c; c = b; b = a; a = (t1 + t2) >>> 0; } H[0] += a; H[1] += b; H[2] += c; H[3] += d; H[4] += e; H[5] += f; H[6] += g; H[7] += h; } return H; } /** * RIPEMD160 e.g.: HashUtil.RIPEMD160(hash, {asBytes : true}) */ static RIPEMD160(message, options) { var ret, digestbytes = Crypto.lWordsToBytes(Crypto._rmd160(message)); if (options && options.asBytes){ ret=digestbytes; }else if (options && options.asString){ ret=Crypto.charenc.Binary.bytesToString(digestbytes); } else { ret=Crypto.bytesToHex(digestbytes); } return ret; } // Public API /** * SHA256 e.g.: HashUtil.SHA256(hash, {asBytes : true}) */ static SHA256 (message, options) { var ret, digestbytes:number[] = Crypto.wordsToBytes(Crypto._sha256(message)); if (options && options.asBytes){ ret = digestbytes; }else if (options && options.asString){ ret = Crypto.charenc.Binary.bytesToString(digestbytes); }else{ ret=Crypto.bytesToHex(digestbytes); } return ret; } // Package private blocksize??? // SHA256._blocksize = 16; // SHA256._digestsize = 32; }//crypto ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// export class Address { static networkVersion = 0x37; // Peercoin mainnet hash:number[]; version; constructor(bytes) { if ("string" == typeof bytes) { bytes = this.decodeString(bytes); } this.hash = bytes; this.version = Address.networkVersion; } decodeString (str:string) { var bytes = Base58.decode(str); var hash = bytes.slice(0, 21); var checksum = Crypto.SHA256(Crypto.SHA256(hash, {asBytes : true}), {asBytes : true}); if (checksum[0] != bytes[21] || checksum[1] != bytes[22] || checksum[2] != bytes[23] || checksum[3] != bytes[24]) { throw "Checksum validation failed!"; } var version = hash.shift(); if (version != Address.networkVersion) { throw "Version " + version + " not supported!"; } return hash; } getHashBase64 () { return Crypto.bytesToBase64(this.hash); } toString () :string { // Get a copy of the hash var hash = this.hash.slice(0); // Version hash.unshift(this.version); var checksum = Crypto.SHA256(Crypto.SHA256(hash, { asBytes : true }), { asBytes : true }); var bytes = hash.concat(checksum.slice(0, 4)); return Base58.encode(bytes); } } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// class Mint { constructor(){ } static day = 60 * 60 * 24; static stakeMaxAge = 90 * Mint.day; static coin = 1000000; static coinDay = Mint.coin * Mint.day; static minStakeMinAge = 2592000; static DiffToTarget(diff:number):BigInteger { //floor it diff = (diff |0); var mantissa = 0x0000ffff / diff; var exp = 1; var tmp = mantissa; while (tmp >= 256.0) { tmp /= 256.0; exp++; } for (var i = 0; i < exp; i++) { mantissa *= 256.0; } var bn = new BigInteger('' + (mantissa | 0), 10); bn = bn.shiftLeft((26 - exp) * 8); return bn; } static IncCompact(compact:number):number { var mantissa = compact & 0x007fffff; var neg = compact & 0x00800000; var exponent = (compact >> 24); if (exponent <= 3) { mantissa += (1 << (8 * (3 - exponent))); } else { mantissa++; } if (mantissa >= 0x00800000) { mantissa >>= 8; exponent++; } return (exponent << 24) | mantissa | neg; } // BigToCompact converts a whole number N to a compact representation using // an unsigned 32-bit number. The compact representation only provides 23 bits // of precision, so values larger than (2^23 - 1) only encode the most // significant digits of the number. See CompactToBig for details. static BigToCompact(n:BigInteger) :number{ // No need to do any work if it's zero. if (n.equals(BigInteger.ZERO)) { return 0; } // Since the base for the exponent is 256, the exponent can be treated // as the number of bytes. So, shift the number right or left // accordingly. This is equivalent to: // mantissa = mantissa / 256^(exponent-3) var mantissa :number; // uint32 var mantissa = compact & 0x007fffff, var exponent = n.toByteArrayUnsigned().length; if (exponent <= 3) { mantissa = n.and(new BigInteger('4294967295', 10)).intValue(); mantissa <<= 8 * (3 - exponent); } else { // Use a copy to avoid modifying the caller's original number. var tn = new BigInteger(n.toString(10), 10); mantissa = tn.shiftRight(8 * (exponent - 3)).and(new BigInteger('4294967295', 10)).intValue(); } // When the mantissa already has the sign bit set, the number is too // large to fit into the available 23-bits, so divide the number by 256 // and increment the exponent accordingly. if ((mantissa & 0x00800000) != 0) { mantissa >>= 8; exponent++; } // Pack the exponent, sign bit, and mantissa into an unsigned 32-bit // int and return it. var compact = ((exponent << 24) | mantissa); if (n.compareTo(BigInteger.ZERO) < 0) { compact |= 0x00800000 } return compact; } static CompactToDiff(bits) :number { var nShift = (bits >> 24) & 0xff; var diff = 1.0 * (0x0000ffff) / (bits & 0x00ffffff); for (var n = 0; nShift < 29; nShift++) { diff *= 256.0; } for (var n = 0; nShift > 29; nShift--) { diff /= 256.0; } return diff; } /////////////////////////////////////////////////////////////////////////////////////////////// // CompactToBig converts a compact representation of a whole number N to an // unsigned 32-bit number. The representation is similar to IEEE754 floating // point numbers. // // Like IEEE754 floating point, there are three basic components: the sign, // the exponent, and the mantissa. They are broken out as follows: // // * the most significant 8 bits represent the unsigned base 256 exponent // * bit 23 (the 24th bit) represents the sign bit // * the least significant 23 bits represent the mantissa // // ------------------------------------------------- // | Exponent | Sign | Mantissa | // ------------------------------------------------- // | 8 bits [31-24] | 1 bit [23] | 23 bits [22-00] | // ------------------------------------------------- // // The formula to calculate N is: // N = (-1^sign) * mantissa * 256^(exponent-3) // // This compact form is only used in bitcoin to encode unsigned 256-bit numbers // which represent difficulty targets, thus there really is not a need for a // sign bit, but it is implemented here to stay consistent with bitcoind. static CompactToBig(compact:number) :BigInteger { // Extract the mantissa, sign bit, and exponent. var mantissa = compact & 0x007fffff, isNegative = (compact & 0x00800000) != 0, exponent = (compact >> 24) >>> 0; // Since the base for the exponent is 256, the exponent can be treated // as the number of bytes to represent the full 256-bit number. So, // treat the exponent as the number of bytes and shift the mantissa // right or left accordingly. This is equivalent to: // N = mantissa * 256^(exponent-3) var bn; if (exponent <= 3) { mantissa >>= 8 * (3 - exponent) bn = new BigInteger('' + mantissa, 10); } else { bn = new BigInteger('' + mantissa, 10); bn = bn.shiftLeft(8 * (exponent - 3)); } // Make it negative if the sign bit is set. if (isNegative) { bn = bn.multiply(new BigInteger('-1', 10, null)); } return bn; } } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// class StakeKernelTemplate { BlockFromTime:number; StakeModifier:BigInteger; PrevTxOffset:number; PrevTxTime:number; PrevTxOutIndex:number; PrevTxOutValue:number; UnspentOutputs:UnspentOutputsToStake; IsProtocolV03:boolean; StakeMinAge:number; Bits:number; Results:any[]; maxResults:number; constructor(tpl :{BlockFromTime:number, StakeModifier:BigInteger, PrevTxOffset:number, PrevTxTime:number, PrevTxOutIndex:number, PrevTxOutValue:number, IsProtocolV03?:boolean, StakeMinAge?:number, Bits?:number}, manager :UnspentOutputsToStake) { this.BlockFromTime = tpl.BlockFromTime; // int64 this.StakeModifier = tpl.StakeModifier; //uint64 => BigInteger!!! this.PrevTxOffset = tpl.PrevTxOffset; //uint32 this.PrevTxTime = tpl.PrevTxTime; //int64 this.PrevTxOutIndex = tpl.PrevTxOutIndex; //uint32 this.PrevTxOutValue = tpl.PrevTxOutValue; //int64 this.UnspentOutputs = manager; this.IsProtocolV03 = ('IsProtocolV03' in tpl) ? tpl.IsProtocolV03 : true; //bool this.StakeMinAge = ('StakeMinAge' in tpl) ? tpl.StakeMinAge : Mint.minStakeMinAge; //int64 this.Bits = ('Bits' in tpl) ? tpl.Bits : this.setBitsWithDifficulty(parseFloat("10.33")); //uint32 this.Results = []; this.maxResults = 7; } setBitsWithDifficulty (diff:number) :number{ this.Bits = Mint.BigToCompact(Mint.DiffToTarget(diff)); return this.Bits; } checkStakeKernelHash() :{success:boolean,minTarget:BigInteger, hash:number[]} { var retobj = {success: false, minTarget: BigInteger.ZERO, hash: []}; if (this.UnspentOutputs.TxTime < this.PrevTxTime) { // Transaction timestamp violation console.log("CheckStakeKernelHash() : nTime violation"); return retobj; } if (this.BlockFromTime + this.StakeMinAge > this.UnspentOutputs.TxTime) { // Min age requirement console.log("CheckStakeKernelHash() : min age violation"); return retobj; } var bnTargetPerCoinDay = Mint.CompactToBig(this.Bits); var timeReduction = (this.IsProtocolV03) ? timeReduction = this.StakeMinAge : 0; var nTimeWeight = this.UnspentOutputs.TxTime - this.PrevTxTime; // int64 if (nTimeWeight > Mint.stakeMaxAge) { nTimeWeight = Mint.stakeMaxAge; } nTimeWeight -= timeReduction; var bnCoinDayWeight:BigInteger; // *big.Int var valueTime:number = this.PrevTxOutValue * nTimeWeight; if (valueTime > 0) { // no overflow bnCoinDayWeight = new BigInteger('' + (Math.floor(valueTime / Mint.coinDay)), 10); } else { // overflow, calc w/ big.Int or return error? // err = errors.New("valueTime overflow") // return var t1 = new BigInteger('' + (24 * 60 * 60), 10); var t2 = new BigInteger('' + (Mint.coin), 10); var t3 = new BigInteger('' + (this.PrevTxOutValue), 10); var t4 = new BigInteger('' + (nTimeWeight), 10); bnCoinDayWeight = ((t3.multiply(t4)).divide(t2)).divide(t1); } var targetInt:BigInteger = bnCoinDayWeight.multiply(bnTargetPerCoinDay); var buf = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; var _o_ = 0; if (this.IsProtocolV03) { // v0.3 protocol var d:number[] = this.StakeModifier.toByteArrayUnsigned().reverse(); for (var i = 0; i < 8; i++) { buf[_o_] = d[i]; _o_++; } } else { // v0.2 protocol var d2:number = this.Bits; for (var i = 0; i < 4; i++) { buf[_o_] = (d2 & 0xff); d2 >>= 8; _o_++; } } var data = [this.BlockFromTime, this.PrevTxOffset, this.PrevTxTime, this.PrevTxOutIndex, this.UnspentOutputs.TxTime]; for (var k = 0, arrayLength = data.length; k < arrayLength; k++) { var dn = data[k]; for (var i = 0; i < 4; i++) { buf[_o_] = (dn & 0xff); dn >>= 8; _o_++; } } var hashProofOfStake = (Crypto.SHA256(Crypto.SHA256(buf, {asBytes : true}), {asBytes : true})).reverse(); var hashProofOfStakeInt:BigInteger = BigInteger.fromByteArrayUnsigned(hashProofOfStake); if (hashProofOfStakeInt.compareTo(targetInt) > 0) { return retobj; } retobj.minTarget = hashProofOfStakeInt.divide(bnCoinDayWeight).subtract(BigInteger.ONE); retobj.success = true; retobj.hash = hashProofOfStake; return retobj; } } ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////// export class UnspentOutputsToStake{ private arrStakeKernelTemplates:StakeKernelTemplate[]; Bits:number; TxTime:number; StartTime:number; MaxTime:number; Stop:boolean; Results:any[]; private orgtpl:any[]; constructor() { this.arrStakeKernelTemplates = []; // this.Bits = Mint.BigToCompact(Mint.DiffToTarget(parseFloat("15"))); //uint32 this.TxTime = (Date.now() / 1000 | 0); //int64 this.StartTime = this.TxTime; this.MaxTime = this.TxTime + 3600; this.Stop = false; this.Results = []; this.orgtpl=[]; } add (tpldata:{BlockFromTime:number, StakeModifier:BigInteger, PrevTxOffset:number, PrevTxTime:number, PrevTxOutIndex:number, PrevTxOutValue:number}) { var addrfound = this.orgtpl.some(function (el:{BlockFromTime:number, StakeModifier:BigInteger, PrevTxOffset:number, PrevTxTime:number, PrevTxOutIndex:number, PrevTxOutValue:number}) { if ((el.PrevTxOffset == tpldata.PrevTxOffset && el.PrevTxOutIndex == tpldata.PrevTxOutIndex && el.PrevTxOutValue == tpldata.PrevTxOutValue && el.StakeModifier.toString() == tpldata.StakeModifier.toString())) { return true; } }); if (!addrfound) { this.orgtpl.push(tpldata); this.arrStakeKernelTemplates.push(new StakeKernelTemplate(tpldata, this)); } } setBitsWithDifficulty (diff:number) { var that = this; this.Bits = Mint.BigToCompact(Mint.DiffToTarget(diff)); this.arrStakeKernelTemplates.forEach((element: StakeKernelTemplate) => {element.Bits = this.Bits; }); } setStartStop (start:number, stop:number) { var that = this; that.TxTime = start; that.StartTime = that.TxTime; that.MaxTime = stop; } stop() { this.Stop = true; } private findStakeAt () : {foundstake:number, mindifficulty:number}[] { var stakesfound = [] ; //filter out oudated templates var newarrKT=[]; this.arrStakeKernelTemplates.forEach((element, index, array) => { if ((element.UnspentOutputs.TxTime < element.PrevTxTime) || (element.BlockFromTime + element.StakeMinAge > element.UnspentOutputs.TxTime)) { // Transaction timestamp violation // console.log("CheckStakeKernelHash() : nTime violation");// Min age requirement }else{ newarrKT.push(element); } }); this.arrStakeKernelTemplates=newarrKT; this.arrStakeKernelTemplates.forEach((element, index, array) => { if (!this.Stop) { var resultobj = element.checkStakeKernelHash(); //{succes: succes, hash, minTarget:minTarget} if (resultobj.success) { var comp = Mint.IncCompact(Mint.BigToCompact(resultobj.minTarget)); var diff = Mint.CompactToDiff(comp); if (diff < 0.25) { console.log('hmmm is this min diff ok: ' + diff); //element.maxResults=1; //debugger; // console.log(element) } var res = { "foundstake" : this.TxTime, "mindifficulty" : ((diff * 10) / 10) }; element.Results.push(res); stakesfound.push(res); } } }); return stakesfound; } private recursiveFind(ob:{progressWhen:number, mintcallback:(arr: any[])=>any, progresscallback:(n:number, s:string)=>any, setZeroTimeout: (a,b?)=>any}){ ob.progressWhen++; this.TxTime++; var res = this.findStakeAt(); if (res.length > 0) { ob.mintcallback(res); this.Results.push(res); } var loopfunc: (a,b)=>any = ob.setZeroTimeout; if (ob.progressWhen > 555 / this.arrStakeKernelTemplates.length) { ob.progressWhen = 0; ob.progresscallback(((this.TxTime - this.StartTime) / (1.0 * (this.MaxTime - this.StartTime))), ((this.MaxTime - this.TxTime) / 60.0).toFixed(1) + ' min remaining'); loopfunc = setTimeout; } if (!this.Stop && this.TxTime < this.MaxTime) loopfunc(() => this.recursiveFind(ob), 40); else ob.progresscallback(100, 'done'); } findStake (mintcallback:(arr:any[])=>any, progresscallback:(n:number, s: string)=>any, setZeroTimeout:(a,b?)=>any) { if (this.arrStakeKernelTemplates.length > 0) { var ob = { progressWhen: 0, mintcallback: mintcallback, progresscallback: progresscallback, setZeroTimeout: setZeroTimeout }; setZeroTimeout(() => this.recursiveFind(ob)); } } } export function valueToBigInt (valueBuffer) :BigInteger { if (valueBuffer instanceof BigInteger) return valueBuffer; // Prepend zero byte to prevent interpretation as negative integer return BigInteger.fromByteArrayUnsigned(valueBuffer); } /** * Format a Peercoin value as a string. * * Takes a BigInteger or byte-array and returns that amount of Peercoins in a * nice standard formatting. * * Examples: * 12.3555 * 0.1234 * 900.99998888 * 34.00 */ export function formatValue (valueBuffer) : string{ var value = valueToBigInt(valueBuffer).toString(); var integerPart = value.length > 8 ? value.substr(0, value.length - 8) : '0'; var decimalPart = value.length > 8 ? value.substr(value.length - 8) : value; while (decimalPart.length < 8) decimalPart = "0" + decimalPart; decimalPart = decimalPart.replace(/0*$/, ''); while (decimalPart.length < 2) decimalPart += "0"; return integerPart + "." + decimalPart; } /** * Parse a floating point string as a Peercoin value. * * Keep in mind that parsing user input is messy. You should always display * the parsed value back to the user to make sure we understood his input * correctly. */ export function parseValue (valueString) :BigInteger { // TODO: Detect other number formats (e.g. comma as decimal separator) var valueComp = valueString.split('.'); var integralPart = valueComp[0]; var fractionalPart = valueComp[1] || "0"; while (fractionalPart.length < 8) fractionalPart += "0"; fractionalPart = fractionalPart.replace(/^0+/g, ''); var value = BigInteger.valueOf(parseInt(integralPart)); value = value.multiply(BigInteger.valueOf(100000000)); value = value.add(BigInteger.valueOf(parseInt(fractionalPart))); return value; } /* export function integerToBytes(e: BigInteger, t:number):number[] { var n = e.toByteArrayUnsigned(); if (t < n.length) n = n.slice(n.length - t); else while (t > n.length) n.unshift(0); return n }*/
f298187769797fd9fb10b050eb2e933f35b18427
TypeScript
future4code/Tania-Oliveira
/projeto_labook/src/model/User.ts
2.875
3
export default interface authenticationData { id: string } enum POST_TYPES { NORMAL = "normal", EVENT = "event" } export class User { constructor( private id: string, private name: string, private email: string, private password: string ) { } getId() { return this.id } getName() { return this.name } getEmail() { return this.email } getPassword() { return this.password } setId(newId: string) { this.id = newId } setName(newName: string) { this.name = newName } setEmail(newEmail: string) { this.email = newEmail } setPassword(newPassword: string) { this.password = newPassword } } export class post{ constructor( private id: string, private photo: string, private description: string, private type: POST_TYPES, private createdAt: Date, private authorId: string ){} getPostId(){ return this.id } getPostPhoto(){ return this.photo } getPostDescripition(){ return this.description } getPostType(){ return this.type } getPostCreatedAt(){ return this.createdAt } getPostAuthorId(){ return this.authorId } }
f849f7227602af7d2c044abdd2218b071065fbb9
TypeScript
mahwish-chohdry/webportaldocker
/SuperAdmin.WebUI/ClientApp/src/reducers/admin_settings.ts
2.546875
3
import { SettingsActions, ActionTypes } from '../action/admin_settings'; import { Reducer } from 'redux'; import { getPersonaPermissionsData, getRolePermissionsData, getFormNameFromID, getPersonaNameFromID, getRoleNameFromID } from 'utils'; export interface settingsState { roles: any[]; persona_roles: any[]; personas: any[]; formNames: any[]; rolePermissionList: any[]; isCreatingPersona: boolean; personaPermissionsList: any[]; isAddingFormName: boolean; isCreatingRolePermission: boolean; } const initialState = { persona_roles: [], roles: [], personas: [], formNames: [], rolePermissionList: [], isCreatingPersona: false, isAddingFormName: false, isCreatingRolePermission: false, personaPermissionsList: [ ] } export const settingsReducer: Reducer<settingsState, SettingsActions> = (state = initialState, action) => { let data = '' as any; let personaPermissionsList = []; let rolePermissionList = []; let clone = {...state}; let afterDelete = [] switch (action.type) { case ActionTypes.GET_ROLES: if (!Array.isArray(action.payload)) data = [] as any[] else data = action.payload rolePermissionList = getRolePermissionsData(state.rolePermissionList, state.formNames, data); return { ...state, roles: data } case ActionTypes.GET_ROLES_FAILED: return { ...state, roles: [] } case ActionTypes.GET_ROLES_BY_PERSONA: if (!Array.isArray(action.payload)) data = [] as any[] else data = action.payload return { ...state, persona_roles: data } case ActionTypes.GET_ROLES_BY_PERSONA_FAILED: return { ...state, persona_roles: [] } case ActionTypes.GET_PERSONAS: if (!Array.isArray(action.payload)) data = [] as any[] else data = action.payload personaPermissionsList = getPersonaPermissionsData(state.personaPermissionsList, state.formNames, data); return { ...state, personas: data, personaPermissionsList } case ActionTypes.GET_PERSONAS_FAILED: return { ...state, personas: [] } case ActionTypes.GET_FORMS: if (!Array.isArray(action.payload)) data = [] as any[] else data = action.payload personaPermissionsList = getPersonaPermissionsData(state.personaPermissionsList, data, state.personas); rolePermissionList = getRolePermissionsData(state.rolePermissionList, data, state.roles); return { ...state, formNames: data, personaPermissionsList, rolePermissionList } case ActionTypes.GET_FORMS_FAILED: return { ...state, formNames: [] } case ActionTypes.ADD_FORM_NAME: return { ...state, isAddingFormName: true } case ActionTypes.ADD_FORM_NAME_SUCCESS: return { ...state, formNames: [...state.formNames, action.payload], isAddingFormName: false, } case ActionTypes.ADD_FORM_NAME_FAILED: return { ...state, isAddingFormName: false, } case ActionTypes.CREATE_PERSONA_PERMISSIONS: return { ...state, isCreatingPersona: true } case ActionTypes.CREATE_PERSONA_PERMISSIONS_SUCCESS: let personaObj = { formId: action.payload.Form.id, formName: action.payload.Form.name, personaId: action.payload.Persona.id, personaName: action.payload.Persona.name } return { ...state, isCreatingPersona: false, personaPermissionsList: [...state.personaPermissionsList, personaObj] } case ActionTypes.CREATE_PERSONA_PERMISSIONS_FAILED: return { ...state, isCreatingPersona: false } case ActionTypes.CREATE_ROLE_PERMISSIONS: return { ...state, isCreatingRolePermission: true, } case ActionTypes.CREATE_ROLE_PERMISSIONS_SUCCESS: let rolePermission = action.payload // Mapping FormName and RoleName rolePermission.formName = getFormNameFromID(rolePermission.formId, clone.formNames) rolePermission.roleName = getRoleNameFromID(rolePermission.roleId, clone.roles) return { ...state, isCreatingRolePermission: false, rolePermissionList: [...state.rolePermissionList, rolePermission] } case ActionTypes.CREATE_ROLE_PERMISSIONS_FAILED: return { ...state, isCreatingRolePermission: false } case ActionTypes.GET_PERSONA_PERMISSIONS: return { ...state, } case ActionTypes.GET_PERSONA_PERMISSIONS_SUCCESS: if (!Array.isArray(action.payload)) data = [] as any[] else data = action.payload data = getPersonaPermissionsData(data, state.formNames, state.personas); return { ...state, personaPermissionsList: data, } case ActionTypes.GET_PERSONA_PERMISSIONS_FAILED: return { ...state, personaPermissionsList: [] } case ActionTypes.GET_ROLE_PERMISSIONS: return { ...state, } case ActionTypes.GET_ROLE_PERMISSIONS_SUCCESS: if (!Array.isArray(action.payload)) data = [] as any[] else data = action.payload data = getRolePermissionsData(data, state.formNames, state.roles); return { ...state, rolePermissionList: data, } case ActionTypes.GET_ROLE_PERMISSIONS_FAILED: return { ...state, rolePermissionList: [] } case ActionTypes.DELETE_PERSONA_PERMISSION: return { ...state, } case ActionTypes.DELETE_PERSONA_PERMISSION_SUCCESS: afterDelete = state.personaPermissionsList.filter((item: any) => item.id != action.payload); return { ...state, personaPermissionsList: afterDelete, } case ActionTypes.DELETE_PERSONA_PERMISSION_FAILED: return { ...state } case ActionTypes.UPDATE_ROLE_PERMISSIONS_SUCCESS: let toBeUpdateItem = action.payload; clone.rolePermissionList = clone.rolePermissionList.map(permission =>{ // additional fields which are modal can be added here if(permission.id == toBeUpdateItem.id) { permission.canView = toBeUpdateItem.canView; permission.canInsert = toBeUpdateItem.canInsert; permission.canUpdate = toBeUpdateItem.canUpdate; permission.canDelete = toBeUpdateItem.canDelete; permission.canExport = toBeUpdateItem.canExport; } return permission; }) return{ ...clone, } case ActionTypes.UPDATE_ROLE_PERMISSIONS_FAILED: return{ ...state, } case ActionTypes.UPDATE_ROLE_PERMISSIONS: return { ...state, } case ActionTypes.UPDATE_FORM_NAME_SUCCESS: let form_Item = action.payload; clone.formNames = clone.formNames.map(form =>{ // additional fields which are modal can be added here if(form.id == form_Item.id) { form.formName = form_Item.formName } return form; }) return{ ...clone, } case ActionTypes.UPDATE_FORM_NAME_FAILED: return{ ...state, } case ActionTypes.UPDATE_FORM_NAME: return { ...state, } case ActionTypes.UPDATE_PERSONA_PERMISSIONS_SUCCESS: let persona_Item = action.payload; clone.personaPermissionsList = clone.personaPermissionsList.map(persona =>{ // additional fields which are modal can be added here if(persona.id == persona_Item.id) { persona.formId = persona_Item.formId; persona.personaId = persona_Item.personaId; persona.formName = getFormNameFromID(persona_Item.formId,clone.formNames); persona.personaName = getPersonaNameFromID(persona_Item.personaId, clone.personas); } return persona; }) return{ ...clone, } case ActionTypes.UPDATE_PERSONA_PERMISSIONS_FAILED: return{ ...state, } case ActionTypes.UPDATE_PERSONA_PERMISSIONS: return { ...state, } case ActionTypes.DELETE_FORM: return { ...state, } case ActionTypes.DELETE_FORM_SUCCESS: afterDelete = state.formNames.filter((item: any) => item.id != action.payload); return { ...state, formNames: afterDelete, } case ActionTypes.DELETE_FORM_FAILED: return { ...state } case ActionTypes.DELETE_ROLE_PERMISSION: return { ...state, } case ActionTypes.DELETE_ROLE_PERMISSION_SUCCESS: afterDelete = state.rolePermissionList.filter((item: any) => item.id != action.payload); return { ...state, rolePermissionList: afterDelete, } case ActionTypes.DELETE_ROLE_PERMISSION_FAILED: return { ...state } default: return state; } }
eef6d31a5fd971b1c36d62ed0cd72623863ec0f7
TypeScript
GeovaneF55/hibridas
/src/providers/itens/itens.ts
2.546875
3
import { Http } from '@angular/http'; import { Injectable } from '@angular/core'; import 'rxjs/add/operator/toPromise' import { Item } from '../../interfaces/Item'; import firebase from 'firebase'; @Injectable() export class ItensProvider { constructor(public http: Http) { console.log('Hello ItensProvider Provider'); } getItens(): Promise<Item[]> { return new Promise(resolve => { const db = firebase.database(); db.ref('items/').once('value').then(function(snapshot) { const resp = snapshot.val() ? snapshot.val() : undefined; let itens : Array<Item> = [] const itemKeys = Object.keys(resp); itemKeys.forEach(key => { const item = resp[key] itens.push({ id: key, nome: item.nome, marca: item.marca, valor: item.valor }); }) resolve(itens); }); }); } getItem(cod: String): Promise<Item> { return new Promise(resolve => { const db = firebase.database(); db.ref('items/' + cod).once('value').then(function(snapshot) { const resp = snapshot.val() ? snapshot.val() : undefined; let item: Item; if(resp) { item = { id: resp.id, nome: resp.nome, marca: resp.marca, valor: resp.valor } } resolve(item); }); }); } editaItem(id: String, nome: string, marca: string, valor: number): Promise <any> { let item = { nome: nome, marca: marca, valor: valor }; return new Promise(resolve => { const db = firebase.database(); db.ref('items/' + id).set(item); resolve(item); }); } deletaItem(id: String): Promise <any> { return new Promise( resolve => { const db = firebase.database(); db.ref('items/' + id).remove(); resolve(id); }); } adicionaItem(nome: string, marca: string, valor: number): Promise <any> { let item = { nome: nome, marca: marca, valor: valor }; return new Promise(resolve => { const db = firebase.database(); db.ref('items/').push(item); resolve(item) }); } }
0e70aa80a674c5fb254b1d869429fd94cac25131
TypeScript
mddr/taiga-ui
/projects/cdk/utils/math/clamp.ts
3.015625
3
import {tuiAssert} from '@taiga-ui/cdk/classes'; /** * Clamps a value between two inclusive limits * * @param value * @param min lower limit * @param max upper limit */ export function clamp(value: number, min: number, max: number): number { tuiAssert.assert(!isNaN(value)); tuiAssert.assert(!isNaN(min)); tuiAssert.assert(!isNaN(max)); tuiAssert.assert(max >= min); return Math.min(max, Math.max(min, value)); }
a7fdbd7077d509b3a009198134e0409f695c0dae
TypeScript
miguelbogota/presentup-me
/src/app/shared/pipes/md-to-html/md-to-html.pipe.ts
2.90625
3
import { Pipe, PipeTransform } from '@angular/core'; import { parse } from 'marked'; @Pipe({ name: 'mdToHtml' }) export class MdToHtmlPipe implements PipeTransform { transform(value: string): string { /** * Firestore sanitize the input send and converts to a string. * In order to have a new line in the fronend the new lines '\\n' * will be converted to '_\\n' to change it with pipe and have them * again without having any conflict with '\\n' in the future. */ const newValue = this.replaceAll(value, '_\\n', '\n'); // With lib marked transform to md return parse(newValue); } /** * Function converts a string into a js string with ReGex. * @param value Value to convert. * @param search String to look in the value. * @param replace String value to replace the search with. */ private replaceAll(value: string, search: string, replace: string): string { return value.split(search).join(replace); } }
5713c09248f5a80d41925bed091bed0130db292e
TypeScript
superxp1412/ng2-series-workshop
/src/app/home/notes/note-creator/index.ts
2.671875
3
import {Component, Input, Output, EventEmitter} from "@angular/core" import {ColorPicker} from './color-picker' import { isEmpty } from 'lodash' @Component({ selector: 'note-creator', template: require('./note-creator.html'), styles: [require('./note-creator.css')], directives: [ColorPicker] }) export class NoteCreator{ newNote = { title: '', value: ''}; @Output() onCreateNote = new EventEmitter(); createNote() { const { title, value } = this.newNote; if( isEmpty(title) || isEmpty(value)){ return false; } this.onCreateNote.emit({title, value, color:this.backgroundColor}); console.log(this.newNote); return false; } backgroundColor = 'rgb(255, 255, 255)' changeBackground(color) { console.log("---") console.log(color) this.backgroundColor = color } }
b0aa7e02720f9ae70a2a3e4fe0d2213c2c135545
TypeScript
yutiansut/tzsq
/src/F/lastNumber.ts
3.171875
3
export const lastNumber = (arr: ArrayLike<number>) => { for (let i = arr.length - 1; i >= 0; i--) { if (isNaN(arr[i]) === false) { return arr[i] } } return NaN }
facff2ad1a09d0f15a3dcdf995765713feaf0630
TypeScript
observerzy/blog-app
/src/common/httpFetch.ts
2.921875
3
//返参可以有多种情况,此处是json // enum ContentType { // json = "application/json;charset=UTF-8", // formData = "multipart/form-data;charset=UTF-8" // } interface Header { 'Content-Type'?: string; [propName: string]: any; //索引签名 } interface Request { method: 'POST' | 'GET'; headers: Header; body: any; } interface HttpFetch { postFetch<R>(url: string, params: FormData): Promise<R>; } class HttpRequest implements HttpFetch { public postFetch<R>(url: string, params: FormData): Promise<R> { let options: Request = { method: 'POST', headers: {}, body: params }; url = `/api${url}?app_login_token=${localStorage.getItem( 'app_login_token' )}`; return fetch(url, options) .then(resp => { //服务错误400、500 if (!resp.ok) { throw new Error('保存失败'); } return resp.json(); }) .then(data => { //参数错误 if (data.header.retCode === '1') { throw new Error(data.header.errotMsg || '保存失败'); } return data; }); } } export default new HttpRequest();
be31c7ac91cd4eed69419d42099fb1b933529f2b
TypeScript
whpac/testina
/frontend/ts/components/survey_lists/no_surveys.ts
2.53125
3
import UserLoader from '../../entities/loaders/userloader'; import Component from '../basic/component'; export default class NoSurveys extends Component<'create-first-survey'> { public constructor(hidden: boolean = false) { super(); this.Element.classList.add('empty-placeholder'); if(hidden) this.Element.style.display = 'none'; let img = document.createElement('img'); img.src = 'images/empty_box.svg'; this.AppendChild(img); let em = document.createElement('em'); this.AppendChild(em); em.textContent = 'Nie stworzyłeś jeszcze żadnych ankiet'; (async () => em.textContent = 'Nie stworzył' + ((await UserLoader.GetCurrent())?.IsFemale() ? 'a' : 'e') + 'ś jeszcze żadnych ankiet')(); let span = document.createElement('span'); this.AppendChild(span); span.textContent = 'W tym miejscu będą się wyświetlały wszystkie ankiety, które utworzysz.'; span.appendChild(document.createElement('br')); let create_first = document.createElement('a'); span.appendChild(create_first); create_first.href = 'javascript:void(0)'; create_first.textContent = 'Utwórz swoją pierwszą ankietę'; create_first.addEventListener('click', (() => this.FireEvent('create-first-survey')).bind(this)); } }
778c350b2b841553b28b52fb5b4017ae9873c5f5
TypeScript
hsjoberg/blixt-wallet
/src/storage/database/db-utils.web.ts
2.546875
3
import { SqlJs } from "sql.js/module"; export const query = async (db: SqlJs.Database, sql: string, params: any[]) => { try { return await db.exec(sql, params); } catch (e) { if (typeof e === "string") { throw new Error(e); } throw e; } }; /** * @returns number Insert ID */ export const queryInsert = async (db: SqlJs.Database, sql: string, params: any[]): Promise<number> => { try { await query(db, sql, params); const r = await query(db, "SELECT last_insert_rowid() AS id", []); return r[0].values[0][0] as number; // TODO } catch (e) { if (typeof e === "string") { throw new Error(e); } throw e; } }; export const queryMulti = async <T>(db: SqlJs.Database, sql: string, params: any[] = []): Promise<T[]> => { try { const r = await query(db, sql, params); return convertToKeyValue(r[0]) as T[]; } catch (e) { if (typeof e === "string") { throw new Error(e); } throw e; } }; export const querySingle = async <T>(db: SqlJs.Database, sql: string, params: any[]): Promise<T | null> => { try { const r = await query(db, sql, params); if (r[0]) { return convertToKeyValue(r)[0] as T; } return null; } catch (e) { if (typeof e === "string") { throw new Error(e); } throw e; } }; // https://github.com/sql-js/sql.js/issues/84#issuecomment-155982147 function convertToKeyValue(query: any) { query = query ?? []; var queryObjects = []; var keys = query.columns; var values = query.values; for(var i = 0; i < values.length; i++) { var valueObject: any = {}; for(var j = 0; j < keys.length; j++){ valueObject[keys[j]] = values[i][j]; } queryObjects.push(valueObject); } return queryObjects; }
18516825e63bfa4402dabc60970d45efcdea6b36
TypeScript
josedaesbar/School-Management-System
/packages/web_application/src/styles/image.ts
2.578125
3
export enum ImageShape { NORMAL = '5px', CIRCULAR = '50%' } export type ImageShapeTypes = 'normal' |'circular';
28dc25a48cb422e56adb4c2bf4533665f61baf17
TypeScript
furkleindustries/sound-manager
/src/Sound/Sound.ts
2.5625
3
import { BaseNode, } from '../Node/BaseNode'; import { getFadeVolume, } from '../Fade/getFadeVolume'; import { getFrozenObject, } from '../functions/getFrozenObject'; import { IFade, } from '../Fade/IFade'; import { IPlaySoundOptions, } from './IPlaySoundOptions'; import { ISound, } from './ISound'; import { ISoundOptions, } from './ISoundOptions'; import { NodeTypes, } from '../enums/NodeTypes'; import { PanelRegisterableNodeMixin, } from '../Node/PanelRegisterableNodeMixin'; import { playAudioSource, } from './playAudioSource'; import { scheduleHtmlAudioFades, } from '../Fade/scheduleHtmlAudioFades'; import { strings, } from './Sound.strings'; import { TaggableNodeMixin, } from '../Node/TaggableNodeMixin'; import { assert, assertValid, } from 'ts-assertions'; export class Sound extends PanelRegisterableNodeMixin( TaggableNodeMixin( BaseNode )) implements ISound { get type(): NodeTypes.Sound { return NodeTypes.Sound; } private __playing = false; private __isStopping = false; private __startedTime = 0; private __pausedTime = 0; private __fadeStartTime = 0; private __fadeStopTime = 0; private __promise: Promise<void> | null = null; private __loop = false; // Tracks how many times the song has looped this play session. private __loopIterationCount = 0; // // Do not initialize. `false` is still a valid override value. private __loopOverride?: boolean; // private __fade: IFade | null = null; private __fadeOnLoops = true; private __fadeOverride?: IFade; private __audioElement: HTMLAudioElement | null = null; private __resolveOnEnd: ((value?: void | PromiseLike<void> | undefined) => void) | undefined = undefined; private __rejectOnError?: (err: string | Error) => Error; /* istanbul ignore next */ /* @ts-ignore */ public getManagerVolume: () => number = () => 1; /* istanbul ignore next */ public getGroupVolume: () => number = () => 1; constructor(options: ISoundOptions) { super({ ...options }); assert(options, strings.CTOR_OPTIONS_INVALID); const { audioElement, fade, fadeOnLoops, getManagerVolume, loop, trackPosition, } = options; this.__audioElement = assertValid<HTMLAudioElement>( audioElement, strings.CTOR_AUDIO_ELEMENT_INVALID, ); /* Needed to calculate volume for HTML5 audio. */ this.getManagerVolume = assertValid<() => number>( getManagerVolume, strings.CTOR_GET_MANAGER_VOLUME_INVALID, (aa) => typeof aa === 'function', ); this.__initializeArgumentProperties({ fade, fadeOnLoops, loop, trackPosition, }); }; private readonly __initializeArgumentProperties = ({ fade, fadeOnLoops, loop, trackPosition, }: { fade: IFade | undefined, fadeOnLoops: boolean | undefined, loop: boolean | undefined, trackPosition: number | undefined, }) => { if (fade) { this.setFade(fade); } if (typeof fadeOnLoops === 'boolean') { this.__fadeOnLoops = fadeOnLoops; } if (typeof loop === 'boolean') { this.setLoop(loop); } if (trackPosition && trackPosition > 0) { this.setTrackPosition(trackPosition); } } public readonly setVolume = (value: number) => { super.setVolume(value); this.updateAudioElementVolume(); return this; }; public readonly getTrackPosition = () => { if (this.isPlaying()) { return assertValid<HTMLAudioElement>( this.__audioElement, strings.GET_TRACK_POSITION_AUDIO_ELEMENT_INVALID, ).currentTime * 1000; } return this.__pausedTime; }; // Must be milliseconds. public readonly setTrackPosition = (milliseconds: number) => { this.__startedTime = milliseconds / 1000; assertValid<HTMLAudioElement>( this.__audioElement, strings.SET_TRACK_POSITION_AUDIO_ELEMENT_INVALID, ).currentTime = this.__startedTime; return this; }; // Returned in milliseconds. public readonly getDuration = () => { return assertValid<HTMLAudioElement>( this.__audioElement, strings.GET_DURATION_AUDIO_ELEMENT_INVALID, ).duration * 1000; }; public readonly isPlaying = () => Boolean(this.__playing); public readonly getLoop = () => typeof this.__loopOverride === 'boolean' ? this.__loopOverride : this.__loop; public readonly setLoop = (loop: boolean) => { this.__loop = Boolean(loop); return this; }; public readonly getFade = () => this.__fadeOverride || this.__fade; public readonly setFade = (fade: IFade | null) => { this.__fade = fade === null ? fade : getFrozenObject({ easingCurve: getFrozenObject({ ...fade.easingCurve, }), length: getFrozenObject({ ...fade.length, }), }); return this; }; public readonly play = ({ fadeOnLoops, fadeOverride, loopOverride, }: Partial<IPlaySoundOptions> = { fadeOnLoops: false, fadeOverride: null, loopOverride: undefined, }) => { try { if (this.isPlaying()) { return assertValid<Promise<void>>(this.__promise); } this.__fadeStartTime = this.getTrackPosition(); this.__updateSoundTimes(); this.__initializeForPlay({ fadeOnLoops, fadeOverride, loopOverride, }); playAudioSource(this, this.__audioElement); /* Reset the paused time. */ this.__pausedTime = 0; /* Ensure the sound knows it's playing. */ this.__playing = true; /* Emit the promise that was either just generated or emitted on previous * unfinished plays. */ return assertValid<Promise<void>>(this.__promise); } catch (err) { if (typeof this.__rejectOnError === 'function') { this.__rejectOnError(err); } } return this.__promise as any; }; /* Regenerates the source node, generates the promise if it does not already * exist, registers events, etc. */ private readonly __initializeForPlay = ({ fadeOnLoops, fadeOverride, loopOverride, }: Partial<IPlaySoundOptions> = {}) => { /* Sets the override properties e.g. if this sound is part of a * playlist, or the changes occurred through play options. */ if (typeof fadeOnLoops === 'boolean') { this.__fadeOnLoops = fadeOnLoops; } if (fadeOverride) { this.__fadeOverride = getFrozenObject({ easingCurve: getFrozenObject({ ...fadeOverride.easingCurve, }), length: getFrozenObject({ ...fadeOverride.length, }), }); } if (typeof loopOverride === 'boolean') { this.__loopOverride = loopOverride; } const fade = this.getFade(); const audioElement = this.__audioElement; if (fade) { /* Update the audio element volume on every tick, including fade * volume. */ /* istanbul ignore next */ this.__initializeFadeForPlay(this.__audioElement); } this.updateAudioElementVolume(); /* If a promise is already on the Sound, it must be respected, and * a new one should not be constructed. */ if (!this.__promise) { this.__initializePromiseForPlay(); } this.__initializeEventsForPlay(audioElement); }; private readonly __updateSoundTimes = () => { assertValid<HTMLAudioElement>( this.__audioElement, ).currentTime = this.getTrackPosition() / 1000; }; private readonly __initializeFadeForPlay = ( audioElement?: HTMLAudioElement | null, ) => { scheduleHtmlAudioFades( assertValid<HTMLAudioElement>(audioElement), this.updateAudioElementVolume, ); }; private readonly __initializeStartStopResolver = ( resolve: (value?: void | PromiseLike<void> | undefined) => void, ) => ( this.__resolveOnEnd = resolve ); private readonly __initializeRejector = (reject: Function) => ( this.__rejectOnError = (message?: string | Error) => reject( message || 'The sound was stopped, probably by a user-created script.' ) ); private readonly __initializePromiseForPlay = () => ( this.__promise = new Promise((resolve, reject) => { /* Allows the same promise to be used across pauses. */ this.__initializeStartStopResolver(resolve); /* Allow the promise to be rejected if the sound fails. */ this.__initializeRejector(reject); }) ); private readonly __initializeEventsForPlay = ( audioElement?: HTMLAudioElement | null, ) => { const source = assertValid<HTMLAudioElement>( audioElement, 'The audio element was not found in Sound.__initializeEventsForPlay.', ); /* Register the ended export function to fire when the audio source emits the * 'ended' event. */ const endHandler = this.__getEndEventHandler( source, ); source.addEventListener('ended', endHandler); // Pass the handler back up. return endHandler; }; private readonly __getEndEventHandler = ( source: AudioBufferSourceNode | HTMLAudioElement, ) => { const ended = (): Promise<void> => { this.__isStopping = true; // Remove the 'ended' event listener. source.removeEventListener('ended', ended); // If the track ended, and loop is true, manually reset it to the // beginning and keep playing. Increment the loop counter as well. this.pause(); this.__isStopping = false; if (this.getLoop()) { this.__loopIterationCount += 1; return this.play({ fadeOnLoops: this.__fadeOnLoops, fadeOverride: this.__fadeOverride, loopOverride: this.__loopOverride, }); } return this.stop(); }; return ended; }; public readonly pause = () => { /* Must be executed before __playing = false. */ this.__fadeStartTime = 0; this.__fadeStopTime = 0; this.__startedTime = 0; if (!this.__isStopping) { this.__pausedTime = this.getTrackPosition(); } try { if (this.isPlaying()) { /* Must be executed after __pausedTime = ... */ assertValid<HTMLAudioElement>(this.__audioElement).pause(); } /* Must be executed after __pausedTime = ... and this.getPlaying(). */ this.__playing = false; } catch (err) { if (typeof this.__rejectOnError === 'function') { this.__rejectOnError(err); } else { throw err; } } return this; }; public readonly stop = (hard = false) => { this.__isStopping = true; this.__loopIterationCount = 0; this.__fadeStopTime = this.getTrackPosition(); this.__initializeFadeForPlay(this.__audioElement); if (hard) { // Delete the rejector. delete this.__rejectOnError; // Delete the resolver. delete this.__resolveOnEnd; } else { const delay = this.getFade()?.length.out || 0; setTimeout(() => { this.pause(); this.setTrackPosition(0); if (typeof this.__resolveOnEnd === 'function') { this.__resolveOnEnd(); } else { Promise.resolve(this.__promise); } this.__isStopping = false; // Delete the rejector. delete this.__rejectOnError; // Delete the resolver. delete this.__resolveOnEnd; }, delay + 50); } return this.__promise!; }; public readonly rewind = (milliseconds: number) => { this.setTrackPosition(this.getTrackPosition() - milliseconds); return this; }; public readonly fastForward = (milliseconds: number) => { this.setTrackPosition(this.getTrackPosition() + milliseconds); return this; }; public readonly updateAudioElementVolume = () => { /* Set the audio element volume to the product of manager, group, and * fade, and sound volumes. */ const managerVolume = this.getManagerVolume(); const groupVolume = this.getGroupVolume(); const soundVolume = this.getVolume(); const fadeVolume = this.getFadeVolume(); const volProduct = managerVolume * groupVolume * soundVolume * fadeVolume; const boundedVol = Math.min(1, Math.max(0, volProduct)); assertValid<HTMLAudioElement>(this.__audioElement).volume = boundedVol; return this; }; // This is a ratio, so it doesn't need to know anything about the sound's // underlying volume(s). This ratio is computed solely from arguments. public readonly getFadeVolume = () => { const fade = this.getFade(); if (fade) { return getFadeVolume({ fade, duration: this.getDuration(), fadeOnLoops: this.__fadeOnLoops, loop: Boolean(this.__loopOverride), isStopping: this.__isStopping, loopIterationCount: this.__loopIterationCount, startingTime: this.__fadeStartTime, stoppingTime: this.__fadeStopTime, time: this.getTrackPosition(), }); } return 1; }; }
cd4b02f382783bb0637f31fb2a3b12b9361a3de3
TypeScript
SamTomashi/marines-core-angular
/src/app/login/login.component.ts
2.59375
3
import { Component, OnInit, OnDestroy } from '@angular/core'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit, OnDestroy { user: string = ""; username!: any; enabled = true; inputType = "password"; val: string = "Sam Tomashi" color!:string ; constructor() { } ngOnInit(): void { console.log("initializing login component") } ngOnDestroy(){ console.log("destroying login component") } getUsername(event: any){ this.enabled = false; console.log(this.username); } enableOrDisable(){ this.enabled = !this.enabled } isChecked = true; showPassword(){ // this.inputType = "text"; this.isChecked = !this.isChecked; console.log("Sam"); } looseFocus(event: any){ this.color = event.target.value; } }
6598eeed0523406bef4ca0f2d2236d6457eb262a
TypeScript
QoVoQ/nestjs-blog
/src/modules/auth/jwt-optional.guard.ts
2.515625
3
import { Injectable, CanActivate, ExecutionContext, HttpException, HttpStatus, } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { jwtFromRequest } from './constants'; import { JwtPayload } from './auth.interface'; import { UserService } from '../user/user.service'; import { UserEntity } from '../user/user.entity'; @Injectable() export class JwtOptionalGuard implements CanActivate { constructor( private readonly userService: UserService, private readonly jwtService: JwtService, ) {} async canActivate(ctx: ExecutionContext): Promise<boolean> { const request = ctx.switchToHttp().getRequest(); const token = jwtFromRequest(request); if (request.user && request.user instanceof UserEntity) { return true; } let userId; let user; if (typeof token === 'string') { try { userId = ((await this.jwtService.verifyAsync(token)) as JwtPayload) .userId; } catch { throw new HttpException( { errors: { guard: 'Invalid access token.' } }, HttpStatus.UNAUTHORIZED, ); } } if (typeof userId === 'number') { try { user = await this.userService.findById(userId); } catch { throw new HttpException( { errors: { guard: 'User not exist.' } }, HttpStatus.UNAUTHORIZED, ); } } if (user instanceof UserEntity) { request.user = user; } return true; } }
44d5fab484e9a7f5ab182433c6e35a2492198ef3
TypeScript
ji03mmy18/BackendTemplate
/src/service/eventRecord.ts
2.59375
3
// src/service/announcement.ts import { DeleteResult, getRepository, InsertResult, Repository, UpdateResult, } from 'typeorm'; import { eventRecord } from '@/entry'; import { filterObjectUndefined } from '@/utils'; export class eventRecordService { private static INSTANCE: eventRecordService; private eventRecordRepo: Repository<eventRecord>; public static init(): eventRecordService { if(this.INSTANCE === undefined) { this.INSTANCE = new eventRecordService(); } return this.INSTANCE; } public static getInstance(): eventRecordService { return this.INSTANCE; } constructor() { this.eventRecordRepo = getRepository(eventRecord); } public async getById(event_id: number): Promise<eventRecord> { const eventrecord: eventRecord | undefined = await this.eventRecordRepo.findOne({ id: event_id, }); if (eventrecord === undefined) { throw new Error(`No such eventRecord with event_id: ${event_id}`); } return eventrecord; } public async deleteById(event_id: number): Promise<boolean> { const result: DeleteResult = await this.eventRecordRepo.delete({ id: event_id, }); return Number(result.affected) > 0; } public async add(date: Date, person: string, content: string): Promise<boolean> { const result: InsertResult = await this.eventRecordRepo.insert({ date, person, content, }); return result.raw["insertId"] >= 1; } public async updateById( event_id: number, date?: Date, person?: string, content?: string, ): Promise<boolean> { const result: UpdateResult = await this.eventRecordRepo .createQueryBuilder() .update(eventRecord) .set(filterObjectUndefined({ date, person, content, })) .where('id = :event_id', { event_id }) .execute(); return result.raw["affectedRows"] >= 1; } }
c927f9e170c28dc9b9719b563f22a7fa5edba67c
TypeScript
kimrejstrom/dice-typescript
/spec/lexer/string-character-stream.spec.ts
3.21875
3
import * as Lexer from '../../src/lexer'; describe('StringCharacterStream', () => { const input = 'floor(4d6!!+5d10kl2/2+4)'; describe('constructor', () => { it('does not throw.', function () { expect(() => { const stream = new Lexer.StringCharacterStream(input); }).not.toThrow(); }); }); describe('currentCharacter', () => { it('starts as null', () => { const stream = new Lexer.StringCharacterStream('face'); expect(stream.getCurrentCharacter()).toEqual(null); }); it('returns the current character', () => { const stream = new Lexer.StringCharacterStream('face'); stream.getNextCharacter(); expect(stream.getCurrentCharacter()).toEqual('f'); expect(stream.getCurrentCharacter()).toEqual('f'); stream.getNextCharacter(); stream.getNextCharacter(); expect(stream.getCurrentCharacter()).toEqual('c'); }); it('returns null at the end.', () => { const stream = new Lexer.StringCharacterStream('face'); stream.getNextCharacter(); stream.getNextCharacter(); stream.getNextCharacter(); stream.getNextCharacter(); stream.getNextCharacter(); expect(stream.getCurrentCharacter()).toBeNull(); }); }); describe('getNextCharacter', () => { it('progresses through the characters, finishing with null.', () => { const stream = new Lexer.StringCharacterStream(input); expect(stream.getNextCharacter()).toEqual('f'); expect(stream.getNextCharacter()).toEqual('l'); expect(stream.getNextCharacter()).toEqual('o'); expect(stream.getNextCharacter()).toEqual('o'); expect(stream.getNextCharacter()).toEqual('r'); expect(stream.getNextCharacter()).toEqual('('); expect(stream.getNextCharacter()).toEqual('4'); expect(stream.getNextCharacter()).toEqual('d'); expect(stream.getNextCharacter()).toEqual('6'); expect(stream.getNextCharacter()).toEqual('!'); expect(stream.getNextCharacter()).toEqual('!'); expect(stream.getNextCharacter()).toEqual('+'); expect(stream.getNextCharacter()).toEqual('5'); expect(stream.getNextCharacter()).toEqual('d'); expect(stream.getNextCharacter()).toEqual('1'); expect(stream.getNextCharacter()).toEqual('0'); expect(stream.getNextCharacter()).toEqual('k'); expect(stream.getNextCharacter()).toEqual('l'); expect(stream.getNextCharacter()).toEqual('2'); expect(stream.getNextCharacter()).toEqual('/'); expect(stream.getNextCharacter()).toEqual('2'); expect(stream.getNextCharacter()).toEqual('+'); expect(stream.getNextCharacter()).toEqual('4'); expect(stream.getNextCharacter()).toEqual(')'); expect(stream.getNextCharacter()).toBeNull(); }); it('returns null when stream ends.', () => { const stream = new Lexer.StringCharacterStream('abc'); stream.getNextCharacter(); stream.getNextCharacter(); stream.getNextCharacter(); for (let x = 0; x < 10; x++) { expect(stream.getNextCharacter()).toBeNull(); } }); }); describe('peekNextCharacter', () => { it('gives next character without cycling through.', () => { const stream = new Lexer.StringCharacterStream(input); stream.getNextCharacter(); expect(stream.peekNextCharacter()).toEqual('l'); expect(stream.peekNextCharacter()).toEqual('l'); stream.getNextCharacter(); expect(stream.peekNextCharacter()).toEqual('o'); stream.getNextCharacter(); stream.getNextCharacter(); expect(stream.peekNextCharacter()).toEqual('r'); }); }); });
e7d5f856d79daeb8c938a15988515ffb3443b3ee
TypeScript
meghoshpritam/courses-server
/src/middleware/checkRole.ts
2.578125
3
import { Request, Response, NextFunction } from 'express'; export const checkRole = (roles: string[] = []) => { return async (req: Request, res: Response, next: NextFunction) => { let authenticate = false; roles.forEach((role) => { if (role === res.locals.role) { authenticate = true; } }); if (!authenticate) { res.status(401).send(); return; } next(); }; };
2f5a8f57edad395b97482af549a5c3530898b838
TypeScript
IVjs/IVjs
/src/lib/command-engine/create-engine.ts
2.53125
3
import { IvCommandEngine } from './command-engine'; import { CommandRunner } from './command-runner'; import { switchFactory } from './switch'; import { Omit } from '../../types'; export function createEngine(engineConstructorInput: CommandEngine.ctor, ...functionFactories) { const { settings, nodes, variables, commandRunnerClass } = engineConstructorInput; const engine = new IvCommandEngine(settings, nodes, commandRunnerClass, variables); functionFactories.forEach(factory => { engine.registerTargetFunction(factory); }); return engine; } export function createBaseEngine( engineConstructorInput: Omit<CommandEngine.ctor, 'commandRunnerClass'>, ...functionFactories ) { const { settings, nodes, variables } = engineConstructorInput; const engine = createEngine({ settings, nodes, variables, commandRunnerClass: CommandRunner }, ...functionFactories); engine.registerTargetFunction(switchFactory); // This powers the if statements that are necessary for base-node return engine; }
1a08d5b40aec7dd9bd2b87b5832747afa76d88bb
TypeScript
sshyam-gupta/dynamic-components-rn
/src/lib/common.ts
2.828125
3
import _ from 'lodash'; import {Platform, Dimensions} from 'react-native'; export const isWeb = Platform.OS === 'web'; export const isAndroid = Platform.OS === 'android'; export const isIOS = Platform.OS === 'ios'; export const isIphoneX = () => { const {height, width} = Dimensions.get('window'); if (Platform.OS === 'ios' && !Platform.isPad && !Platform.isTVOS) { return ( (width === 375 && height === 812) || // Iphone X (width === 414 && height === 896) // IPhone XS ); } return false; }; export const Capitalize = (text: string): string => { return `${text.charAt(0).toUpperCase()}${text.substr(1).toLowerCase()}`; }; export const extractNumber = (text?: string): number => { const matches = text && text.match(/\d+$/); if (matches) { return parseInt(matches[0], 10); } else { return -1; } }; export const hexToRgb = ( hex: string, ): {r: number; g: number; b: number} | null => { // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF") const shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, (r, g, b) => { return r + r + g + g + b + b; }); const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); return result ? { r: parseInt(result[1], 16), g: parseInt(result[2], 16), b: parseInt(result[3], 16), } : null; }; export const deleteKeyForFalsyValues = (data: any) => { return _.pickBy(data, _.identity); }; export const pushItemInArray = (item?: any, array: any[] = []) => { return _.concat(array, item); }; export const generateRankThreadObj = ( widgetType: string, rank?: string | number, ...props: any ) => { return rank ? { ...props, widgetType, rank, } : undefined; }; export const formatToCurrency = ( value: number, optionsOverride?: Intl.NumberFormatOptions, ) => { if (value >= 0) { return Number(value).toLocaleString('en-IN', { style: 'currency', currency: 'INR', maximumFractionDigits: 0, minimumFractionDigits: 0, ...optionsOverride, }); } return ''; };
80193bba96ca7e3b7e14bacc9e9c92886e9d9c36
TypeScript
Rocking-horse/TrelloWIPLimits-exclusions
/src/ts/trello-list.ts
2.734375
3
/** Represents an individual list in Trello. Observes the list for changes. */ class TrelloList { public readonly listNode: Element; private listContentNode: Element; private listObserver: MutationObserver; private listHeaderNode: Element; private listHeaderObserver: MutationObserver; private minCards: number = -1; private maxCards: number = Number.POSITIVE_INFINITY; private exepColors: string = null; // modif. by Max private wipLimitPattern: RegExp = /\[(\d+)(?:-(\d+))?( +\w+)?\]/; // modif. by Max constructor(listNode: Element) { this.listNode = listNode; this.listObserver = new MutationObserver(this.observeListChanges); this.listObserver.observe(this.listNode, { childList: true, subtree: true }); this.listHeaderNode = this.listNode.querySelector("h2.list-header-name-assist"); this.listHeaderObserver = new MutationObserver(this.observeListHeaderChanges); this.listHeaderObserver.observe(this.listHeaderNode, { childList: true }); this.listContentNode = this.listNode.querySelector(".js-list-content"); this.processListTitle(); } /** Applies the card limit via CSS */ public applyCardLimit() { const classList = this.listContentNode.classList; classList.remove("over-limit"); classList.remove("at-limit"); // exception cards by Max let colorName=null; let exCardCount=0; if (this.exepColors !=null){ for (let i=0; i<this.exepColors.length; i++){ switch (this.exepColors.substr(i,1)){ case "g": colorName = "green"; break; case "y": colorName = "yellow"; break; case "r": colorName = "red"; break; case "b": colorName = "blue"; break; case "s": colorName = "sky"; break; case "l": colorName = "lime"; break; case "p": colorName = "pink"; break; } if (colorName != null){ exCardCount= exCardCount + this.listContentNode.querySelectorAll("span.card-label-"+ colorName).length; } } } const cardCountList = this.listContentNode.querySelectorAll("a.list-card").length; const cardCount=cardCountList - exCardCount; if (cardCount > this.maxCards || cardCount < this.minCards) { classList.add("over-limit"); } if (cardCount === this.maxCards || cardCount === this.minCards) { classList.add("at-limit"); } } /** Determines whether the provided element represents a Trello Card */ private isListCard(element: Element): boolean { return element.classList.contains("list-card"); } // Mod. by Max /** Determines whether the provided element represents a Card Label */ private isLabelCard(element: Element): boolean { return element.classList.contains("card-label"); } /** MutationObserver callback for changes to the list title */ private observeListHeaderChanges = (mutations: MutationRecord[]) => { this.processListTitle(); this.applyCardLimit(); } // Mod. by Max /** MutationObserver callback for changes to the list */ private observeListChanges = (mutations: MutationRecord[]) => { let cardAddedOrRemoved = false; let labelAddedOrRemoved = false; for (const mutation of mutations) { for (const entry of [].slice.call(mutation.addedNodes)) { if (entry instanceof Element && this.isListCard(entry)) { cardAddedOrRemoved = true; break; } } for (const entry of [].slice.call(mutation.removedNodes)) { if (entry instanceof Element && this.isListCard(entry)) { cardAddedOrRemoved = true; break; } } // card-label for (const entry of [].slice.call(mutation.addedNodes)) { if (entry instanceof Element && this.isLabelCard(entry)) { labelAddedOrRemoved = true; break; } } for (const entry of [].slice.call(mutation.removedNodes)) { if (entry instanceof Element && this.isLabelCard(entry)) { labelAddedOrRemoved = true; break; } } } if (cardAddedOrRemoved || labelAddedOrRemoved) { this.applyCardLimit(); } } /** Parse the list title text and attempts to extract the min/max card count */ // modif. by Max private parseListTitle(listTitle: string): [number, number, string] { const matches = this.wipLimitPattern.exec(listTitle); if (!matches || matches.length !== 4) { return [-1, Number.POSITIVE_INFINITY, null]; } // ex. [1-6 #g] if (matches[1] && matches[2] && matches[3]) { return [Number(matches[1]), Number(matches[2]), String (matches[3])]; } // ex. [1 #g] else if (matches[1] && !matches[2] && matches[3]) { return [-1, Number(matches[1]), String (matches[3])]; } // ex. [1-6] else if (matches[1] && matches[2] && !matches[3]) { return [Number(matches[1]), Number(matches[2]), null]; } //ex. [1] else { return [-1, Number(matches[1]), null]; } } private processListTitle() { // modif. by Max const listTitle = this.listHeaderNode.textContent; const limits = this.parseListTitle(listTitle); this.minCards = limits[0]; this.maxCards = limits[1]; if (limits[2]){ this.exepColors = limits[2].match(/\w+/)[0]; } else{ this.exepColors=null; } } }
271ae207ed1c25581e6bbca6b3ba744dc61918c9
TypeScript
edgarsit/cse416
/src/model/user.ts
2.609375
3
import type { Types } from 'mongoose'; import { hash, pre } from './RT-PROP'; import type { Description, Fields } from './util'; import { fields, ruprop } from './util'; @fields // TODO updates do not use this handler @pre<User>('save', async function userPreSave() { if (this.isModified('password')) { this.password = await hash(this.password); } }) export class User { declare static fields: Description<Fields<User>> declare public __t: 'GPD' | 'Student'; declare public _id: Types.ObjectId; @ruprop() public firstName!: string; @ruprop() public lastName!: string; @ruprop({ unique: true }) public email!: string; @ruprop() public password!: string; } export class GPD extends User { declare public __t: 'GPD'; } @fields export class Student extends User { declare static fields: Description<Fields<Student>> declare public __t: 'Student'; @ruprop({ short: 'Dept' }) public department!: string @ruprop() public track!: string @ruprop() public entrySemester!: string @ruprop() public entryYear!: string @ruprop() public requirementVersionSemester!: string @ruprop() public requirementVersionYear!: string @ruprop({ short: 'Grad Sem' }) public graduationSemester!: string @ruprop({ short: 'Grad Year' }) public graduationYear!: string @ruprop({ default: false }) public graduated!: boolean @ruprop({ default: '' }) public comments!: string @ruprop({ unique: true }) public sbuId!: number }
45882450286bc35a0da719b9157ecbc02d64e7ea
TypeScript
ToonoW/autoDocstring
/src/extension.ts
2.65625
3
'use strict'; import * as vs from 'vscode'; import { AutoDocstring } from "./autodocstring"; export function activate(context: vs.ExtensionContext): void { console.log('autoDocstring has been activated'); context.subscriptions.push(vs.commands.registerCommand('extension.generateDocstring', () => { generateDocstring(); })); if (vs.workspace.getConfiguration("autoDocstring").get('generateDocstringOnEnter')) { context.subscriptions.push(vs.workspace.onDidChangeTextDocument(change_event => { const editor = vs.window.activeTextEditor; if (editor.document !== change_event.document) return; if (change_event.contentChanges[0].text.replace(/ |\t|\r/g, "") === "\n" && change_event.contentChanges[0].rangeLength === 0) { const position: vs.Position = change_event.contentChanges[0].range.end; const range: vs.Range = new vs.Range(position.translate(0, -3), position); if (editor.document.getText(range) === '"""') { // Delete the opening quotes and the new line deleteRange(range); deleteLine(position.line + 1); generateDocstring(); } } })); } } export function deactivate() { } function deleteRange(range: vs.Range) { const editor = vs.window.activeTextEditor; const ws_edit = new vs.WorkspaceEdit(); ws_edit.delete(editor.document.uri, range) vs.workspace.applyEdit(ws_edit); } function deleteLine(line_num: number) { const editor = vs.window.activeTextEditor; const line = editor.document.lineAt(line_num); const ws_edit = new vs.WorkspaceEdit(); ws_edit.delete(editor.document.uri, line.rangeIncludingLineBreak) vs.workspace.applyEdit(ws_edit); } function generateDocstring() { var editor = vs.window.activeTextEditor; let document = editor.document; let position = editor.selection.active; let auto_docstring = new AutoDocstring(); let docstring_snippet: vs.SnippetString = auto_docstring.getDocstring(document, position); editor.insertSnippet(docstring_snippet, position) console.log('Docstring inserted'); }
32d4107fa476e9566fd86d307f69e774296720e1
TypeScript
powerpuffpenguin/jsgenerate_grpc
/jsgenerate/src/helper.ts
2.8125
3
import { join, sep } from "path" export class Exclude { private set_: Set<string> constructor( public readonly prefix?: Array<string>, public readonly suffix?: Array<string>, exclude?: Array<string>, ) { if (exclude) { const set = new Set<string>() for (let i = 0; i < exclude.length; i++) { set.add(exclude[i]) } this.set_ = set } } check(str: string): boolean { if (this.set_) { if (this.set_.has(str)) { return true } } if (this.prefix) { for (let i = 0; i < this.prefix.length; i++) { const element = this.prefix[i] if (str.startsWith(element)) { return true } } } if (this.suffix) { for (let i = 0; i < this.suffix.length; i++) { const element = this.suffix[i]; if (str.endsWith(element)) { return true } } } return false } } export class NameService { private rename_ = new Map<string, string>() constructor(public readonly output: string, public readonly uuid: string, public readonly exclude: Exclude, ) { } rename(dst: string, src: string, ...prefix: Array<string>) { if (prefix && prefix.length > 0) { this.rename_.set(join(join(...prefix), src), join(join(...prefix), dst)) } else { this.rename_.set(src, dst) } return this } checkExclude(name: string): boolean { if (this.exclude) { if (name.endsWith('.art')) { name = name.substr(0, name.length - 4) } return this.exclude.check(name) } return false } getOutput(name: string): string { if (name.endsWith('.art')) { name = name.substr(0, name.length - 4) if (this.rename_.has(name)) { name = this.rename_.get(name) } } const prefix = `pb` + sep if (name.startsWith(prefix)) { name = join(`pb`, this.uuid, name.substring(prefix.length)) } return join(this.output, name) } isTemplate(name: string) { return name.endsWith('.art') } }
5bc0ef3432ce84f88747df1840397326a4364a5d
TypeScript
INSIDE-information-systems/api-sensorthing
/src/server/utils/getId.ts
2.96875
3
/** * getId. * * @copyright 2020-present Inrae * @author mario.adam@inrae.fr * */ /** * * @param input string or number search * @returns the bigint extract number */ export const getId = (input: string | number): bigint | undefined => { try { return typeof input == "string" ? BigInt(input.match(/[0-9]/g)?.join("")) : BigInt(input); } catch (error) { return undefined; } };
3e48cc01e30afab9d1ad2d61f690999bc14840f7
TypeScript
DanteDeRuwe/DamienExperience-Web
/src/app/models/registration.model.ts
2.828125
3
import { ShirtSize } from "../enums.model"; export interface RegistrationJson { registrationId: string, timeStamp: Date, routeId: string, orderedShirt: boolean, shirtSize: string, paid: boolean } export class Registration { constructor( private _registrationId: string, private _timeStamp: Date, private _routeId: string, private _orderedShirt: boolean, private _shirtSize: string, private _paid: boolean ) { } static fromJson(json: RegistrationJson) { var enumValue = (<any>ShirtSize)[json.shirtSize]; const registration = new Registration( json.registrationId, json.timeStamp, json.routeId, json.orderedShirt, enumValue, json.paid ) return registration; } toJson(): RegistrationJson { return { registrationId: this._registrationId, timeStamp: this._timeStamp, routeId: this._routeId, orderedShirt: this._orderedShirt, shirtSize: this._shirtSize, paid: this._paid }; } get paid(){ return this._paid; } get registrationId() { return this._registrationId; } get timeStamp() { return this._timeStamp; } get routeId() { return this._routeId; } get orderedShirt() { return this._orderedShirt; } get shirtSize() { return this._shirtSize; } }
bc77198db85ca8c65059d719193edcdb5116fc32
TypeScript
crimx/ext-saladict
/src/components/dictionaries/weblio/engine.ts
2.578125
3
import { fetchDirtyDOM } from '@/_helpers/fetch-dom' import { HTMLString, getInnerHTML, handleNoResult, handleNetWorkError, getOuterHTML, SearchFunction, GetSrcPageFunction, DictSearchResult, getText, removeChild } from '../helpers' export const getSrcPage: GetSrcPageFunction = text => { return `https://www.weblio.jp/content/${text}` } const HOST = 'https://www.weblio.jp' export type WeblioResult = Array<{ title: HTMLString def: HTMLString }> type WeblioSearchResult = DictSearchResult<WeblioResult> export const search: SearchFunction<WeblioResult> = ( text, config, profile, payload ) => { return fetchDirtyDOM( 'https://www.weblio.jp/content/' + encodeURIComponent(text.replace(/\s+/g, ' ')) ) .catch(handleNetWorkError) .then(handleDOM) } function handleDOM( doc: Document ): WeblioSearchResult | Promise<WeblioSearchResult> { const result: WeblioResult = [] const $titles = doc.querySelectorAll<HTMLAnchorElement>( '#cont>.pbarT .pbarTL>a' ) doc .querySelectorAll<HTMLDivElement>('#cont>.kijiWrp>.kiji') .forEach(($dict, i) => { const $title = $titles[i] if (!$title) { if (process.env.DEBUG) { console.error(`Dict Weblio: missing title`) } return } if ($title.title === '百科事典') { // too long return } result.push({ title: getOuterHTML(HOST, $title, { config: {} }), def: getInnerHTML(HOST, $dict, { config: {} }) }) }) if (result.length <= 0) { doc.querySelectorAll('.section-card .basic-card').forEach($card => { const title = getText($card, '.pbarT h2') if (title) { removeChild($card, '.pbarT') result.push({ title, def: getInnerHTML(HOST, $card, { config: {} }) }) } }) } return result.length > 0 ? { result } : handleNoResult() }
10193fb5a3eac3c932b2b5f90ffcd619e0776e0d
TypeScript
ahuounan/weather-app
/src/store/models/weather/transformers.ts
2.71875
3
import { OpenWeatherCurrent, OpenWeatherDaily, OpenWeatherHourly, OpenWeatherCommon, OpenWeatherOneCallResponse } from 'models/api/openWeatherApi'; import { WeatherCommon, Weather, WeatherDaily, WeatherHourly, WeatherCurrent } from 'models/weather'; const openWeatherToWeatherCommon = (data: OpenWeatherCommon): WeatherCommon => { return { time: data.dt * 1000, pressure: data.pressure, humidity: data.humidity, dewPoint: data.dew_point, clouds: data.clouds, uvi: data.uvi, visibility: data.visibility, windSpeed: data.wind_speed, windGust: data.wind_gust, windDeg: data.wind_deg, rain: data.rain && data.rain['1h'], snow: data.snow && data.snow['1h'], icon: data.weather[0].icon, description: data.weather[0].description }; }; const openWeatherCurrentToCurrent = (current: OpenWeatherCurrent): WeatherCurrent => { /* eslint-disable-next-line @typescript-eslint/camelcase */ const { sunrise, sunset, temp, feels_like, ...data } = current; return { sunrise: sunrise * 1000, sunset: sunset * 1000, temp, /* eslint-disable-next-line @typescript-eslint/camelcase */ feelsLike: feels_like, ...openWeatherToWeatherCommon(data) }; }; const openWeatherHourlyToData = (hourly: OpenWeatherHourly): WeatherHourly => { /* eslint-disable-next-line @typescript-eslint/camelcase */ const { temp, feels_like, ...data } = hourly; return { temp, /* eslint-disable-next-line @typescript-eslint/camelcase */ feelsLike: feels_like, ...openWeatherToWeatherCommon(data) }; }; const openWeatherDailyToData = (daily: OpenWeatherDaily): WeatherDaily => { /* eslint-disable-next-line @typescript-eslint/camelcase */ const { sunrise, sunset, temp, feels_like, ...data } = daily; return { sunrise: sunrise * 1000, sunset: sunset * 1000, tempMorn: temp.morn, tempDay: temp.day, tempEve: temp.eve, tempNight: temp.night, tempMin: temp.min, tempMax: temp.max, /* eslint-disable-next-line @typescript-eslint/camelcase */ feelsLikeMorn: feels_like.morn, /* eslint-disable-next-line @typescript-eslint/camelcase */ feelsLikeDay: feels_like.day, /* eslint-disable-next-line @typescript-eslint/camelcase */ feelsLikeEve: feels_like.eve, /* eslint-disable-next-line @typescript-eslint/camelcase */ feelsLikeNight: feels_like.night, ...openWeatherToWeatherCommon(data) }; }; const openWeatherOneCallResponseToWeather = (response: OpenWeatherOneCallResponse): Weather => { return { lat: response.lat, lng: response.lon, timezone: response.timezone, current: openWeatherCurrentToCurrent(response.current), hourly: response.hourly.map(openWeatherHourlyToData), daily: response.daily.map(openWeatherDailyToData) }; }; export const weatherTransformers = { openWeatherOneCallResponseToWeather };
6fb524172b573bf7cb10f67ef573571dfc4434d2
TypeScript
HOVOH/beacon-feed-service
/src/feed/GetFeedRequest.ts
2.515625
3
import { Transform } from 'class-transformer'; import { IsIn, IsOptional } from 'class-validator'; import { FeedEventType, FeedEventTypes } from './feed.service'; export class GetFeedRequest { @IsOptional() @Transform( ({ value }) => { return value ?.split(',') .map((string) => string.toUpperCase()) .filter((string) => FeedEventTypes.includes(string)); }, { toClassOnly: true }, ) types: FeedEventType[]; }
d7da65ebcead5e4507bf10558e9e367a00592275
TypeScript
prysmex/ember-scopes
/addon/utils/scope.ts
2.671875
3
import { assert } from '@ember/debug'; export type LocalScope = ( record: unknown, index: number, collection: Array<unknown> ) => boolean; export type RemoteScope = () => Record<string, unknown>; export interface IRemoteAndLocalScope { remote: RemoteScope; local: LocalScope; } export type Scope = ( owner: unknown, ...rest: Array<unknown> ) => IRemoteAndLocalScope | RemoteScope | LocalScope; export function scope<T>( _target: unknown, _key: string, descriptor: TypedPropertyDescriptor<T> ): TypedPropertyDescriptor<T> { const { value } = descriptor; assert( 'Must provide a function for a scope', value && typeof value === 'function' ); return descriptor; }
8816b48f2c46d10353423e7b43f0466adb087de4
TypeScript
Andrea-MariaDB/aws-s3-tools
/lib/api/move.ts
3.078125
3
import AWS, { S3 } from "aws-sdk"; import { deleteObject } from "./delete"; /** * Move S3 object from source bucket and key to destination * @param {string} sourceBucket - S3 bucket where the object is stored * @param {string} sourceKey - S3 key where the object is referenced * @param {string} destinationBucket - S3 destination bucket * @param {string} destinationKey - S3 destination key. */ export const moveObject = async ( sourceBucket: string, sourceKey: string, destinationBucket: string, destinationKey: string ): Promise<void> => { const s3: S3 = new AWS.S3({ apiVersion: "2006-03-01" }); await s3 .copyObject({ CopySource: `${sourceBucket}/${sourceKey}`, Bucket: destinationBucket, Key: destinationKey, }) .promise(); await deleteObject(sourceBucket, sourceKey); }; /** * Move a list of S3 objects from source bucket to destination * @param {string} sourceBucket - S3 bucket where the objects are stored * @param {string[]} sourceKeys - S3 keys where the objects are referenced * @param {string} destinationBucket - S3 destination bucket * @param {string[]} destinationKeys - S3 destination keys */ export const moveKeys = async ( sourceBucket: string, sourceKeys: string[], destinationBucket: string, destinationKeys: string[] ): Promise<void> => { if (!sourceKeys.length) { throw new Error("Key list length must be greater than zero"); } if (sourceKeys.length !== destinationKeys.length) { throw new Error("Key lists must have the same length"); } await Promise.all( sourceKeys.map((sourceKey: string, index: number) => moveObject( sourceBucket, sourceKey, destinationBucket, destinationKeys[index] ) ) ); };
b4f53d9e3ae62d011ab51ae9e664cb1426ba5f19
TypeScript
afuhge/TODOApp2
/backend/src/data.ts
2.84375
3
import {User} from './model/user'; import {Todo} from './model/todo'; let idGen = 10; export const id = () => ++idGen; const user1: User = { id: 1, firstName: 'Annika', lastName: 'Fuh', userName: 'annie', password: '12345', color: '#dddddd', eMail: 'a.fuh@blah.de', isAdmin: true, todos: [5, 6, 7, 8, 9, 10], }; const user2: User = { id: 2, firstName: 'Anni', lastName: 'Fu', userName: 'Annifu', password: '12345', color: '#d11001', eMail: 'a.fuh@blah.de', isAdmin: false, todos: [5, 10], }; const user3: User = { id: 3, firstName: 'Peter', lastName: 'Parker', userName: 'peterparker', password: '12345', color: '#06b6d4', eMail: 'a.fuh@blah.de', isAdmin: false, todos: [5, 6, 9], }; const user4: User = { id: 4, firstName: 'Alex', lastName: 'Ba', userName: 'Alex', password: '12345', color: '#404040', eMail: 'a.fuh@blah.de', isAdmin: false, todos: [5, 10], }; const todo2: Todo = { id: 6, name: '2) Clean dishes', deadline: '2021-08-27T22:00:00.000Z', creator: 3, assignees: [ 1, 3, ], isDone: false, order: 1, }; const todo1: Todo = { id: 5, name: '1) Clean dishes', deadline: '2021-08-24T22:00:00.000Z', creator: 1, assignees: [ 1, 2, 3, 4, ], isDone: false, order: 0, }; const todo3: Todo = { id: 7, name: '3) Cook dinner', deadline: '2021-08-25T22:00:00.000Z', creator: 1, assignees: [ 1, ], isDone: false, order: 2, }; const todo4: Todo = { id: 8, name: '4) Wash clothes', deadline: '2021-08-26T22:00:00.000Z', creator: 1, assignees: [ 1, ], isDone: false, order: 3, }; const todo5: Todo = { id: 9, name: '5) Clean dishes', deadline: '2021-08-29T22:00:00.000Z', creator: 1, assignees: [ 1, 2, 3, 4, ], isDone: false, order: 4, }; const todo6: Todo = { id: 10, name: '6) Clean dishes', deadline: '2021-08-28T22:00:00.000Z', creator: 1, assignees: [ 1, 2, 3, 4, ], isDone: false, order: 5, }; export const todos: Todo[] = [ todo1, todo2, todo3, todo4, todo5, todo6, ]; export const users: User[] = [ user1, user2, user3, user4, ];
5471e5a48a860234ada466d69ca4d60c7f425e7c
TypeScript
asesh/electron_update
/main.ts
2.515625
3
// Modules to control application life and create native browser window //import BrowserWindow = require('electron') import {app, BrowserWindow, autoUpdater, dialog} from "electron" // Keep a global reference of the window object, if you don't, the window will // be closed automatically when the JavaScript object is garbage collected. let mainWindow function createWindow () { // Create the browser window. mainWindow = new BrowserWindow({width: 800, height: 600}) //let child = new BrowserWindow({parent: mainWindow}) mainWindow.setMenuBarVisibility(false) mainWindow.show() console.log('User data directory: ' + app.getPath("userData")) console.log(app.getVersion()) console.log(process.versions.chrome) // Setup auto updater //autoUpdater. // const dialog_options = { // type: 'info', // buttons: ['Restart', 'Later'], // title: 'Application Update', // message: 'Can you see this message?', // detail: 'A new version has been downloaded. Restart the application to apply the updates' // } // dialog.showMessageBox(dialog_options) // Load the specified website mainWindow.loadFile('index.html') //mainWindow.loadURL('http://www.google.com') let contents = mainWindow.webContents console.log(contents) // Open the DevTools. // mainWindow.webContents.openDevTools() mainWindow.once('did-finish-load', () => { console.log('Web page has finished loading') }) // Emitted when the window is closed. mainWindow.on('closed', function () { // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. mainWindow = null }) // Emitted when the window loses focus mainWindow.on('blur', function() { console.log('Window lost focus') }) // Emitted when the window gains focus mainWindow.on('focus', function() { console.log('Window gained focus') }) // Emitted when the window is maximized mainWindow.on('maximize', function() { console.log('Window is maximized') }) // Emitted when the window is minimized mainWindow.on('minimize', function() { console.log('Window is minimized') }) // Emitted when the window is restored mainWindow.on('restore', function() { console.log('Window is restored') }) // Emitted whe the window is unmaximized mainWindow.on('unmaximize', function() { console.log('Window is unmaximized') }) } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.on('ready', createWindow) // Quit when all windows are closed. app.on('window-all-closed', function () { // On OS X it is common for applications and their menu bar // to stay active until the user quits explicitly with Cmd + Q if (process.platform !== 'darwin') { app.quit() } }) app.on('activate', function () { // On OS X it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (mainWindow === null) { createWindow() } }) // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here.
9fda4a60de88bf7769e4d2c64f22b888dabe054b
TypeScript
angleshe/leetcode
/src/longestPalindromeSubseq.ts
3.421875
3
function getPalindromeMaxLength( s: string, left: number, right: number, cache: Map<string, number> ): number { let res: number = 0; const key = `${left}-${right}`; if (left >= 0 && right < s.length) { if (cache.has(key)) { return cache.get(key)!; } if (s[left] === s[right]) { res = 2 + getPalindromeMaxLength(s, left - 1, right + 1, cache); } else { const len1 = getPalindromeMaxLength(s, left, right + 1, cache); const len2 = getPalindromeMaxLength(s, left - 1, right, cache); const len3 = getPalindromeMaxLength(s, left - 1, right + 1, cache); res = Math.max(len1, len2, len3); } } cache.set(key, res); return res; } export function longestPalindromeSubseq(s: string): number { let res: number = 0; const cache = new Map<string, number>(); for (let i = 0; i < s.length; i++) { res = Math.max( res, 1 + getPalindromeMaxLength(s, i - 1, i + 1, cache), getPalindromeMaxLength(s, i, i + 1, cache) ); } return res; }
6a6ba0c8e07c6a9ef9818384fa72993360bfd758
TypeScript
wangeditor-team/wangEditor
/packages/core/src/render/index.ts
2.671875
3
/** * @description formats entry * @author wangfupeng */ import { Element as SlateElement, Descendant } from 'slate' import { VNode } from 'snabbdom' import { IDomEditor } from '../editor/interface' // ------------------------------------ render style ------------------------------------ export type RenderStyleFnType = (node: Descendant, vnode: VNode) => VNode // 存储:处理文本样式的函数,如 b u color 等 export const RENDER_STYLE_HANDLER_LIST: RenderStyleFnType[] = [] /** * 注册处理文本样式的函数 * @param fn 处理文本样式的函数 */ export function registerStyleHandler(fn: RenderStyleFnType) { RENDER_STYLE_HANDLER_LIST.push(fn) } // ------------------------------------ render elem ------------------------------------ export type RenderElemFnType = ( elemNode: SlateElement, children: VNode[] | null, editor: IDomEditor ) => VNode // 注册 render element 配置 export const RENDER_ELEM_CONF: { [key: string]: RenderElemFnType // key 要和 node.type 对应 !!! } = {} export interface IRenderElemConf { type: string renderElem: RenderElemFnType } /** * 注册 render elem 函数 * @param conf { type, renderElem } ,type 即 node.type */ export function registerRenderElemConf(conf: IRenderElemConf) { const { type, renderElem } = conf const key = type || '' // 如果 key 重复了,就后者覆盖前者 RENDER_ELEM_CONF[key] = renderElem }
9cc865b09ba74d5e25fee0fc1db8e5e27d59f5ec
TypeScript
mtcairneyleeming/robot-web-interface
/src/routes/errors.ts
2.6875
3
export var init = function(app) { // catch 404 and forward to error handler app.use(function(req, res, next) { res.status(404); // respond with html page if (req.accepts('html')) { res.render('404', { url: req.url }); return; } // respond with json if (req.accepts('json')) { res.send({ error: 'Not found' }); return; } // default to plain-text. send() res.type('txt').send('Not found'); var err = new Error('Not Found'); next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('pages/status', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('pages/status', { message: err.message, error: {} }); }); };
6c0ddf7b0f6b46d659c7bd3e9dcc822d8571e742
TypeScript
ceoseo/velog-server
/src/cache.ts
2.546875
3
import Redis from 'ioredis'; class Cache { client: Redis.Redis | null = null; connect() { this.client = new Redis({ maxRetriesPerRequest: 3, host: process.env.REDIS_HOST || 'localhost', }); } remove(...keys: string[]) { if (!this.client) { this.connect(); } return this.client!.del(...keys); } async disconnect() { if (this.client) { await this.client.quit(); this.client = null; return; } return Promise.resolve(); } } const cache = new Cache(); cache.connect(); export default cache;
359eff5f538ac0c86e9564477af18e20ade90ad3
TypeScript
DavidBerryUK/CompanyResourceManager
/Client/src/components/interfaces/ComponentMetaDataInterfaces.ts
2.78125
3
export interface IComponentMetaData { componentName: string; componentDescription: string; } export default class ComponentMetaDataInterfaceGuards { public static doesSupportIComponentMetaData(classInstance: any): classInstance is IComponentMetaData { const doesUseInterface = classInstance.componentName !== undefined; return doesUseInterface; } }
165b3022cc9299eeb891fa6cfe1d90463f343c6b
TypeScript
kitsune7/revenge-of-the-pancakes
/src/flipPancakes/flipPancakes.ts
3.109375
3
function flipPancakes(s: string): number { const happyPancake = '+' const endsOnHappyPancake = s.charAt(s.length - 1) === happyPancake let flipCount = endsOnHappyPancake ? -1 : 0 let currentGroupType = null for (let i = 0; i < s.length; i++) { if (currentGroupType !== s.charAt(i)) { flipCount++ currentGroupType = s.charAt(i) } } return flipCount } export default flipPancakes
3759acf6422e8926b337adea72f497ce16d1a078
TypeScript
dannielsousa/udm_dev_web
/typescript/app2.ts
3.046875
3
import { Concessionaria } from './Concessionaria'; import { Carro } from './Carro'; import { Pessoa } from './Pessoa'; /*--- Criar Carros ---*/ let carroA = new Carro('dodge', 4); let carroB = new Carro('ferari', 4); let carroC = new Carro('veloster', 3); /*--- montar a lista de carros da concessionaria --*/ let listaDeCarros: Carro[] = [carroA, carroB, carroC]; let concessionaria = new Concessionaria('João Naves', listaDeCarros); /*--- Exibir a lista de carros ---*/ //console.log(concessionaria.mostrarListaDeCarros()); /* --- Comprar o carro --- */ let pessoa = new Pessoa('Danniel', 'veloster'); concessionaria.mostrarListaDeCarros().map( (carro: Carro) => { if (carro['modelo'] === pessoa.dizerCarroPreferido()) { pessoa.comprarCarro(carro); } }); console.log(pessoa.dizerCarroQueTem());
605fb59a807ad8182bb9fd3c9f27774dbe78d8ce
TypeScript
xh/hoist-react
/utils/js/Decorators.ts
2.984375
3
/* * This file belongs to Hoist, an application development toolkit * developed by Extremely Heavy Industries (www.xh.io | info@xh.io) * * Copyright © 2023 Extremely Heavy Industries Inc. */ import {XH} from '@xh/hoist/core'; import {debounce, isFunction} from 'lodash'; import {throwIf, getOrCreate, warnIf} from './LangUtils'; import {withDebug} from './LogUtils'; /** * Decorates a class method so that it is debounced by the specified duration. * Based on https://github.com/bvaughn/debounce-decorator. * * @param duration - milliseconds to debounce. */ export function debounced(duration: number) { return function (target, key, descriptor) { const baseFn = descriptor.value; throwIf(!isFunction(baseFn), '@debounced must be applied to a class method.'); return { ...descriptor, value: function () { // synthesize an inner debounced function to the instance (not the class) const fn = getOrCreate(this, '_xh_' + key, () => debounce(baseFn, duration)); fn.apply(this, arguments); } }; }; } /** * Modify a method or getter so that it will compute once lazily and then cache the results. * Not appropriate for methods that take arguments. Typically useful on immutable objects. */ export function computeOnce(target, key, descriptor) { const {value, get} = descriptor; throwIf( !isFunction(value) && !isFunction(get), '@computeOnce must be applied to a zero-argument class method or getter.' ); const isMethod = isFunction(value), baseFnName = isMethod ? 'value' : 'get', baseFn = isMethod ? value : get; return { ...descriptor, [baseFnName]: function () { return getOrCreate(this, '_xh_' + key, () => baseFn.call(this)); } }; } /** * Modify a method so that its execution is tracked and timed with a debug message. * @see withDebug */ export function logWithDebug(target, key, descriptor) { const {value} = descriptor; throwIf(!isFunction(value), '@logWithDebug must be applied to a class method.'); return { ...descriptor, value: function (...args) { return withDebug(key, () => value.apply(this, args), this); } }; } /** * Modify a member so that it is enumerable. Useful for getters, which default to enumerable = false */ export function enumerable(target, key, descriptor) { warnIf(descriptor.enumerable, `Unnecessary use of @enumerable: ${key} is already enumerable.`); return {...descriptor, enumerable: true}; } /** * Designate a method or getter as abstract so that it throws if it is called directly */ export function abstract(target, key, descriptor) { const {value, get} = descriptor; throwIf( !isFunction(value) && !isFunction(get), '@abstract must be applied to a class method or getter.' ); const isMethod = isFunction(value), baseFnName = isMethod ? 'value' : 'get'; return { ...descriptor, [baseFnName]: function () { throw XH.exception(`${key} must be implemented by ${this.constructor.name}`); } }; }
6cd0917c90664cbff24e6c1335930ef61b38f39d
TypeScript
linuxcarl/learn-typescript
/types-typescript/src/type-union.ts
3.875
4
export = {}; // string or number let idUser: number | string; idUser = 4; idUser = "3"; //Buscar username dado un ID function getUsernameById(id: number | string): Array<object> { const users: Array<Object> = [ { id: 1, user: "Carlos" }, { id: 2, user: "Enrique" }, { id: 3, user: "Tonny" }, { id: 4, user: "Maria" }, ]; return users.filter((u: Object) => Number(u.id) === Number(id)); } console.log(getUsernameById(idUser)); console.log(getUsernameById("1")); console.log(getUsernameById(2)); //################# //Alias de tipos: TS type NumberAndString = number | string; let idUser2: NumberAndString; idUser2 = "3"; type arrayReturn = Array<object>; //Buscar username dado un ID function getUsernameById2(id: NumberAndString): arrayReturn { const users: Array<Object> = [ { id: 1, user: "Carlos" }, { id: 2, user: "Enrique" }, { id: 3, user: "Tonny" }, { id: 4, user: "Maria" }, ]; return users.filter((u: Object) => Number(u.id) === Number(id)); } console.log(getUsernameById2(idUser)); console.log(getUsernameById2("1")); console.log(getUsernameById2(2)); //################# //Tipos Literales: TS //ejemplo imagenes de : 100x100, 300x300, 500x500 type SquareSize = '100x100' | '300x300' | '500x500'; //const smallPicture: SquareSize = '200x200';//error porque solo tenemos 3 opciones const smallPicture: SquareSize = '100x100'; const mediumPicture: SquareSize = '300x300'; console.log(mediumPicture, smallPicture);
b08c752ebd2e3ab98a6a20d94a6b605c41825b59
TypeScript
scottohara/tvmanager
/spec/public/mocks/program-model-mock.ts
2.625
3
import type { SerializedModel } from "~/models"; import type { SinonStub } from "sinon"; import sinon from "sinon"; const saveStub: SinonStub<unknown[], Promise<string | undefined>> = sinon.stub(), removeStub: SinonStub = sinon.stub(), listStub: SinonStub = sinon.stub(), findStub: SinonStub<string[], Promise<ProgramMock>> = sinon.stub(), countStub: SinonStub = sinon.stub(), removeAllStub: SinonStub<unknown[], Promise<string | undefined>> = sinon.stub(), fromJsonStub: SinonStub<[SerializedModel], ProgramMock> = sinon.stub(); let programs: ProgramMock[] = [], removeAllOk: boolean; export default class ProgramMock { public progressBarDisplay = ""; public programGroup = ""; public toJson: SinonStub; public setProgramName: SinonStub = sinon.stub(); public setEpisodeCount: SinonStub = sinon.stub(); public setWatchedCount: SinonStub = sinon.stub(); public setRecordedCount: SinonStub = sinon.stub(); public setExpectedCount: SinonStub = sinon.stub(); public constructor(public readonly id: string | null, public programName: string | null, public seriesCount = 0, public readonly episodeCount = 0, public readonly watchedCount = 0, public readonly recordedCount = 0, public readonly expectedCount = 0) { this.toJson = sinon.stub().returns({}); saveStub.resetHistory(); removeStub.reset(); } public static get list(): SinonStub<unknown[], Promise<ProgramMock[]>> { return listStub.returns(Promise.resolve(this.programs)); } public static get find(): SinonStub<string[], Promise<ProgramMock>> { return findStub.returns(Promise.resolve(new ProgramMock(String(findStub.args[0]), "test-program"))); } public static get count(): SinonStub<unknown[], Promise<number>> { return countStub.returns(Promise.resolve(1)); } public static get removeAll(): SinonStub<unknown[], Promise<string | undefined>> { if (!removeAllOk) { removeAllStub.returns(Promise.resolve("Force failed")); } return removeAllStub; } public static get fromJson(): SinonStub<[SerializedModel], ProgramMock> { return fromJsonStub.returns(new ProgramMock("", "")); } public static get programs(): ProgramMock[] { return programs; } public static set programs(items: ProgramMock[]) { programs = items; } public get save(): SinonStub<unknown[], Promise<string | undefined>> { return saveStub.returns(Promise.resolve("1")); } public get remove(): SinonStub<unknown[], Promise<void>> { return removeStub; } public static removeAllOk(): void { removeAllOk = true; } public static removeAllFail(): void { removeAllOk = false; } }
59cf30af17d1bfcc01ba15689238f1098dbb255c
TypeScript
openslice/io.openslice.tmf.web
/src/app/openApis/ServiceOrderingManagement/models/service-order-update.ts
2.671875
3
/* tslint:disable */ import { Note } from './note'; import { ServiceOrderItem } from './service-order-item'; import { ServiceOrderRelationship } from './service-order-relationship'; import { RelatedParty } from './related-party'; /** * Skipped properties: id,href,externalId,priority,state,orderDate,completionDate,orderItem */ export interface ServiceOrderUpdate { /** * Contact attached to the order to send back information regarding this order */ notificationContact?: string; /** * When sub-classing, this defines the super-class */ '@baseType'?: string; /** * When sub-classing, this defines the sub-class entity name */ '@type'?: string; /** * Used to categorize the order, useful for the OM system, such as: Broadband, TVOption */ category?: string; /** * A free-text description of the service order */ description?: string; /** * Expected delivery date amended by the provider */ expectedCompletionDate?: string; /** * Extra-information about the order; e.g. useful to add extra delivery information that could be useful for a human process */ note?: Array<Note>; /** * A URI to a JSON-Schema file that defines additional attributes and relationships */ '@schemaLocation'?: string; orderItem?: Array<ServiceOrderItem>; /** * A list of service orders related to this order (e.g. prerequisite, dependent on) */ orderRelationship?: Array<ServiceOrderRelationship>; /** * A list of parties which are involved in this order and the role they are playing */ relatedParty?: Array<RelatedParty>; /** * Requested delivery date from the requestors perspective */ requestedCompletionDate?: string; /** * Order start date wished by the requestor */ requestedStartDate?: string; /** * Date when the order was started for processing */ startDate?: string; state?: 'INITIAL' | 'ACKNOWLEDGED' | 'REJECTED' | 'PENDING' | 'HELD' | 'INPROGRESS' | 'CANCELLED' | 'COMPLETED' | 'FAILED' | 'PARTIAL'; }
c1eaa1a0933e4c0007be658f1339c3f4bfddf097
TypeScript
ankur-sardar/project-feedback-app
/client/src/reducers/employee.ts
3.484375
3
import Employee from '../models/employee'; import {ActionTypes} from '../actions/action'; import {Action} from '../actions/action'; // Define our State interface for the current reducer export interface State { employeeList: Employee[] } // Define our initialState export const initialState: State = { employeeList: [] // We don't have any Employee List at the start of the app } /* * Reducer takes 2 arguments * state: The state of the reducer. By default initialState ( if there was no state provided) * action: Action to be handled. Since we are in employeelist reducer, action type is Action defined in our actions/employees file. */ export function reducer(state: State = initialState, action: Action) { switch (action.type) { case ActionTypes.ADD_EMPLOYEE: { /* * We have autocompletion here * Typescript knows the action is type of AddEmployeeAction thanks to the ActionTypes enum * todo is type of Todo */ const employee = action.payload.employee console.log(employee); return { ...state, employeeList: [...state.employeeList, employee] // Add employee to employeeList array } } case ActionTypes.REMOVE_EMPLOYEE: { /* * This is the same as * const todoId = action.payload.todoId */ const { id } = action.payload; return { ...state, employeeList: state.employeeList.filter(employee => employee.id !== id) } } case ActionTypes.GET_EMPLOYEE_LIST: { /* * This is the same as * const todoId = action.payload.todoId */ console.log('in Action Payload'); console.log(action.payload); return { ...state, employeeList: action.payload.employeeList } } default: return state } }
f3b2265bd38b90806c5f1c424a25474a82857763
TypeScript
MinionsDave/Data-Structures-Algorithms-with-Javascript-exercise-answer
/src/chapter6-linked-list/doubly-linked-list.ts
3.3125
3
import { TwoWayNode } from "./two-way-node"; export class DoublyLinkedList<T> { head = new TwoWayNode<any>('head') currentNode = this.head find(item: T): TwoWayNode<T> { let currentNode = this.head while (currentNode.element !== item && currentNode.next) currentNode = currentNode.next return currentNode } insert(element: T, item: T) { const newNode = new TwoWayNode<T>(element) const current = this.find(item) newNode.next = current.next newNode.previous = current current.next = newNode } remove(element: T) { const currentNode = this.find(element) if (currentNode.next !== null) { currentNode.previous.next = currentNode.next currentNode.next.previous = currentNode.previous currentNode.next = null currentNode.previous = null } } findLast(): TwoWayNode<T> { let currentNode = this.head while (currentNode.next !== null) currentNode = currentNode.next return currentNode } display(): void { let currentNode = this.head while (currentNode.next !== null) { console.log(currentNode.next.element) currentNode = currentNode.next } } dispReverse() { let currentNode = this.head currentNode = this.findLast() while (currentNode.previous !== null) { console.log(currentNode.element) currentNode = currentNode.previous } } // 6.2 back(n = 1) { while (n > 0 && this.currentNode.element !== 'head') { this.currentNode = this.currentNode.previous n-- } } }
74195b512972f75b2683cea30aa51323c1f9c080
TypeScript
marcosvega91/node-request-interceptor
/src/XMLHttpRequest/override.ts
2.5625
3
import { ModuleOverride } from '../glossary' import { createXMLHttpRequestOverride } from './XMLHttpRequest/createXMLHttpRequestOverride' const debug = require('debug')('XHR') const original = { XMLHttpRequest: // Although executed in node, certain processes emulate the DOM-like environment // (i.e. `js-dom` in Jest). The `window` object would be avilable in such environments. typeof window === 'undefined' ? undefined : window.XMLHttpRequest, } /** * Conditionally overrides the `XMLHttpRequest` class using a given request middleware. */ export const overrideXhrModule: ModuleOverride = (middleware) => { if (original.XMLHttpRequest) { debug('patching "XMLHttpRequest" module...') const XMLHttpRequestOverride = createXMLHttpRequestOverride( middleware, original.XMLHttpRequest ) // @ts-ignore window.XMLHttpRequest = XMLHttpRequestOverride } return () => { if (original.XMLHttpRequest) { debug('restoring patches...') window.XMLHttpRequest = original.XMLHttpRequest } } }
ec029c219178dcec1c59d6d05477099ac998da5a
TypeScript
cr7yash/realworld-remix.run
/src/http/remix/app/lib/users/users.ts
2.953125
3
import type { Session } from "@remix-run/core"; import { fetchWithToken } from "../api-client"; import { AUTH_TOKEN_SESSION_KEY, removeAuthToken } from "../session-utils"; /** * User object returned from the Conduit api */ export type User = { /** Displayable name of the user */ username: string; /** User email address */ email: string; /** Small presentation of the user */ bio: string; /** URL of the profile picture */ image: string | null; }; export type UserWithToken = User & { /** jwt token to use for authenticated requests */ token: string; }; /** * Registration info submitted by a new user. * Send to the API to register. */ export type UserRegistration = { username: string; email: string; password: string; }; /** * Login info submitted by an user. * Send to the API to login. */ export type UserLogin = { email: string; password: string; }; /** * Get the current user from the api * @param apiAuthToken */ export async function getUser(apiAuthToken: string): Promise<UserWithToken | null> { const fetch = fetchWithToken(apiAuthToken); const response = await fetch("/user"); if (response.status !== 200) { return null; } const body: { user: UserWithToken } = await response.json(); return body.user; } /** * Check if the user is authenticated (ie. a valid token is present in the session) and returns its * info. * * Returns null if the user isn't authenticated. * * If there is a token but it's not valid, it is removed from the session. */ export async function getAuthenticatedUser(session: Session): Promise<UserWithToken | null> { const token = session.get(AUTH_TOKEN_SESSION_KEY); if (!token) { return null; } const user = await getUser(token); if (!user) { removeAuthToken(session); return null; } return user; }
71e228079201454a3c53b8cd21ef14321a7c94a5
TypeScript
eslawski/quick-colors
/src/app/toolbar/toolbar.component.ts
3.140625
3
import { CurrentColorService } from './../current-color.service'; import { Color } from './../shared/color.model'; import { ColorCollectionService } from 'app/color-collection.service'; import { Component, EventEmitter, Output, OnInit } from '@angular/core'; /** * Toolbar that contains controls for manipulating the color collection. */ @Component({ selector: 'toolbar', templateUrl: './toolbar.component.html', styleUrls: ['./toolbar.component.css'] }) export class ToolbarComponent implements OnInit { // The user inputed hex string. Used in two way data binding. hexString: string; rainbowSteps: string; // Triggers when the user encounters an error or does something to address // correct their error. @Output() errorStateChanged: EventEmitter<string> = new EventEmitter<string>(); // Used to subscribe this component to color changes. When the color changes we // want to populate the input field automatically. _subscription; /** * Constructor * @param colorCollectionService * @param currentColorService */ constructor(private colorCollectionService : ColorCollectionService, private currentColorService: CurrentColorService) { } /** * Called after angular is done creating this component. */ ngOnInit() { // Subscribes this component to the color change event this._subscription = this.currentColorService.colorChange.subscribe((color) => { if(color != null) { this.hexString = color.hexCode; } }); // Initialize the rainbow steps drop down to 10 this.rainbowSteps = "10"; // Initialize the hexString to the empty string this.hexString = ""; } /** * To avoid possibility of memory leak it is good practice to unsubscribe * once the component is destoryed. */ ngOnDestroy() { if(this._subscription != null) { this._subscription.unsubscribe(); } } /** * Fires the errorStateChanged event to notify listeners that there * is no longer an active error. */ clearError() { this.errorStateChanged.next(null); } /** * Called as the user types into the hex code input field. Every time * the user types their input is passivley validated. Once it becomes a * valid hex code it informs the CurrentColorService so it can provide * the user with instant feedback. * @param event The hex string */ onHexStringChange($event) { this.hexString = $event.toUpperCase(); let error = this.validateHexString(this.hexString); // Always clear the error right when the user types this.clearError(); // As the user types, if the hex color is valid take advantage // of the two way binding to show them their color instantly. // If it is not valid do nothing, validation will happen once // they try to click add. if(error == null) { this.hexString = this.hexString.toUpperCase(); this.currentColorService.setCurrentColor(new Color(this.hexString)); } else { this.currentColorService.setCurrentColor(null); } } /** * Invoked once the user clicks the add button. At this point is when the * hex string is validated. If it is invalid we need to fire the errorStateChanged * event to inform our parent of the error. Otherwise add the valid color to our * collection. */ onAddClicked() { let error = this.validateHexString(this.hexString); if(error == null) { // The hex string was formatted properly. Add it to the collection. let color = new Color(this.hexString); this.colorCollectionService.addColor(color); } else { // The hex string was invalid. Inform our parent so we can display // the error message in the jumbotron. this.errorStateChanged.next(error); } } /** * Invoked once the user pushes the generate rainbow button to generate * colors of the rainbow. */ onRainbowClicked() { this.colorCollectionService.generateRainbow(parseInt(this.rainbowSteps)); } /** * Invoked once the user clicks the clear button to remove all colors from the collection. */ onClearClicked() { this.colorCollectionService.clearColors(); this.currentColorService.setCurrentColor(null); } /** * Validates the provided hex string and returns an error message if * necessary. Returns null if the hex string is valid. */ validateHexString(hexString: String) { if(hexString.length != 6) { return "Hex code too short"; } // Validate the characters of the hexString let validHexChars = "1234567890ABCDEF"; for(let i = 0; i < hexString.length; i++) { if(validHexChars.indexOf(hexString[i]) == -1) { return "Valid characters are 0-9 or A-F"; } } // Hex string was valid return null; } }
fbfbdafbb5170e155b969495a7c2b355a831b96f
TypeScript
ShaatsSucher/antonius-phaser
/src/gameObjects/button.ts
2.8125
3
import GameObject from './gameObject' import { Spritesheets } from '../assets' export enum ButtonState { DEFAULT, HOVERED, DOWN, DISABLED } type Frames = null | number[] | string[] export class Button extends GameObject { /** * The internal state of the button. ButtonState.DISABLED will never be * assigned to this value but is only returned through the state getter. */ private _state = ButtonState.DEFAULT private hovering = false public get state() { if (!this.interactionEnabled) return ButtonState.DISABLED return this._state } public onStateChanged = new Phaser.Signal() constructor(game: Phaser.Game, x: number, y: number, key: string, defaultFrames: Frames = ['default'], hoverFrames: Frames = ['hovered'], downFrames: Frames = ['down'], disabledFrames: Frames = ['disabled'], private useAnimations = true) { super(game, x, y, key) if (useAnimations) { this.animations.add('default', defaultFrames, 8, false) this.animations.add('hovered', hoverFrames, 8, false) this.animations.add('down', downFrames, 8, false) this.animations.add('disabled', disabledFrames, 8, false) } this.anchor = new Phaser.Point(0.5, 0.5) this.events.onInputOver.add(this.onInputOver, this) this.events.onInputOut.add(this.onInputOut, this) this.events.onInputDown.add(this.onInputDown, this) this.events.onInputUp.add(this.onInputUp, this) this.interactionEnabled = true } public setInteractionEnabled(value: boolean) { super.setInteractionEnabled(value) this.alpha = value ? 1 : 0.6 this.updateTexture() this.onStateChanged.dispatch(this.state) } private onInputOver() { this.hovering = true if (this.state === ButtonState.DOWN) return this._state = ButtonState.HOVERED this.updateTexture() this.onStateChanged.dispatch(this.state) } private onInputOut() { this.hovering = false if (this.state === ButtonState.DOWN) return this._state = ButtonState.DEFAULT this.updateTexture() this.onStateChanged.dispatch(this.state) } private onInputDown() { if (this.state === ButtonState.DOWN) return this._state = ButtonState.DOWN this.updateTexture() this.onStateChanged.dispatch(this.state) } private onInputUp() { if (this.state !== ButtonState.DOWN) return const bounds = new Phaser.Rectangle(this.x, this.y, this.width, this.height) this._state = this.hovering ? ButtonState.HOVERED : ButtonState.DEFAULT this.updateTexture() this.onStateChanged.dispatch(this.state) } protected updateTexture() { if (!this.useAnimations) return this.play(ButtonState[this.state].toLowerCase()) } }
9eeb6a8a3218cfb9ab33b2fc8cd9493b96411dac
TypeScript
lekhachuy08/shogi-board
/src/fn/movings-ka.ts
2.859375
3
import { MovProps } from './movings'; import PieceObj from '../game-handler/piece'; import EmpObj from '../game-handler/emp'; import PromotionConfirmObj from '../game-handler/promotion-confirm'; import empLocations from './movings-emp-loc'; import { isPiece, isEmp } from '../fn/type-checker'; type Fn = (n: number) => number; type PieceOrEmp = PieceObj | EmpObj; type CellComponent = PieceOrEmp | PromotionConfirmObj; type PieceOrEmpTargets = Array<PieceOrEmp>; interface PosTurnPieceFn { pos: Array<Array<CellComponent>>; turn: number; piece: PieceObj; fn: Array<Array<Fn>>; } interface AddIfEnemyProps { target: PieceObj; movs: PieceOrEmpTargets; turn: number; } interface AddIfEmpProps { target: EmpObj | PromotionConfirmObj; movs: PieceOrEmpTargets; turn: number; row: number; col: number; } export default function movKa(props: MovProps): PieceOrEmpTargets { const piece = props.pieceObj; const positions = props.positions; const pos = positions.pos; const turn = positions.turn; if (isCapturePiece(piece)) { return empLocations(pos); } else { const fncs = [ [(r: number) => r - 1, (c: number) => c - 1], [(r: number) => r - 1, (c: number) => c + 1], [(r: number) => r + 1, (c: number) => c - 1], [(r: number) => r + 1, (c: number) => c + 1], ]; return movOnBoard({ pos: pos, turn: turn, piece: piece, fn: fncs }); } } export function movOnBoard(props: PosTurnPieceFn): PieceOrEmpTargets { const pos = props.pos; const turn = props.turn; const piece = props.piece; const row = piece.row; const col = piece.col; const movs: PieceOrEmpTargets = []; return checkRec(movs, row, col, props.fn[0][0], props.fn[0][1]) .concat(checkRec(movs, row, col, props.fn[1][0], props.fn[1][1])) .concat(checkRec(movs, row, col, props.fn[2][0], props.fn[2][1])) .concat(checkRec(movs, row, col, props.fn[3][0], props.fn[3][1])); function checkRec( movs: PieceOrEmpTargets, r: number, c: number, rowFn: Fn, colFn: Fn, ): PieceOrEmpTargets { const movs_ = movs.slice(); const row = rowFn(r); const col = colFn(c); if (isOutOfBoard(row, col)) { return movs_; } else { return handleRec(movs_); } function handleRec(movs: PieceOrEmpTargets) { const target: CellComponent = pos[row][col]; if (isPiece(target)) { return addTargetIfEnemyPiece({ target, movs, turn }); } else { return addIfEmpAndRec({ target, movs, turn, row, col }); } } function addTargetIfEnemyPiece( addProps: AddIfEnemyProps, ): PieceOrEmpTargets { if (isMine(addProps.target, turn)) { return movs.slice(); } else { return movs.concat(addProps.target); } } function addIfEmpAndRec(addProps: AddIfEmpProps): PieceOrEmpTargets { const targets = isEmp(addProps.target) ? movs.concat(addProps.target) : movs.slice(); return checkRec(targets, addProps.row, addProps.col, rowFn, colFn); } function isMine(piece: PieceObj, turn: number): boolean { return piece.whose === turn; } } } function isCapturePiece(piece: PieceObj): boolean { return piece.row === -1; } function isOutOfBoard(row: number, col: number): boolean { return 0 > row || row > 8 || 0 > col || col > 8; }