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
|
|---|---|---|---|---|---|---|
cc8b46ad0fb51317ede105e2da320be650bdc90b
|
TypeScript
|
jsonchou/zax-eventbus
|
/libs/cjs/eventbus.d.ts
| 2.5625
| 3
|
export declare type EventHandler = (param?: any) => any;
export declare type EventHandlers = EventHandler[];
export declare type EventOptions = {
channel: string;
debug: boolean;
};
export declare type EventSource = {
[name: string]: EventHandlers;
};
export default class EventBus {
channel: string;
debug: boolean;
constructor(opts: Partial<EventOptions>);
private formatKey;
eventSource: EventSource;
on(name: string, handler: EventHandlers | EventHandler): EventBus;
off(name: string, handler?: EventHandlers | EventHandler): EventBus;
once(name: string, handler: EventHandlers | EventHandler): EventBus;
emit(name: string, ...params: any[]): EventBus;
has(name: string): boolean;
get(name: string): EventHandler | EventHandlers;
keys(): string[];
values(): EventHandlers[];
remove(...name: string[]): EventBus;
removeAll(): EventBus;
}
|
666c963bd0914257532d95d7e8a56d72cd0104c5
|
TypeScript
|
alexaaaant/patterns_on_ts
|
/facade.ts
| 3.453125
| 3
|
class Subsystem1 {
operation1() {
console.log('sub 1 oper1')
}
operation2() {
console.log('sub 1 oper2')
}
}
class Subsystem2 {
operation1() {
console.log('sub 2 oper1')
}
operation2() {
console.log('sub 2 oper2')
}
}
class Facade {
protected sub1: Subsystem1;
protected sub2: Subsystem2;
constructor(subsystem1: Subsystem1, subsystem2: Subsystem2) {
this.sub1 = subsystem1 || new Subsystem1();
this.sub2 = subsystem2 || new Subsystem2();
}
operation() {
this.sub2.operation2();
this.sub1.operation1();
this.sub2.operation1();
this.sub1.operation2();
}
}
let sub1 = new Subsystem1();
let sub2 = new Subsystem2();
let facade = new Facade(sub1, sub2);
facade.operation();
|
2b447e6f3483491021ff898004ef8cb70fe7eed0
|
TypeScript
|
SZ559/ToDoItems
|
/frontend-todoitem/src/app/services/todoitem.service.spec.ts
| 2.609375
| 3
|
// import { ToDoItem } from 'src/models/todoitem';
// import { ToDoItemService } from "./todoitem.service";
// let httpClientSpy: { get: jasmine.Spy };
// let heroService: ToDoItemService;
// beforeEach(() => {
// // TODO: spy on other methods too
// httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
// heroService = new ToDoItemService(httpClientSpy as any);
// });
// it('should return expected heroes (HttpClient called once)', () => {
// const expectedHeroes: ToDoItem[] =
// [];
// httpClientSpy.get.and.returnValue(expectedHeroes);
// heroService.getToDoItems().subscribe(
// heroes => expect(heroes).toEqual(expectedHeroes, 'expected heroes'), fail);
// expect(httpClientSpy.get.calls.count()).toBe(1, 'one call');
// // })
|
ca8bfd0087d93c0419cf3a51671b9f81943a0126
|
TypeScript
|
haenah/agari.haseyo-client
|
/src/MouseTracker.ts
| 2.703125
| 3
|
import $ from 'jquery';
import { Position } from './types/common.types';
enum MouseTrackerState {
ON,
OFF,
}
class _MouseTracker {
private state: MouseTrackerState = MouseTrackerState.OFF;
/** x, y */
position: Position = { x: 0, y: 0 };
start() {
this.state === MouseTrackerState.OFF &&
$('#game').get(0).addEventListener('mousemove', this.updatePosition);
this.state = MouseTrackerState.ON;
}
stop() {
this.state === MouseTrackerState.ON &&
$('#game').get(0).removeEventListener('mousemove', this.updatePosition);
this.state = MouseTrackerState.OFF;
}
updatePosition = ({ offsetX, offsetY }: MouseEvent) => {
this.position = { x: offsetX, y: offsetY };
};
}
const MouseTracker = new _MouseTracker();
export default MouseTracker;
|
64e95b67aca95a3976048c5d609b4d42aa86d78a
|
TypeScript
|
cyrilleverrier/pgtest
|
/tests/integration/query.ts
| 2.515625
| 3
|
import * as env from 'env-var';
import pRetry from 'p-retry';
export async function connectedToTimescale() {
console.log("Try to connect ot PostgreSQL...")
var result = await pRetry(async () => {
return await getPostgresVersion();
}, {
retries: 500,
factor: 2,
minTimeout: 200,
maxTimeout: 2000,
});
console.log(`Done. ${result}`)
return result;
}
async function getPostgresVersion() {
try {
const dbAndHelpers = PostgresDbConnectionProvider.getDatabase({
host: "localhost",
port: 5432,
database: 'dev',
user: 'tfmc',
password: env.get("POSTGRES_PW").required().asString(),
ssl: false
});
// Retry to connect until the client can query the PostgreSQL version
const r = await dbAndHelpers.db.any('SELECT version();', [true]);
expect(r[0]["version"]).toEqual(expect.stringContaining('PostgreSQL'));
return r;
}
catch (e) {
// Catch and throws exceptions
// Just because ps library throws exceptions that are not of type "Error"...
if (e instanceof env.EnvVarError) {
console.log(e);
}
throw new Error(e);
}
}
|
53372d23dd7c0f642e0a78c6af11a026d0690bb4
|
TypeScript
|
oladotunsobande/mini-bank-api
|
/src/helpers/index.ts
| 2.796875
| 3
|
import { randomBytes } from 'crypto';
export function throwIfUndefined<T>(x: T | undefined, name?: string): T {
if (x === undefined) {
throw new Error(`${name} must not be undefined`);
}
return x;
}
export function randomizeMongoURL(url: string): string {
return url.replace(
/([^/]\/)([^/][a-zA-Z-_0-9]+)/,
`$1${randomBytes(4).toString('hex')}`,
);
}
export function setRetryAfterTimeText(retrySeconds: number): string {
if (retrySeconds < 60) {
return `${retrySeconds} second(s)`;
}
return `${Math.ceil(retrySeconds / 60)} minute(s)`;
}
|
a5d198bfb248eedd2d1200cb819cf755eb21931e
|
TypeScript
|
alexmitic/booking-application
|
/booking-app/src/app/bookings.service.ts
| 2.5625
| 3
|
import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
export class Booking {
constructor(public booking_id: number,
public date: string,
public from: string,
public to: string,
public room: string) {
}
}
export class Participants {
constructor(full_name: string) {
}
}
export class Person {
constructor(public person_id: number,
public full_name: string) {
}
}
export class Room {
constructor(public resource_id: number,
public room: string,
public cost: number,
public facility: string) {
}
}
@Injectable()
export class BookingsService {
public personId: number;
constructor(private http: HttpClient) { }
public reqMeetings(): Promise<Booking[]> {
return new Promise((resolve, reject) => {
const URL = 'http://localhost:3000/getbookings?person_id=' + this.personId;
this.http.get(URL, { responseType: 'json' }).subscribe((response) => {
resolve(response as Booking[]);
});
});
}
public getParticipants(bookingId: number): Promise<Participants[]> {
return new Promise((resolve, reject) => {
const URL = 'http://localhost:3000/getparticipants?booking_id=' + bookingId;
this.http.get(URL, { responseType: 'json' }).subscribe((response) => {
resolve(response as Participants[]);
});
});
}
public deleteBooking(bookingId): void {
const URL = 'http://localhost:3000/deletebooking?booking_id=' + bookingId + '&person_id=' + this.personId;
this.http.delete(URL, { responseType: 'json' }).subscribe((response) => {
});
}
public getRooms(): Promise<Room[]> {
return new Promise((resolve, reject) => {
const URL = 'http://localhost:3000/getrooms';
this.http.get(URL, { responseType: 'json' }).subscribe((response) => {
resolve(response as Room[]);
});
});
}
public getpeople(): Promise<Person[]> {
return new Promise((resolve, reject) => {
const URL = 'http://localhost:3000/getpeople';
this.http.get(URL, { responseType: 'json' }).subscribe((response) => {
resolve(response as Person[]);
});
});
}
public book(booking): void {
const URL = 'http://localhost:3000/book';
this.http.post(URL, JSON.stringify(booking), { responseType: 'text', headers: {'Content-Type' : 'application/json'} }).subscribe((response) => {
console.log(response);
});
}
}
|
fd8699c9fbc9a7cc1fe80f9f37fdce02621b4e70
|
TypeScript
|
vsDizzy/leetcode
|
/test/house-robber.spec.ts
| 2.578125
| 3
|
import * as assert from 'assert';
import { rob } from '../src/house-robber';
describe('house-robber', () => {
it('should pass standard cases', () => {
assert.equal(rob([1, 2, 3, 1]), 4);
assert.equal(rob([2, 7, 9, 3, 1]), 12);
});
it('should handle special cases', () => {
assert.equal(rob([4, 1, 2, 7, 5, 3, 1]), 14);
});
});
|
af683bb809be797aa8125eff36fe43d6c89646c7
|
TypeScript
|
TimVosch/shortcut
|
/src/web/shortcut.api.ts
| 2.796875
| 3
|
import { plainToClass } from 'class-transformer';
import { validate } from 'class-validator';
import { Request, Response, Router } from 'express';
import { inject, injectable } from 'inversify';
import { ShortcutNameAlreadyInUseError } from '../application/errors/shortcut-name-already-in-use.error';
import { ShortcutService } from '../application/shortcut.service';
import { KeyNotFoundError } from '../data/errors/key-not-found.error';
import { ShortcutTokenValue } from '../domain/shortcut/shortcut-token.value';
import { CreateShortcutRequest } from './create-shortcut.request';
@injectable()
export class ShortcutAPI {
@inject(ShortcutService)
protected readonly shortcutService: ShortcutService;
// ---- Initialization ----
createRouter(): Router {
const r = Router();
r.get('/:name', this.takeShortcut.bind(this));
r.post('/api/shortcuts', this.createShortcut.bind(this));
r.delete('/api/shortcuts/:name', this.deleteShortcut.bind(this));
return r;
}
createUrl(protocol: string, hostname: string, shortcutName: string): string {
return `${protocol}://${hostname}/${shortcutName}`;
}
createEditUrl(protocol: string, hostname: string, token: ShortcutTokenValue): string {
return `${protocol}://${hostname}/edit/${token.shortcutName}?key=${token.value}`;
}
extractAuthToken(header?: string) {
if (typeof header !== 'string') {
return null;
}
const parts = header.split(' ');
if (parts.length < 2) {
return null;
}
return parts[1];
}
// ---- Routes ----
/**
* Called when a shortcut is visited.
* This redirects the visitor to the correct destination
*/
async takeShortcut(req: Request, res: Response) {
const name = req.params['name'];
try {
const shortcut = await this.shortcutService.get(name);
res.redirect(shortcut.getDestination());
} catch (e: unknown) {
if (e instanceof KeyNotFoundError) {
res.status(404).send({
message: `No shortcut with name ${name} found`,
});
} else {
throw e;
}
}
}
/**
* Called when a new shortcut is created
*/
async createShortcut(req: Request, res: Response) {
// Validate body
const body = plainToClass(CreateShortcutRequest, req.body);
await validate(body);
try {
const shortcut = await this.shortcutService.create(body.destination, body.name);
const token = await this.shortcutService.getToken(shortcut);
// Create URLs for the token
const editURL = this.createEditUrl(req.protocol, req.hostname, token);
const url = this.createUrl(req.protocol, req.hostname, shortcut.getName());
res.status(201).send({
message: `Created shortcut with name ${shortcut.getName()}`,
data: {
shortcut: shortcut.getName(),
edit: editURL,
URL: url,
},
});
} catch (e: unknown) {
if (e instanceof ShortcutNameAlreadyInUseError) {
res.status(400).send({
message: `A shortcut with the name '${body.name}' already exists`,
});
} else {
throw e;
}
}
}
/**
*
*/
async deleteShortcut(req: Request, res: Response) {
const shortcutName = req.params['name'];
const tokenValue = this.extractAuthToken(req.header('Authorization'));
if (tokenValue === null) {
res.status(400).send({
message: 'Missing authentication token',
});
return;
}
try {
// Check whether the request is authenticated
// TODO: would be nice to create some generic authz wrapper \
// that can be injected with some specific logic through an interface
const authorized = await this.shortcutService.isAuthorizedByToken(shortcutName, tokenValue);
if (!authorized) {
res.status(401).send({
message: 'Unauthorized',
});
return;
}
await this.shortcutService.delete(shortcutName);
res.send({
message: `Shortcut '${shortcutName}' has been removed`,
});
} catch (e) {
if (e instanceof KeyNotFoundError) {
res.status(404).send({
message: `No shortcut with name ${shortcutName} found`,
});
} else {
throw e;
}
}
}
}
|
eb9f28065ca34cb124ffb0f2c509fe86df5ad260
|
TypeScript
|
IhorPopovskyi/AngularForms
|
/src/app/custom.validators.ts
| 2.6875
| 3
|
import {
FormControl,
AbstractControl,
ValidationErrors,
ValidatorFn,
} from '@angular/forms';
export class CustomValidators {
static emailCustomValidator(control: FormControl) {
if (
[
'face@gmail.com',
'qwerty@gmail.com',
'test@gmail.com',
'name@gmail.com',
'morgenshtern@gmail.com',
].includes(control.value)
) {
return { restrictedEmail: true };
}
return null;
}
static passwordCustomValidator(
regex: RegExp,
error: ValidationErrors
): ValidatorFn {
return (control: AbstractControl): { [key: string]: boolean } => {
if (!control.value) {
return null;
}
const valid = regex.test(control.value);
return valid ? null : error;
};
}
}
|
f1d3efb8d0f0d001ad7644aba838ca53347cbbf4
|
TypeScript
|
Shinpeim/GroovePartner
|
/src/app/domain/player/ticker.ts
| 3.09375
| 3
|
import { Subject } from "rxjs"
export class Ticker {
private bpm: number
private playing: boolean
private noteSize: number
public tickEvent: Subject<void>
constructor(initialBpm: number, initialNoteSize: number){
this.bpm = initialBpm
this.noteSize = initialNoteSize
this.playing = false
this.tickEvent = new Subject()
}
setBpm(bpm: number){
this.bpm = bpm
}
setNoteSize(size: number) {
this.noteSize = size
}
start(){
this.playing = true
this.tick()
}
stop(){
this.playing = false
}
private tick(){
const tickPerSecond = (this.bpm / 60.0) * this.noteSize
if ( this.playing ) {
this.tickEvent.next()
setTimeout(() => {this.tick()}, ( 1.0 / tickPerSecond ) * 1000)
}
}
}
|
12eac804ffdfb5b8b22e8d8d07dc63fdab14a0f4
|
TypeScript
|
jaspenlind/args-any
|
/src/types/Option.ts
| 3.203125
| 3
|
import { StringConvertible } from "string-converter";
import { Operator } from ".";
/**
* Represents a set of arguments describing a critera
* @example
* const serverInSweden: Option = {
* key: "location",
* operator: Operator.Eq,
* value: "Sweden"
* }
*/
export interface Option extends StringConvertible {
key: string;
operator: Operator;
value: string;
}
|
646470eb7815685bcc84f63011e92f9ba3d8199b
|
TypeScript
|
dakir08/resf
|
/src/test/message.spec.ts
| 2.921875
| 3
|
import { message } from '../message';
import { HttpCode } from '../data/httpCode';
/**
* test 1:
* A simple data
*/
test('A simple data', () => {
const result = message()
.addData('id', 1)
.toOutput(200);
const actual = {
errors: {
technicalErrors: null,
clientMessage: null,
httpCode: 200
},
status: 'OK',
data: {
id: 1
}
};
expect(result).toStrictEqual(actual);
});
/**
* test 2:
* A simple error
*/
test('A simple error', () => {
const result = message()
.addError('error', 'Could not found item')
.toOutput(404);
const actual = {
errors: {
technicalErrors: {
error: 'Could not found item'
},
clientMessage: null,
httpCode: 404
},
status: 'Not Found',
data: null
};
expect(result).toStrictEqual(actual);
});
/**
* test 3:
* A complicated data
*/
test('A complicated data', () => {
const result = message()
.addData('id', 1)
.addData('name', 'Max')
.addData('email', 'sample@gmail.com')
.addData('phone', 1234567897)
.removeFrom('email', 'data')
.toOutput(HttpCode.Created);
const actual = {
errors: {
technicalErrors: null,
clientMessage: null,
httpCode: 201
},
status: 'Created',
data: {
id: 1,
name: 'Max',
phone: 1234567897
}
};
expect(result).toStrictEqual(actual);
});
/**
* test 4:
* A complicated error
*/
test('A complicated error', () => {
const result = message()
.addError('warning', 'Cannot run test file')
.addError('from', 'line 4, test.ts')
.addError('cmd', 'This is a sample command')
.addError('idNumber', 5)
.removeFrom('from', 'technicalErrors')
.toOutput(HttpCode.Forbidden);
const actual = {
errors: {
technicalErrors: {
warning: 'Cannot run test file',
cmd: 'This is a sample command',
idNumber: 5
},
clientMessage: null,
httpCode: 403
},
status: 'Forbidden',
data: null
};
expect(result).toStrictEqual(actual);
});
/**
* test 5:
* switch between data and error
*/
test('switch between data and error', () => {
const result = message()
.addData('id', 1)
.addData('name', 'Max')
.addData('email', 'sample@gmail.com')
.addError('warning', 'Cannot run test file')
.addError('from', 'line 4, test.ts')
.addData('phone', 1234567897)
.addError('cmd', 'This is a sample command')
.addError('idNumber', 5)
.removeFrom('from', 'technicalErrors')
.removeFrom('idNumber', 'technicalErrors')
.toOutput(HttpCode.Gone);
const actual = {
errors: {
technicalErrors: {
cmd: 'This is a sample command'
},
clientMessage: null,
httpCode: 410
},
status: 'Gone',
data: null
};
expect(result).toStrictEqual(actual);
});
/**
* test 6:
* A full version of error message
*/
test('A full version of error message', () => {
const result = message()
.addError('warning', 'Cannot run test file')
.addError('from', 'line 4, test.ts')
.addError('cmd', 'This is a sample command')
.addError('idNumber', 5)
.clientMessage(
'There are something trouble on the server, please contact to our technical support.'
)
.toOutput(HttpCode['Precondition Failed']);
const actual = {
errors: {
technicalErrors: {
warning: 'Cannot run test file',
from: 'line 4, test.ts',
cmd: 'This is a sample command',
idNumber: 5
},
clientMessage:
'There are something trouble on the server, please contact to our technical support.',
httpCode: 412
},
status: 'Precondition Failed',
data: null
};
expect(result).toStrictEqual(actual);
});
/**
* test 7:
* Add 2 client Message
*/
test('Add 2 client Message', () => {
const result = message()
.clientMessage('first client message')
.clientMessage('second client message')
.toOutput(HttpCode['Precondition Failed']);
const actual = {
errors: {
technicalErrors: null,
clientMessage: 'second client message',
httpCode: 412
},
status: 'Precondition Failed',
data: null
};
expect(result).toStrictEqual(actual);
});
|
afea0821b3b3752b5c0f759cdf6aa1b5ebb3d1ba
|
TypeScript
|
plantdata-jr/plantdata-sdk-docs
|
/versions/5.6.3/@plantdata/sdk/src/container/panel-box/panel-box.d.ts
| 2.6875
| 3
|
/// <reference types="jquery" />
import { PdComponent, PdComponentSettings } from '../../core/component';
import { PdSelector } from '../../common/common';
/**
* 盒子容器组件配置
*/
export interface PdPanelBoxSettings extends PdComponentSettings {
/**
* 盒子主体内容
*/
body?: PdSelector;
/**
* 是否允许关闭
*/
closeable?: boolean;
/**
* 盒子底部内容
*/
footer?: PdSelector;
/**
* 盒子头部内容
*/
header?: PdSelector;
/**
* 功能图标
*/
icon?: PdSelector;
/**
* 盒子容器初始状态是否展开
*/
isOpen?: boolean;
/**
* 是否允许最小化
*/
minEnable?: boolean;
/**
* 盒子标题
*/
title?: PdSelector;
/**
* 盒子标题的提示
*/
tooltip?: string;
}
/**
* 盒子容器组件
*/
export declare class PdPanelBox extends PdComponent {
/**
* 默认配置
*/
static defaultSettings: PdPanelBoxSettings;
/**
* 配置
*/
settings: PdPanelBoxSettings;
/**
* 构造方法
* @param {PdPanelBoxSettings} settings - 用户配置
*/
constructor(settings?: PdPanelBoxSettings);
/**
* 销毁实例
*/
destroy(): void;
/**
* 是否关闭或最小化状态
*/
isClosedOrMini(): boolean;
/**
* 更新状态
* @param {'close' | 'mini' | 'open' | ''} status - 'close'表示关闭状态, 'mini'表示最小化状态, 'open'或''表示展开状态
*/
updateStatus(status: 'close' | 'mini' | 'open' | ''): void;
/**
* 绑定事件
*/
protected bindEvent(): void;
/**
* 初始化配置
* @param {PdPanelBoxSettings} settings - 用户定义配置
* @return {PdPanelBoxSettings} 配置
*/
protected initSettings(settings: PdPanelBoxSettings): PdPanelBoxSettings;
/**
* 初始化Dom结构并返回
* @return {JQuery} 模板JQuery对象
*/
protected initTemplate(): JQuery;
/**
* 组件JQuery容器生成后回调
*/
protected mounted(): void;
/**
* 取消绑定事件
*/
protected unbindEvent(): void;
}
|
2b1b76051d05d36b99733debf83d35e9f3dac96a
|
TypeScript
|
yichang8421/leetcode
|
/844. Backspace-String-Compare/844. Backspace-String-Compare.ts
| 3.6875
| 4
|
function backspaceCompare(s: string, t: string): boolean {
let SDelCount: number = 0, TDelCount: number = 0;
let i = s.length - 1, j = t.length - 1;
while (!(i < 0) || !(j < 0)) {
/* 寻找待比较元素的位置。
遇到“#”,则计数器加一。
遇到非“#”,则看计数器是否不为0:
若计数器>0,则向前跳一位同时计数器减一,以此表示删除元素。
若计数器=0,说明“#”用完了,此时下标就是待比较元素的位置。直接 break 退出该次循环。 */
while (!(i < 0)) {
if (s[i] === "#") {
i--;
SDelCount++;
} else if (SDelCount) {
i--;
SDelCount--;
} else {
break;
}
}
while (!(j < 0)) {
if (t[j] === "#") {
TDelCount++;
} else if (TDelCount) {
TDelCount--;
} else {
break;
}
j--;
}
// 比较元素,值相同则指针前进一位,值不同直接返回false
if (s[i] !== t[j]) return false;
i--;
j--;
}
// 当i,j同时小于0(或等于-1)时,说明s和t删除元素之后都为空。返回true
return true;
};
|
9f944ccedaed269b89a965de6a66dccc1f162fb6
|
TypeScript
|
TalissonJunior/coffee
|
/src/extensions/database-extension.ts
| 2.515625
| 3
|
import { GluegunToolbox } from 'gluegun'
import * as _ from 'lodash'
import * as mysql from 'mysql'
import { ConnectionString } from '../models/connection-string'
module.exports = (toolbox: GluegunToolbox) => {
const {} = toolbox
toolbox.database = {
validateConnection: validateConnection
}
function _checkConnection(
connection: ConnectionString
): Promise<mysql.MysqlError | boolean> {
const conn = mysql.createConnection({
host: connection.hostname,
user: connection.username,
database: connection.schema,
password: connection.password
})
return new Promise((resolve, reject) => {
conn.connect(function(err) {
if (err) {
reject(err)
conn.end()
}
resolve(true)
conn.end()
})
})
}
async function validateConnection(connection: ConnectionString) {
if (!connection) {
return { isValid: false, message: 'Must provide a valid connection' }
} else if (!connection.hostname) {
return { isValid: false, message: 'Must provide a valid Hostname' }
} else if (!connection.username) {
return { isValid: false, message: 'Must provide a valid Username' }
} else if (!connection.schema) {
return { isValid: false, message: 'Must provide a valid schema' }
} else if (!connection.password) {
return { isValid: false, message: 'Must provide a valid password' }
} else {
try {
await _checkConnection(connection)
return { isValid: true, message: null }
} catch (error) {
return { isValid: false, message: error.message }
}
}
}
}
|
7ce744c10696e20aaf7de3efe0608c45b1d4e5d8
|
TypeScript
|
stemey/feature-hub
|
/packages/dom/src/feature-app-container.ts
| 2.78125
| 3
|
import {
FeatureAppDefinition,
FeatureAppManager,
FeatureAppScope,
Logger
} from '@feature-hub/core';
import {LitElement, html, property} from 'lit-element';
import {TemplateResult} from 'lit-html';
/**
* A DOM Feature App allows the use of any frontend technology such as Vue.js,
* React, or Angular.
*/
export interface DomFeatureApp {
/**
* @param container The container element to which the Feature App can attach
* itself.
*/
attachTo(container: Element): void;
}
/**
* A custom element defined by [[defineFeatureAppContainer]] as
* `feature-app-container`.
*
* It is possible to pass a slot named `error` to the `feature-app-container`
* element which is rendered if the Feature App could not be created or if the
* Feature App throws in its [[DomFeatureApp.attachTo]] method.
*/
export interface FeatureAppContainerElement extends HTMLElement {
/**
* The absolute or relative base URL of the Feature App's assets and/or BFF.
*/
baseUrl?: string;
/**
* The definition of the Feature App that should be rendered.
*/
featureAppDefinition?: FeatureAppDefinition<DomFeatureApp>;
/**
* If multiple instances of the same Feature App are placed on a single web
* page, an `idSpecifier` that is unique for the Feature App ID must be
* defined.
*/
idSpecifier?: string;
/**
* A config object that is intended for the specific Feature App instance
* that the `feature-app-container` renders.
*/
instanceConfig?: unknown;
}
const elementName = 'feature-app-container';
export interface DefineFeatureAppContainerOptions {
/**
* A custom logger that shall be used instead of `console`.
*/
readonly logger?: Logger;
}
/**
* Define a custom element implementing the [[FeatureAppContainerElement]]
* interface under the name `feature-app-container` at the
* `CustomElementRegistry`.
*/
export function defineFeatureAppContainer(
featureAppManager: FeatureAppManager,
options: DefineFeatureAppContainerOptions = {}
): void {
if (customElements.get(elementName)) {
return;
}
const {logger = console} = options;
class FeatureAppContainer extends LitElement
implements FeatureAppContainerElement {
@property({type: String})
public baseUrl?: string;
@property({type: Object})
public featureAppDefinition?: FeatureAppDefinition<DomFeatureApp>;
@property({type: String})
public idSpecifier?: string;
@property({type: Object})
public instanceConfig?: unknown;
@property({type: Object, reflect: false})
private error?: Error;
private featureAppScope: FeatureAppScope<DomFeatureApp> | undefined;
private readonly appElement = document.createElement('div');
public firstUpdated(): void {
if (!this.featureAppDefinition) {
return;
}
try {
this.featureAppScope = featureAppManager.getFeatureAppScope(
this.featureAppDefinition,
{
baseUrl: this.baseUrl,
idSpecifier: this.idSpecifier,
instanceConfig: this.instanceConfig
}
);
this.featureAppScope.featureApp.attachTo(this.appElement);
} catch (error) {
logger.error(error);
this.error = error;
}
}
public render(): TemplateResult {
if (this.error) {
return html`
<slot name="error"></slot>
`;
}
return html`
${this.appElement}
`;
}
public disconnectedCallback(): void {
if (this.featureAppScope) {
this.featureAppScope.destroy();
}
super.disconnectedCallback();
}
}
customElements.define(elementName, FeatureAppContainer);
}
|
338d4abb73935f5f9777eaedc83bd2efca0f1065
|
TypeScript
|
gsoft-inc/sg-orbit
|
/packages/components/src/shared/src/size.ts
| 3.28125
| 3
|
export type Size = "2xs" | "xs" | "sm" | "md" | "lg" | "xl" | "2xl" | "3xl" | "4xl" | "5xl" | "inherit";
export function normalizeSize<T extends Size>(size?: T) {
return size || "md";
}
export type SizeAdapter<T extends Size> = Partial<Record<Size, T>>;
export function createSizeAdapter<T extends Size>(adapter: SizeAdapter<T>) {
return (size: Size) => adapter[normalizeSize(size)];
}
export function adaptSize<T extends Size>(size: Size, adapter: SizeAdapter<T>) {
return adapter[normalizeSize(size)];
}
|
9b9e4e9a1b8e0dbd1175be433412360cebef6635
|
TypeScript
|
hernanpatronc/sistema-pcya
|
/src/app/notify/notify.service.ts
| 2.515625
| 3
|
import { Injectable } from '@angular/core';
@Injectable()
export class NotifyService {
constructor() { }
notificationList = [];
marginTop = 0;
newNotification = (type : string, text : string) => {
this.marginTop += 80;
const newNotification = {
text : text,
type : type,
marginTop : this.marginTop,
class : "create"
}
this.notificationList.push(newNotification);
//const index = this.notificationList.length;
setTimeout(()=>{
this.notificationList[0].class = "destroy";
this.marginTop -= 80;
setTimeout(()=>{
this.notificationList.splice(0,1);
},1000);
}, 4000)
}
}
|
ace9d3723eacf83c24265bafd7e5876f61a130d7
|
TypeScript
|
ng-docs/material2
|
/src/lib/select/select-animations.ts
| 2.578125
| 3
|
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {
animate,
AnimationTriggerMetadata,
state,
style,
transition,
trigger,
} from '@angular/animations';
/**
* The following are all the animations for the mat-select component, with each
* const containing the metadata for one animation.
*
* The values below match the implementation of the AngularJS Material mat-select animation.
* @docs-private
*/
export const matSelectAnimations: {
readonly transformPanel: AnimationTriggerMetadata;
readonly fadeInContent: AnimationTriggerMetadata;
} = {
/**
* This animation transforms the select's overlay panel on and off the page.
*
* When the panel is attached to the DOM, it expands its width by the amount of padding, scales it
* up to 100% on the Y axis, fades in its border, and translates slightly up and to the
* side to ensure the option text correctly overlaps the trigger text.
*
* When the panel is removed from the DOM, it simply fades out linearly.
*/
transformPanel: trigger('transformPanel', [
state('void', style({
transform: 'scaleY(0.8)',
minWidth: '100%',
opacity: 0
})),
state('showing', style({
opacity: 1,
minWidth: 'calc(100% + 32px)', // 32px = 2 * 16px padding
transform: 'scaleY(1)'
})),
state('showing-multiple', style({
opacity: 1,
minWidth: 'calc(100% + 64px)', // 64px = 48px padding on the left + 16px padding on the right
transform: 'scaleY(1)'
})),
transition('void => *', animate('120ms cubic-bezier(0, 0, 0.2, 1)')),
transition('* => void', animate('100ms 25ms linear', style({opacity: 0})))
]),
/**
* This animation fades in the background color and text content of the
* select's options. It is time delayed to occur 100ms after the overlay
* panel has transformed in.
* @deprecated Not used anymore. To be removed.
* @breaking-change 8.0.0
*/
fadeInContent: trigger('fadeInContent', [
state('showing', style({opacity: 1})),
transition('void => showing', [
style({opacity: 0}),
animate('150ms 100ms cubic-bezier(0.55, 0, 0.55, 0.2)')
])
])
};
/**
* @deprecated
* @breaking-change 8.0.0
* @docs-private
*/
export const transformPanel = matSelectAnimations.transformPanel;
/**
* @deprecated
* @breaking-change 8.0.0
* @docs-private
*/
export const fadeInContent = matSelectAnimations.fadeInContent;
|
f785da9caf3a060366ac0489439c40038e2dd279
|
TypeScript
|
karihei/BeamQuest
|
/app/beamQuest/listener/entity.ts
| 2.6875
| 3
|
/// <reference path="../../../typings/tsd.d.ts" />
import UserStore = require('../store/userStore');
declare var EntitiesStore:any;
/**
* @fileoverview Entityの状態が変化した時などなどを扱う
*/
class Entity {
private static instance_:Entity;
public static getInstance():Entity {
if (Entity.instance_ === undefined) {
Entity.instance_ = new Entity();
}
return Entity.instance_;
}
constructor() {
if (Entity.instance_){
throw new Error("Error: Instantiation failed: Use Entity.getInstance() instead of new.");
}
Entity.instance_ = this;
}
io_;
listen(socket, io) {
this.io_ = io;
socket.on('user:position:update', _.partial(this.handlePlayerMove_, socket));
socket.on('user:respawn', _.partial(this.handleRespawn, socket));
socket.on('user:dodge', _.partial(this.handleDodge, socket));
socket.on('user:status:get', _.partial(this.handleGetStatus_, socket));
EntitiesStore = require('beamQuest/store/entities');
}
/**
* プレイヤーの移動
* @param {Object} data
*/
private handlePlayerMove_(socket:any, data:any) {
// プレイヤーが移動したら位置情報が送られてくる
EntitiesStore.getInstance().updatePlayerPosition(data);
// 自分以外の全プレイヤーにブロードキャスト
socket.broadcast.emit('notify:user:move', data);
}
/**
* プレイヤーの緊急回避
*/
private handleDodge(socket:any, data:any) {
if (EntitiesStore.getInstance().updatePlayerDodge(data)) {
socket.broadcast.emit('notify:user:dodge', data);
}
}
/**
* mobがPOPするよってクライアントに伝える
* @param {ctrl.Mob} mob
*/
popMob(mob:any) {
if (this.io_) {
var data = {mob: mob.model.toJSON()};
this.io_.sockets.emit('notify:entity:mob:pop', data);
}
}
/**
* mobが動いたよってクライアントに伝える
* @param {ctrl.Mob} mob
*/
moveMob(mob:any) {
if (this.io_) {
this.io_.sockets.emit('notify:entity:mob:move', {mob: mob.model.toJSON()});
}
}
/**
* mobがタゲったよってクライアントに伝える
* @param {ctrl.Mob} mob
* @param {ctrl.Entity} entity
*/
targetTo(mob:any, entity:any) {
var data = {mob: mob.model.toJSON(), target: entity.model.toJSON()};
this.io_.sockets.emit('notify:entity:mob:targetTo', data);
}
/**
* mobが近接攻撃の構えを取ったよってクライアントに伝える
* @param {string} mobId
* @param {model.Position} srcPos
* @param {model.Position} destPos
* @param {number} range 射程距離(px)
* @param {number} castTime 発動までの時間(msec)
*/
startAttackShortRange(mobId, srcPos, destPos, range, castTime) {
if (this.io_) {
this.io_.sockets.emit('notify:entity:mob:startAttackShortRange',
{
mobId: mobId,
srcPos: srcPos,
destPos: destPos,
range: range,
castTime: castTime
});
}
}
/**
* hpの増減をクライアントに伝える
* @param {Array.<entity: model.Entity, hpAmount: number, isCritical: boolean>} hpAmounts
*/
updateHp(data){
if (this.io_) {
this.io_.sockets.emit('notify:entity:hp:update', {hpDatas: data});
}
}
/**
* bpの増減をクライアントに伝える
* @param {Object.<entity: model.Player, bpAmount: number, isCritical: boolean>} data
*/
updateBp(data) {
if (this.io_ && data.entity) {
data.entity.socket.emit('user:status:bp:update', data);
}
}
/**
* Mob殺すよってクライアントに伝える
* @param {ctrl.Mob} mob
*/
killMob(mob:any) {
var data = {entity: mob.model.toJSON()};
this.io_.sockets.emit('notify:entity:mob:kill', data);
_.each(mob.hateList, (hate:any) => {
this.addExp(hate.entityId, mob);
});
}
/**
* mobのもつ経験値をplayerに与える
* @param {string} playerId
* @param {ctrl.Mob} mob
*/
addExp(playerId, mob:any) {
var player:any = EntitiesStore.getInstance().getPlayerById(playerId);
if (player) {
player.addExp(mob.model.exp);
player.model.socket.emit('user:status:exp:update', {
exp: mob.model.exp,
prevLvExp: player.model.prevLvExp,
currentExp: player.model.exp,
nextLvExp: player.model.nextLvExp,
mobName: mob.model.name
});
}
}
/**
* レベルアップしたよってクライアントに伝える
* @param {model.Player} playerModel
*/
levelUp(playerModel) {
this.io_.sockets.emit('notify:entity:player:levelup', playerModel);
}
/**
* player死んだよってクライアントに伝える
* @param player
*/
killPlayer(player) {
var data = {entity: player.model.toJSON()};
this.io_.sockets.emit('notify:entity:player:kill', data);
}
/**
* プレイヤーが復活したよ
* @param {Object} data
*/
handleRespawn(socket:any, data:any) {
if (data) {
var playerId = data.id;
var player:any = EntitiesStore.getInstance().getPlayerById(playerId);
if (player) {
player.respawn();
var d = {entity: player.model.toJSON()};
socket.broadcast.emit('notify:entity:player:respawn', d);
}
}
}
/**
* entityのステータスを返す
* @param {Object} data
* @private
*/
handleGetStatus_(socket:any, data:any) {
if (data && socket) {
var player:any = EntitiesStore.getInstance().getPlayerById(data.entityId);
if (player) {
socket.emit('user:status:receive', player.model.toJSON());
}
}
}
}
export = Entity;
|
e8972f7cfcaa2ca7c6b33a88160e43a993a2d60f
|
TypeScript
|
GAMS-Organization/GAMS-Repository
|
/packages/api/src/Application/Handlers/Area/StoreAreaHandler.ts
| 2.515625
| 3
|
import IAreaRepository from '../../../Domain/Interfaces/IAreaRepository';
import ISectorRepository from '../../../Domain/Interfaces/ISectorRepository';
import { inject, injectable } from 'inversify';
import { INTERFACES } from '../../../Infrastructure/DI/interfaces.types';
import Area from '../../../Domain/Entities/Area';
import StoreAreaCommand from '../../Commands/Area/StoreAreaCommand';
import EntityNotFoundException from '../../Exceptions/EntityNotFoundException';
import AreaServiceService from '../../../Domain/Services/AreaServiceService';
@injectable()
export default class StoreAreaHandler {
private areaRepository: IAreaRepository;
private sectorRepository: ISectorRepository;
private areaServiceService: AreaServiceService;
public constructor(
@inject(INTERFACES.IAreaRepository) areaRepository: IAreaRepository,
@inject(INTERFACES.ISectorRepository) sectorRepository: ISectorRepository,
@inject(AreaServiceService) areaServiceService: AreaServiceService,
) {
this.areaRepository = areaRepository;
this.sectorRepository = sectorRepository;
this.areaServiceService = areaServiceService;
}
public async execute(command: StoreAreaCommand): Promise<Area> {
const sector = await this.sectorRepository.findOneBySectorName(command.getSector());
if (!sector) {
throw new EntityNotFoundException(`No se encontró el sectorcon nombre: ${command.getSector()}`);
}
const area = new Area(command.getName(), command.getCode(), sector);
return await this.areaServiceService.setServiceToArea(
command.getServices(),
await this.areaRepository.persist(area),
);
}
}
|
a869bf50522fbfe4d76bf629e09e3c4cccd2d4ec
|
TypeScript
|
sadewole/NestJS-1.0
|
/src/user/user.controller.ts
| 2.515625
| 3
|
import {
Controller,
Get,
Post,
Delete,
Body,
Param,
UsePipes,
UseGuards,
UnauthorizedException,
HttpException,
HttpStatus
} from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { User } from './interfaces/user.interface';
import { UserService } from './user.service';
import { ValidationPipe } from '../pipe/validation.pipe';
import { AuthGuard } from '@nestjs/passport';
import * as bcrypt from 'bcryptjs';
@Controller('/api/v1/user')
export class UserController {
constructor(private readonly userService: UserService) {}
@UseGuards(AuthGuard('jwt'))
@Get()
fetchAllUser(): Promise<User[]> {
return this.userService.fetchAllUser();
}
@Post()
@UsePipes(ValidationPipe)
async createUser(@Body() createUserDto: CreateUserDto): Promise<User> {
createUserDto.password = await this.hashPassword(createUserDto.password);
const user = await this.userService.findOne(createUserDto.email);
if (user)
throw new HttpException('User already exists', HttpStatus.BAD_REQUEST);
return await this.userService.createUser(createUserDto);
}
@UseGuards(AuthGuard('jwt'))
@Delete(':id')
deleteUser(@Param('id') id): Promise<User> {
return this.userService.deleteUser(id);
}
private async hashPassword(pass: string): Promise<string> {
return await bcrypt.hashSync(pass, bcrypt.genSaltSync(10));
}
}
|
823afda9c2ddbc67a1d30dc07af2fbba79032ce0
|
TypeScript
|
forrestbicker/InertiaSimulator
|
/src/Math/DynamicVector.ts
| 2.765625
| 3
|
import { PhysicsBody } from "../PhysicsObjects/PhysicsBody";
import { Vector } from "./Vector";
/** a vector that changes magnitude and direction depending on the body state and time */
export interface DynamicVector {
at(body: PhysicsBody, time: number): Vector;
getName(): string;
}
|
b755156dcb46613d15fc38c6028fe7483ab2073b
|
TypeScript
|
lucbouchard1/poker-public
|
/src/path.ts
| 2.859375
| 3
|
export const ROOM_PATH_PREFIX = "/game/"
export function getRoomPath(roomId: string) {
return ROOM_PATH_PREFIX + roomId
}
export function isRoomPath(path: string): boolean {
return path.length > 6 && path.slice(0, 6) == ROOM_PATH_PREFIX
}
export function getRoomId(path: string): string | undefined {
if (isRoomPath(path)) return path.slice(6)
return undefined
}
|
b64b3b0236c6418b170d0e6d778ee33795d2adcc
|
TypeScript
|
lilchim/wbt-api
|
/model/auth.ts
| 2.609375
| 3
|
import { v4 as uuidv4 } from 'uuid';
export enum Roles {
OFFICER = 'OFFICER',
MEMBER = 'MEMBER'
}
export interface User {
_id: string;
token: string;
name: string;
role: string;
organization: string;
discordTag?: string;
lastLogin: number;
}
export const generateAuthModel = ({ req, client, officers, authKeys, registeredUsers }) => ({
login: async ({ name, token, discordTag }) => { //check
console.log(`authorizing ${name} with token ${token}`)
let auth = authKeys.get(token);
console.log(auth);
const existingUser = await client.db('wbt-data').collection('users').findOne({ name: name, token: token });
console.log(existingUser);
if (existingUser) return existingUser;
console.log(`${name} is a new user registering with token ${token}`);
if (auth && auth.role === Roles.OFFICER) {
console.log('Officer role requires whitelist');
if (officers.indexOf(name) < 0) {
throw new Error('User is not authorized for this role');
}
}
// Create a new User
let user: User = {
_id: uuidv4(),
token: token,
name: name,
role: auth.role,
discordTag: discordTag ? discordTag : '',
organization: auth.guild,
lastLogin: Date.now()
}
const result = await client.db('wbt-data').collection('users').insertOne(
user,
);
return user;
},
getById: async (id) => {
const result = await client.db('wbt-data').collection('users').findOne({_id: id});
return result;
},
getAll: async () => {
const result = await client.db('wbt-data').collection('users').find().toArray()
return result;
},
getRole: ({ token }) => { return authKeys.get(token).role },
getGuildByToken: ({ token }) => { return authKeys.get(token).guild},
isAuthorized: async ({ name, token }) => { //check
console.log(`verifying authorization for ${name} with token ${token}`)
let existingUser = await client.db('wbt-data').collection('users').findOne({ name: name, token: token });
return existingUser ? true : false;
},
})
|
78afaa5b70461aef7396957435141fd2fb8783ef
|
TypeScript
|
Rareloop/ionic-typeorm
|
/projects/ionic-typeorm/src/lib/services/db-service.ts
| 2.53125
| 3
|
import { BaseEntity, FindManyOptions } from 'typeorm';
export interface IDBService<T extends BaseEntity> {
/** Fetch the entity with id */
fetch(id: any): Promise<T | null>;
/** Fetch all entities */
all(options?: FindManyOptions): Promise<T[]>;
/** Remove the list of entities */
remove(entities: T[]): Promise<void>;
/** Save and entity */
save(data: T): Promise<void>;
}
|
4067bc316de411519700e256a154d65d8ee3a6f1
|
TypeScript
|
deepkit/deepkit-framework
|
/packages/orm/src/database-adapter.ts
| 2.6875
| 3
|
/*
* Deepkit Framework
* Copyright (C) 2021 Deepkit UG, Marc J. Schmidt
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the MIT License.
*
* You should have received a copy of the MIT License along with this program.
*/
import { OrmEntity } from './type.js';
import { AbstractClassType, arrayRemoveItem, ClassType, getClassName, getClassTypeFromInstance, isClass, stringifyValueWithType } from '@deepkit/core';
import { is, isSameType, ItemChanges, PrimaryKeyFields, ReceiveType, ReflectionClass, ReflectionKind, stringifyType, Type } from '@deepkit/type';
import { Query } from './query.js';
import { DatabaseSession, DatabaseTransaction } from './database-session.js';
export abstract class DatabaseAdapterQueryFactory {
abstract createQuery<T extends OrmEntity>(type?: ReceiveType<T> | ClassType<T> | AbstractClassType<T> | ReflectionClass<T>): Query<T>;
}
export interface DatabasePersistenceChangeSet<T extends object> {
changes: ItemChanges<T>;
item: T;
primaryKey: PrimaryKeyFields<T>;
}
export abstract class DatabasePersistence {
abstract remove<T extends OrmEntity>(classSchema: ReflectionClass<T>, items: T[]): Promise<void>;
abstract insert<T extends OrmEntity>(classSchema: ReflectionClass<T>, items: T[]): Promise<void>;
abstract update<T extends OrmEntity>(classSchema: ReflectionClass<T>, changeSets: DatabasePersistenceChangeSet<T>[]): Promise<void>;
/**
* When DatabasePersistence instance is not used anymore, this function will be called.
* Good place to release a connection for example.
*/
abstract release(): void;
}
export class RawFactory<A extends Array<any>> {
create(...args: A): any {
throw new Error(`Current database adapter does not support raw mode.`);
}
}
/**
* A generic database adapter you can use if the API of `Query` is sufficient.
*
* You can specify a more specialized adapter like MysqlDatabaseAdapter/MongoDatabaseAdapter with special API for MySQL/Mongo.
*/
export abstract class DatabaseAdapter {
abstract queryFactory(session: DatabaseSession<this>): DatabaseAdapterQueryFactory;
rawFactory(session: DatabaseSession<this>): RawFactory<any> {
return new RawFactory();
};
abstract createPersistence(session: DatabaseSession<this>): DatabasePersistence;
abstract createTransaction(session: DatabaseSession<this>): DatabaseTransaction;
abstract disconnect(force?: boolean): void;
abstract migrate(entityRegistry: DatabaseEntityRegistry): Promise<void>;
abstract getName(): string;
abstract getSchemaName(): string;
abstract isNativeForeignKeyConstraintSupported(): boolean;
}
/**
* This is a container knowing what entities are registered. It is able to register and resolve based on Type | ReflectionClass | ClassType.
*
* This container is necessary since TypeScript interfaces have no identity (TypeObjectLiteral) and property types are not equal by identity.
* This means there can be multiple ReflectionClass describing the same structure/type.
* We need to do type comparison to get always the correct (registered) ReflectionClass.
*/
export class DatabaseEntityRegistry {
protected entities: ReflectionClass<any>[] = [];
static from(items: (Type | ReflectionClass<any> | ClassType)[]) {
const e = new DatabaseEntityRegistry();
e.add(...items);
return e;
}
all(): ReflectionClass<any>[] {
return this.entities;
}
forMigration(): ReflectionClass<any>[] {
return this.entities.filter(v => !v.data['excludeMigration']);
}
add(...types: (Type | ReflectionClass<any> | ClassType)[]): void {
for (const type of types) {
const reflection = ReflectionClass.from(type);
if (this.entities.indexOf(reflection) === -1) this.entities.push(reflection);
}
}
remove(type: Type | ReflectionClass<any> | ClassType): void {
const reflection = ReflectionClass.from(type);
arrayRemoveItem(this.entities, reflection);
}
getFromInstance<T>(item: T): ReflectionClass<any> {
if ((item as any).constructor === Object) {
//search using type guards
for (const entity of this.entities) {
if (is(item, undefined, undefined, entity.type)) return entity;
}
} else {
//its a regular class
return ReflectionClass.from(getClassTypeFromInstance(item));
}
throw new Error(`No entity for item ${stringifyValueWithType(item)} registered.`);
}
get(type: Type | ReflectionClass<any> | ClassType): ReflectionClass<any> {
if (isClass(type)) {
for (const entity of this.entities) {
if (entity.type.kind === ReflectionKind.class && entity.type.classType === type) return entity;
}
throw new Error(`No entity for ${getClassName(type)} registered`);
}
type = type instanceof ReflectionClass ? type.type : type;
if (type.kind !== ReflectionKind.class && type.kind !== ReflectionKind.objectLiteral) {
throw new Error(`Only TypeClass|TypeObjectLiteral expected, but got kind ${type.kind}`);
}
for (const entity of this.entities) {
if (entity.type === type) return entity;
if (type.kind === ReflectionKind.class && entity.type.kind === ReflectionKind.class) {
if (type.classType === entity.type.classType) {
//if both don't use generic, return directly
if (!type.typeArguments && !entity.type.typeArguments) return entity;
//check if generic type is compatible
//we could cache the result for faster lookups
if (isSameType(type, entity.type)) return entity;
}
}
if (type.kind === ReflectionKind.objectLiteral && entity.type.kind === ReflectionKind.objectLiteral) {
//check if type is compatible
if (type.types.length === entity.type.types.length) {
//we could cache the result for faster lookups
if (isSameType(type, entity.type)) return entity;
}
}
}
throw new Error(`No entity for ${stringifyType(type)} registered`);
}
}
|
8e5becf3d0fbf15f6c1580774916fcb1804aa788
|
TypeScript
|
iimog/tidy
|
/packages/tidy/src/tally.ts
| 3.078125
| 3
|
import { summarize } from './summarize';
import { n } from './summary/n';
import { sum } from './summary/sum';
import { TidyFn } from './types';
type TallyOptions = {
readonly name?: string;
readonly wt?: string;
};
type TallyOutput<Options extends TallyOptions> = Options['name'] extends string
? { [K in Options['name']]: number }
: { n: number };
export function tally<T extends object, Options extends TallyOptions>(
options?: Options
): TidyFn<T, TallyOutput<Options>> {
const _tally: TidyFn<T, TallyOutput<Options>> = (
items: T[]
): TallyOutput<Options>[] => {
const { name = 'n', wt } = options ?? {};
const summarized = summarize({ [name]: wt == null ? n() : sum(wt as any) })(
items
);
return summarized as TallyOutput<Options>[];
};
return _tally;
}
|
5343d7263b8793d0c4641dccde313cf0521b2e96
|
TypeScript
|
Rjpdude/redux-pods
|
/__tests__/unit/reducer.test.ts
| 3
| 3
|
import pod, {
PodProperties,
PodReducer,
PodMethods,
ProxiedAction,
INTERNAL_ACTION_TYPES
} from '../../src'
describe('[unit] reducer class', () => {
test('instantiates function producer super class', () => {
expect(typeof new PodReducer({ initialState: '' }).getBoundFunc()).toBe(
'function'
)
})
test('get props method', () => {
const props = new PodProperties({ initialState: '' })
expect(new PodReducer(props).getProps()).toBe(props)
})
test('chain method', () => {
const reducer = new PodReducer({ initialState: 'initial-state' })
const chainedReducer = reducer.chain({ path: 'an-arbitrary-string' })
expect(typeof chainedReducer).toBe('function')
expect(chainedReducer.instance() instanceof PodReducer).toBe(true)
expect(chainedReducer.props()).toEqual({
initialState: 'initial-state',
path: 'an-arbitrary-string'
})
})
test('bound function members method', () => {
const reducer = new PodReducer({
initialState: '',
actionSet: {
actionOne: new ProxiedAction('actionOne', undefined, jest.fn()),
actionTwo: new ProxiedAction('actionTwo', undefined, jest.fn())
}
})
const boundFunctionMembersRes = reducer.boundFunctionMembers()
const keys = Object.keys(boundFunctionMembersRes)
expect(keys.includes('actionOne') && keys.includes('actionTwo')).toBe(true)
expect(
Object.keys(PodMethods.prototype).every((key) => keys.includes(key))
).toBe(true)
expect(
Object.values(boundFunctionMembersRes).every(
(val) => typeof val === 'function'
)
).toBe(true)
})
describe('produced reducer function', () => {
test('returns initial state by default', () => {
const initialState = { elem: '' }
const reducer = pod(initialState)
expect(
reducer(undefined, {
type: 'external-action'
})
).toBe(initialState)
})
test('returns incoming state obj on invalid action', () => {
const reducer = pod({})
const state = { elem: '' }
expect(reducer(state, undefined)).toBe(state)
// @ts-ignore
expect(reducer(state, {})).toBe(state)
// @ts-ignore
expect(reducer(state, jest.fn())).toBe(state)
// @ts-ignore
expect(reducer(state, 'string')).toBe(state)
// @ts-ignore
expect(reducer(state, 7)).toBe(state)
})
test('responds to internal init action', () => {
const initAction = {
type: INTERNAL_ACTION_TYPES.init,
init: jest.fn()
}
const unconnectedReducer = pod({})
const connectedReducer = pod({})
.instance()
.chain({ connected: true })
connectedReducer(undefined, initAction)
expect(initAction.init).not.toHaveBeenCalled()
unconnectedReducer(undefined, initAction)
expect(initAction.init).toHaveBeenCalled()
})
test('responds to internal connect action', () => {
const connectAction = {
type: INTERNAL_ACTION_TYPES.connect,
connect: jest.fn()
}
const unconnectedReducer = pod({})
const connectedReducer = pod({})
.instance()
.chain({ connected: true })
connectedReducer(undefined, connectAction)
expect(connectAction.connect).not.toHaveBeenCalled()
unconnectedReducer(undefined, connectAction)
expect(connectAction.connect).toHaveBeenCalled()
})
test('responds to internal register trackers action', () => {
const registerAction = {
type: INTERNAL_ACTION_TYPES.registerTrackers,
register: jest.fn()
}
const mockedPod = {}
const reducer = pod({})
reducer.props().trackers = new Map().set(mockedPod, '')
reducer(undefined, registerAction)
expect(registerAction.register).toHaveBeenCalledWith(mockedPod)
})
test('calls actions in proxied action set', () => {
const actionSet = { action: jest.fn(), secondAction: jest.fn() }
const reducer = pod({}).on(actionSet)
reducer.action('arg')
reducer.secondAction('secondArg')
expect(actionSet.action).toHaveBeenCalledWith('arg')
expect(actionSet.secondAction).toHaveBeenCalledWith('secondArg')
})
test('does not mutate incoming state', () => {
const state = { prop: '', anotherProp: { nestedVal: '' } }
const identicalState = { prop: '', anotherProp: { nestedVal: '' } }
const reducer = pod(state).on('action-type', (draft) => {
draft.prop = 'bla'
draft.anotherProp.nestedVal = 'bla'
})
const nextState = reducer(undefined, { type: 'action-type' })
expect(state).toEqual(identicalState)
expect(nextState).not.toBe(state)
expect(nextState).toEqual({
prop: 'bla',
anotherProp: { nestedVal: 'bla' }
})
})
describe('primitive states', () => {
test('boolean', () => {
const booleanPod = pod(true).on('action-type', () => false)
expect(booleanPod(undefined, { type: 'action-type' })).toBe(false)
})
test('number', () => {
const numberPod = pod(10).on('action-type', (state) => state * 5)
expect(numberPod(undefined, { type: 'action-type' })).toBe(50)
})
test('string', () => {
const stringPod = pod('something').on(
'action-type',
(state) => `${state} happened`
)
expect(stringPod(undefined, { type: 'action-type' })).toBe(
'something happened'
)
})
})
})
})
|
7f1f9f3629fb6f8baf50422fd9b8eb8011d86c28
|
TypeScript
|
DavidFeldhoff/al-codeactions
|
/src/extension/Entities/alVariable.ts
| 3.171875
| 3
|
export class ALVariable {
public name: string | undefined;
public type: string;
public isLocal: boolean = false;
public isVar: boolean = false;
public canBeVar: boolean = false;
public procedure: string | undefined;
public memberAttributes: string[] = [];
public isResultParameter: boolean = false;
constructor(name: string | undefined, type: string);
constructor(name: string | undefined, type: string, memberAttributes: string[]);
constructor(name: string | undefined, type: string, procedure: string | undefined, isVar: boolean);
constructor(name: string | undefined, type: string, procedure: string | undefined, isVar: boolean, canBeVar: boolean);
constructor(name: string | undefined, type: string, procedure: string | undefined, isVar: boolean, memberAttributes: string[]);
public constructor(...args: any[]) {
this.name = args[0];
this.type = args[1];
switch (args.length) {
case 3:
this.memberAttributes = args[2]
break;
case 4:
this.procedure = args[2]
this.isVar = args[3];
break;
case 5:
this.procedure = args[2];
this.isVar = args[3];
if (typeof (args[4]) == 'boolean')
this.canBeVar = args[4];
else
this.memberAttributes = args[4];
break;
default:
break;
}
this.isLocal = this.procedure !== undefined
}
public getVariableDeclarationString(indent: string = ''): string {
let declarationString = indent;
for (const memberAttribute of this.memberAttributes)
declarationString += memberAttribute + '\r\n' + indent;
declarationString += this.name + ": " + this.type;
return declarationString;
}
public getParameterDeclarationString(indent: string = ''): string {
let declarationString = indent;
if (this.isVar) {
declarationString = "var ";
}
declarationString += this.name + ": " + this.type;
return declarationString;
}
public getTypeShort(): string {
return this.type.split(' ')[0].split('[')[0]
}
public getNameOrEmpty(): string {
return this.name == undefined ? "" : this.name
}
public sanitizeName(): ALVariable {
if (this.name == undefined)
return this
this.name = this.name.trim();
this.name = this.name.replace(/ä/g, 'ae').replace(/ö/g, 'oe').replace(/ü/g, 'ue').replace(/ß/g, 'ss');
this.name = this.name.replace(/Ä/g, 'Ae').replace(/Ö/g, 'Oe').replace(/Ü/g, 'Ue');
this.name = this.name.replace(/[^\w]/g, '');
return this;
}
}
|
4113227d3886f150bef37efb24ac5b909cdd0ac9
|
TypeScript
|
PerryHuan9/react-ts
|
/src/testTs/variable.ts
| 3.9375
| 4
|
export default function testVariable(): void {
let bool: boolean = true;
let num: number = 188;
let num2: number = 0xff;
const str: string = `hello word ${bool}`;
const arr: number[] = [12,34,45,65];
const arr2: Array<string> = ['hello', 'word']
const tuple: [String, Number] = ['',12]
enum Color {Red, Blue, Yello}
let color:Color = Color.Red;
let redName:string = Color[color];
console.log(redName);
enum Animal {Dog=666, Cat, Pin}
console.log(Animal);
// Any
let anyVar: any = 'hello'
anyVar = 888;
let obj: object = {a: '上山打老虎'}
let anyArr: any [] = [12,'', true];
// void 类型的值只能是undefined或null
let voidVar:void = undefined;
// null和undefined类型
let nullVar: null = null;
const undefVar: undefined = undefined;
// never类型, 永不存在的类型
function testNever(name:object|null): never {
throw new Error();
}
// 类型断言
let a:any = 'this is a book.';
let len:number = (a as string).length;
let len2:number = (<string>a).length;
console.log(len, len2);
type C ={a: string, b: number}
let object: C ;
object = {a: '', b: 132};
console.log(object)
}
testVariable();
|
36c7a3dd669f252ea450766d18a4698187e268ae
|
TypeScript
|
apollographql/apollo-ios
|
/Sources/ApolloCodegenLib/Frontend/JavaScript/src/utilities/apolloCodegenSchemaExtension.ts
| 2.5625
| 3
|
import { DirectiveDefinitionNode, DocumentNode, Kind, NameNode, StringValueNode, concatAST } from "graphql";
export const directive_apollo_client_ios_localCacheMutation: DirectiveDefinitionNode = {
kind: Kind.DIRECTIVE_DEFINITION,
description: stringNode("A directive used by the Apollo iOS client to annotate operations or fragments that should be used exclusively for generating local cache mutations instead of as standard operations."),
name: nameNode("apollo_client_ios_localCacheMutation"),
repeatable: false,
locations: [nameNode("QUERY"), nameNode("MUTATION"), nameNode("SUBSCRIPTION"), nameNode("FRAGMENT_DEFINITION")]
}
function nameNode(name :string): NameNode {
return {
kind: Kind.NAME,
value: name
}
}
function stringNode(value :string): StringValueNode {
return {
kind: Kind.STRING,
value: value
}
}
export const apolloCodegenSchemaExtension: DocumentNode = {
kind: Kind.DOCUMENT,
definitions: [
directive_apollo_client_ios_localCacheMutation
]
}
export function addApolloCodegenSchemaExtensionToDocument(document: DocumentNode): DocumentNode {
return document.definitions.some(definition =>
definition.kind == Kind.DIRECTIVE_DEFINITION &&
definition.name.value == directive_apollo_client_ios_localCacheMutation.name.value
) ?
document :
concatAST([document, apolloCodegenSchemaExtension])
}
|
033c97e069a44b34510f4acaf51a20730ab1cb85
|
TypeScript
|
CyberFlameGO/Maru
|
/src/Connection.ts
| 2.78125
| 3
|
/**
* Copyright (c) 2020 August
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import { PoolClient, Pool } from 'pg';
import type { Pipeline } from './Pipeline';
import { getKindOf } from './util';
import { Batch } from './Batch';
// credit: https://stackoverflow.com/questions/32608842/validating-if-string-contains-date
const DateRegex = /(\d{4})([\/-])(\d{1,2})\2(\d{1,2})/;
function convertResults(sql: Pipeline | string, results: any) {
if (Array.isArray(results)) return results.map(result => convertResults(sql, result));
if (typeof sql === 'object' && !Array.isArray(sql)) {
switch (sql.id) {
case 'select':
case 'select_all': {
const keys = Object.keys(results);
keys.map((key) => {
const value = results[key];
if (getKindOf(value) === 'string') {
try {
// Check if the value is JSONable
JSON.parse(value);
results[key] = JSON.parse(value);
} catch {
// ignore since it's not a JSON object/array
}
if (DateRegex.test(value)) {
results[key] = new Date(value);
}
}
});
} break;
}
if (sql.id === 'count_docs') return Number(results['count']);
} else if (typeof sql === 'string') {
if (sql.startsWith('SELECT')) {
const lines = sql.split(' ');
if (lines[1].includes('count')) return Number(results['count']);
else {
const keys = Object.keys(results);
keys.map((key) => {
const value = results[key];
if (getKindOf(value) === 'string') {
try {
// Check if the value is JSONable
JSON.parse(value);
results[key] = JSON.parse(value);
} catch {
// ignore since it's not a JSON object/array
}
if (DateRegex.test(value)) {
results[key] = new Date(value);
}
}
});
}
}
}
return results;
}
/**
* The core of actually connecting to the database
*/
export class Connection {
/** Check if the connection exists */
public connected: boolean;
/** The client */
private client!: PoolClient;
/** The connection pool */
private pool: Pool;
/**
* Creates a new Connection
* @param pool The pool instance
*/
constructor(pool: Pool) {
this.connected = false;
this.pool = pool;
}
/**
* Connects to the database
*/
async connect() {
if (this.connected) throw new Error('Connection already exists');
await this.pool.connect()
.then((client) => {
this.client = client;
this.connected = true;
});
}
/**
* Creates a new Transaction
*/
createBatch() {
return new Batch(this);
}
/**
* Queries SQL and returns the values as an array
* @param sql The SQL to execute
*/
query<T>(sql: string | Pipeline, array: false): Promise<T | null>;
/**
* Queries SQL and returns the values as an array
* @param sql The SQL to execute
*/
query<T>(sql: string | Pipeline, array: true): Promise<T[] | null>;
/**
* Queries SQL and returns the value
* @param sql The SQL to execute
*/
query<T>(sql: string | Pipeline, array: boolean = false): Promise<T | T[] | null> {
const query = typeof sql === 'string' ? sql : sql.getSql();
return new Promise((resolve, reject) => this.client.query(query, (error, results) => {
if (error) return reject(error);
if (results.rowCount < 1) return resolve(null);
else resolve(array ? convertResults(sql, results.rows) : convertResults(sql, results.rows[0]));
}));
}
}
|
5ddc9d594214b63fd547b3a90756a51e71b11e88
|
TypeScript
|
senwong/type-challenges
|
/src/459-medium-flatten.ts
| 3.25
| 3
|
type Flatten<T> = T extends [infer F, ...infer R] ? F extends any[] ? [...Flatten<F>, ...Flatten<R>] : [F, ...Flatten<R>] : [];
type flatten = Flatten<[1, 2, [3, 4], [[[5]]]]> // [1, 2, 3, 4, 5]
|
de28020a2f69ceca139da59c5601d672a58758f5
|
TypeScript
|
navikom/dashboard
|
/src/api/index.ts
| 2.78125
| 3
|
import MainApi from "api/MainApi/Api";
import { ErrorHandler } from "utils/ErrorHandler";
export enum Apis {
Main,
}
export function api(type: Apis) {
if (type === Apis.Main) {
return new MainApi();
}
throw new ErrorHandler('There is not Api type provided');
}
|
8b3be98812457916333298a7b7a01a4bd25edda4
|
TypeScript
|
dzearing/new-merge-styles-proto
|
/src/styled/css.ts
| 2.96875
| 3
|
import { getStyleElement } from "./getStyleElement";
import { parseSelectors } from "./parseSelectors";
const _rules: {
[key: string]: {
[key: string]: {
[key: string]: string;
};
};
} = {};
export function css(rulesString) {
const classNames = [];
const selectors = parseSelectors(rulesString);
for (const selector in selectors) {
const rules = selectors[selector];
for (let name in rules) {
const value = rules[name];
classNames.push(
_findClass(selector, name, value) || _addClass(selector, name, value)
);
}
}
return classNames.join(" ");
}
function _findClass(selector, name, value) {
const names = (_rules[selector] = _rules[selector] || {});
const values = (names[name] = names[name] || {});
return values[value];
}
function _addClass(selector: string, name: string, value: string): string {
const className = (_rules[selector][name][value] = getClassName());
_insertRule(selector.replace(/&/g, "." + className), name, value);
return className;
}
function _insertRule(selector, name, value) {
const style = getStyleElement();
const rule = `${selector}{${name}:${value};}`;
console.log(rule);
style.sheet.insertRule(rule);
}
const Characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
let _counter = 0;
function getClassName(): string {
return "a" + _counter++;
}
|
b9a6239004d96c1a8fb5b0c2f90fecc5e37043a6
|
TypeScript
|
yushunwang123/DesignPattern
|
/Visitor/Visitor.ts
| 4.34375
| 4
|
abstract class AbstractElement {
// 定义业务逻辑
public abstract doSomething() : void;
// 允许谁来访问
public abstract accept (visitor : Visitor) : void;
}
class ConcreteElement1 extends AbstractElement{
public doSomething() : void {
console.log('ConcreteElement1执行的业务逻辑');
}
public accept(visitor : Visitor) : void {
visitor.visit1(this)
}
}
class ConcreteElement2 extends AbstractElement{
public doSomething() : void {
console.log('ConcreteElement1执行的业务逻辑');
}
public accept(visitor : Visitor) : void {
visitor.visit2(this)
}
}
abstract class Visitor {
public abstract visit1(element1 : ConcreteElement1) : void;
public abstract visit2(element2 : ConcreteElement2) : void;
}
class ConcreteVistor extends Visitor {
public visit1(element1 : ConcreteElement1) : void {
console.log('进入处理element1')
element1.doSomething();
}
public visit2(element2 : ConcreteElement2) : void {
console.log('进入处理element2');
element2.doSomething();
}
}
// 数据结构,管理很多元素(ConcreteElement1,ConcreteElement1)
class ObjectStructure {
private listSet : Set<AbstractElement>;
constructor() {
this.listSet = new Set();
}
// 增加
public attach(element : AbstractElement) : void {
this.listSet.add(element);
}
// 删除
public detach(element : AbstractElement) : void {
this.listSet.delete(element);
}
// 显示
public display(visitor : Visitor) : void {
for (let element of this.listSet.values()) {
element.accept(visitor);
}
}
}
function main() {
const objectStructure : ObjectStructure = new ObjectStructure();
objectStructure.attach(new ConcreteElement1());
objectStructure.attach(new ConcreteElement2());
const visitor :Visitor = new ConcreteVistor();
objectStructure.display(visitor);
}
main();
|
dfd14c6b04c8b049aa9c74563c679faef61c33da
|
TypeScript
|
icebob/fakerator
|
/fakerator.d.ts
| 2.890625
| 3
|
declare module 'fakerator' {
export interface RandomStringOptions {
min?: number;
max?: number;
}
export type TimesOptions = RandomStringOptions;
export interface CountryAndCode {
code: string;
name: string;
}
export interface LatitudeAndLongitude {
latitude: number;
longitude: number;
}
export enum LoremPixelCategories {
Abstract = 'abstract',
Animals = 'animals',
Business = 'business',
Cats = 'cats',
City = 'city',
Food = 'food',
Nightlife = 'nightlife',
Fashion = 'fashion',
People = 'people',
Nature = 'nature',
Sports = 'sports',
Technics = 'technics',
Transport = 'transport',
ColorImage = 'color',
GrayImage = 'gray'
}
export interface User {
"firstName": string;
"lastName": string;
"userName": string;
"password": string;
"email": string;
"phone": string;
"dob": string;
"website": string;
"ip": string;
"avatar": string;
"gravatar": string;
"address": Address;
"status": boolean;
}
export interface Company {
"name": string;
"email": string;
"phone": string;
"website": string;
"ip": string;
"address": Address;
}
export interface Address {
"country": string;
"countryCode": string;
"state": string;
"city": string;
"street": string;
"zip": string;
"geo": LatitudeAndLongitude;
}
export interface Post {
"title": string;
"keywords": Array<string>;
"created": string;
"content": string;
}
class FakeratorRandom {
/**
* It starts from 0
* Sample: 0
* @param max Max number function will select
* @returns number
*/
number(max: number): number;
/**
* Random number selection between min and max. Min and max values are included.
* Sample: 0
* @param min Min number function will select
* @param max Max number function will select
* @returns number
*/
number(min: number, max: number): number;
/**
* Random number selection between min and max. Min and max values are included.
* Sample: 45.2
* @param min Min number function will select
* @param max Max number function will select
* @param precision Can generate floating number if you define this parameter. Note: Do not use 0
* @returns number
*/
number(min: number, max: number, precision?: number): number;
/**
* Random boolean value.
* Sample: true
* @returns boolean
*/
boolean(): boolean;
/**
* Random boolean value if it below likelyhood
* Sample: true
* @param likelyhood Returns true if selected random value between 0 and 100 below this parameter.
* @returns boolean
*/
boolean(likelyhood?: number): boolean;
/**
* Random 9 character string
* Sample:
* @returns string
*/
digit(): string;
/**
* Random hexedemical string
* @returns string
*/
hex(): string;
/**
* Random hexedemical string
* @param length Length of the generated string
* @returns string
*/
hex(length?: number): string;
/**
* Just one letter.
*/
letter(): string;
string(): string;
string(length: number): string;
string(options: RandomStringOptions): string;
arrayElement<T>(array: Array<T>): T;
objectElement<returnType>(object: object): returnType;
masked(format: string): string;
}
class FakeratorNames {
/**
* Dr. Sheryl Gleichner
*/
name(): string;
/**
* Bruce Weber
*/
nameM(): string;
/**
* Juanita Daniel
*/
nameF(): string;
/**
* Marco
*/
firstName(): string;
/**
* Bruce
*/
firstNameM(): string;
/**
* Kelly
*/
firstNameF(): string;
/**
* Reilly
*/
lastName(): string;
/**
* Collier
*/
lastNameM(): string;
/**
* Moore
*/
lastNameF(): string;
/**
* Mr.
*/
prefix(): string;
/**
* MD
*/
suffix(): string;
}
class FakeratorAddress {
/**
* Romania
*/
country(): string;
/**
* RO
*/
countryCode(): string;
/**
* { code: "RO", name: "Romania" }
*/
countryAndCode(): CountryAndCode;
/**
* Merlestad
*/
city(): string;
/**
* 96214 Annette Radial Apt. 543
*/
street(): string;
/**
* Gabriel Islands
*/
streetName(): string;
/**
* 196
*/
buildingNumber(): string;
/**
* 54360-6405
*/
postCode(): string;
/**
* { latitude: 40.4233, longitude: -131.9741 }
*/
geoLocation(): LatitudeAndLongitude;
/**
* 1180
*/
altitude(): number;
}
class FakeratorPhone {
/**
* (640) 552-0763
*/
number(): string;
}
class FakeratorCompany {
/**
* Weber, Gleichner and Kertzmann Inc.
*/
name(): string;
/**
* LLC
*/
suffix(): string;
}
class FakeratorInternet {
/**
* kelly.moore14
*/
userName(): string;
/**
* Generate a username based an existing name
* Sample: johndoe19
* @param firstName First name
* @param lastName Last Name
*/
userName(firstName: string, lastName: string): string;
/**
* Generates a password
*/
password(): string;
/**
* Generates a password
*/
password(length: number): string;
password(length: number, memorable: boolean): string;
password(length: number, memorable: boolean, pattern: string): string;
password(length: number, memorable: boolean, pattern: string, prefix: string): string;
/**
* merle-gleichner.net
*/
domain(): string;
/**
* http://ella-parisian.com
*/
url(): string;
url(isHttps: boolean): string;
url(isHttps: boolean, hasWWW: boolean): string;
/**
* kelly.moore@gmail.com
*/
email(): string;
/**
* Generate an email address from an existing name
* Sample: john.doe@hotmail.com
* @param firstName First name
* @param lastName Last name
*/
email(firstName: string, lastName: string): string;
email(firstName: string, lastName: string, domain: string): string;
/**
* http://lorempixel.com/640/480
*/
image(): string;
/**
* http://lorempixel.com/640/480
*/
image(width: number, height: number): string;
/**
* http://lorempixel.com/640/480/sports
*/
image(width: number, height: number, category: LoremPixelCategories): string;
/**
* 65:a1:a6:18:94:0b
*/
mac(): string;
/**
* 69.45.112.94
*/
ip(): string;
/**
* b2e9:4275:95a9:65a1:a618:940b:a6ce:adb6
*/
ipv6(): string;
/**
* Generates a hexedemical color string
* b76f49
*/
color(): string;
/**
* Give an avatar link (uifaces.com)
* https://s3.amazonaws.com/uifaces/faces/twitter/snowwrite/128.jpg
*/
avatar(): string;
/**
* Generate a gravatar link
* https://www.gravatar.com/avatar/a91004b566f80271f0a3577f71d43cd4
*/
gravatar(): string;
/**
* Generate a gravatar link from an email address
* https://www.gravatar.com/avatar/a91004b566f80271f0a3577f71d43cd4
*/
gravatar(email: string): string;
}
class FakeratorLorem {
/**
* lorem
*/
word(): string;
/**
* Libero similique quam voluptas soluta.
*/
sentence(): string;
/**
* Ut velit enim vel. Unde aut sint possimus velit commodi numquam. Autem expedita dignissimos est qui consequatur et delectus. Et qui necessitatibus voluptas quam. Dicta temporibus animi optio tempora aperiam repudiandae beatae. Placeat quo voluptatibus neque repellendus dolorem.
*/
paragraph(): string;
}
class FakeratorDate {
/**
* Asia/Bangkok
*/
timezone(): string;
past(years: number, refDate: Date): Date;
future(years: number, refDate: Date): Date;
between(from: Date, to: Date): Date;
recent(days): Date;
age(min: number, max: number): number;
month(): string;
weekday(): string;
weekdayShort(): string;
weekdayMin(): string;
}
class FakeratorMisc {
uuid(): string;
}
class FakeratorEntity {
user(): User;
user(sex: 'M' | 'F'): User;
address(): Address;
company(): Company;
post(): Post;
}
class Fakerator {
constructor(localeID?: string);
seed(newSeed: number | number[]);
capitalize(textWillBeCapitalized: string): string;
slugify(textWillBeSlugified: string): string;
replaceSymbols(format: string): string;
replaceSymbols(format: string, numberSymbol?: string, alphaSymbol?: string): string;
shuffle(textWillBeShuffled: string): string;
shuffle<T>(arrayWillBeShuffled: Array<T>): Array<T>;
populate(format: string, ...args: Array<any>): string;
times(functionWillRepeat: Function, nTimes: number, ...args: Array<any>): Array<any>;
times(functionWillRepeat: Function, options: TimesOptions, ...args: Array<any>): Array<any>;
utimes(functionWillRepeat: Function, nTimes: number, ...args: Array<any>): Array<any>;
utimes(functionWillRepeat: Function, options: TimesOptions, ...args: Array<any>): Array<any>;
generate(functionWillBeUsedForGeneration: Function, ...args: Array<any>): string;
public random: FakeratorRandom;
public names: FakeratorNames;
public address: FakeratorAddress;
public phone: FakeratorPhone;
public company: FakeratorCompany;
public internet: FakeratorInternet;
public lorem: FakeratorLorem;
public date: FakeratorDate;
public misc: FakeratorMisc;
public entity: FakeratorEntity;
}
const fn: (localeID?: string) => Fakerator;
export default fn;
}
|
265fb6409081a9f5c758c3751de79dad2e80f237
|
TypeScript
|
w960603/cat-mall-server
|
/server/public/resFunc.ts
| 2.6875
| 3
|
import {statusCode} from '../config/statusCode'
import * as interf from '../interfaces/publicInterfaces'
import {Request, Response, NextFunction} from 'express'
// 成功的响应
export const success = (data: object, res: Response, msg?:string):void => {
const temp:interf.IResponse = {
code: statusCode.SUCCESS.code,
msg: msg || statusCode.SUCCESS.msg,
data
}
res.json(temp)
}
// 回复指定内容
export const appoint = (target: any,res: Response, data:object = {}):void => {
const temp:interf.IResponse = {
code: target.code,
msg: target.msg,
data
}
res.json(temp)
}
|
e8e3c9275bd90c5e9337519118ca76a712b76ea1
|
TypeScript
|
cdnjs/cdnjs
|
/ajax/libs/react-dnd/14.0.1/types/types/monitors.d.ts
| 2.875
| 3
|
import { Identifier, Unsubscribe } from 'dnd-core';
export interface XYCoord {
x: number;
y: number;
}
export interface HandlerManager {
receiveHandlerId: (handlerId: Identifier | null) => void;
getHandlerId: () => Identifier | null;
}
export interface DragSourceMonitor<DragObject = unknown, DropResult = unknown> extends HandlerManager, MonitorEventEmitter {
/**
* Returns true if no drag operation is in progress, and the owner's canDrag() returns true or is not defined.
*/
canDrag(): boolean;
/**
* Returns true if a drag operation is in progress, and either the owner initiated the drag, or its isDragging() is defined and returns true.
*/
isDragging(): boolean;
/**
* Returns a string or a symbol identifying the type of the current dragged item. Returns null if no item is being dragged.
*/
getItemType(): Identifier | null;
/**
* Returns a plain object representing the currently dragged item. Every drag source must specify it by returning an object from its beginDrag() method.
* Returns null if no item is being dragged.
*/
getItem<T = DragObject>(): T;
/**
* Returns a plain object representing the last recorded drop result. The drop targets may optionally specify it by returning an object from their
* drop() methods. When a chain of drop() is dispatched for the nested targets, bottom up, any parent that explicitly returns its own result from drop()
* overrides the child drop result previously set by the child. Returns null if called outside endDrag().
*/
getDropResult<T = DropResult>(): T | null;
/**
* Returns true if some drop target has handled the drop event, false otherwise. Even if a target did not return a drop result, didDrop() returns true.
* Use it inside endDrag() to test whether any drop target has handled the drop. Returns false if called outside endDrag().
*/
didDrop(): boolean;
/**
* Returns the { x, y } client offset of the pointer at the time when the current drag operation has started. Returns null if no item is being dragged.
*/
getInitialClientOffset(): XYCoord | null;
/**
* Returns the { x, y } client offset of the drag source component's root DOM node at the time when the current drag operation has started.
* Returns null if no item is being dragged.
*/
getInitialSourceClientOffset(): XYCoord | null;
/**
* Returns the last recorded { x, y } client offset of the pointer while a drag operation is in progress. Returns null if no item is being dragged.
*/
getClientOffset(): XYCoord | null;
/**
* Returns the { x, y } difference between the last recorded client offset of the pointer and the client offset when the current drag operation has started.
* Returns null if no item is being dragged.
*/
getDifferenceFromInitialOffset(): XYCoord | null;
/**
* Returns the projected { x, y } client offset of the drag source component's root DOM node, based on its position at the time when the current drag operation has
* started, and the movement difference. Returns null if no item is being dragged.
*/
getSourceClientOffset(): XYCoord | null;
/**
* Returns the ids of the potential drop targets.
*/
getTargetIds(): Identifier[];
}
export interface MonitorEventEmitter {
subscribeToStateChange(fn: () => void, options?: {
handlerIds?: Identifier[];
}): Unsubscribe;
}
export interface DropTargetMonitor<DragObject = unknown, DropResult = unknown> extends HandlerManager, MonitorEventEmitter {
/**
* Returns true if there is a drag operation in progress, and the owner's canDrop() returns true or is not defined.
*/
canDrop(): boolean;
/**
* Returns true if there is a drag operation in progress, and the pointer is currently hovering over the owner.
* You may optionally pass { shallow: true } to strictly check whether only the owner is being hovered, as opposed
* to a nested target.
*/
isOver(options?: {
shallow?: boolean;
}): boolean;
/**
* Returns a string or a symbol identifying the type of the current dragged item. Returns null if no item is being dragged.
*/
getItemType(): Identifier | null;
/**
* Returns a plain object representing the currently dragged item. Every drag source must specify it by returning an object from
* its beginDrag() method. Returns null if no item is being dragged.
*/
getItem<T = DragObject>(): T;
/**
* Returns a plain object representing the last recorded drop result. The drop targets may optionally specify it by returning an
* object from their drop() methods. When a chain of drop() is dispatched for the nested targets, bottom up, any parent that explicitly
* returns its own result from drop() overrides the drop result previously set by the child. Returns null if called outside drop().
*/
getDropResult<T = DropResult>(): T | null;
/**
* Returns true if some drop target has handled the drop event, false otherwise. Even if a target did not return a drop result,
* didDrop() returns true. Use it inside drop() to test whether any nested drop target has already handled the drop. Returns false
* if called outside drop().
*/
didDrop(): boolean;
/**
* Returns the { x, y } client offset of the pointer at the time when the current drag operation has started. Returns null if no item
* is being dragged.
*/
getInitialClientOffset(): XYCoord | null;
/**
* Returns the { x, y } client offset of the drag source component's root DOM node at the time when the current drag operation has started.
* Returns null if no item is being dragged.
*/
getInitialSourceClientOffset(): XYCoord | null;
/**
* Returns the last recorded { x, y } client offset of the pointer while a drag operation is in progress. Returns null if no item is being dragged.
*/
getClientOffset(): XYCoord | null;
/**
* Returns the { x, y } difference between the last recorded client offset of the pointer and the client offset when current the drag operation has
* started. Returns null if no item is being dragged.
*/
getDifferenceFromInitialOffset(): XYCoord | null;
/**
* Returns the projected { x, y } client offset of the drag source component's root DOM node, based on its position at the time when the current
* drag operation has started, and the movement difference. Returns null if no item is being dragged.
*/
getSourceClientOffset(): XYCoord | null;
}
export interface DragLayerMonitor {
/**
* Returns true if a drag operation is in progress. Returns false otherwise.
*/
isDragging(): boolean;
/**
* Returns a string or a symbol identifying the type of the current dragged item.
* Returns null if no item is being dragged.
*/
getItemType(): Identifier | null;
/**
* Returns a plain object representing the currently dragged item.
* Every drag source must specify it by returning an object from its beginDrag() method.
* Returns null if no item is being dragged.
*/
getItem(): any;
/**
* Returns the { x, y } client offset of the pointer at the time when the current drag operation has started.
* Returns null if no item is being dragged.
*/
getInitialClientOffset(): XYCoord | null;
/**
* Returns the { x, y } client offset of the drag source component's root DOM node at the time when the current
* drag operation has started. Returns null if no item is being dragged.
*/
getInitialSourceClientOffset(): XYCoord | null;
/**
* Returns the last recorded { x, y } client offset of the pointer while a drag operation is in progress.
* Returns null if no item is being dragged.
*/
getClientOffset(): XYCoord | null;
/**
* Returns the { x, y } difference between the last recorded client offset of the pointer and the client
* offset when current the drag operation has started. Returns null if no item is being dragged.
*/
getDifferenceFromInitialOffset(): XYCoord | null;
/**
* Returns the projected { x, y } client offset of the drag source component's root DOM node, based on its
* position at the time when the current drag operation has started, and the movement difference.
* Returns null if no item is being dragged.
*/
getSourceClientOffset(): XYCoord | null;
}
|
4ff9d06636010d07240222cb8d1bc0a4355709f0
|
TypeScript
|
cmwendwa/vscode-resjson
|
/src/lib/diagnostics/comma-validator.ts
| 2.734375
| 3
|
import * as vscode from "vscode";
import { BaseDiagnosticsValidation } from "./base-diagnostic-validator";
import { isCommaMissing } from '../utils/comma-missing';
import { Strings } from '../../resources/res-strings';
import { DiagnosticCodes } from '../constants/general';
import { Regexes } from '../constants/regexes';
export class EndCommaDiagnosticValidator extends BaseDiagnosticsValidation {
public static validate(splitDoc: string[], index: number): vscode.Diagnostic[] {
const line = splitDoc[index];
const diagnostics: vscode.Diagnostic[] = [];
const restOfContent = splitDoc.slice(index + 1).join('').trim();
if (isCommaMissing(line, restOfContent)) {
const missingEndCharDiag: vscode.Diagnostic = new vscode.Diagnostic(
new vscode.Range(
new vscode.Position(
index, line.search(/\S/)
),
new vscode.Position(index, line.length)
),
Strings.diagnosticMessages.missingCommaError,
vscode.DiagnosticSeverity.Error
);
missingEndCharDiag.code = DiagnosticCodes.MissingCommaError;
diagnostics.push(missingEndCharDiag);
}
if(this.isTrailingComma(line, restOfContent)){
const trailingCommaDiag: vscode.Diagnostic = new vscode.Diagnostic(
new vscode.Range(
new vscode.Position(
index, line.search(Regexes.endOfLineComma)
),
new vscode.Position(
index, line.search(Regexes.endOfLineComma)
)
),
Strings.diagnosticMessages.trailingCommaError,
vscode.DiagnosticSeverity.Error
);
trailingCommaDiag.code = DiagnosticCodes.TrailingCommaError;
diagnostics.push(trailingCommaDiag);
}
return diagnostics;
}
private static isTrailingComma(line: string, restOfContent: string): boolean {
const lastLineChar = line && line.trimRight().substr(-1);
const firstContentChar = restOfContent && restOfContent.trimLeft()[0];
return lastLineChar === ',' && firstContentChar === '}';
}
}
|
9c678ce6a8da92a2db0fe9ef1122701d26371647
|
TypeScript
|
re2005/angular-login-app
|
/src/app/services/auth/auth.service.ts
| 2.65625
| 3
|
import {Injectable} from '@angular/core';
import {IUser} from '../../interfaces/user';
import {BehaviorSubject, Observable} from 'rxjs';
@Injectable()
export class AuthService {
private usersArray = new BehaviorSubject<IUser[]>(this.getUsers());
getToken(): string {
return localStorage.getItem('token');
}
public isPasswordValid(username, password) {
const user = this.getUser(username);
return user.password === password;
}
public isAuthenticated(): boolean {
return this.getToken() !== null;
}
public setToken(username): void {
localStorage.setItem('token', username);
}
public removeToken(): void {
localStorage.removeItem('token');
}
public getUsersOb(): Observable<IUser[]> {
return this.usersArray;
}
public setUser(user: IUser): void {
const users = this.getUsers() || [];
users.push(user);
this.setUsers(users);
this.usersArray.next(users);
}
public setUsers(users: Array<IUser>): void {
this.usersArray.next(users);
localStorage.setItem('users', JSON.stringify(users));
}
public getUsers(): Array<IUser> {
return JSON.parse(localStorage.getItem('users'));
}
public getUser(username: string): IUser {
if (!this.getUsers()) {
return;
}
return this.getUsers().find(u => u.username === username);
}
public removeUser(username: string): void {
this.setUsers(this.getUsers().filter(u => u.username !== username));
}
public getCurrentUser(): IUser {
return this.getUser(this.getToken());
}
}
|
95e801d6a7e195815a8cf0255b9af5df4607f4d7
|
TypeScript
|
benmvp/bart-salmon
|
/_scripts/gen-station-routes-data.ts
| 2.8125
| 3
|
import zipObject from 'lodash/zipObject'
import mapValues from 'lodash/mapValues'
import keyBy from 'lodash/keyBy'
import sum from 'lodash/sum'
import startOfWeek from 'date-fns/startOfWeek'
import endOfWeek from 'date-fns/endOfWeek'
import addDays from 'date-fns/addDays'
import formatDate from 'date-fns/format'
import { fetchBartInfo } from '../src/api/bart'
import { DepartureApiRequest } from '../src/api/types'
import { genDataFile, processSequentially } from './utils'
import { StationName, StationLookup, RouteId } from '../src/utils/types'
import stationsLookup from '../src/data/stations.json'
const STATION_NAMES = Object.keys(
(stationsLookup as unknown) as StationLookup
) as StationName[]
const _fetchDepartSchedules = (
orig: StationName,
dest: StationName,
date: Date,
) =>
fetchBartInfo<DepartureApiRequest>({
type: 'sched',
command: 'depart',
params: {
orig,
dest,
date: formatDate(date, 'MM/dd/yyyy'),
time: '5:00pm',
}
})
const _getRoutesForOriginDestination = async (
origin: StationName,
destination: StationName,
) => {
const nextWeek = addDays(Date.now(), 7)
const sunday = startOfWeek(nextWeek)
const saturday = endOfWeek(nextWeek)
const wednesday = addDays(sunday, 3)
// Get the departure schedule on different days to ensure
// we get the normal routes plus the off-peak routes
const allDepartureSchedules = await Promise.all([
_fetchDepartSchedules(origin, destination, wednesday),
_fetchDepartSchedules(origin, destination, saturday),
_fetchDepartSchedules(origin, destination, sunday),
])
// Merge the trip information from all schedules
const trips = allDepartureSchedules
.map((schedules) => schedules.schedule.request.trip)
.flat()
// Get the unique route IDs for trips that only needed one leg
// (i.e. direct routes)
const directRoutes = [
...new Set(
trips
.filter((tripInfo) => tripInfo.leg.length === 1)
.map((tripInfo) => tripInfo.leg[0]['@line'])
),
]
// Get the unique tuples of route IDs that are needed for multi-leg trips
const multiRoutes = [
...new Set(
trips
.filter((tripInfo) => tripInfo.leg.length > 1)
.map((tripInfo) => tripInfo.leg.map((leg) => leg['@line']))
.map((tripRoutes) => tripRoutes.join('|'))
)
]
.map((tripRouteString) => tripRouteString.split('|') as RouteId[])
// get the average time between the two stations
const time = Math.ceil(
sum(trips.map((tripInfo) => +tripInfo['@tripTime'])) / trips.length
)
return {
destination,
directRoutes,
multiRoutes,
time,
}
}
/**
* For the given origin station, returns a promise that when fulfilled returns a
* lookup of destination stations to direct and multi routes
*/
const _getAllDestinationRoutesForStation = async (origin: StationName) => {
console.log(`Fetching destination route info for: ${origin}`)
// Build up a list of destination stations by removing the
// origin station
const destinationStations = STATION_NAMES.filter((station) => station !== origin)
// Get the destination routes for all the destination stations.
const destinationRoutes = await processSequentially(
destinationStations,
(destination) => _getRoutesForOriginDestination(origin, destination),
10,
)
// Convert the routes list into a look up by the destination
const destinationRoutesLookup = keyBy(destinationRoutes, 'destination')
// Only keep `directRoutes` & `multiRoutes` in the look up (removing `destination`
// that was used to create the lookup)
return mapValues(
destinationRoutesLookup,
({ directRoutes, multiRoutes, time }) => ({ directRoutes, multiRoutes, time })
)
}
/**
* Return a promise that when fulfilled contains a lookup of origin stations to
* destination stations to direct and multi routes
*/
const _getStationRoutes = async () => {
const stationRoutesList = await processSequentially(
STATION_NAMES,
_getAllDestinationRoutesForStation,
)
return zipObject(STATION_NAMES, stationRoutesList)
}
(async () => {
try {
await genDataFile(
_getStationRoutes,
'../src/data/station-routes.json',
'routes between stations'
)
} catch (err) {
console.error(err)
process.exit(1)
}
})()
|
520f73b69fd4560564ec74a8a6e1cba0d07cdbad
|
TypeScript
|
CBSM-Finance/rx-designer
|
/electron/log.ts
| 2.765625
| 3
|
import * as chalk from 'chalk';
const logger = console.log;
const ctx = new chalk.Instance({ level: 3 });
const toString = (args: any[]) => args.map(arg => typeof arg === 'object' ? JSON.stringify(arg) : arg.toString());
type logLevels = 'error' | 'notify' | 'warn';
export const log: { [level in logLevels]: (...args: any[]) => void } = {
error: (...args) => logger(ctx.red(...toString(args))),
notify: (...args) => logger(ctx.hex('#0010e0').bgHex('#8899bb')(...toString(args))),
warn: (...args) => logger(ctx.yellow(...toString(args))),
};
|
c0c537700ccfd2002a5565608d2837d8a13eec75
|
TypeScript
|
valpr/adventofcode-2020
|
/src/day25/part01.ts
| 3.265625
| 3
|
import { readFileSync } from 'fs';
let [cardPublicKey, doorPublicKey] = readFileSync('./input.txt', 'utf-8').split('\r\n').map(x => parseInt(x));
/*
Loop Size is unknown
Assuming subjectNumber for each key is always 7?...
*/
const searchingTransform = (subjectNumber: number, publicKey: number) => {
let value =1;
let loopSize = 0;
while (value !== publicKey) {
value *= subjectNumber;
value = value % 20201227
loopSize++;
}
return loopSize;
}
const transform = (subjectNumber: number, testLoopSize: number) => {
let value = 1;
for (let i = 0; i <testLoopSize; i++) {
value *= subjectNumber;
value = value % 20201227
}
return value;
}
let subjectNumber = 7;
let cardLoopSize = searchingTransform(subjectNumber, cardPublicKey);
let doorLoopSize = searchingTransform(subjectNumber, doorPublicKey);
console.log(cardLoopSize, doorLoopSize);
let encryptionKey = transform(doorPublicKey, cardLoopSize);
let shouldBeSameKey = transform(cardPublicKey, doorLoopSize);
console.log(encryptionKey, shouldBeSameKey);
|
6c0a48385fba1bfe0907864ac6eb8cecc4f13162
|
TypeScript
|
PauloHSOliveira/estudos-ts
|
/src/AULA06-tuples-type/aula06.ts
| 3.703125
| 4
|
// tuple
const dadosCliente: readonly [number, string] = [1, 'Luiz']; // Apenas leitura - Imutável
const dadosCliente2: [number, string, string] = [1, 'Luiz', 'Paulo'];
const dadosCliente3: [number, string, string?] = [1, 'Luiz'];
const dadosCliente4: [number, string, ...string[]] = [1, 'Luiz'];
console.log(dadosCliente);
console.log(dadosCliente2);
console.log(dadosCliente3);
console.log(dadosCliente4);
//readonly array
const array: readonly string[] = ['Paulo', 'Blu', 'teco'];
const array2: ReadonlyArray<string> = ['Paulo', 'Blu', 'teco'];
console.log(array);
console.log(array2);
|
952886fa9a3cb0a18c669d6eeaf2a7bba1cf224c
|
TypeScript
|
NilsHolger/typescriptdesignpatterns
|
/src/app/designpatterns/facade.ts
| 3.53125
| 4
|
class Technology1 {
public function1() : void {
console.log("function1 of technology1");
}
}
class Technology2 {
public function2() : void {
console.log("function2 of technology2");
}
}
class Technology3 {
public function3() : void {
console.log("function3 of technology3");
}
}
export class Facade {
private tech1: Technology1 = new Technology1();
private tech2: Technology2 = new Technology2();
private tech3: Technology3 = new Technology3();
public implementation1(): void {
console.log("implementation1 is invoked -------");
this.tech1.function1();
this.tech2.function2();
console.log("----------------------------------");
}
public implementation2(): void {
console.log("implementation2 is invoked -------");
this.tech1.function1();
this.tech3.function3();
console.log("----------------------------------");
}
}
|
f3da7f6bc6f4272edf71f235adffb4213545b1bc
|
TypeScript
|
witsawa-corporation/assignment-backend-2020
|
/app/middlewares/errorHandler.ts
| 2.59375
| 3
|
import express from 'express'
function errorHandler(
err: Error,
req: express.Request,
res: express.Response,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
next: express.NextFunction,
): void {
const errMessage: string = err.message
const status: number = +errMessage.substring(0, 3) || 500
const messageTemp = errMessage.substring(5)
const message = messageTemp.split(',')[0]
res.status(status)
res.send({ status, message })
}
export default errorHandler
|
61d86fb800b0a9b4fc1616cd8e0ced7cc98d323d
|
TypeScript
|
ozawa940/portfolio
|
/src/store/common/CommonReducer.ts
| 2.71875
| 3
|
import {createSlice} from "@reduxjs/toolkit";
export type CommonStateType = {
showErrorFlg: boolean,
errorTitle: string,
errorMsg: string,
}
const initialState: CommonStateType = {
showErrorFlg: false,
errorTitle: "",
errorMsg: ""
}
export const CommonSlice = createSlice({
name: "common",
initialState,
reducers: {
setError: (state, action) => ({
...state,
showErrorFlg: action.payload.showErrorFlg,
errorTitle: action.payload.errorTitle,
errorMsg: action.payload.errorMsg
}),
clearError: (state) => ({
...state,
showErrorFlg: false,
errorTitle: "",
errorMsg: ""
})
}
})
|
991453f49065bd20b0e30e64cdc921c47eed9f8b
|
TypeScript
|
NoelDeMartin/kinko
|
/resources/js/models/Collection.ts
| 2.921875
| 3
|
export interface CollectionJson {
name: string;
}
export default class Collection {
public static fromJson(json: CollectionJson): Collection {
return new Collection(json);
}
public readonly name: string;
constructor(json: CollectionJson) {
this.name = json.name;
}
}
|
ae976cf9161db3a5971bed2e392d38f09466f8a4
|
TypeScript
|
qogoist/Prima_BulletHell
|
/Game/Config.ts
| 2.625
| 3
|
namespace Game {
export interface Config {
map: Map;
colors: string[];
player: Player;
standardProjectile: StandardProjectile;
spawner: Spawner;
smallEnemy: SmallEnemy;
}
export interface Map {
size: number;
color: string;
camera: number[];
spawnRate: number;
spawnRateReduction: number;
}
export async function loadJSON(): Promise<Config> {
let content: Config = await load("Externals/config.json");
return content;
}
async function load(_filename: string): Promise<Config> {
let response: Response = await fetch(_filename);
let text: string = await response.text();
let json: Config = JSON.parse(text);
return (json);
}
}
|
7e3486f9d4786504cb0357ac18102b8ea0ef1f13
|
TypeScript
|
priwatm/favelagroup
|
/src/stores/security-store.ts
| 2.5625
| 3
|
import {action, makeObservable, observable} from "mobx";
import {User} from "src/types/models";
import {anonymous} from 'src/constants/security'
export class SecurityStore {
@observable
user: User = anonymous;
@observable
error: string = '';
constructor() {
makeObservable(this)
}
@action
setUser(user: User) {
this.user = user
}
@action
setError(error: string) {
this.error = error;
}
@action
unauthorize() {
this.user = anonymous;
}
}
|
a02655da94fefcfc9ddd0fca05451751c23fd1c4
|
TypeScript
|
AlphaLupine/Moosic
|
/src/commands/music/pause.ts
| 2.625
| 3
|
import { Command } from 'discord-akairo';
import { Message } from 'discord.js';
import { Player } from 'erela.js';
export default class PauseCommand extends Command {
constructor() {
super('pause', {
aliases: ['pause'],
description: {
content: 'Pauses the current track'
},
category: 'music'
});
}
async exec(message: Message) {
const guild = message.guild!.id;
const voiChannel = message.member?.voice.channel;
const player: Player = this.client.musicManager.get(guild)!;
if (!player) message.reply('there is no player in this guild');
if (!voiChannel) return message.reply('I cannot find you voice channel');
if (voiChannel.id !== player.voiceChannel) return message.reply('You are not in my voice channel');
if (!player.queue.current) return message.reply('there is no music to pause')
if (player.paused) {
return message.channel.send("The player is already paused.")
}
player.pause(true);
message.channel.send(new this.client.embed().setMain()
.setTitle(`Player paused by ${message.author.username}`)
.setDescription(`Music Paused!`)
)
}
}
|
7e6dc6f4fed04d9f3bbc9078b8e3b50451a26a2c
|
TypeScript
|
andrwj/vscode-markdown-scripture
|
/src/ScriptureReferenceProvider.ts
| 2.96875
| 3
|
import * as vscode from "vscode";
function rangeToString(range: vscode.Range): string {
return `${range.start.line}:${range.start.character}-${range.end.line}:${range.end.character}`;
}
export class ScriptureReferenceProvider implements vscode.ReferenceProvider {
/**
* Provide a set of project-wide references for the given position and document.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param token A cancellation token.
*
* @return An array of locations or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideReferences(
document: vscode.TextDocument,
position: vscode.Position,
context: vscode.ReferenceContext,
token: vscode.CancellationToken
): vscode.ProviderResult<vscode.Location[]> {
const range = ScriptureReferenceProvider.parseReference(document, position);
if (range) {
vscode.window.showInformationMessage(`Found a reference (${rangeToString(range)})!`);
}
return undefined;
}
static parseReference(document: vscode.TextDocument, position: vscode.Position): vscode.Range | undefined {
const range = document.getWordRangeAtPosition(position, /scripture/);
if (!range) { return; }
return range;
}
}
|
6392725e1ef57b0e11376d097bff05fbaaabe5cd
|
TypeScript
|
green-fox-academy/salfayanna
|
/week-01/day-03/draw-diagonal.ts
| 3.53125
| 4
|
'use strict';
export { };
// Write a program that draws a
// square like this:
//
// %%%%%
// %% %
// % % %
// % %%
// % %
// %%%%%
//
// The square should have as many lines as lineCount is
let lineCount: number = 6;
let empty = " "
let fill = '%'
for (let row = 0; row < lineCount; row++) {
if (row === 0 || row === lineCount - 1) {
console.log(fill.repeat(lineCount));
} else {
let strg: string = '';
strg = fill + strg;
for (let col = 1; col < lineCount - 1; col++) {
if (col === row) {
strg = strg + fill;
} else {
strg = strg + empty;
}
}
strg = strg + fill;
console.log(strg);
}
}
|
33d3ae88d2d09d095a86136b4e6f611e9f9b4900
|
TypeScript
|
sebasdb2111/mm_chat_api
|
/src/apps/mmc/controllers/psychic/PsychicDeactivateController.ts
| 2.5625
| 3
|
import {Request, Response} from 'express';
import * as httpStatus from 'http-status';
import Controller from '../Controller';
import PsychicDeactivate from '../../../../contexts/mmc/psychics/application/PsychicDeactivate';
import PsychicDeactivateDto from '../../../../contexts/mmc/psychics/domain/dto/PsychicDeactivateDto';
import PsychicNotExistsException from '../../../../contexts/mmc/shared/domain/exceptions/PsychicNotExistsException';
export class PsychicDeactivateController implements Controller
{
constructor(private psychicDeactivate: PsychicDeactivate)
{
}
async run(req: Request, res: Response)
{
return new Promise(async (resolve, reject) =>
{
const psychicDeactivateDto: PsychicDeactivateDto = new PsychicDeactivateDto(
Number(req.params.id),
Boolean(req.body.isActive)
);
try {
await this.psychicDeactivate.run(psychicDeactivateDto);
resolve(res.status(httpStatus.OK).send(`Psychic ${req.params.id} has been deactivated successfully`));
}
catch (error) {
let httpStatusError = httpStatus.INTERNAL_SERVER_ERROR;
if (error instanceof PsychicNotExistsException) {
httpStatusError = httpStatus.BAD_REQUEST;
}
reject(res.status(httpStatusError).send(error.message));
}
});
}
}
|
dc56027c464f5e69b15b7421d5d5d513ef85bf8d
|
TypeScript
|
frysztak/markdown-to-quill-delta
|
/test/transform.test.ts
| 2.765625
| 3
|
import fs from "fs";
import path from "path";
import { fileURLToPath } from 'url';
import markdownToDelta from "../src/markdownToDelta";
import Op from "quill-delta/dist/Op";
interface Test {
name: string;
ops: Op[];
markdown: string;
}
describe("Remark-Delta Transformer", () => {
const isDirectory = (name: string) => fs.lstatSync(name).isDirectory();
const __filename = fileURLToPath(import.meta.url);
const folderPath: string = path.dirname(__filename);
const directories = fs
.readdirSync(folderPath)
.map((fileName: string) => path.join(folderPath, fileName))
.filter((fileName: string) => isDirectory(fileName));
const tests: Test[] = [];
for (const directory of directories) {
const files = fs.readdirSync(directory);
while (files.length !== 0) {
const file = files[0];
files.splice(0, 1);
const baseFileName = file.replace(".md", "").replace(".json", "");
let matchingFileName: string;
if (file.endsWith(".md")) {
matchingFileName = `${baseFileName}.json`;
} else if (file.endsWith(".json")) {
matchingFileName = `${baseFileName}.md`;
} else {
throw Error(
`Illegal file: ${file}. Allowed file extensions are .md and .json`
);
}
const matchingFileIdx = files.findIndex(f => f === matchingFileName);
if (matchingFileIdx === -1) {
throw Error(`No matching file found for ${file}`);
}
files.splice(matchingFileIdx, 1);
const jsonFilePath = path.join(directory, `${baseFileName}.json`);
const markdownFilePath = path.join(directory, `${baseFileName}.md`);
tests.push({
name: `${path.basename(directory)}/${baseFileName}`,
ops: JSON.parse(fs.readFileSync(jsonFilePath, "utf-8")),
markdown: fs.readFileSync(markdownFilePath, "utf-8")
});
}
}
for (const t of tests) {
test(`Markdown to Delta: ${t.name}`, () => {
const ops = markdownToDelta(t.markdown);
expect(ops).toEqual(t.ops);
});
}
});
|
da89ac649fe8e425603fb7d14f165bc61869fb2a
|
TypeScript
|
carlaofernandesedu/frontbase
|
/angularbase7/iniciando-angular2-mais/src/app/employee.service.ts
| 2.78125
| 3
|
import { Injectable } from '@angular/core';
export interface Employee{
name:string,
salary:number
}
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
employees: Employee[] = [];
constructor() { }
addEmployee(emp:Employee)
{
this.employees.push(emp);
}
}
|
fa55a31b024df2900b6a1f9f26a185c232bde630
|
TypeScript
|
msrikanth508/weather-app
|
/src/api/index.test.ts
| 2.71875
| 3
|
import { fetchWeatherData } from './index';
import mockData from '../mockData';
const mockFetch = (fn) => {
window.fetch = fn;
};
describe('fetchWeatherData', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('should call fetch fn', async () => {
const mockFn = jest.fn();
mockFn.mockResolvedValue({});
mockFetch(mockFn);
await fetchWeatherData('hyderabad', 'In');
expect(mockFn).toBeCalledWith(
'https://cors-anywhere.herokuapp.com/https://samples.openweathermap.org/data/2.5/forecast?q=hyderabad,In&appid=b6907d289e10d714a6e88b30761fae22'
);
});
it('should handle error', async () => {
const mockFn = jest.fn();
mockFn.mockRejectedValueOnce(new Error('error'));
mockFetch(mockFn);
const data = await fetchWeatherData('hyderabad', 'In');
expect(data).toEqual(null);
});
it('should do data transformation', async () => {
const mockFn = jest.fn(() =>
Promise.resolve({
ok: true,
json: () =>
Promise.resolve({
list: [mockData.list[0]],
}),
})
);
mockFetch(mockFn);
const data = await fetchWeatherData('München', 'DE');
expect(mockFn).toBeCalledWith(
'https://cors-anywhere.herokuapp.com/https://samples.openweathermap.org/data/2.5/forecast?q=München,DE&appid=b6907d289e10d714a6e88b30761fae22'
);
expect(data).toEqual([
{
date: new Date('2017-02-16T11:00:00.000Z'),
id: 1487246400,
isCloudy: false,
temp: { max: 13, min: 8, val: 13 },
},
]);
});
it('should return empty array when response is null', async () => {
const mockFn = jest.fn(() =>
Promise.resolve({
ok: true,
json: () =>
Promise.resolve({
list: null,
}),
})
);
mockFetch(mockFn);
const data = await fetchWeatherData('München', 'DE');
expect(mockFn).toBeCalledWith(
'https://cors-anywhere.herokuapp.com/https://samples.openweathermap.org/data/2.5/forecast?q=München,DE&appid=b6907d289e10d714a6e88b30761fae22'
);
expect(data).toEqual([]);
});
});
|
88d43d3bdd08c2a4a5a9f69d761a6782e5296440
|
TypeScript
|
samsoft00/subtitle-and-translator
|
/src/Utils/Emittery.ts
| 2.65625
| 3
|
import { EventEmitter2 } from 'eventemitter2';
const eventEmitter = new EventEmitter2();
export enum EventType {
SendEmail = 'SendEmail',
}
interface IEvent {
payload: any;
type: EventType;
}
export const LengooEmitter = {
emit(event: IEvent) {
eventEmitter.emit(`lengoo:${event.type}`, event.payload);
},
addListener(eventType: EventType, listener: (payload: any) => void | Promise<void>) {
eventEmitter.addListener(`lengoo:${eventType}`, listener);
},
};
|
d01f1f656c96567957dc515689e2420667ab8acb
|
TypeScript
|
poppinss/youch
|
/index.d.ts
| 2.671875
| 3
|
declare module "youch" {
interface YouchOptionsContract {
/**
* Number of lines to be displayed above the error
* in the stack trace.
*/
preLines?: number;
/**
* Number of lines to be displayed below the error
* in the stack trace.
*/
postLines?: number;
}
class Youch<Error, Request> {
constructor(error: Error, request: Request, options?: YouchOptionsContract);
/**
* Stores the link `callback` which
* will be processed when rendering
* the HTML view.
*/
addLink(callback: Function): this;
/**
* Returns error stack as JSON.
*/
toJSON(): Promise<{
error: {
message: string;
name: string;
cause?: any;
help?: any;
status: number;
frames: {
file: string;
filePath: string;
line: number;
column: number;
callee: string;
calleeShort: string;
context: {
start: number;
pre: string;
line: string;
post: string;
};
isModule: boolean;
isNative: boolean;
isApp: boolean;
}[];
};
}>;
/**
* Returns HTML representation of the error stack
* by parsing the stack into frames and getting
* important info out of it.
*/
toHTML(): Promise<string>;
}
export default Youch;
}
|
bfb2f3196655a3320a9315fa38a9c26d8a441140
|
TypeScript
|
vitaly-redkin/Wonderschool-task-list
|
/src/model/BaseEntity.ts
| 3.140625
| 3
|
/**
* Base class for task and group entities.
*/
export class BaseEntity<TId> {
/**
* Constructor.
*
* @param id Entity ID
*/
constructor(public readonly id: TId) {
}
}
|
39e7be0619fe5461e2f807349a8a79773fec53a3
|
TypeScript
|
jeonjonghyeok/reputation-service
|
/src/utils/server/createNewTwitterAccount.ts
| 2.53125
| 3
|
import TwitterAccount from "src/models/web2Accounts/twitter/TwitterAccount.model";
import {
ITwitterAccount,
ITwitterAccountDocument,
} from "src/models/web2Accounts/twitter/TwitterAccount.types";
import { Web2Providers } from "src/models/web2Accounts/Web2Account.types";
export const createTwitterAccountObject = (
props: Omit<ITwitterAccount, "provider" | "createdAt" | "uniqueKey">
) => ({
provider: Web2Providers.TWITTER,
uniqueKey: `${Web2Providers.TWITTER}:${props.providerAccountId}`,
createdAt: Date.now(),
...props,
});
export const instantiateNewTwitterAccount = (
props: Omit<ITwitterAccount, "provider" | "createdAt" | "uniqueKey">
): ITwitterAccountDocument =>
new TwitterAccount(createTwitterAccountObject(props));
|
e5f19f84ae14ab10ceb802a59543d9617ed41030
|
TypeScript
|
PhilippMi/schnoin
|
/src/server/eventBus.ts
| 2.734375
| 3
|
import {Event, EventMap, EventType} from "../shared/Event";
import {GameModel} from "./GameModel";
import {v4 as uuid} from 'uuid';
interface Listener {
game?: GameModel
eventType?: EventType
callback: (payload: any, game: GameModel) => void
}
let listeners: Listener[] = [];
export const eventBus = {
register<K extends keyof EventMap>(game: GameModel | undefined, eventType: K | undefined, callback: (event: EventMap[K], game: GameModel) => void) {
listeners.push({game, eventType, callback})
},
trigger(game: GameModel, event: Omit<Event, 'id'>) {
const fullEvent = Object.assign({id: uuid()}, event)
listeners
.filter(l => (!l.eventType || l.eventType === event.eventType) && (!l.game || l.game === game))
.forEach(l => setTimeout(() => {
try {
l.callback(fullEvent, game);
} catch(e) {
console.error(e)
}
}, 0))
},
deregister(callback: Function) {
listeners = listeners.filter(l => l.callback !== callback)
},
deregisterAll(game: GameModel) {
listeners = listeners.filter(l => l.game !== game)
}
}
|
e12629cd5ef8d0a62ba64f5c7bb6406a152cc636
|
TypeScript
|
kjirou/tilto
|
/src/box.ts
| 2.5625
| 3
|
import * as stripAnsi from 'strip-ansi';
import {
Borders,
placeBorders,
validateMatrixWithBorders,
} from './border';
import {
Element,
ElementBody,
ElementSymbol,
Matrix,
SymbolRuler,
createElementBody,
createMatrix,
createMatrixFromText,
cropMatrix,
getHeight,
getWidth,
matrixToRectangle,
overwriteMatrix,
parseContent,
pourContent,
renderMatrix,
validateMatrix,
} from './matrix';
import {
Rectangle,
moveRectangle,
rectangleToCoordinate,
rectangleToSize,
} from './rectangle';
import {
placeScrollBar,
} from './scroll-bar';
import {
Coordinate,
Size,
validateSize,
} from './utils';
const eaw = require('eastasianwidth');
export type Box = {
borders: Borders;
children: Box[];
content: string,
matrix: Matrix,
scroll?: {
thumbElement?: ElementBody,
trackElement?: ElementBody,
y: number,
},
symbolRuler: SymbolRuler,
x: number,
y: number,
zIndex: number,
};
export function defaultSymbolRuler(symbol: ElementSymbol): 0 | 1 | 2 {
const escapedSymbol = stripAnsi(symbol);
return eaw.characterLength(escapedSymbol);
};
function createDefaultTrackElement(): ElementBody {
return createElementBody('|');
};
function createDefaultThumbElement(): ElementBody {
return createElementBody('#');
};
export function createBox(
rectangleLike: {
x?: Rectangle['x'],
y?: Rectangle['y'],
width: Rectangle['width'],
height: Rectangle['height'],
},
options: {
defaultSymbol?: ElementSymbol | null,
} = {}
): Box {
const settings = Object.assign({}, {
defaultSymbol: null,
}, options);
const rectangle = Object.assign({}, {x: 0, y: 0}, rectangleLike);
const matrix = createMatrix(rectangleToSize(rectangle), settings.defaultSymbol);
if (!validateMatrix(matrix)) {
throw new Error('The matrix size is invalid');
}
return {
symbolRuler: defaultSymbolRuler,
x: rectangle.x,
y: rectangle.y,
zIndex: 0,
content: '',
borders: {
topWidth: 0,
bottomWidth: 0,
leftWidth: 0,
rightWidth: 0,
topSymbols: [],
rightSymbols: [],
bottomSymbols: [],
leftSymbols: [],
topRightSymbols: [],
bottomRightSymbols: [],
bottomLeftSymbols: [],
topLeftSymbols: [],
},
matrix,
children: [],
};
}
function applyBoxSettingsToMatrix(box: Box): Matrix {
const pourableElements = parseContent(box.content, box.symbolRuler);
type FilterArguments = {
matrix: Matrix,
contentArea: Rectangle,
contentAreaCoordinate: Coordinate,
contentAreaSize: Size,
contentAreaMatrix: Matrix,
};
type FilterResult = {
matrix: Matrix,
contentArea: Rectangle,
errorOccured: boolean,
};
type Filter = (args: FilterArguments) => FilterResult;
const filters: Filter[] = [];
// Borders
filters.push(
({matrix, contentAreaMatrix, contentArea, contentAreaCoordinate}) => {
if (validateMatrixWithBorders(contentAreaMatrix, box.borders) === false) {
return {
matrix,
contentArea,
errorOccured: true,
};
}
const placed = placeBorders(contentAreaMatrix, box.borders);
return {
matrix: overwriteMatrix(matrix, placed.matrix, contentAreaCoordinate, box.symbolRuler),
contentArea: moveRectangle(placed.contentArea, contentAreaCoordinate),
errorOccured: false,
};
}
);
// Scroll Bar
if (box.scroll !== undefined) {
const scrollSettings = box.scroll; // To avoid TypeScript's undefined check
filters.push(
({matrix, contentAreaMatrix, contentArea, contentAreaCoordinate, contentAreaSize}) => {
if (validateSize(contentAreaSize) === false || contentAreaSize.width < 1) {
return {
matrix,
contentArea,
errorOccured: true,
};
}
const placed = placeScrollBar(
contentAreaMatrix,
pourableElements,
scrollSettings.y,
scrollSettings.trackElement || createDefaultTrackElement(),
scrollSettings.thumbElement || createDefaultThumbElement()
);
return {
matrix: overwriteMatrix(matrix, placed.matrix, contentAreaCoordinate, box.symbolRuler),
contentArea: moveRectangle(placed.contentArea, contentAreaCoordinate),
errorOccured: false,
};
}
);
}
// Content
if (box.content !== '') {
const scrollY = box.scroll ? box.scroll.y : 0;
filters.push(
({matrix, contentAreaMatrix, contentArea, contentAreaCoordinate}) => {
const placedMatrix = pourContent(contentAreaMatrix, pourableElements, scrollY);
return {
matrix: overwriteMatrix(matrix, placedMatrix, contentAreaCoordinate, box.symbolRuler),
contentArea,
errorOccured: false,
};
}
);
}
// Children
if (box.children.length > 0) {
filters.push(
({matrix, contentAreaMatrix, contentArea, contentAreaCoordinate}) => {
box.children
.slice()
.sort((a, b) => a.zIndex - b.zIndex)
.forEach(childBox => {
const childMatrix = applyBoxSettingsToMatrix(childBox);
contentAreaMatrix = overwriteMatrix(
contentAreaMatrix,
childMatrix,
{
x: childBox.x,
y: childBox.y,
},
box.symbolRuler
);
})
;
return {
matrix: overwriteMatrix(matrix, contentAreaMatrix, contentAreaCoordinate, box.symbolRuler),
contentArea,
errorOccured: false,
};
}
);
}
const filterResult = filters.reduce(
(preFilterResult: FilterResult, filter: Filter) => {
if (preFilterResult.errorOccured) {
return preFilterResult;
}
return filter(
Object.assign({
matrix: preFilterResult.matrix,
contentArea: preFilterResult.contentArea,
contentAreaMatrix: cropMatrix(preFilterResult.matrix, preFilterResult.contentArea),
contentAreaCoordinate: rectangleToCoordinate(preFilterResult.contentArea),
contentAreaSize: rectangleToSize(preFilterResult.contentArea),
})
);
},
{
matrix: box.matrix,
contentArea: matrixToRectangle(box.matrix),
errorOccured: false,
}
);
return overwriteMatrix(
box.matrix,
filterResult.matrix,
{x: 0, y: 0},
box.symbolRuler
);
}
export function renderBox(
box: Box,
options: {
backgroundSymbol?: ElementSymbol,
} = {}
): string {
const settings = Object.assign({
backgroundSymbol: ' ',
}, options);
const matrix = applyBoxSettingsToMatrix(box);
return renderMatrix(matrix, settings.backgroundSymbol);
}
|
15ddd2ed2477bde76074f2cf19a073517efab0e8
|
TypeScript
|
danielearwicker/bidi-mobx
|
/src/project.ts
| 2.6875
| 3
|
import * as React from "react";
import { observer } from "mobx-react";
export function project<Model, View>(projection: (model: Model) => View) {
return {
render<ExtraProps>(
render: (props: ExtraProps & { model: Model } & { view: View }) => JSX.Element
): React.ComponentClass<ExtraProps & { model: Model }> {
return observer(class extends React.Component<ExtraProps & { model: Model }, {}> {
private view: View;
private model: Model;
constructor(props: ExtraProps & { model: Model }) {
super(props);
this.model = props.model;
this.view = projection(props.model);
}
componentWillReceiveProps(props: ExtraProps & { model: Model }) {
if (props.model !== this.model) {
this.model = props.model;
this.view = projection(props.model);
}
}
render() {
return render({ ...this.props as any, view: this.view });
}
});
}
}
}
|
b8ba21a41c809b7a78f9c893136e2de1bef5e9af
|
TypeScript
|
zeevbritz/homework
|
/84/weatherApp/src/app/shared/weather.service.ts
| 2.59375
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { Weather } from './weather';
interface WeatherData {
name: string;
main: { temp: number };
weather: [{ description: string, icon: string }];
}
@Injectable({
providedIn: 'root'
})
export class WeatherService {
constructor(private httpClient: HttpClient) { }
getWeather(zip: string): Observable<Weather> {
return this.httpClient.get<WeatherData>(`http://api.openweathermap.org/data/2.5/weather?APPID=47d15dd6522572a23f6ce80a58cdf231&zip=${zip}&units=imperial`)
.pipe(map(data => ({
name: data.name,
temp: Math.floor(data.main.temp),
img: `http://openweathermap.org/img/w/${data.weather[0].icon}.png`,
description: data.weather[0].description
})
))
}
}
|
85c2f7909dae5ca197b0a4fca0ae3dd97065b3cc
|
TypeScript
|
tsriram/astro
|
/packages/astro/src/transitions/index.ts
| 2.703125
| 3
|
import type { TransitionAnimationPair, TransitionDirectionalAnimations } from '../@types/astro';
const EASE_IN_OUT_QUART = 'cubic-bezier(0.76, 0, 0.24, 1)';
export function slide({
duration,
}: {
duration?: string | number;
} = {}): TransitionDirectionalAnimations {
return {
forwards: {
old: [
{
name: 'astroFadeOut',
duration: duration ?? '90ms',
easing: EASE_IN_OUT_QUART,
fillMode: 'both',
},
{
name: 'astroSlideToLeft',
duration: duration ?? '220ms',
easing: EASE_IN_OUT_QUART,
fillMode: 'both',
},
],
new: [
{
name: 'astroFadeIn',
duration: duration ?? '210ms',
easing: EASE_IN_OUT_QUART,
delay: duration ? undefined : '30ms',
fillMode: 'both',
},
{
name: 'astroSlideFromRight',
duration: duration ?? '220ms',
easing: EASE_IN_OUT_QUART,
fillMode: 'both',
},
],
},
backwards: {
old: [{ name: 'astroFadeOut' }, { name: 'astroSlideToRight' }],
new: [{ name: 'astroFadeIn' }, { name: 'astroSlideFromLeft' }],
},
};
}
export function fade({
duration,
}: {
duration?: string | number;
} = {}): TransitionDirectionalAnimations {
const anim = {
old: {
name: 'astroFadeOut',
duration: duration ?? 180,
easing: EASE_IN_OUT_QUART,
fillMode: 'both',
},
new: {
name: 'astroFadeIn',
duration: duration ?? 180,
easing: EASE_IN_OUT_QUART,
fillMode: 'both',
},
} satisfies TransitionAnimationPair;
return {
forwards: anim,
backwards: anim,
};
}
|
a5f6cfe7190b1164b1b9b897f99e05e7029eb233
|
TypeScript
|
emclaug2/react-showcase-demo
|
/src/redux/reducers/app.ts
| 2.9375
| 3
|
import { AppState } from '../../__types__';
import {
OPEN_DRAWER,
CLOSE_DRAWER,
TOGGLE_DRAWER,
LIGHT_THEME,
DARK_THEME,
TOGGLE_THEME,
DIR_LTR,
DIR_RTL,
TOGGLE_DIR,
} from '../actions';
const initialAppState: AppState = {
theme: 'light',
direction: 'ltr',
drawerOpen: false,
};
export const AppReducer = (state = initialAppState, action: any): AppState => {
switch (action.type) {
case OPEN_DRAWER:
return {
...state,
drawerOpen: true,
};
case CLOSE_DRAWER:
return {
...state,
drawerOpen: false,
};
case TOGGLE_DRAWER:
return {
...state,
drawerOpen: !state.drawerOpen,
};
case LIGHT_THEME:
return {
...state,
theme: 'light',
};
case DARK_THEME:
return {
...state,
theme: 'dark',
};
case TOGGLE_THEME:
return {
...state,
theme: state.theme === 'light' ? 'dark' : 'light',
};
case DIR_LTR:
return {
...state,
direction: 'ltr',
};
case DIR_RTL:
return {
...state,
direction: 'rtl',
};
case TOGGLE_DIR:
return {
...state,
direction: state.direction === 'ltr' ? 'rtl' : 'ltr',
};
default:
return state;
}
};
|
f44fb59c26edb1d4088736e6006b6dcde70ea348
|
TypeScript
|
AronGomu/toche
|
/src/app/classes/card.ts
| 2.5625
| 3
|
export class Card {
idInt: number;
colorString: string;
factionString: string;
nameString: string;
levelInt: number;
manacostString: string;
typeStringArray: string[];
archetypeStringArray: string[];
subtypeStringArray: string[];
attackInt: number;
powerInt: number;
instantSpeedplayableBoolBool: boolean;
imgUrlString: string;
inGameIdInt: number;
ownerPlayer: object;
revealedBool: boolean;
playableBool: boolean;
selectableBool: boolean;
selectedBool: boolean;
constructor(idInt:number, colorString:string, factionString:string, nameString:string, levelInt: number, manacostString:string, typeStringArray:string[], archetypeStringArray:string[], subtypeStringArray:string[], attackInt:number, powerInt:number, instantSpeedplayableBoolBool: boolean, imgUrlString:string) {
this.idInt = idInt;
this.colorString = colorString;
this.factionString = factionString;
this.nameString = nameString;
this.levelInt = levelInt;
this.manacostString = manacostString;
this.typeStringArray = typeStringArray;
this.archetypeStringArray = archetypeStringArray;
this.subtypeStringArray = subtypeStringArray;
this.attackInt = attackInt;
this.powerInt = powerInt;
this.instantSpeedplayableBoolBool = instantSpeedplayableBoolBool;
this.imgUrlString = imgUrlString;
this.inGameIdInt = null;
this.ownerPlayer = null;
this.revealedBool = false;
this.playableBool = false;
this.selectableBool = false;
this.selectedBool = false;
}
}
|
64a6f7efb621bbbe5c7f68ff64706e0e43c51f09
|
TypeScript
|
NguyenDytrich/NellieCat_2.0
|
/server/src/Bot.ts
| 2.609375
| 3
|
import Discord from 'discord.js';
import { ServerConfig } from './index';
const bot = new Discord.Client();
bot.commands = new Discord.Collection();
const prefix = '$';
const ping = {
name: 'ping',
description: 'Ping!',
execute(message, args) {
message.channel.send('Pong.');
},
};
const rules = {
name: 'rules-create',
description: 'Creates a rules post',
execute: async (message, args) => {
// Strip the pinged channel of <# >
if (!args[0]) {
message.channel.send(
"Use `$rules-create #[channel]` to create a post for the rules of your server! If you haven't configured any rules, default rules will be used instead. Visit the configuration panel to update the rules of your server! (WIP)",
);
return;
}
try {
const channel = message.mentions.channels.first();
// Find the config for our rules
const config = await ServerConfig.findOne({
attributes: ['serverId', 'rulesMsgId', 'rules'],
where: {
serverId: message.guild.id,
},
});
if (config.rulesMsgId) {
message.channel.send(
'The rules have already been posted! Use the command `$rules-update` to update the rules',
);
} else {
const rulesEmbed = new Discord.MessageEmbed().setTitle('Rules');
if (!config.rules || config.rules === '') {
rulesEmbed.addField('\u200b', 'These are placeholder rules');
} else {
rulesEmbed.addField('\u200b', config.rules);
}
const rulesMsg = await channel.send(rulesEmbed);
// Update the config in the database
config.rulesChannel = channel.id;
config.rulesMsgId = rulesMsg.id;
config.save();
}
} catch (error) {
console.error(error);
message.channel.send(
"Sorry, I couldn't find the channel to put the rules in...",
);
}
},
};
bot.commands.set(ping.name, ping);
bot.commands.set(rules.name, rules);
bot.on('message', (message) => {
// return if message doesn't start with the prefix, or the author is a bot
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
// remove the prefix, then change the command name to all lowercase
const command = args.shift().toLowerCase();
// return if there's no command exists
if (!bot.commands.has(command)) return;
try {
bot.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
}
});
const createConfig = async (guild) => {
const [_, created] = await ServerConfig.findOrCreate({
where: { serverId: guild.id },
});
if (created) {
console.log(
`Created config in database for guild ${guild.id} (${guild.name})`,
);
}
};
export default {
start(): void {
bot.once('ready', () => {
console.log('Bot ready.');
bot.guilds.cache.forEach((g) => {
createConfig(g);
});
});
bot.login(process.env.DISCORD_TOKEN);
},
};
|
47264fa80daf971c4a13c2e78b186f6eb7384844
|
TypeScript
|
DefinitelyTyped/DefinitelyTyped
|
/types/lzma-native/lzma-native-tests.ts
| 2.6875
| 3
|
import * as fs from "fs";
import * as lzma from "lzma-native";
const compressor = lzma.createCompressor();
const input = fs.createReadStream("tsconfig.json");
const output = fs.createWriteStream("tsconfig.json.xz");
input.pipe(compressor).pipe(output);
lzma.compress("Banana", undefined, result => {
console.log(result); // <Buffer fd 37 7a 58 5a 00 00 01 69 22 de 36 02 00 21 ...>
});
lzma.compress("Bananas", 6, result => {
lzma.decompress(result, undefined, decompressedResult => {
console.log(decompressedResult.toString() === "Bananas");
});
});
lzma.LZMA().compress("Bananas", 4, result => {
lzma.LZMA().decompress(result, decompressedResult => {
console.log("Bananas" === decompressedResult.toString());
});
});
const comp = lzma.Compressor();
process.stdin.pipe(comp).pipe(process.stdout);
lzma.crc32("Banana"); // => 69690105
lzma.checkSize("CHECK_SHA256"); // => 16
lzma.checkSize("CHECK_CRC32"); // => 4
lzma.easyDecoderMemusage(6); // => 8454192
lzma.easyEncoderMemusage(6); // => 97620499
lzma.versionString(); // => '5.2.3'
lzma.versionNumber(); // => 50020012
lzma.isXZ("Banana"); // => false
fs.open("test/hamlet.txt.xz", "r", (err: any, fd: number) => {
if (err) return;
// handle error
lzma.parseFileIndexFD(fd, (err, info) => {
// handle error
if (err) {
console.log(err);
}
// do something with e.g. info.uncompressedSize
fs.close(fd, (err: any) => {
/* handle error */
if (err) {
console.log(err);
}
});
});
});
|
cf5ce94982b871591b4238c1cc0fe776a040d8ca
|
TypeScript
|
nunof07/space-patrol
|
/src/random/RandomInt.ts
| 2.875
| 3
|
import { Scalar } from '@src/core/Scalar';
import * as Random from 'random-js';
export class RandomInt implements Scalar<number> {
private readonly engine: Random.Engine;
private readonly min: number;
private readonly max: number;
constructor(engine: Random.Engine, min: number, max: number) {
this.engine = engine;
this.min = min;
this.max = max;
}
public get value(): number {
return Random.integer(this.min, this.max)(this.engine);
}
}
|
d622003c4a43c1b1e7ea6b316e7fcf33d48a7277
|
TypeScript
|
arturobarbaro/pruebasAngular
|
/redux-app/src/app/contador/contador.reducer.ts
| 2.734375
| 3
|
import * as fromContador from './contador.actions';
export function contadorReducer( state: number = 10, action: fromContador.actions) {
switch( action.type ) {
case fromContador.INCREMENTAR:
return state +1;
case fromContador.DECREMENTAR:
return state -1;
case fromContador.MULTIPLICAR:
return state * action.payload;
case fromContador.DIVIDIR:
return state / action.payload;
case fromContador.RESETEAR:
return 0;
default:
return state;
}
}
|
18124069d1ecaeefcad4c780c3cc748018faa37b
|
TypeScript
|
rapr04/ADALTest
|
/src/app/main/employee/model/employee.ts
| 3.015625
| 3
|
export interface IEmployee{
id: number;
name:string;
function:string;
}
export class Employee implements IEmployee
{
id: number;
name:string;
function:string;
constructor(obj?: Employee){
if(obj){
Object.assign(this,obj);
}
}
}
|
49e19c957e6a91b3eccf72779ca3830da1e15b52
|
TypeScript
|
yohnwolfs/iceball-client
|
/www/src/gameobject/Ball.ts
| 2.546875
| 3
|
const BallAttr = {
width: 74,
height: 74,
imgWidth: 90,
imgHeight: 90,
velocity: 6,
weight: 2.2
}
/**
* 比赛球类0
*/
class Ball extends BaseBall {
// 摩擦力
private _friction: number = 0.01;
// 旋转方向 -1:逆时针 1:顺时针 0:不旋转
private _roDirection: number = 0;
// 方向同步辅助值
private _direction: number;
// 球的状态 1: 正常 2:下降动画中 3: 停止状态
private _status: number = 1;
// 动画执行时刻辅助值
private _animTime: number = 0;
private _weight: number;
private _fallPosList: number[] = [];
constructor(direction: number) {
super();
this.graphics.loadImage(Assets.Img.ball);
this.pivot(BallAttr.imgWidth / 2, BallAttr.imgHeight / 2);
this.size(BallAttr.width, BallAttr.height);
this.zOrder = DisplayOrder.Ball;
this.posCenter();
this._direction = direction;
this._radius = BallAttr.width / 2;
this.initVelocity();
this._weight = BallAttr.weight;
}
get roDirection() {
return this._roDirection;
}
set roDirection(d: number) {
this._roDirection = d;
}
get weight() {
return this._weight;
}
set weight(w: number) {
this._weight = w;
}
set direction(d: number) {
this._direction = d;
}
/**
* 帧更新
*/
public update() {
// 不同状态下的动作
if (this.actionInStatus()) return;
this.x = Utils.floatN(this.x + this._vx);
this.y = Utils.floatN(this.y + this._vy);
// 自旋转
if (this._roDirection !== 0) {
let rv = Utils.floatN(Math.sqrt(Math.pow(this._vx, 2) + Math.pow(this._vy, 2)) * 2);
this.rotation = this.rotation + (this._roDirection < 0 ? -1 : 1) * rv;
}
// 越界
this._nextX = this.x + this._vx;
this._nextY = this.y + this._vy;
// 碰到两边的墙壁
if (this._nextX < BallAttr.width / 2 || this._nextX > config.gameWidth - BallAttr.width / 2) {
this.x = (this._nextX < BallAttr.width / 2) ? BallAttr.width / 2 : config.gameWidth - BallAttr.width / 2;
this._vx *= -1;
SoundManager.playSound(Assets.Sound.hit_002);
}
// 进入己方或对方的龙门
let whoseball = this._nextY < -50 ? 'mine' : 'your';
if (this._nextY < -50 || this._nextY > config.gameHeight + 50) {
this.vx = 0;
this.vy = 0;
let game = Game.Instance;
game.status = 0;
// 使缓存中的子弹爆炸
Bullet.boomAllBullets();
for (let child of Main.Instance.gamePage._childs) {
if (child.className && child.className === 'Bullet') Main.Instance.gamePage.removeChild(child);
}
// 清理未完成的计时器任务
Game.Instance.timer.clearTaskList();
// 进球得分
if (this._nextY < -50) {
ScoreManager.Instance.mballs++;
Socket.Instance.ballIn();
SoundManager.playSound(Assets.Sound.mscore);
}
else {
ScoreManager.Instance.yballs++;
SoundManager.playSound(Assets.Sound.yscore);
}
// 判断是否结束比赛
ScoreManager.Instance.checkBalls(whoseball);
// 延迟一段时间后执行掉落动画
this._animTime = 0;
this._status = 3;
}
// 摩擦减速
let fx = Utils.floatN(Math.abs(this._friction * this.vx / BallAttr.velocity));
let fy = Utils.floatN(Math.abs(this._friction * this.vy / BallAttr.velocity));
this._vx = Math.abs(this._vx) < 0.1 ? 0 : Utils.floatN(this._vx > 0 ? this._vx - fx : this._vx + fx);
this._vy = Math.abs(this._vy) < 0.1 ? 0 : Utils.floatN(this._vy > 0 ? this._vy - fy : this._vy + fy);
}
/**
* 计算旋转方向
* @param x 子弹的x位置
* @param y 子弹的y位置
* @param vx 子弹的x速度
* @param vy 子弹的y速度
*/
public compRDirection(x: number, y: number, vx: number, vy: number) {
let p = Utils.posToLine(this.x, this.y, x, y, vx, vy);
if ((vx <= 0 && vy <= 0) || (vx < 0 && vy >= 0)) {
if (p > 0) this.roDirection = 1;
if (p < 0) this.roDirection = -1;
}
else if ((vx > 0 && vy < 0) || (vx >= 0 && vy > 0)) {
if (p > 0) this.roDirection = -1;
if (p < 0) this.roDirection = 1;
}
if (global.syn) this.roDirection *= -1;
}
/**
* 初始化速度向量
*/
public initVelocity() {
this._vx = Utils.floatN(BallAttr.velocity * Math.round(Math.sin(90 * Math.PI / 180)) * (this._direction === 0 ? -1 : 1));
this._vy = Utils.floatN(-1 * BallAttr.velocity * Math.round(Math.cos(90 * Math.PI / 180)));
}
/**
* 定位到中心
*/
public posCenter() {
this.pos(config.gameWidth / 2, config.gameHeight / 2);
}
/**
* 不同状态下的动作
*/
private actionInStatus() {
// 停止一段时间后执行掉落动画
if (this._status === 3) {
this._animTime += 1;
if (this._animTime > 30) {
this.fallDown();
}
return true;
}
// 下降动画
if (this._status === 2) {
let easeValue = Ease.bounceOut(this._animTime, 5, -4, 1000);
this._animTime += 16;
this.scale(easeValue, easeValue);
this._fallPosList.push(easeValue);
// 判断最低点时播放声音
if (this._fallPosList.length > 3) this._fallPosList.shift();
if (this._fallPosList[1] < this._fallPosList[0] && this._fallPosList[1] < this._fallPosList[2]) SoundManager.playSound(Assets.Sound.hit_002);
if (this._animTime > 1000) {
let direction = Game.Instance.getBallDirection();
this.scale(1, 1);
this._status = 1;
this._roDirection = 0;
this._direction = Game.Instance.ballDirectionFactor? direction : 1 - direction;
this.initVelocity();
Game.Instance.status = 1;
Game.Instance.toolTagContainer.unlock();
this._fallPosList = [];
}
return true;
}
return false
}
/**
* 执行掉落动画
*/
public fallDown() {
this._animTime = 0;
this.posCenter();
this._status = 2;
this.weight = BallAttr.weight;
this.removeChildren();
}
public isNormalStatus() {
return this._status === 1;
}
public getFrozen() {
let ice = new Sprite();
ice.loadImage(Assets.Img.ball_effect_ice);
ice.pivot(41, 41);
ice.x = 45;
ice.y = 45;
this.removeChildren();
this.addChild(ice);
this.weight = 8;
if (global.syn) {
this.vx = Utils.floatN(this.vx / this.weight);
this.vy = Utils.floatN(this.vy / this.weight);
}
else {
this.vx = Utils.floatN((this.vx * -1) / this.weight);
this.vy = Utils.floatN((this.vy * -1) / this.weight);
this.vx *= -1;
this.vy *= -1;
}
Game.Instance.timer.clearTaskByName('frozen');
Game.Instance.timer.setTimeout(() => {
this.weight = BallAttr.weight;
this.removeChildren();
}, 300, this, 'frozen');
}
private release() {
this.weight = BallAttr.weight;
this.removeChildren();
}
}
|
c8efd3b51b1dedc63f2bc22c0547a3843c0ae88f
|
TypeScript
|
aaronheath/afl-2016
|
/src/app/services/match-summary.ts
| 3.125
| 3
|
import { Injectable } from '@angular/core';
import { Match, MatchItem, ModelWhereAttrs } from '../models/index';
/**
* Interface(s)
*/
export interface SummaryOfMatches {
goals: number;
behinds: number;
totalPoints: number;
accuracy: number;
highestScore: MatchItem[];
lowestScore: MatchItem[];
attendance: number;
highestAttendance: MatchItem[];
lowestAttendance: MatchItem[];
played: number;
}
/**
* Match Summary Service
*
* Primary purpose is to generate a summary for a given set of matches.
*
* TODO:
* - May .where() calls are made against the Match model. This is expensive. When Model supports optimising this
* senario we'll be able to optimise this service.
*/
@Injectable()
export class MatchSummaryService {
/**
* Summary for an individual AFL Premiership Round.
*
* @returns {SummaryOfMatches}
* @param roundNo
*/
getSummaryForRound(roundNo : number) : SummaryOfMatches {
const where = [{key: 'roundNo', value: +roundNo}, {key: 'played', value: true}];
return this.summaryForQuery(where);
}
/**
* Using where query array a summary of matching matches is returned.
*
* @param where
* @returns {{goals: number, behinds: number, totalPoints: number, accuracy: number, highestScore: MatchItem[],
* lowestScore: MatchItem[], attendance: number, highestAttendance: MatchItem[], lowestAttendance: MatchItem[],
* played: number}}
*/
protected summaryForQuery(where : ModelWhereAttrs[]) : SummaryOfMatches {
const played = this.played(where);
const highestAttendance = this.highestAttendance(where);
const lowestAttendance = this.lowestAttendance(where);
const attendance = this.overallAttendance(where);
const goals = this.goals(where);
const behinds = this.behinds(where);
const points = this.points(goals, behinds);
const accuracy = this.accuracy(goals, behinds);
const highestScore = this.highestScore(where);
const lowestScore = this.lowestScore(where);
return {
goals: goals,
behinds: behinds,
totalPoints: points,
accuracy: accuracy,
highestScore: highestScore,
lowestScore: lowestScore,
attendance: attendance,
highestAttendance: highestAttendance,
lowestAttendance: lowestAttendance,
played: played,
};
}
/**
* Count of matches played.
*
* @param where
* @returns {any}
*/
protected played(where : ModelWhereAttrs[]) : number {
const finalWhere = where.concat({key: 'result', value: undefined, operator: '!='});
return Match.where(finalWhere).count();
}
/**
* Array of matches with the highest attendance.
*
* @param where
* @returns {TValue[]}
*/
protected highestAttendance(where : ModelWhereAttrs[]) : MatchItem[] {
const sorted = Match.where(where).orderBy('attendance', 'desc').get();
let attendance;
return _.takeWhile(sorted, (match) => {
if(!match.get('attendance') || attendance > match.get('attendance')) {
return false;
}
attendance = match.get('attendance');
return true;
});
}
/**
* Array of matches with the lowest attendance.
*
* @param where
* @returns {TValue[]}
*/
protected lowestAttendance(where : ModelWhereAttrs[]) : MatchItem[] {
const sorted = Match.where(where).orderBy('attendance').get();
let attendance;
return _.takeWhile(sorted, (match) => {
if(!match.get('attendance') || attendance < match.get('attendance')) {
return false;
}
attendance = match.get('attendance');
return true;
});
}
/**
* Overall attendance integer for the matches.
*
* @param where
* @returns {number|LoDashExplicitWrapper<number>}
*/
protected overallAttendance(where : ModelWhereAttrs[]) : number {
return Match.where(where).sum('attendance');
}
/**
* Goals scored in all matches.
*
* @param where
* @returns {number}
*/
protected goals(where : ModelWhereAttrs[]) : number {
return this.scores(where, 'Goals');
}
/**
* Behinds scored in all matches
*
* @param where
* @returns {number}
*/
protected behinds(where : ModelWhereAttrs[]) : number {
return this.scores(where, 'Behinds');
}
/**
* Count of goals or behinds scored in all matches.
*
* @param where
* @param type
* @returns {any}
*/
protected scores(where : ModelWhereAttrs[], type : 'Goals' | 'Behinds') : number {
const home = Match.where(where).sum(`home${type}`);
const away = Match.where(where).sum(`away${type}`);
return home + away;
}
/**
* Points score that corresponds to given goals and behinds.
*
* @param goals
* @param behinds
* @returns {number}
*/
protected points(goals : number, behinds : number) {
return goals * 6 + behinds;
}
/**
* Shooting accuracy determined by how many goals were scored against all scoring events.
*
* @param goals
* @param behinds
* @returns {number}
*/
protected accuracy(goals : number, behinds : number) : number {
return goals / (goals + behinds) * 100;
}
/**
* Narrows down all matches with those that have the highest score by either a home or away team. The returns
* an array of matches with the highest individual team score.
*
* @param where
* @returns {MatchItem[]}
*/
protected highestScore(where : ModelWhereAttrs[]) : MatchItem[] {
const sortedHomeScores = this.sortedByScore(where, 'homePoints', 'desc');
const highestHomeScore = this.highestScores(sortedHomeScores, 'homePoints');
const sortedAwayScores = this.sortedByScore(where, 'awayPoints', 'desc');
const highestAwayScore = this.highestScores(sortedAwayScores, 'awayPoints');
const mergedScores = highestHomeScore.concat(highestAwayScore);
return this.takeHighestScore(mergedScores);
}
/**
* Array of matches with highest scores by either home or away points.
*
* @param matches
* @param fn
* @returns {MatchItem[]|TValue[]}
*/
protected highestScores(matches : MatchItem[], fn : string) : MatchItem[] {
let highestScore = 0;
return _.takeWhile(matches, (match : MatchItem) => {
if (!match[fn]() || highestScore > match[fn]()) {
return false;
}
highestScore = match[fn]();
return true;
});
}
/**
* Array of matches with the highest individual team score.
*
* @param matches
* @returns {Array}
*/
protected takeHighestScore(matches : MatchItem[]) : MatchItem[] {
let response = [];
let notableScore = 0;
matches.forEach((match) => {
if(response.length && notableScore > match.homePoints() && notableScore > match.awayPoints()) {
return;
}
const matchNotableScore = match.homePoints() > match.awayPoints()
? match.homePoints() : match.awayPoints();
if(matchNotableScore !== notableScore) {
response = [];
}
notableScore = matchNotableScore;
response.push(match);
});
return this.uniqueByUid(response);
}
/**
* Parses list of items and only returns
*
* @param matches
* @returns {MatchItem[]|T[]}
*/
protected uniqueByUid(matches : MatchItem[]) : MatchItem[] {
const knownUids = [];
return matches.filter((match) => {
if(knownUids.includes(match.uid())) {
return false;
}
knownUids.push(match.uid());
return true;
});
}
/**
* Narrows down all matches with those that have the lowest score by either a home or away team. The returns
* an array of matches with the lowest individual team score.
*
* @param where
* @returns {MatchItem[]}
*/
protected lowestScore(where : ModelWhereAttrs[]) : MatchItem[] {
const sortedHomeScores = this.sortedByScore(where, 'homePoints', 'asc');
const lowestHomeScore = this.lowestScores(sortedHomeScores, 'homePoints');
const sortedAwayScores = this.sortedByScore(where, 'awayPoints', 'asc');
const lowestAwayScore = this.lowestScores(sortedAwayScores, 'awayPoints');
const mergedScores = lowestHomeScore.concat(lowestAwayScore);
return this.takeLowestScore(mergedScores);
}
/**
* Array of matches with lowest scores by either home or away points.
*
* @param matches
* @param fn
* @returns {TValue[]}
*/
protected lowestScores(matches : MatchItem[], fn : string) : MatchItem[] {
let lowestScore = 0;
return _.takeWhile(matches, (match) => {
if (!match[fn]() || (lowestScore && lowestScore < match[fn]())) {
return false;
}
lowestScore = match[fn]();
return true;
});
}
/**
* Array of matches with the lowest individual team score.
*
* @param matches
* @returns {Array}
*/
protected takeLowestScore(matches : MatchItem[]) : MatchItem[] {
let response = [];
let notableScore = 0;
matches.forEach((match) => {
if(response.length && notableScore < match.homePoints() && notableScore < match.awayPoints()) {
return;
}
const matchNotableScore = match.homePoints() < match.awayPoints()
? match.homePoints() : match.awayPoints();
if(matchNotableScore !== notableScore) {
response = [];
}
notableScore = matchNotableScore;
response.push(match);
});
return this.uniqueByUid(response);
}
/**
* Array of matches sorted by attribute in desired direction.
*
* @param where
* @param attr
* @param direction
* @returns {any}
*/
protected sortedByScore(where : ModelWhereAttrs[], attr : string, direction : 'asc' | 'desc') : MatchItem[] {
return Match.where(where).orderBy(attr, direction).get();
}
}
|
905efaf67c27a8cb40029fee0888a4033a0f20f2
|
TypeScript
|
zephyrJS/typescript-practice
|
/EnumDemo/EnumDemo.ts
| 3.015625
| 3
|
// 数字枚举,可设置初始化值
enum Directory {
Up=1,
Down,
Left,
Right
}
// 字符串枚举
enum DirectoryString {
Up = 'Up',
Down = 'Down',
Left = 'Left',
Right = 'Right'
}
// Heterogeneous Enum
enum HeterogeneousEnum {
Up = 1,
Down = 'Down'
}
enum E { X }
enum E1 { X, Y, Z }
|
f1eabb6ff79dcf1e04c7164c309252e4e2a9c971
|
TypeScript
|
wan54/datahub
|
/datahub-web/@datahub/metadata-types/addon/constants/entity/dataset/compliance-field-types.ts
| 2.78125
| 3
|
/**
* Defines the string values that are allowed for a classification
* @export
* @namespace Dataset
* @enum {string}
*/
export enum Classification {
Confidential = 'CONFIDENTIAL',
LimitedDistribution = 'LIMITED_DISTRIBUTION',
HighlyConfidential = 'HIGHLY_CONFIDENTIAL',
Internal = 'GENERAL',
Public = 'PUBLIC'
}
/**
* Defines the string values for a logical type that is a member ID
* @export
* @namespace Dataset
* @enum {string}
*/
export enum MemberIdLogicalType {
// Numerical format, 12345
Numeric = 'NUMERIC',
// URN format, urn:li:member:12345
Urn = 'URN',
// Reversed URN format, 12345:member:li:urn
ReversedUrn = 'REVERSED_URN',
// [Deprecated] Use CUSTOM format + pattern instead
CompositeUrn = 'COMPOSITE_URN',
// Any other non-standard format. A pattern for the value is expected to be provided
Custom = 'CUSTOM',
// Data is stored in reversible encoded/serialized/encrypted format
Encoded = 'ENCODED',
// Data is stored in irreversible hashed format
Hashed = 'HASHED'
}
/**
* Enum of values for non-member id / generic logical types
* @export
* @namespace Dataset
* @enum {string}
*/
export enum NonMemberIdLogicalType {
Name = 'NAME',
Email = 'EMAIL',
Phone = 'PHONE',
Address = 'ADDRESS',
LatitudeLongitude = 'LATITUDE_LONGITUDE',
CityStateRegion = 'CITY_STATE_REGION',
IpAddress = 'IP_ADDRESS',
FinancialNumber = 'FINANCIAL_NUMBER',
PaymentInfo = 'PAYMENT_INFO',
PasswordCredential = 'PASSWORD_CREDENTIAL',
AuthenticationToken = 'AUTHENTICATION_TOKEN',
Message = 'MESSAGE',
NationalId = 'NATIONAL_ID',
SocialNetworkId = 'SOCIAL_NETWORK_ID',
EventTime = 'EVENT_TIME',
TransactionTime = 'TRANSACTION_TIME',
CookieBeaconBrowserId = 'COOKIE_BEACON_BROWSER_ID',
DeviceIdAdvertisingId = 'DEVICE_ID_ADVERTISING_ID'
}
/**
* Possible string values for field Identifier type in compliance
* @export
* @namespace Dataset
* @enum {string}
*/
export enum ComplianceFieldIdValue {
None = 'NONE',
MemberId = 'MEMBER_ID',
SubjectMemberId = 'SUBJECT_MEMBER_ID',
GroupId = 'GROUP_ID',
CompanyId = 'COMPANY_ID',
MixedId = 'MIXED_ID',
CustomId = 'CUSTOM_ID',
EnterpriseProfileId = 'ENTERPRISE_PROFILE_ID',
EnterpriseAccountId = 'ENTERPRISE_ACCOUNT_ID',
ContractId = 'CONTRACT_ID',
SeatId = 'SEAT_ID',
AdvertiserId = 'ADVERTISER_ID',
SlideshareUserId = 'SLIDESHARE_USER_ID'
}
/**
* String values for the keys in the export policy data types
* @export
* @namespace Dataset
* @enum {string}
*/
export enum ExportPolicyKeys {
UGC = 'containsUserGeneratedContent',
UAGC = 'containsUserActionGeneratedContent',
UDC = 'containsUserDerivedContent'
}
|
6053c2879182708903b924222ab9da3c5afc4831
|
TypeScript
|
wahello/wigfrid
|
/src/clarity-angular/wigfrid/core/src/util/lang/is-number.ts
| 2.5625
| 3
|
export function isNumber(value: any): boolean {
return typeof (value) == 'number';
}
|
e82ab4ddc135d17ef517e83b06bcb7f9b50d98f7
|
TypeScript
|
Flariumapp/backend-node
|
/src/routes/search/index.ts
| 2.5625
| 3
|
import express, { Request, Response, NextFunction } from 'express';
import { Location } from '../../models/location';
import { Company } from '../../models/company';
import Fuse from 'fuse.js';
const Router = express.Router();
Router.get('/api/search', async (req: Request, res: Response, next: NextFunction) => {
try {
// api/search/?type=location&input=text
const type = req.query.type as string;
const input = req.query.input as string;
if (type === 'location') {
const locations = await Location.find().populate('gallery');
const fuse = new Fuse(locations, {
includeScore: true,
keys: ['name', 'country'],
});
const results = fuse.search(input);
res.status(200).send({
message: 'Search results fetched succesfully',
results,
});
} else {
const companies = await Company.find().populate('logo');
const fuse = new Fuse(companies, {
includeScore: true,
keys: ['name']
});
const results = fuse.search(input);
res.status(200).send({
message: 'Search results fetched succesfully',
results,
});
}
} catch (err) {
next(err);
}
});
export { Router as SearchIndexRouter };
|
b78d87d32fc1b076fd5f071b0117318465708049
|
TypeScript
|
hexgraphix/day2
|
/src/app/app.component.ts
| 3.328125
| 3
|
import { Component, OnInit } from '@angular/core';
class Greeting {
message: string;
constructor(message: string){
this.message = message;
}
greet(){
return "Hello, " + this.message;
}
}
class Animal{
name: string;
constructor(animalName: string){
this.name = animalName;
}
move(distance: number = 0){
console.log(`${this.name} moved ${distance}m.`)
}
}
class Dog extends Animal {
constructor(name: string){
super(name);
}
bark(){
console.log("Woof!");
}
move(distanceMoveByDog: number = 5){
super.move(distanceMoveByDog);
}
}
class Horse extends Animal{
// create constructor to set animal name
// create move to set default distance to 44
constructor(name: string){
super(name);
}
move(distanceMoveByHorse: number = 45){
console.log('Horse is charging...');
super.move(distanceMoveByHorse);
}
}
class User{
private name: string;
constructor (name: string){
this.name = name;
}
}
class John extends User {
constructor(){
super("John");
}
}
class Employee {
private name: string;
constructor (name: string){
this.name = name;
}
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app works!';
ngOnInit() {
// this.classTesting();
// this.animalClassTesting();
}
classTesting(){
const greeter = new Greeting('world.');
console.log(greeter.greet);
}
animalClassTesting() {
const dog = new Dog("Goofy");
dog.bark();
dog.move(20);
const horse: Animal = new Horse("buck");
horse.move(20);
}
classCompatibilityTesting(){
let user = new User("Doe");
const john = new John();
console.log(user);
console.log(john);
const employee = new Employee("Smith");
console.log(employee);
user = john;
console.log(user);
}
}
|
ec446d10a94f71f4d1f039eae3de3a5bc8f16261
|
TypeScript
|
WepILoK/react-pizza
|
/src/store/ducks/pizzas/reducer.ts
| 2.640625
| 3
|
import produce, {Draft} from "immer";
import {EnumSortByOrder, EnumSortByType, IPizzasState} from "./contracts/state";
import {ActionsType, IActions} from "./contracts/actionTypes";
const initialState: IPizzasState = {
items: [],
isLoaded: false,
category: null,
sortBy: {
type: EnumSortByType.POPULAR,
order: EnumSortByOrder.DESC,
}
}
export const pizzasReducer = produce((draft: Draft<IPizzasState>, action: IActions) => {
switch (action.type) {
case ActionsType.SET_LOADED:
draft.isLoaded = action.payload
break;
case ActionsType.SET_PIZZAS:
draft.items = action.payload
break;
case ActionsType.SET_SORT_BUY:
draft.sortBy = action.payload
break;
case ActionsType.SET_CATEGORY:
draft.category = action.payload
break;
default:
break;
}
}, initialState)
|
1ed0e643958117e84caab141b1423bc393b52aa6
|
TypeScript
|
nthnluu/bouncer-web
|
/src/util/auth/auth_helpers.test.ts
| 3.09375
| 3
|
import {AuthService, User, UserRole} from "./auth_helpers";
class TestUser implements User {
email: string;
image: string;
name: string;
role: UserRole;
constructor(email: string, image: string, name: string, role: UserRole) {
this.email = email;
this.image = image;
this.name = name;
this.role = role;
}
}
class TestAuthService implements AuthService {
currentUser: TestUser | undefined;
isAuthenticated: boolean;
userDatabase: TestUser[];
constructor() {
this.isAuthenticated = false;
const demoUser = new TestUser("demo@test.com", "/vercel.svg", "John Doe", UserRole.USER);
const demoAdmin = new TestUser("admin@test.com", "/vercel.svg", "Jane Doe", UserRole.ADMIN);
this.userDatabase = [demoAdmin, demoUser];
}
loginWithEmailAndPassword(email: string, password: string): Promise<TestUser> {
if (this.userDatabase.some(user => user.email === email) && password === "asdf") {
return Promise.resolve(this.userDatabase.find(user => user.email === email)!);
} else {
return Promise.reject({
message: "Invalid email or password"
});
}
}
registerWithEmailAndPassword(name: string, email: string, password: string): Promise<TestUser> {
if (this.userDatabase.some(user => user.email === email) && password === "asdf") {
return Promise.reject({
message: "This user already exists"
});
} else {
const newUser = new TestUser(email, "/vercel.svg", name, UserRole.USER);
this.userDatabase.push(newUser);
return Promise.resolve(newUser);
}
}
}
describe('auth service', () => {
let authService: TestAuthService;
beforeEach(() => {
authService = new TestAuthService();
});
it('returns a user when logged in successfully', () => {
const demoUser = new TestUser("demo@test.com", "/vercel.svg", "John Doe", UserRole.USER);
authService.loginWithEmailAndPassword("demo@test.com", "asdf")
.then(user => {
expect(user).toBe(demoUser);
});
});
it('returns a user when logged in succesfully', () => {
const demoUser = new TestUser("demo@test.com", "/vercel.svg", "John Doe", UserRole.USER);
authService.loginWithEmailAndPassword("demo@test.com", "asdf")
.then(user => {
expect(user).toBe(demoUser);
});
});
});
|
dbbdd6e81919929b37a20ef6c523ad7abc9cdaf6
|
TypeScript
|
cryptokrok/mancala.bawo_standalone
|
/src/js/Utility.ts
| 2.859375
| 3
|
/*
* bawo.zone - <a href="https://bawo.zone">https://bawo.zone</a>
* <a href="https://github.com/fumba/bawo.zone">https://github.com/fumba/bawo.zone</a>
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Vector from "../js/core/Vector";
class Utility {
/**
* Adds zero to a number that is less than 9
*
* @param {number} num number representing hole ID
* @returns {string} the number after being padded or not
*/
public static padZero(num: number): string {
const str = num.toString();
return str.length < 2 ? "0".concat(str) : str;
}
/**
* Generates a random point in a circle using polar notation.
* This implementation adopted from https://dev.to/seanpgallivan/solution-generate-random-point-in-a-circle-ldh#idea
*
* @param {number} radius the radius of the circle
* @param {number} xCenter center x coordinate value
* @param {number} yCenter center y coordinate value
* @returns {Vector} randomly generated (x,y) coordinates
*/
public static randomPointWithinCircle(
radius: number,
xCenter: number,
yCenter: number
): Vector {
const angle = Math.random() * 2 * Math.PI;
const hypotenuse = Math.sqrt(Math.random()) * radius;
const adjacent = Math.cos(angle) * hypotenuse;
const opposite = Math.sin(angle) * hypotenuse;
return new Vector(xCenter + adjacent, yCenter + opposite, 0);
}
/**
* Generates a random integer that is less than the specified max
*
* @param {number} max the maximum limit of the generated integer
* @returns {number} a random generated number
*/
public static getRandomInt(max: number): number {
return Math.floor(Math.random() * max);
}
/**
* Sleep function
*
* @param {number} ms time in milliseconds to pause code execution
* @returns {Promise<void>} void
*/
public static sleep(ms: number): Promise<void> {
console.info(`Sleeping for ${ms} ms`);
return new Promise((resolve) => setTimeout(resolve, ms));
}
}
export default Utility;
|
7410969c6bccd34aa2423d947c3aafa5febfe8f5
|
TypeScript
|
hipek146/ZTI-myFilms-fe
|
/src/app/interfaces/User.ts
| 2.625
| 3
|
export interface User {
login: string;
password?: any;
name: string;
surname: string;
role: 'USER' | 'ADMIN';
}
|
e61725f1ed912190c2ceea8564a0f07f5c92a94c
|
TypeScript
|
a7urag/node-express-mysql-typescript-api-boilerplate
|
/src/services/user.service.test.ts
| 2.578125
| 3
|
import * as typeorm from 'typeorm';
import UserService from './user.service';
import { mockRepository } from '../tests/unit/dbMock';
import { User } from '../entities/user/user.entity';
import { verifyHash } from '../utilities/encryptionUtils';
describe('User service', () => {
test('getUserById with existing user', async () => {
mockRepository({ id: 1, password: '123', name: 'Test user' });
const actual = await UserService.getUserById(1);
expect(actual.id).toBe(1);
// @ts-ignore
expect(actual.password).toBe(undefined);
expect(actual.name).toBe('Test user');
expect(typeorm.getRepository(User).findOne).toHaveBeenCalledTimes(
1,
);
expect(typeorm.getRepository(User).findOne).toHaveBeenCalledWith({
id: 1,
});
});
test('getUserById with non-existing user', async () => {
// @ts-ignore
typeorm.getRepository = jest.fn().mockReturnValue({
findOne: jest.fn().mockImplementation(() => {
throw new Error();
}),
});
const actual = await UserService.getUserById(1);
expect(actual).toBe(null);
// @ts-ignore
expect(typeorm.getRepository(User).findOne).toHaveBeenCalledTimes(
1,
);
expect(typeorm.getRepository(User).findOne).toHaveBeenCalledWith({
id: 1,
});
});
test('createUser', async () => {
const user = {
id: 1,
password: '123',
name: 'Test user',
email: 'test@test.com',
};
mockRepository(user);
const actual = await UserService.createUser(
user.email,
user.password,
user.name,
);
expect(actual.id).toBe(1);
// @ts-ignore
expect(actual.password).toBe(undefined);
expect(actual.name).toBe(user.name);
// expect(actual.email).toBe(user.email);
expect(typeorm.getRepository(User).save).toHaveBeenCalledTimes(1);
expect(typeorm.getRepository(User).save).toHaveBeenCalledWith(
expect.objectContaining({
email: user.email,
password: expect.any(String),
name: user.name,
}),
);
});
test('emailUser with non-existing user', async () => {
const user = {
id: 1,
password: '123',
name: 'Test user',
email: 'test@test.com',
};
// @ts-ignore
typeorm.getRepository = jest.fn().mockReturnValue({
findOne: jest.fn().mockImplementation(() => {
throw new Error();
}),
save: jest.fn().mockReturnValue(null),
});
const actual = await UserService.loginUser(
user.email,
user.password,
);
expect(actual).toBe(null);
// @ts-ignore
expect(typeorm.getRepository(User).findOne).toHaveBeenCalledTimes(
1,
);
expect(typeorm.getRepository(User).findOne).toHaveBeenCalledWith({
email: user.email,
});
expect(typeorm.getRepository(User).save).toHaveBeenCalledTimes(0);
});
test('emailUser with existing user wrong password', async () => {
const user = {
id: 1,
password: '123',
name: 'Test user',
email: 'test@test.com',
};
// @ts-ignore
mockRepository(user);
const actual = await UserService.loginUser(
user.email,
user.password,
);
expect(actual).toBe(null);
// @ts-ignore
expect(typeorm.getRepository(User).findOne).toHaveBeenCalledTimes(
1,
);
expect(typeorm.getRepository(User).findOne).toHaveBeenCalledWith({
email: user.email,
});
expect(typeorm.getRepository(User).save).toHaveBeenCalledTimes(0);
});
test('emailUser with valid credentials', async () => {
const user = {
id: 1,
password: '123',
name: 'Test user',
email: 'test@test.com',
};
// @ts-ignore
mockRepository(user);
// @ts-ignore
verifyHash = () => new Promise<boolean>(resolve => resolve(true));
const actual = await UserService.loginUser(
user.email,
user.password,
);
expect(actual.id).toBe(user.id);
expect(actual.email).toBe(user.email);
// @ts-ignore
expect(typeorm.getRepository(User).findOne).toHaveBeenCalledTimes(
1,
);
expect(typeorm.getRepository(User).findOne).toHaveBeenCalledWith({
email: user.email,
});
expect(typeorm.getRepository(User).save).toHaveBeenCalledTimes(1);
expect(typeorm.getRepository(User).save).toHaveBeenCalledWith(
expect.objectContaining({
...user,
lastLogin: expect.any(String),
}),
);
});
});
|
7f699597aa94ceca7c71c61e2d8a26e22ea32d69
|
TypeScript
|
srdjan/glitched-clob
|
/server/orderid.ts
| 2.890625
| 3
|
import { IOrderId, Ticker, Side } from './model'
class OrderId {
static idSequence = 0
static next (ticker: Ticker, side: Side): string {
let uid = OrderId.idSequence++
return `${ticker}.${side}.${uid}`
}
static fromString (id: string): IOrderId {
let idFields = id.split('.')
try {
return {
ticker: idFields[0] as Ticker,
side: idFields[1] as Side,
id: idFields[2] as string
}
} catch (e) {
throw new Error(`Order: Invalid id string format ${id}`)
}
}
static asString (orderId: IOrderId): string {
return `${orderId.ticker}.${orderId.side}.${orderId.id}`
}
}
export default OrderId
|
c1ddca754a42dd92f8b1c48e48b769a5f2f135b1
|
TypeScript
|
WonderPanda/schematics
|
/src/utils/module-metadata.declarator.ts
| 2.921875
| 3
|
import { DeclarationOptions } from './module.declarator';
export class ModuleMetadataDeclarator {
private METADATA_REGEXP: RegExp = /@Module\(([\s\S]*?)\)/;
constructor() {}
public declare(content: string, options: DeclarationOptions): string {
const metadata: any = this.extract(content);
return content
.replace(
this.METADATA_REGEXP,
`@Module(${ JSON.stringify(this.addSymbol(metadata, options), null, 2) })`
)
.replace(/"/g, '');
}
private extract(source: string): any {
const results: RegExpExecArray | null = this.METADATA_REGEXP.exec(source);
return JSON.parse(
results[ 1 ]
.replace(/([a-zA-Z]+)(,)(.*\n.*])/, '$1$3')
.replace(/(])(,)(.*\n.*})/, '$1$3')
.replace(/([a-zA-Z]+)/g, '"$1"')
);
}
private addSymbol(metadata: any, options: DeclarationOptions): any {
const updatedMetadata: any = Object.assign({}, metadata);
if (updatedMetadata[ options.metadata ] === undefined) {
updatedMetadata[ options.metadata ] = [ options.symbol ];
} else {
updatedMetadata[ options.metadata ].push(options.symbol);
}
return updatedMetadata;
}
}
|
cebc8fa9d2aea61ace6f599194ee497d48667204
|
TypeScript
|
ctymcom/store-ban-thuoc
|
/src/base/error.ts
| 2.703125
| 3
|
import dotenv from "dotenv";
import express from "express";
// import Raven from 'raven';
// import { config } from '..';
dotenv.config();
// let sentry: Raven.Client;
// if (config.enableSentry) {
// if (!process.env.SENTRY_CONNECTSTRING) throw new Error('Missing config SENTRY_CONNECTSTRING');
// sentry = Raven.config(process.env.SENTRY_CONNECTSTRING).install();
// }
export interface IErrorInfo {
status: number;
code: string;
message: string;
data?: any;
}
export class BaseError extends Error {
constructor(status: number, code: string, message: string, data?: any) {
super(message);
this.info = { status, code, message, data };
}
info: IErrorInfo;
}
export class BaseErrorHelper {
static handleError(func: (req: express.Request, rep: express.Response) => Promise<any>) {
return (req: express.Request, res: express.Response) =>
func
.bind(this)(req, res)
.catch((error: any) => {
if (!error.info) {
const err = this.somethingWentWrong();
res.status(err.info.status).json(err.info);
this.logUnknowError(error);
} else {
res.status(error.info.status).json(error.info);
}
});
}
static logUnknowError(error: Error) {
console.log("*** UNKNOW ERROR ***");
console.log(error);
console.log("********************");
// if (sentry) {
// try {
// sentry.captureException(error);
// } catch (err) {
// console.log('*** CANNOT CAPTURE EXCEPTION TO SENTRY ***');
// console.log(err.message);
// console.log('******************************************');
// }
// }
}
static logError(prefix: string, logOption = true) {
return (error: any) => {
console.log(prefix, error.message || error, logOption ? error.options : "");
};
}
// Unknow
static somethingWentWrong(message?: string) {
return new BaseError(500, "500", message || "Có lỗi xảy ra");
}
// Auth
static unauthorized() {
return new BaseError(401, "401", "Chưa xác thực");
}
static badToken() {
return new BaseError(401, "-1", "Không có quyền truy cập");
}
static tokenExpired() {
return new BaseError(401, "-2", "Mã truy cập đã hết hạn");
}
static permissionDeny() {
return new BaseError(405, "-3", "Không đủ quyền để truy cập");
}
// Request
static requestDataInvalid(message: string) {
return new BaseError(403, "-4", "Dữ liệu gửi lên không hợp lệ " + message);
}
// External Request
static externalRequestFailed(message: string) {
return new BaseError(500, "-5", message);
}
// Mongo
static mgRecoredNotFound(objectName: string = "dữ liệu yêu cầu") {
return new BaseError(404, "-7", "Không tìm thấy " + objectName);
}
static mgQueryFailed(message: string) {
return new BaseError(403, "-8", message || "Truy vấn không thành công");
}
static branchNotWorking() {
return new BaseError(403, "-9", "Chi nhánh không làm việc vào ngày này");
}
static recoredNotFound(message: string) {
return new BaseError(404, "-10", `Không tìm thấy dữ liệu yêu cầu: ${message}`);
}
}
export class ErrorHelper extends BaseErrorHelper {
static userNotExist() {
return new BaseError(403, "-103", "Người dùng không tồn tại");
}
static userExisted() {
return new BaseError(403, "-104", "Người dùng đã tồn tại");
}
static userRoleNotSupported() {
return new BaseError(401, "-105", "Người dùng không được cấp quyền");
}
static userError(message: string) {
return new BaseError(403, "-106", "Lỗi người dùng: " + message);
}
static duplicateError(key: string) {
return new BaseError(403, "-107", `${key} đã bị trùng.`);
}
static readOnlyError(key: string) {
return new BaseError(403, "-108", `${key} chỉ được phép xem.`);
}
static createUserError(message: string) {
return new BaseError(401, "-109", `Lỗi tạo người dùng: ${message}`);
}
static updateUserError(message: string) {
return new BaseError(401, "-110", `Lỗi cập nhật người dùng: ${message}`);
}
static userPasswordNotCorrect() {
return new BaseError(403, "-111", `Mật khẩu không đúng.`);
}
static farmerPinNotCorrect() {
return new BaseError(403, "-112", `Mã pin không đúng`);
}
static deliveryStatusWrong() {
return new BaseError(403, "-113", `Trạng thái đơn hàng không đúng`);
}
static notEnoughtPoint() {
return new BaseError(403, "-114", "Tài khoản không đủ điểm");
}
static spinError(message: string) {
return new BaseError(403, "-115", message);
}
static invalidPin() {
return new BaseError(403, "-116", "Mã pin phải là 6 số");
}
static validateJSONError(message: string = "") {
return new BaseError(500, "-117", message);
}
static error(message: string) {
return new BaseError(403, "-118", message);
}
}
|
9bf84414b2b1519ffddfff6f0ad04a5936eb3582
|
TypeScript
|
anthoDevWeb/Mon-agence-immo
|
/src/app/services/properties.service.ts
| 2.609375
| 3
|
import { Injectable } from '@angular/core';
import {Observable, Subject} from 'rxjs';
import {Property} from '../interfaces/property';
import * as firebase from 'firebase';
@Injectable({
providedIn: 'root'
})
export class PropertiesService {
properties: Property[] = [];
propertiesSubject = new Subject<Property[]>();
constructor() {
}
// Emission des propriétés
emitProperties = () => {
this.propertiesSubject.next(this.properties);
}
saveProperties = () => {
firebase.database().ref('/properties').set(this.properties);
}
getProperties = () => {
firebase.database().ref('/properties').on('value', (data) => {
this.properties = data.val() ? data.val() : [] ;
this.emitProperties();
});
}
// Création d'une propriété
createProperty = (property: Property) => {
this.properties.push(property);
this.saveProperties();
this.emitProperties();
}
// Suppresion d'une propriété
deleteProperty = (index) => {
this.properties.splice(index, 1);
this.saveProperties();
this.emitProperties();
}
// Mise à jour d'une propriété
updateProperty = (property: Property, index) => {
// this.properties[index] = property;
// this.saveProperties();
// this.emitProperties();
firebase.database().ref('/properties/' + index).update(property);
}
getSingleProperty = (id) => {
return new Promise(
(resolve, reject) => {
firebase.database().ref('/properties/' + id).once('value').then(
(data) => {
resolve(data.val());
}
).catch(
(err) => {
reject(err);
}
);
}
);
}
}
|
4cd46c82d6c9a56fe70af1688f8e61f7c7ace70b
|
TypeScript
|
codaxy/cxjs
|
/packages/cx/src/widgets/form/TextField.d.ts
| 3.140625
| 3
|
import * as Cx from "../../core";
import { Instance } from "../../ui/Instance";
import { FieldProps } from "./Field";
export interface TextFieldProps extends FieldProps {
/**
* Set to `true` to hide the clear button. It can be used interchangeably with the `showClear` property.
* Default value is `true`.
*/
hideClear?: boolean;
/**
* Set to `false` to hide the clear button. It can be used interchangeably with the `hideClear` property.
* Default value is `false`.
*/
showClear?: boolean;
/**
* Set to `true` to display the clear button even if `required` is set. Default is `false`.
*/
alwaysShowClear?: boolean;
/** Textual value of the input. */
value?: Cx.StringProp;
/** Defaults to `false`. Used to make the field read-only. */
readOnly?: Cx.BooleanProp;
/** The opposite of `disabled`. */
enabled?: Cx.BooleanProp;
/** Default text displayed when the field is empty. */
placeholder?: Cx.StringProp;
/** Minimal length of the input text. */
minLength?: Cx.NumberProp;
/** Maximal length of the input text. */
maxLength?: Cx.NumberProp;
/** Base CSS class to be applied to the field. Defaults to `textfield`. */
baseClass?: string;
/**
* Event used to report a new value. Defaults to `input`, which means that entered value will be written to the store on each keystroke.
* Other permitted values are `enter` (Enter key pressed) and `blur` (field looses focus).
* Multiple values should be separated by space, e.g. `enter blur`.
*/
reactOn?: string;
/** Defaults to `text`. Other permitted value is `password`. */
inputType?: "text" | "password";
/** Message to be shown to the user if validation fails. */
validationErrorText?: string;
/** Message to be shown to the user if input text is too short. */
minLengthValidationErrorText?: string;
/** Message to be shown to the user if input text is too long. */
maxLengthValidationErrorText?: string;
/** Regular expression used to validate the user's input. */
validationRegExp?: RegExp;
/** Name of the icon to be put on the left side of the input. */
icon?: Cx.StringProp;
/** If trackFocus is set, this value will be set when the field receives or loses focus. */
focused?: Cx.BooleanProp;
/** Trim text to remove whitespace. Default is false. */
trim?: Cx.BooleanProp;
onKeyDown?: string | ((event: KeyboardEvent, instance: Instance) => boolean | void);
}
export class TextField extends Cx.Widget<TextFieldProps> {}
|
e6f5c5f8f9045b5c6e647852aeb01c251ba39ec0
|
TypeScript
|
MaxLarue/moonshot
|
/src/common/components/CircleBodyComponent.ts
| 2.796875
| 3
|
import * as tags from "../tags"
import Entity from '~/general/Entity';
import BodyComponent, { BodyOption } from './BodyComponent';
import RendererComponent from './RendererComponent';
export interface CircleBodyComponentOptions extends BodyOption {
radius: number,
offsetX: number,
offsetY: number,
disabled?: boolean
}
export default class CircleBodyComponent extends BodyComponent {
protected radius: number
protected offsetX: number
protected offsetY: number
protected disabled: boolean
constructor(entity: Entity, options: CircleBodyComponentOptions) {
super(entity, options, [])
this.radius = options.radius
this.offsetX = options.offsetX
this.offsetY = options.offsetY
this.disabled = !!options.disabled
}
create() {
super.create()
const renderer = this.entity.getComponentByTag<RendererComponent>(tags.RENDERER_COMPONENT_TAG, RendererComponent)
const sprite = renderer.sprite
this.body.setCircle(
this.radius,
(-1*this.radius + 0.5 * sprite.width),
(-1*this.radius + 0.5 * sprite.width)
)
if (this.disabled) this.body.enable = false
}
}
|
8f02b02ae18d6ae1265ff4418b67972b149d5eee
|
TypeScript
|
jason1105/org
|
/src/app/cts/measure/org/common/org-management-missionService.service.ts
| 2.578125
| 3
|
import {Injectable} from "@angular/core";
import {Subject, Observable, Observer, Subscription} from "rxjs";
/**
* Created by lv-wei on 2017-06-01.
*/
@Injectable()
export class MissionService {
// Observable string sources
private missionAnnouncedSource = new Subject<any>();
private missionConfirmedSource = new Subject<any>();
// Observable string streams
missionAnnounced$ = this.missionAnnouncedSource.asObservable();
missionConfirmed$ = this.missionConfirmedSource.asObservable();
// Service message commands
announceMission(mission: any) {
this.missionAnnouncedSource.next(mission);
}
confirmMission(astronaut: any) {
this.missionConfirmedSource.next(astronaut);
}
private topics = {};
subscribe = function (topic, handler) {
if (!this.topics[topic]) {
this.topics[topic] = new Topic();
}
this.topics[topic].subscribe(handler);
};
unsubscribe = function (topic) {
if (this.topics[topic]) {
this.topics[topic].unsubscribe();
delete this.topics[topic];
}
};
sendMsg = function (topic, msg) {
if (!this.topics[topic]) {
this.topics[topic] = new Topic();
}
this.topics[topic].next(msg);
};
}
class Topic {
private _observer: Observer<any>;
private _subscription: Subscription;
private _observable = function(_this){
return Observable.create(function (observer) {
_this._observer = observer;
}).share();
}(this);
subscribe = function (handler) {
this._subscription = this._observable.subscribe(handler);
};
unsubscribe = function() {
this._subscription.unsubscribe();
};
next = function (msg) {
this._observer.next(msg);
};
}
|
6348532ffee93558cc2f443651c81e07f7e38deb
|
TypeScript
|
jcollins-axway/amplify-choreo-async
|
/item-id-aggregation/main.ts
| 2.515625
| 3
|
import * as ace from '@axway/ace-sdk';
import * as ByteBuffer from 'bytebuffer';
import {SpanContext} from 'opentracing';
let businessMessageProcessor: ace.MessageProcessorInterface = function(
spanCtx: SpanContext,
bMsgs: Array<ace.BusinessMessage>,
clientRelay: ace.MessageProducer
): Error | null {
//this simulates 'splitting' the received message by ' ' character
// Sample Input, each in a different business message
// [
// {
// "customer_id": "ZYX012",
// "order_number":"0001",
// "item_id":"ABC",
// "quantity": 5
// }
// ],
// [
// {
// "customer_id": "XYZ123",
// "order_number":"0002",
// "item_id":"DEF",
// "quantity": 2
// }
// ],
// [
// {
// "customer_id": "XYZ123",
// "order_number":"0003",
// "item_id":"ABC",
// "quantity": 13
// }
// ],
// [
// {
// "customer_id": "ZYX012",
// "order_number":"0004",
// "item_id":"CAB",
// "quantity": 8
// }
// ],
// [
// {
// "customer_id": "ZYX012",
// "order_number":"0005",
// "item_id":"DEF",
// "quantity": 8
// }
// ]
//
// Sample Output 1
// {
// "orders":
// [{
// "customer_id": "ZYX012",
// "order_number":"0001",
// "item_id":"ABC",
// "quantity": 5
// },{
// "customer_id": "XYZ123",
// "order_number":"0003",
// "item_id":"ABC",
// "quantity": 13
// }]
// "item_id": "ABC",
// "qunatity": 18
// }
//
// Sample Output 2
// {
// "orders":
// [{
// "customer_id": "XYZ123",
// "order_number":"0002",
// "item_id":"DEF",
// "quantity": 2
// },{
// "customer_id": "ZYX012",
// "order_number":"0005",
// "item_id":"DEF",
// "quantity": 8
// }]
// "item_id": "DEF",
// "quantity": 10
// }
//
// Sample Output 3
// {
// "orders":
// [{
// "customer_id": "ZYX012",
// "order_number":"0004",
// "item_id":"CAB",
// "quantity": 8
// }]
// "item_id": "CAB",
// "quantity": 8
// }
// Load the business message body, which is a byte array, by creating a new Buffer object
// Convert that buffer object to be a string type
let span = ace.tracing.startSpanFromContext(spanCtx, 'Item ID Aggregation Service');
let orders = [];
for (let i in bMsgs) {
let spanLog = {};
let payloadString = Buffer.from(bMsgs[i].getPayload().getBody_asU8()).toString();
orders.push(JSON.parse(payloadString));
spanLog['Order[' + i + ']'] = payloadString;
span.log(spanLog);
}
var groupBy = function(objArray: Array<any>, key: string) {
return objArray.reduce(function(rv: any, x: any) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
let orderGroups = groupBy(orders, 'item_id');
for (let grouping in orderGroups) {
// Creating an object with an array of orders
let ordersObj = {orders: orderGroups[grouping]};
// Sum the quantity of all orders
let total = 0;
for (let order of ordersObj.orders) {
total = total + order.quantity;
}
ordersObj['quantity'] = total;
// Put the item_id in the top level object
ordersObj['item_id'] = ordersObj.orders[0].item_id;
// Create new Business Message using current o ne as base
createNewBusinessMessage(bMsgs[0], JSON.stringify(ordersObj), newBusinessMessage => {
// Send that Business Message back to the linker client
span.log({Payload: JSON.stringify(ordersObj)});
let error = clientRelay.send(newBusinessMessage);
if (error) {
span.finish();
return error;
}
});
}
span.finish();
return;
};
function createNewBusinessMessage(bMsg: ace.BusinessMessage, newPayload: string, callback: any) {
let newBMsg = ace.cloneBusinessMessage(bMsg);
// Set the new payload, converting the UTF8 string into a byte array
newBMsg.getPayload().setBody(ByteBuffer.fromUTF8(newPayload).buffer);
callback(newBMsg);
}
function main() {
// Create new App Config and register the service with the ACE Linker
let serviceType = ace.ServiceType[process.env.SERVICE_TYPE];
let cfg = new ace.ServiceConfig(process.env.SERVICE_NAME, process.env.SERVICE_VERSION, serviceType, process.env.SERVICE_DESCRIPTION);
ace.logger.info('Business service config', {[ace.fields.logFieldServiceName]: cfg.name});
ace.register(cfg, businessMessageProcessor, (link, error) => {
if (error) {
ace.logger.error('registration error', {[ace.fields.logFieldError]: error.message});
return;
}
// Start the link between the business message processor and linker
link.start();
});
}
main();
|
7dde9ab9ee218c293c5e50721313f826a9aa174a
|
TypeScript
|
ericlobdell/ExercismTS
|
/ExerecismTS/src/gradeschool.ts
| 3.015625
| 3
|
class School {
constructor(private db = {}) { }
add( student: string, grade : number ) {
if (this.db[grade])
this.db[grade].push(student);
else
this.db[grade] = [student];
this.db[grade].sort();
}
grade( grade: number) {
return this.db[grade] ? this.db[grade] : [];
}
roster() {
return this.db;
}
}
|
564f4d8b2874a00834b30a23cd90984c019bc1c0
|
TypeScript
|
interledgerjs/interledgerjs
|
/packages/ilp-spsp-payout/src/lib/Logger.ts
| 2.875
| 3
|
export interface Logger {
debug: LogMethod
info: LogMethod
warn: LogMethod
error: LogMethod
}
/* eslint-disable @typescript-eslint/no-explicit-any */
type LogMethod = (message: string, ...optionalParams: any[]) => void
export const defaultLogger = { debug: noop, info: noop, warn: noop, error: noop }
/* eslint-disable @typescript-eslint/no-empty-function */
/* eslint-disable @typescript-eslint/no-unused-vars */
function noop(_s: string): void {}
|
6b5079fd5b274803e51c4088045f13c8cf7add47
|
TypeScript
|
Torphage/EasyDoc
|
/src/languages/python/syntax.ts
| 2.796875
| 3
|
/**
* Implementation of Python
*/
/**
* EasyDoc.
*/
import { ISyntaxVariable } from "../../interfaces";
import { WorkShop } from "../workshop";
import { PythonParse } from "./parse";
/**
* Python, extends WorkShop.
*
* @export
* @class Python
* @extends {WorkShop}
*/
export class Python extends WorkShop {
/**
* The Python parser.
*
* @protected
* @type {PythonParse}
* @memberof Python
*/
protected parse: PythonParse;
/**
* Creates an instance of Python.
*
* @param {string} syntaxFile The template file text.
* @param {string} docType The type of documentation to make.
* @memberof Python
*/
constructor(syntaxFile: string, docType: string) {
super(syntaxFile);
this.parse = new PythonParse(this.docRows, docType);
}
/**
* Check if the cursor is correctly placed in the function.
*
* @protected
* @param {string} functionLineIndex The row to search on.
* @returns {boolean} If cursor is correctly placed.
* @memberof Python
*/
protected correctlyPlacedFunction(functionLineIndex: string): boolean {
const regex = /^\s*def\s/g;
if (regex.exec(functionLineIndex) !== null) {
return true;
} else {
return false;
}
}
/**
* Get the variables based on the language.
*
* @protected
* @param {number} index The start index of the function.
* @returns {Promise<ISyntaxVariable>} An promise to return the variables.
* @memberof Python
*/
protected getVariables(index: number): Promise<ISyntaxVariable> {
const parse = this.parse.parse(this.block);
const params = this.parse.parseParams(parse.params);
const variables: ISyntaxVariable = {
NAME: parse.name,
PARAMS: params.paramList,
PARAMS_TYPES: undefined,
PARAMS_TEMPLATE: params.template,
ABSTRACT: undefined,
EXPORT: undefined,
ACCESS: undefined,
CONST: undefined,
RELATION: undefined,
RELATIONNAME: undefined,
PARENT: undefined,
PARENT_CONST: undefined,
RETURN_TYPE: undefined,
BLOCK_COMMENT_START: this.getComment("BLOCK_COMMENT_START"),
BLOCK_COMMENT_END: this.getComment("BLOCK_COMMENT_END"),
COMMENT: this.getComment("COMMENT"),
BLOCK: undefined,
ROUTE: undefined,
};
return new Promise((resolve, reject) => {
resolve(variables);
reject(undefined);
});
}
}
|
b34196d8f106d174ad0f024c27260bd25faf22f8
|
TypeScript
|
gksander/react-native-turbo-styles
|
/lib/colorStringToRgb.ts
| 2.890625
| 3
|
import { rgbStringToRgb } from "./rgbStringToRgb";
import { hexToRgb } from "./hexToRgb";
const RgbRegExp = /rgb\(/;
export const colorStringToRgb = (val: string) => {
if (RgbRegExp.test(val)) {
return rgbStringToRgb(val);
} else {
return hexToRgb(val);
}
};
|