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
|
|---|---|---|---|---|---|---|
f051415e87ab95c7d1693186e31b3548554f9387
|
TypeScript
|
rnsell/ts-pattern-demo
|
/2-basic-pattern-examples/2-objects.ts
| 3.5
| 4
|
// Website
import { match, select } from "ts-pattern";
type Data = { type: "text"; content: string } | { type: "img"; src: string };
type Result = { type: "ok"; data: Data } | { type: "error"; error: Error };
const resultInput: Result = {
type: "ok",
data: {
type: "text",
content: "hello world",
},
};
// Note the type matching here. if its an error you cant have a data propery
match<Result, string>(resultInput)
.with({ type: "error" }, (res) => `<p>Oups! An error occured</p>`)
.with(
{ type: "ok", data: { type: "text" } },
(res) => `<p>${res.data.content}</p>`
)
.with(
{ type: "ok", data: { type: "img", src: select() } },
(src) => `<img src=${src} />`
)
// .with(
// { type: "error", data: { type: "text" } },
// (res) => `<p>${res.error}</p>`
// )
.exhaustive();
// *************************************************
export enum BoardDescription {
TURN_X = "X's Turn",
WIN_X = "X Wins",
TURN_O = "O's Turn",
WIN_O = "O Wins",
TIE = "Tie",
IMPOSSIBLE = "Impossible",
}
const { difference } = { difference: 0 }; //numberOfXandOs(board);
const hasDoubleMoved = false; //doubleMoved(board);
const xWin = true; //playerHasWon(Player.X)(board);
const oWin = false; // playerHasWon(Player.O)(board);
const noMoreMovesExists = true; //noMoreSpots(board);
const pattern = { hasDoubleMoved, xWin, oWin, noMoreMovesExists, difference };
const noWinner = {
xWin: false,
oWin: false,
};
match<any, any>(pattern)
.with({ hasDoubleMoved: true }, () => BoardDescription.IMPOSSIBLE)
.with({ xWin: true, oWin: true }, () => BoardDescription.IMPOSSIBLE)
.with(
{ hasDoubleMoved: false, xWin: true, oWin: false },
() => BoardDescription.WIN_X
)
.with(
{ hasDoubleMoved: false, xWin: false, oWin: true },
() => BoardDescription.WIN_O
)
.with(
{
hasDoubleMoved: false,
xWin: false,
oWin: false,
noMoreMovesExists: true,
},
() => BoardDescription.TIE
)
.with(
{
hasDoubleMoved: false,
...noWinner,
noMoreMovesExists: false,
difference: 0,
},
() => BoardDescription.TURN_X
)
.otherwise(() => {
return BoardDescription.TURN_O;
});
|
cbffcac01347811d97295f3d81da8ab2c38f8792
|
TypeScript
|
huaweicloud/huaweicloud-sdk-nodejs-v3
|
/services/sms/v3/model/UpdateTaskSpeedRequest.ts
| 2.625
| 3
|
import { UpdateTaskSpeedReq } from './UpdateTaskSpeedReq';
export class UpdateTaskSpeedRequest {
private 'task_id'?: string;
public body?: UpdateTaskSpeedReq;
public constructor(taskId?: string) {
this['task_id'] = taskId;
}
public withTaskId(taskId: string): UpdateTaskSpeedRequest {
this['task_id'] = taskId;
return this;
}
public set taskId(taskId: string | undefined) {
this['task_id'] = taskId;
}
public get taskId(): string | undefined {
return this['task_id'];
}
public withBody(body: UpdateTaskSpeedReq): UpdateTaskSpeedRequest {
this['body'] = body;
return this;
}
}
|
7307aba058e590ddda82f3561437421533d705d1
|
TypeScript
|
Myns18/Ts_Bank
|
/app/index.ts
| 2.734375
| 3
|
import { Client } from "./Client";
import { Compte } from "./Comptes/Compte";
import { CompteASeuil } from "./Comptes/CompteASeuil";
import { CompteASeuilRemunere } from "./Comptes/CompteASeuilRemunere";
import { CompteRemunere } from "./Comptes/CompteRemunere";
const compte = new Compte();
compte.ajouter(5);
const client = new Client("Sansnom", "Pierre", 21);
const compterenumerer = new CompteRemunere(0.40);
const compteaseul = new CompteASeuil();
const compteASeuilRemunere = new CompteASeuilRemunere(0.50);
client.ajouterCompte(compte);
client.ajouterCompte(compterenumerer);
client.ajouterCompte(compteaseul);
client.ajouterCompte(compteASeuilRemunere);
console.log("--------------------------");
console.log("--------------------------");
console.log("--------------------------");
compterenumerer.ajouter(5);
compteASeuilRemunere.ajouter(10);
compterenumerer.calculerInterets();
compterenumerer.verserInterets();
// client.compte.forEach((comptes: Compte)=>{
// if(compte instanceof CompteRemunere){
// compte.verserInterets();
// }
// })
console.log(client);
|
f5bc7e869b6b37f08d0adc5383d1517d0a95c560
|
TypeScript
|
GarboMuffin/garbomuffin.github.io
|
/nightlight/src/engine/vector.ts
| 3.703125
| 4
|
import { Vector2D } from "./vector2d";
/*
* A 3D Vector: (x, y, z)
*
* z is optional when creating Vectors
*/
// a simple position class that removes some verbosity from code
// can make for some nicer code sometimes
export class Vector extends Vector2D {
public z: number;
constructor(x: number | Vector = 0, y: number = 0, z: number = 0) {
super(x, y);
if (typeof x === "object") {
this.z = x.z;
} else {
this.z = z;
}
}
}
|
d443233d2b1bb91ef455736de141d86bfbf04d8c
|
TypeScript
|
n-wach/protractr
|
/scripts/ui/history.ts
| 3.78125
| 4
|
/**
* @module ui/history
*/
/**
* Editing history manager. Consists of two stacks: undo and redo history.
* New states clear redo history, are added to undo history.
* It's possible for current state to be undefined, in which case the app should load some default state.
*/
export default class History<T = string> {
undoHistory: HistoryStack<T>;
redoHistory: HistoryStack<T>;
currentState: T;
constructor(startingState: T) {
this.undoHistory = new HistoryStack<T>();
this.redoHistory = new HistoryStack<T>();
this.currentState = startingState;
}
/**
* A new state produced by something other than undo or redo.
*/
recordStateChange(newState: T) {
if (this.currentState != newState) {
this.undoHistory.push(this.currentState);
this.redoHistory.clear();
this.currentState = newState;
}
}
/**
* moves current state into redo, pops undo onto current state
*/
undo(): T {
if (this.undoHistory.empty()) return this.currentState;
this.redoHistory.push(this.currentState);
this.currentState = this.undoHistory.pop();
return this.currentState;
}
/**
* moves current state into undo, pops redo onto current state
*/
redo(): T {
if (this.redoHistory.empty()) return this.currentState;
this.undoHistory.push(this.currentState);
this.currentState = this.redoHistory.pop();
return this.currentState;
}
}
/**
* Simple stack structure. Adjacent elements must be distinct.
*/
class HistoryStack<T> {
stack: T[];
constructor() {
this.stack = [];
}
/**
* Get top element of stack
*/
top(): T {
if (this.empty()) return undefined;
return this.stack[this.stack.length - 1];
}
push(element: T) {
if (this.top() != element) {
this.stack.push(element);
}
}
/**
* Get top element of stack and remove
*/
pop(): T {
if (this.empty()) return undefined;
return this.stack.pop();
}
empty(): boolean {
return this.stack.length == 0;
}
clear() {
this.stack = [];
}
}
|
ccf8f2989203356a884d6500e0926d754585e4fd
|
TypeScript
|
horvay/simple-dux
|
/__tests__/store-test.ts
| 3.34375
| 3
|
import SimpleDux from "../src/index";
it("Successfully register a persistent store and retrieve it", () =>
{
let simple_dux = new SimpleDux();
let store = simple_dux.Store;
class Person
{
public name = "greg";
}
let greg: Person = { name: "greg" };
store.RegisterPersistentStore(greg, "greg");
let greg2 = store.GetPersistentStore("greg");
expect(greg2).toEqual(greg);
});
it("Deregister a persistent store and cant retrieve it", () =>
{
let simple_dux = new SimpleDux();
let store = simple_dux.Store;
class Person
{
public name = "greg";
}
let greg: Person = { name: "greg" };
store.RegisterPersistentStore(greg, "greg");
store.DeregisterPersistentStore("greg");
let greg2 = store.GetPersistentStore("greg");
expect(greg2).toBeUndefined();
});
it("Successfully register a factory method store and retrieve it with argument", () =>
{
let simple_dux = new SimpleDux();
let store = simple_dux.Store;
class Person
{
public name = "not-set";
public age = 54;
public yourmother = true;
constructor(name: string)
{
this.name = name;
}
}
let factory_method = (name: string) => new Person(name);
store.RegisterScopedStore(factory_method, "greg");
let greg = store.GetScopedStore<Person>("greg", "fredarg");
expect(greg).toMatchSnapshot();
});
it("Deregister a factory method and retrieve with argument throws error", () =>
{
let simple_dux = new SimpleDux();
let store = simple_dux.Store;
class Person
{
public name = "not-set";
public age = 54;
public yourmother = true;
constructor(name: string)
{
this.name = name;
}
}
let factory_method = (name: string) => new Person(name);
store.RegisterScopedStore(factory_method, "greg");
store.DeregisterScopedStore("greg");
expect(() => {
let greg = store.GetScopedStore<Person>("greg", "fredarg");
}).toThrowError("factory method called greg is not defined");
});
it("Successfully register a factory method store and retrieve it without argument", () =>
{
let simple_dux = new SimpleDux();
let store = simple_dux.Store;
class Person
{
public name = "not-set";
public age = 54;
}
let factory_method = () => new Person();
store.RegisterScopedStore(factory_method, "greg");
let greg = store.GetScopedStore<Person>("greg");
expect(greg).toMatchSnapshot();
});
it("Deregister a factory method and retrieve without argument throws error", () =>
{
let simple_dux = new SimpleDux();
let store = simple_dux.Store;
class Person
{
public name = "not-set";
public age = 54;
}
let factory_method = () => new Person();
store.RegisterScopedStore(factory_method, "greg");
store.DeregisterScopedStore("greg");
expect(() => {
let greg = store.GetScopedStore<Person>("greg");
}).toThrowError("factory method called greg is not defined");
});
|
d422dd8deefe68f8f4be702099b6bb1119df97e5
|
TypeScript
|
jmhalire/api-veterinaria
|
/src/models/usuario.ts
| 2.8125
| 3
|
import {Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, BeforeInsert, TableForeignKey, OneToMany} from "typeorm";
import bcrypt from "bcrypt";
import { Venta } from "./venta";
export enum UserRole {
ADMIN = "ADMIN",
GENERAL = "GENERAL"
}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column({type: "varchar",length: 40, nullable: false})
Names: string;
@Column({type: "varchar",length: 40, nullable: false})
FirstName: string;
@Column({type: "varchar",length: 40, nullable: false})
LastName: string;
@Column({type: "numeric", nullable: false})
Celular: string;
@Column({type: "varchar",length: 40})
Address: string;
@Column({type: "varchar",length: 20, nullable: false})
Email: string;
@Column({type: "varchar", length:80, nullable: false})
Password: string;
@Column({type: "enum", enum: UserRole, default: UserRole.GENERAL})
Role: UserRole;
@Column({type: "int",default:1})
Estado: number
@Column()
@CreateDateColumn()
CreatedAt: Date;
@Column()
@UpdateDateColumn()
UpdatedAt: Date;
@OneToMany(type => Venta, venta => venta.usuario)
ventas: Venta[]
//se ejecuta antes de guardar el usuario
@BeforeInsert()
public encryptPasword(): void{
const salt = bcrypt.genSaltSync(10);
this.Password = bcrypt.hashSync(this.Password, salt);
}
//metodo validar
public validPassword(password: string): boolean{
return bcrypt.compareSync(password, this.Password);
}
}
|
edb15b31e2198976eb56b2627f77ab16e160e9f5
|
TypeScript
|
jacoor/complete-typescript-course
|
/shared/model/course-detail.ts
| 3.03125
| 3
|
import { Lesson } from "./lesson";
import { CourseSummary } from "./course-summary";
// type could be used here, however since this is object type
// interface is recommended.
export interface CourseDetail extends CourseSummary {
longDescription: string;
comingSoon?: boolean;
isNew?: boolean; //optional
isOngoing?: boolean;
lessons: Lesson[];
// readonly lessons: Lesson[],
// note: lessons.push will work. Readonly here only means that reference
// is immutable, the array itself can be modified.
// Best way to prevent changes would be to use immutable.js or similar lib.
}
|
26b0133309ae6335f8d89bdbacffbeeb7a195d6e
|
TypeScript
|
faruzzy/snake
|
/src/Shape/Matrix.test.ts
| 2.765625
| 3
|
import { fromJS } from 'immutable'
import { Matrix } from './Matrix'
describe('Matrix', () => {
const matrix = Matrix.fill([3, 2], 0)
test('generated matrix', () => {
expect(matrix.rows.toJS()).toEqual([
[0, 0, 0],
[0, 0, 0],
])
})
it('is a functor', () => {
expect(matrix.map((cell, [x, y]) => {
expect(cell).toBe(0)
return x + y
}).rows.toJS()).toEqual([
[0+0, 1+0, 2+0],
[0+1, 1+1, 2+1],
])
})
test('updating a cell', () => {
expect(matrix.updateCell([2, 1], 2).rows.toJS()).toEqual([
[0, 0, 0],
[0, 0, 2],
])
})
})
|
e680056b40648987631e0b1071b57f94a269214a
|
TypeScript
|
angus-c/just
|
/packages/string-replace-all/index.d.ts
| 2.703125
| 3
|
type ReplaceAll<
Str extends string,
SubStr extends string,
NewSubStr extends string
> = Str extends `${infer Before}${SubStr}${infer After}`
? `${Before}${NewSubStr}${ReplaceAll<After, SubStr, NewSubStr>}`
: Str;
declare function replaceAll<
Str extends string,
SubStr extends string,
NewSubStr extends string
>(
str: Str,
subStr: SubStr,
newSubStr: NewSubStr
): ReplaceAll<Str, SubStr, NewSubStr>;
export default replaceAll;
|
6c1036a8692bbeff54885c815d2572bbd1da18b5
|
TypeScript
|
huddle-brasil/slush-ts-functions-firestore
|
/templates/functions/src/utils/crossDomain.ts
| 2.578125
| 3
|
import { Request, NextFunction, Response } from "express";
export const crossDomain = (req: Request, res: Response, next: NextFunction) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS,PATCH');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// intercept OPTIONS method
if ('OPTIONS' === req.method) {
res.sendStatus(200);
}
else {
next();
}
}
|
ba2fe1f19d3df934f1c124c91970ef3a10eb939c
|
TypeScript
|
mudachyo/pixelplanet-bot
|
/src/userInput.ts
| 2.8125
| 3
|
import * as readline from 'readline';
import logger from './logger';
export interface IProgramParameters {
xLeftMost: number;
yTopMost: number;
imgPath: string;
ditherTheImage: boolean;
constantWatch: boolean;
doNotOverrideColors: number[];
customEdgesMapImagePath: string;
}
class UserInput {
public currentParameters?: IProgramParameters;
public async gatherProgramParameters(): Promise<void> {
if (process.argv[2]) {
return this.parseParametersFromArguments();
}
const rl: readline.Interface = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return this.parseParametersFromInput(rl)
.then(() => rl.close())
.catch(() => rl.close());
}
private parseParametersFromArguments() {
const args = process.argv.slice(2);
let xLeftMost: number;
if (args[0]) {
xLeftMost = parseInt(args[0], 10);
logger.log(`x=${xLeftMost}`);
} else {
throw new Error('Значение X не указано');
}
let yTopMost: number;
if (args[1]) {
yTopMost = parseInt(args[1], 10);
logger.log(`y=${yTopMost}`);
} else {
throw new Error('Значение Y не указано');
}
let imgPath: string;
if (args[2]) {
imgPath = args[2];
logger.log(`imgPath=${imgPath}`);
} else {
throw new Error('Путь к изображению не указан');
}
let ditherTheImage: boolean = false;
if (args[3]) {
ditherTheImage = args[3].toLowerCase() === 'y';
}
logger.log(`Дизеринг изображения=${ditherTheImage}`);
let constantWatch: boolean = false;
if (args[4]) {
constantWatch = args[4].toLowerCase() === 'y';
}
logger.log(`constantWatch=${constantWatch}`);
const doNotOverrideColors: number[] = [];
if (args[5]) {
const inColorsStrArr = args[5].split(',');
inColorsStrArr.forEach((el) => {
doNotOverrideColors.push(parseInt(el, 10));
});
}
let customEdgesMapImagePath: string = '';
if (args[6]) {
customEdgesMapImagePath = args[6];
logger.log(`customEdgesMapImagePath=${customEdgesMapImagePath}`);
}
this.currentParameters = {
constantWatch,
customEdgesMapImagePath,
ditherTheImage,
doNotOverrideColors,
imgPath,
xLeftMost,
yTopMost,
};
}
private async parseParametersFromInput(rl: readline.Interface) {
const xLeftMost = await this.readNumber(rl, 'TopLeft x: ');
const yTopMost = await this.readNumber(rl, 'TopLeft y: ');
const imgPath = await this.readString(rl, 'Path to an image: ');
let tmpStr = await this.readString(rl, 'Dither the image? [default=n] (y/n): ');
const ditherTheImage: boolean = tmpStr.toLowerCase() === 'y';
tmpStr = await this.readString(rl,
// tslint:disable-next-line: max-line-length
'Continue watching for changes after script finishes (grief fix mode)? [default=n] (y/n): ');
const constantWatch: boolean = tmpStr.toLowerCase() === 'y';
const doNotOverrideColors: number[] = [];
tmpStr = await this.readString(rl,
// tslint:disable-next-line: max-line-length
'Do not paint over colors list ("script-collab mode"): [default=NONE] (\'2,3,12,23\'): ');
const inColorsStrArr = tmpStr.split(',');
inColorsStrArr.forEach((el) => {
doNotOverrideColors.push(parseInt(el, 10));
});
const customEdgesMapImagePath = await this.readString(rl,
// tslint:disable-next-line: max-line-length
'[Optional] Provide with custom edges drawing map (Greyscale image showing how to draw the image): ');
this.currentParameters = {
constantWatch,
customEdgesMapImagePath,
ditherTheImage,
doNotOverrideColors,
imgPath,
xLeftMost,
yTopMost,
};
}
private async readString(rl: readline.Interface, question: string): Promise<string> {
const promise = new Promise<string>((resolve, reject) => {
rl.question(question, (str: string) => {
resolve(str);
return;
});
});
return promise;
}
private async readNumber(rl: readline.Interface, question: string): Promise<number> {
const promise = new Promise<number>((resolve, reject) => {
rl.question(question, (numStr: string) => {
const num = parseInt(numStr, 10);
if (isNaN(num)) {
reject('invalid number');
return;
}
resolve(num);
return;
});
});
return promise;
}
}
export default new UserInput();
|
5b85dc5e9ced041e9e8495583757f0d7f340826d
|
TypeScript
|
smkamble/protractor-jasmine-typescript-framework
|
/Library/PropertyFileReader.ts
| 2.578125
| 3
|
/**
* Created by Deepak on 07/02/18.
*/
import {isNullOrUndefined} from "util";
import {Constants} from "./Constants";
const propertiesReader: any = require("properties-reader");
let propFile: any = "";
export class PropertyFileReader {
private static pfReader: PropertyFileReader;
// private logger: any = Constants.log4js.getLog(this.constructor.name);
private constructor() {
}
public static getInstance = () => {
if (!PropertyFileReader.pfReader) {
PropertyFileReader.pfReader = new PropertyFileReader();
}
return PropertyFileReader.pfReader;
};
public setPropertyFile = (fileName: string) => {
propFile = propertiesReader(fileName);
};
public getPropValue = (propName: string) => {
let propValue: any;
try {
if (!isNullOrUndefined(propName)) {
propValue = propFile.get(propName);
// console.log("property value for '" + propName + "' :", propValue);
} else {
console.error("Please provide valid property name.");
}
return propValue;
} catch (e) {
console.error("error is :" + e.stack);
}
};
}
|
ef9b989bdb4a2e4b50b58c7935b8db917e0ff329
|
TypeScript
|
pcsteppan/ghost-bot
|
/src/Test.ts
| 3.390625
| 3
|
import TrieNode from "./Trie";
import { StateMachine, State } from "./StateMachine";
import { StateEvent } from "./Types";
import { shuffleArray } from "./Utils";
const dict = require('../resources/dict.json');
const assert = require('assert');
const {performance} = require('perf_hooks');
describe('Trie', () => {
let head: TrieNode;
beforeEach(() => {
head = new TrieNode();
})
afterEach(() => {
TrieNode.trieNodeCount = 0;
})
describe('.addChild', () => {
it('adds a child to an empty trie', () => {
const cCode = char('c');
const newNode = new TrieNode();
head.addChild(cCode, newNode);
assert.ok(head.children.get(cCode) === newNode);
});
});
describe('.addWord', () => {
it('adds a word to an empty trie', () => {
const word = 'cat';
head.addWord(word);
const charCodes = Array.from('cat').map(c => char(c));
let currentNode = head;
charCodes.forEach(c => {
const child = currentNode.children.get(c);
assert.ok(child !== undefined);
if(child !== undefined){
assert.ok(child instanceof TrieNode);
currentNode = child;
}
});
assert.ok(currentNode.isWord);
});
it('adds a second word with a different suffix correctly', () => {
const word1 = 'cat';
const word2 = 'car';
head.addWord(word1);
head.addWord(word2);
const charCodes = charCodesFromString('cat');
let currentNode = head;
charCodes.forEach(c => {
const child = currentNode.children.get(c);
assert.ok(child !== undefined);
if(child!==undefined){
assert.ok(child instanceof TrieNode);
if(c === charCodes[1]){
assert.ok(child.children.size === 2);
assert.ok(child.children.has(char('r')));
assert.ok(child.children.get(char('r'))?.isWord);
}
currentNode = child;
}
});
assert.ok(currentNode.isWord);
});
it('does not take forever to add all the words in the english dictionary', () => {
const t0 = performance.now();
dict.forEach((word: string) => {
head.addWord(word);
})
const t1 = performance.now();
});
});
describe('.contains', () => {
it('returns true for words contained in the trie', () => {
head.addWord('cat');
assert.ok(head.contains('cat'));
});
it('returns false for strings contained in the trie that are not words', () => {
head.addWord('cats');
assert.ok(!(head.contains('cat')));
});
})
describe('.wordsStartingWith', () => {
it('returns the correct words that start with a given prefix', () => {
head.addWord('cots');
head.addWord('dogs');
head.addWord('core');
head.addWord('colder');
head.addWord('callous');
head.addWord('continuity');
const wordsStartingWithC = head.wordsStartingWith('co');
assert.ok(head.wordsStartingWith('co').length === 4);
})
})
});
const charCodesFromString = (str: string) => {
return Array.from(str).map(char);
}
const char = (str: string) => {
return str.charCodeAt(0);
}
describe('StateMachine', () => {
describe('.addTransition', () => {
it('transitions from one state to another when called with the correct event', () => {
const machine = new StateMachine();
const stateA = new State("A");
const stateB = new State("B");
machine.activeState = stateA;
machine.addStateTransition(StateEvent.QUIT, stateA, stateB);
machine.transition(StateEvent.QUIT);
assert.ok(machine.activeState === stateB);
})
})
})
describe('Utils', () => {
describe('.shuffleArray', () => {
it('contains all the elements that were present in the original array', () => {
const arr = [0, 1, 2, 3, 4, 5];
const shuffledArray = shuffleArray(arr);
const allElementsPresentInShuffleArray = arr.filter(el => shuffledArray.includes(el)) && arr.length === shuffledArray.length;
assert.ok(allElementsPresentInShuffleArray);
})
it('can handle empty arrays', () => {
const arr : Array<any> = [];
const shuffledArray = shuffleArray(arr);
const allElementsPresentInShuffleArray = arr.filter(el => shuffledArray.includes(el)) && arr.length === shuffledArray.length;
assert.ok(allElementsPresentInShuffleArray);
})
it('can handle arrays with only one element', () => {
const arr = [0];
const shuffledArray = shuffleArray(arr);
const allElementsPresentInShuffleArray = arr.filter(el => shuffledArray.includes(el)) && arr.length === shuffledArray.length;
assert.ok(allElementsPresentInShuffleArray);
})
})
})
describe('GameState', () => {
describe('addPlayer', () => {
})
describe('', () => {
})
describe('!start', () => {
})
describe('!join', () => {
})
})
|
52911da7a988b6f0b1dc5d06ae05d88fa44d502c
|
TypeScript
|
leo2707/learningEglish_APP
|
/learning-english/src/app/util/util.ts
| 2.890625
| 3
|
export class Util {
static getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
static generateRequestId(){
return new Date().getTime() + this.getRandomInt(1,100);
}
}
|
aae0c3a929faa0a17af7afcc58a3ca8c56e6dd5f
|
TypeScript
|
1ziton/pixelmon
|
/packages/theme/src/services/i18n/i18n.ts
| 2.546875
| 3
|
import { Injectable, InjectionToken } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { filter } from 'rxjs/operators';
export interface PixelmonI18NService {
[key: string]: any;
/**
* 调用 `use` 触发变更通知
*/
readonly change: Observable<string>;
/**
* 变更语言
* @param lang 语言代码
* @param emit 是否触发 `change`,默认:true
*/
use(lang: string, emit?: boolean): void;
/**
* 返回当前语言列表
*/
getLangs(): any[];
/**
* 翻译
* - `params` 模板所需要的参数对象
* - `isSafe` 是否返回安全字符,自动调用 `bypassSecurityTrustHtml`
*/
fanyi(key: string, params?: {}, isSafe?: boolean): string;
}
export const PIXELMON_I18N_TOKEN = new InjectionToken<PixelmonI18NService>('pixelmonTranslatorToken', {
providedIn: 'root',
factory: PIXELMON_I18N_TOKEN_FACTORY,
});
export function PIXELMON_I18N_TOKEN_FACTORY() {
return new PixelmonI18NServiceFake();
}
@Injectable({ providedIn: 'root' })
export class PixelmonI18NServiceFake implements PixelmonI18NService {
private change$ = new BehaviorSubject<string | null>(null);
get change(): Observable<string> {
return this.change$.asObservable().pipe(filter(w => w != null)) as Observable<string>;
}
use(lang: string): void {
this.change$.next(lang);
}
getLangs(): any[] {
return [];
}
fanyi(key: string) {
return key;
}
}
|
6171c548c1b01b54fc22d5034ce339de12ec1b7d
|
TypeScript
|
ofirgeller/cache-ms
|
/src/cache.controller.ts
| 2.609375
| 3
|
import { ForbiddenException, HttpCode, Query, Req } from '@nestjs/common';
import { Controller, Delete, Get, NotFoundException, Post } from '@nestjs/common';
import { FastifyRequest } from 'fastify'
import { LRU } from './LRU';
const isLoopbackAddr = require('is-loopback-addr');
@Controller()
export class CacheController {
static _cache = new LRU(3);
@Delete()
@HttpCode(204)
delete(@Query('key') key: string,) {
CacheController._cache.delete(key);
}
@Get('deleteAll')
@HttpCode(204)
deleteAll(@Req() request: FastifyRequest) {
if (!isLoopbackAddr(request.ip)) {
throw new ForbiddenException();
}
CacheController._cache = new LRU(3);
}
@Get()
get(@Query('key') key: string): string {
const hasValue = CacheController._cache.has(key);
if (!hasValue) {
throw new NotFoundException();
}
return CacheController._cache.get(key);
}
@Post()
set(
@Query('key') key: string,
@Query('value') value: string) {
CacheController._cache.set(key, value);
}
}
|
17dcc992d0ee01eb6e4a86266cfaacdf4d0237d6
|
TypeScript
|
RetroAstro/data-structures-and-algorithms
|
/src/data-structures/binary-tree/node.ts
| 2.75
| 3
|
export class Node<T> {
left: Node<T> = null
right: Node<T> = null
parent?: Parent<T>
constructor(public data: T) {}
}
export class Parent<T> {
constructor(public node: Node<T>, public path: string) {}
}
|
3e854a3c035121b44217985be58be22f4decb03d
|
TypeScript
|
dqube/simple-ui
|
/tools/release/version-name/publish-branches.ts
| 3.25
| 3
|
import { Version } from './parse-version';
export type VersionType = 'major' | 'minor' | 'patch';
/** 确定用于发布指定版本的允许分支名称 */
export function getAllowedPublishBranches(version: Version): string[] {
const versionType = getSemverVersionType(version);
if (versionType === 'major') {
return ['master'];
} else if (versionType === 'minor') {
// 看守者也可能希望从“master”分支以外的其他分支进行次要释放。
// 如果重大更改已合并到“master”中,而非重大更改被挑选到单独的分支中(例如7.x),则可能会发生这种情况
return ['master', `${version.major}.x`];
}
return [`${version.major}.${version.minor}.x`];
}
/** 确定指定的Semver版本的类型 */
export function getSemverVersionType(version: Version): VersionType {
if (version.minor === 0 && version.patch === 0) {
return 'major';
} else if (version.patch === 0) {
return 'minor';
} else {
return 'patch';
}
}
|
870a659e3e442195aa25c744a5070bbe356b3763
|
TypeScript
|
jinderSingh/decorators
|
/src/decorators/excel-column.decorator.ts
| 2.84375
| 3
|
import { CELL_VALUE_TRANSFORMER, COLUMN_NAMES, COLUMN_NUMBERS, EXCEL_METADATA, PROP } from '../constants/constants';
import { hasValue, isFunction } from '../util-methods';
import { ExcelColumnType } from './../models/excel-column.type';
/**
* Sets metadata to class type
* @param param0
* @param transformer
*/
export function excelColumn({
columnNumber,
header
}: ExcelColumnType, transformer ? : (v) => any) {
return function (target, key) {
const metadata = target[EXCEL_METADATA] || {};
const properties = {
writable: true,
enumerable: true,
configurable: true
}
throwErrorIfBothArePresent(columnNumber, header, target);
if (metadata[COLUMN_NAMES] === undefined) {
metadata[COLUMN_NAMES] = {};
}
if (columnNumber !== undefined && columnNumber !== null) {
if (metadata[COLUMN_NUMBERS] === undefined) {
metadata[COLUMN_NUMBERS] = {};
}
metadata[COLUMN_NUMBERS][key] = {
[PROP]: columnNumber,
[CELL_VALUE_TRANSFORMER]: transformer && isFunction(transformer) ? transformer : null
};
}
metadata[COLUMN_NAMES][key] = {
[PROP]: header || key,
[CELL_VALUE_TRANSFORMER]: transformer && isFunction(transformer) ? transformer : null
};
Object.defineProperty(target, EXCEL_METADATA, {
...properties,
value: metadata
});
};
}
/**
* throws exception, if both arguments values are present
* @param first
* @param second
*/
function throwErrorIfBothArePresent(first, second, type: any) {
const bothArePresent = hasValue(first) && hasValue(second);
if (bothArePresent) {
throw new Error(`Can't use both properties 'targetPropertyName' & 'columnNumber' at same time in ${type && type.constructor.name}.`);
}
}
|
740d38f5246fb0b2f7f9ecf5480f584508ec8a12
|
TypeScript
|
Spark-NF/novel-updates-notifier
|
/src/common/time.spec.ts
| 2.75
| 3
|
import { secondsToString } from "./time";
describe("secondsToString", () => {
it("Works with hours", () => {
expect(secondsToString(7 * 60 * 60 + 27 * 60 + 17, true)).toBe("7:27:17");
expect(secondsToString(27 * 60 + 17, true)).toBe("0:27:17");
expect(secondsToString(17, true)).toBe("0:00:17");
expect(secondsToString(0, true)).toBe("0:00:00");
});
it("Works with minutes", () => {
expect(secondsToString(27 * 60 + 17, false)).toBe("27:17");
expect(secondsToString(92, false)).toBe("1:32");
expect(secondsToString(60, false)).toBe("1:00");
expect(secondsToString(17, false)).toBe("0:17");
expect(secondsToString(0, false)).toBe("0:00");
});
it("Works with negative numbers", () => {
expect(secondsToString(-17, false)).toBe("-0:17");
});
});
|
071498f59f987d36657cd0249d7335bd537d8b20
|
TypeScript
|
Davitron/ays-server
|
/src/shared/interceptors/error.filter.ts
| 2.546875
| 3
|
import { Injectable, ExceptionFilter, Catch, ArgumentsHost, HttpException, HttpStatus } from '@nestjs/common';
import { Response } from './response.interceptor';
const handleValidationError = (error: any) => {
const response = error.map(err => {
const { property, constraints } = err;
return { property, constraints };
});
return response;
};
@Injectable()
@Catch()
export class ErrorFilter implements ExceptionFilter {
catch(exception: any, host: ArgumentsHost) {
console.log(exception);
const control = host.switchToHttp();
const response = control.getResponse();
const request = control.getRequest();
const { status: code } = exception;
let {message: { error: name, message }} = exception;
let data: Response<any>;
if (typeof message !== 'string') {
const validtionError = message;
message = 'Invalid Request';
data = handleValidationError(validtionError);
}
const payload = {
...(name && { name }),
...(code && { code }),
...((message) && { message } ),
...(data && { type: 'VALIDATION'}),
...(data && { data }),
};
response
.status(code)
.json({error: payload });
}
}
|
27f365a802afe29532e318af59341eccc3c26c1e
|
TypeScript
|
pjayneet97/1st-year-angular-project1
|
/src/app/testcomp/testcomp.component.ts
| 2.734375
| 3
|
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-testcomp',
templateUrl: './testcomp.component.html',
styleUrls: ['./testcomp.component.css']
})
export class TestcompComponent implements OnInit {
number1:number;
number2:number;
resultAvailable:boolean=false;
resultColor='red'
result:number=0;
operation;
constructor() {
this.printHello();
}
ngOnInit() {
console.log("hello form ngoninit")
}
printHello(){
console.log("function print hello called")
}
addNumbers(){
if(this.isInputValid()){
this.result=this.number1+this.number2;
this.operation="addition"
//this.resultAvailable=true;
this.resultColor='green'
setTimeout(()=>{
//this.resultAvailable=false;
this.resultColor='red'
this.result=undefined;
},5000)
this.resetNumbers()
}
else{
alert("please enter a valid number")
}
}
subtractNumbers(){
if(this.isInputValid()){
this.result=this.number1-this.number2;
this.operation="Subtraction"
this.resetNumbers()
}
else{
alert("please enter a valid number")
}
}
multiplyNumbers(){
if(this.isInputValid()){
this.result=this.number1*this.number2;
this.operation="multiplicatin"
this.resetNumbers()
}
else{
alert("please enter a valid number")
}
}
divideNumbers(){
if(this.isInputValid()){
this.result=this.number1/this.number2;
this.operation="division"
this.resetNumbers()
}
else{
alert("please enter a valid number")
}
}
isInputValid(){
if(this.number1 && this.number2){
console.log("valid numbers")
return true
}
else{
console.log("invalid input")
return false
}
}
resetNumbers(){
this.number1=undefined;
this.number2=null;
}
showAlert(){
alert("hello");
}
getColor(){
if(this.result){
return "green";
}
else{
return "red"
}
}
isGreen(){
if(this.result){
return true
}
else{
return false
}
}
}
|
96a35b09edb7d3a655f67b3f1a8bba97e7fe2bdb
|
TypeScript
|
s-skubedin/react-picture-annotation
|
/src/annotation/CreatingAnnotationState.ts
| 2.53125
| 3
|
import { ReactPictureAnnotation } from "../index";
import { IAnnotationState } from "./AnnotationState";
import { DefaultAnnotationState } from "./DefaultAnnotationState";
import Transformer from "../Transformer";
export default class CreatingAnnotationState implements IAnnotationState {
private readonly context: ReactPictureAnnotation;
constructor(context: ReactPictureAnnotation) {
this.context = context;
}
public onMouseDown = () => undefined;
public onMouseMove = (positionX: number, positionY: number) => {
const { shapes, selectedId } = this.context;
if (shapes.length > 0 && (!selectedId || selectedId === -1)) {
const currentShape = shapes[shapes.length - 1];
const {
mark: { x, y },
} = currentShape.getAnnotationData();
currentShape.adjustMark({
width: positionX - x,
height: positionY - y,
});
}
};
public onMouseUp = () => {
const { shapes, onShapeChange, setAnnotationState } = this.context;
const data = shapes.pop();
this.context.selectedId = null;
const annotationData = data && data.getAnnotationData();
if (
data &&
annotationData &&
annotationData.mark.width !== 0 &&
annotationData.mark.height !== 0
) {
const [width, height] = this.context.props.defaultAnnotationSize;
if (
Math.abs(annotationData.mark.width) >= width &&
Math.abs(annotationData.mark.height) >= height
) {
if (typeof annotationData.id !== "number") {
this.context.selectedId = annotationData.id;
}
this.context.currentTransformer = new Transformer(
data,
this.context.scaleState.scale
);
shapes.push(data);
}
}
onShapeChange();
setAnnotationState(new DefaultAnnotationState(this.context));
};
public onMouseLeave = () => {
if (!this.context.selectedId || this.context.selectedId === -1) {
this.onMouseUp();
}
};
}
|
c373f5995ba46cb06bf98578a5f790314d7f10bc
|
TypeScript
|
blsnwbrdr/traveltracker-ng-app
|
/src/app/list/list.component.ts
| 2.734375
| 3
|
import { Component, OnInit } from '@angular/core';
// INTERFACES
import { ICountry } from '../interfaces/country.model';
// SERVICES
import { CountriesService } from '../services/countries.service';
import { LocalStorageService } from '../services/local-storage.service';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.scss'],
})
export class ListComponent implements OnInit {
errorMessage!: string;
selectedCountries!: Array<string>;
countries!: ICountry[];
constructor(
private countriesService: CountriesService,
private localStorageService: LocalStorageService
) {}
ngOnInit(): void {
// if there is local storage data, update selectedCountries array with data
if (this.localStorageService.get('Visited') !== null) {
this.selectedCountries = this.localStorageService.get('Visited');
}
// import countries json data
this.countriesService.getCountries().subscribe({
next: (data: ICountry[]) => {
// sort countries alphabetically by name
data.sort((a, b) => {
if (a.name < b.name) return -1;
if (a.name > b.name) return 1;
return 0;
});
// add 'checked' property for selectedCountries from local storage
for (const countriesKey of data) {
for (const selectedCountriesKey of this.selectedCountries) {
if (countriesKey.name === selectedCountriesKey) {
countriesKey['checked'] = true;
}
}
}
this.countries = data;
},
error: (err) => (this.errorMessage = err),
});
}
// ON CHANGE CHECKBOX METHOD
onChange(name: string, isChecked: boolean) {
// update selected countries data to local storage
if (isChecked) {
this.selectedCountries.push(name);
this.saveData('Visited', this.selectedCountries);
} else {
const index = this.selectedCountries.indexOf(name);
this.selectedCountries.splice(index, 1);
this.saveData('Visited', this.selectedCountries);
}
}
// SAVE DATA TO LOCAL STORAGE METHOD
saveData(key: string, value: Array<string>) {
this.localStorageService.set(key, value);
}
}
|
54d0b3154add0530b2dd1c164dd08068f1d9172a
|
TypeScript
|
G3F4/moxy-proxy
|
/src/common/hooks/useLocalstorage.ts
| 3
| 3
|
import { useCallback, useState } from 'react';
export default function useLocalstorage<T>(key: string, initialValue: T) {
const [storedValue, setLocalValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.log(error);
return initialValue;
}
});
const setValue = useCallback(
(value: T) => {
try {
window.localStorage.setItem(key, JSON.stringify(value));
setLocalValue(value);
} catch (error) {
console.error(error);
}
},
[key],
);
return [storedValue, setValue];
}
|
c59eff5e0bb07f4049d3434fb4b1672d11eae856
|
TypeScript
|
vigneshpa/ffmpeg-wasm
|
/package/src/index.worker.ts
| 2.78125
| 3
|
//interfaces
interface Options {
distFolder: string;
tool: ("ffmpeg" | "ffprobe");
args: string[];
bufferSize: number;
getStdErrFile: boolean;
getStdOutFile: boolean;
}
interface EmscriptenModule {
FS: typeof FS;
IDBFS: Emscripten.FileSystemType;
WORKERFS: Emscripten.FileSystemType;
}
interface WorkerGlobalScope {
FFmpegFactory?: EmscriptenModuleFactory;
}
//Variables
let options: Options;
const files = [] as File[];
let isExecuting = false;
let mainScript: string;
//Functions static
const init = (optionsa: Options) => {
options = optionsa;
if (!self.FFmpegFactory) {
mainScript = `${options.distFolder}/bin/${options.tool}.js`;
importScripts(mainScript);
};
return;
}
const loadFile = (file: File) => {
files.push(file);
return;
};
const getFile = (name: string) => {
return files[0];
};
const execute = async () => {
if (!self.FFmpegFactory) return console.error("Please init before executing");
if (isExecuting) return console.error("Wasm is already executing");
isExecuting = true;
const stdout = createBuffer(!options.getStdOutFile, ({ buffer }, length) => postMessage({ std: "stdout", buffer, length }, [buffer]));
const stderr = createBuffer(!options.getStdErrFile, ({ buffer }, length) => postMessage({ std: "stderr", buffer, length }, [buffer]));
const Module = {
// Locating file
locateFile(path, prefix) {
return prefix + "bin/" + path;
},
mainScriptUrlOrBlob:mainScript,
// prerun
preRun: [() => {
Module.FS.init(null, stdout.writer, stderr.writer);
Module.FS.mkdir("/input");
Module.FS.mount(Module.WORKERFS, { files }, "/input");
Module.FS.mkdir("/output");
Module.FS.mount(Module.IDBFS, {}, "/output");
}],
// Passing arguments
arguments: options.args,
// Logging and events
logReadFiles: false,
// Print streams
print(print) {
postMessage({ stream: "stdOut", print });
},
printErr(print) {
postMessage({ stream: "stdErr", print });
},
// postrun
postRun: [
() => {
stdout.flush();
stderr.flush();
postMessage({ event: "postRun" });
console.log(Module);
}
],
onAbort() {
postMessage({ event: "abort" });
},
onRuntimeInitialized() {
postMessage({ event: "runtimeInitialized" });
},
} as Partial<EmscriptenModule> as EmscriptenModule;
await self.FFmpegFactory(Module);
isExecuting = false;
return;
}
//Adding event listener after initilising static functions
addEventListener("message", async ev => {
if (ev.data.req) {
const reqId = ev.data.reqId;
if (ev.data.req.init) return postMessage({ reqId, reqData: init(ev.data.req.init) });
if (ev.data.req.execute) return postMessage({ reqId, reqData: await execute() });
if (ev.data.req.loadFile) return postMessage({ reqId, reqData: loadFile(ev.data.req.loadFile) });
if (ev.data.req.getFile) return postMessage({ reqId, reqData: getFile(ev.data.req.getFile) });
console.error("Unknown request recived", ev.data);
}
})
// Hoisted Util functions
function createBuffer(isNull: boolean, flush: (bfr: Uint8Array, length: number) => void) {
if (isNull) return { writer: null, flush: () => null };
const buffer = new Uint8Array(options.bufferSize);
let pointer = 0;
const writer = (num: number | null) => {
if (num !== null) {
buffer[pointer] = num
pointer += 1;
}
if (num === null || pointer == (options.bufferSize - 1)) {
flush(buffer, pointer + 1);
pointer = 0;
};
};
return { writer, flush: () => flush(buffer, pointer + 1) };
}
|
35afa9332bd06f846617f883ec5a0f4b6793bc8b
|
TypeScript
|
teyrana/annum
|
/src/storage_type.ts
| 3.25
| 3
|
export class StorageType {
readonly name: string;
private readonly _code: number;
private static lookup = new Map<number,StorageType>();
constructor(n:string, id:string){
this.name = n;
this._code = id.charCodeAt(0);
StorageType.lookup.set( this._code, this);
}
static readonly ABSTRACT = new StorageType('ABSTRACT', 'a'); // used for items which have no storage limit: money, prestige, or experience
static readonly BULK = new StorageType('BULK', 'b'); // for solid resources in continuous, indeterminate quantities -- sand or coal
static readonly DISCRETE = new StorageType('DISCRETE', 'd'); // for resources in discrete sizes: i.e. a sheep, a missile
static readonly GAS = new StorageType('GAS', 'g');
static readonly LIQUID = new StorageType('LIQUID', 'l');
static readonly NONE = new StorageType('NONE', 'n'); // cannot be stored:
static readonly PERSONNEL =new StorageType('PERSONNEL','p'); // people (i.e. seats)
static readonly POWER = new StorageType('POWER', 'e'); // for storage of electricity:
get code(): string {
return String.fromCharCode(this._code);
}
static parse( text: string ): StorageType {
const code = text.charCodeAt(0);
if( StorageType.lookup.has(code) ){
return StorageType.lookup.get( code );
}
return StorageType.DISCRETE;
}
}
export default StorageType;
|
6fd1de43a07dcda0ff44fab829d2d67b34b110af
|
TypeScript
|
SOUNDBOKS/react-native-interactable
|
/lib/src/PhysicsAnchorBehavior.ts
| 2.78125
| 3
|
import { PhysicsBehavior } from "./PhysicsBehavior";
import { IPoint, ITarget } from "./types";
import { PhysicsObject } from "./PhysicsObject";
export class PhysicsAnchorBehavior extends PhysicsBehavior {
initWithTarget(target: ITarget, anchorPoint: IPoint) {
super.initWithTarget(target, anchorPoint);
this.priority = 3;
}
executeFrameWithDeltaTime(deltaTime: number, object: PhysicsObject) {
if (deltaTime == 0.0) {
return;
}
const dx = this.anchorPoint.x - this.target.center.x;
const vx = dx / deltaTime;
const dy = this.anchorPoint.y - this.target.center.y;
const vy = dy / deltaTime;
object.velocity = { x: vx, y: vy };
}
}
|
59831f3add968989075928ce5a8ee9057d99d883
|
TypeScript
|
SergeyKirintsev/JavaScript-Total
|
/assets/patterns/typescript/creational/prototype.ts
| 3.8125
| 4
|
/**
* Пример класса, имеющего возможность клонирования. Мы посмотрим как происходит
* клонирование значений полей разных типов.
*/
class Prototype {
public primitive: any
public component: object
public circularReference: ComponentWithBackReference
public clone(): this {
const clone = Object.create(this)
clone.component = Object.create(this.component)
// Клонирование объекта, который имеет вложенный объект с обратной
// ссылкой, требует специального подхода. После завершения клонирования
// вложенный объект должен указывать на клонированный объект, а не на
// исходный объект. Для данного случая хорошо подойдёт оператор
// расширения (spread).
clone.circularReference = {
...this.circularReference,
prototype: { ...this }
}
return clone
}
}
class ComponentWithBackReference {
public prototype
constructor(prototype: Prototype) {
this.prototype = prototype
}
}
/**
* Клиентский код.
*/
function clientCode() {
const p1 = new Prototype()
p1.primitive = 245
p1.component = new Date()
p1.circularReference = new ComponentWithBackReference(p1)
const p2 = p1.clone()
if (p1.primitive === p2.primitive) {
console.log(
'Primitive field values have been carried over to a clone. Yay!'
)
} else {
console.log('Primitive field values have not been copied. Booo!')
}
if (p1.component === p2.component) {
console.log('Simple component has not been cloned. Booo!')
} else {
console.log('Simple component has been cloned. Yay!')
}
if (p1.circularReference === p2.circularReference) {
console.log('Component with back reference has not been cloned. Booo!')
} else {
console.log('Component with back reference has been cloned. Yay!')
}
if (p1.circularReference.prototype === p2.circularReference.prototype) {
console.log(
'Component with back reference is linked to original object. Booo!'
)
} else {
console.log('Component with back reference is linked to the clone. Yay!')
}
}
clientCode()
/**
*
* Output
*
* Primitive field values have been carried over to a clone. Yay!
* Simple component has been cloned. Yay!
* Component with back reference has been cloned. Yay!
* Component with back reference is linked to the clone. Yay!
*
*/
|
6a05b248fce1856c5543a5a8e512166f2ec9a409
|
TypeScript
|
buurperezoso/bingo
|
/src/utils/index.ts
| 2.875
| 3
|
import { CardElement } from "../interfaces/Cards";
export const removeItemFromArray = (cardsArray: CardElement[], index: number) => {
if (index > -1) {
cardsArray.splice(index, 1);
}
return cardsArray;
};
export const findElementInArray = (indexValue: number, array: number[]) => {
return array.includes(indexValue);
}
|
da3b33017017f06d51b12410b208c13cdc66620c
|
TypeScript
|
LukasMirbt/learning-system
|
/src/Media/getSearchableSections.ts
| 2.65625
| 3
|
import { SearchableSection, Section } from "./Media";
const getSearchableSections = (sections: Section[], title: string) => {
const searchableSections: SearchableSection[] = [];
sections.forEach(({ sectionName, startTime, endTime, chapters }) => {
searchableSections.push({
text: sectionName,
startTime,
endTime,
videoTitle: title,
isCue: false,
});
chapters.forEach(
({
chapterName,
startTime: startTime2,
endTime: endTime2,
paragraphs,
}) => {
searchableSections.push({
text: chapterName,
startTime: startTime2,
endTime: endTime2,
videoTitle: title,
isCue: false,
});
paragraphs.forEach(([name, sTime, eTime]) => {
searchableSections.push({
text: name,
startTime: sTime,
endTime: eTime,
videoTitle: title,
isCue: false,
});
});
}
);
});
return searchableSections;
};
export default getSearchableSections;
|
1729115dcda5117d56ef965e7509a9c6479847c8
|
TypeScript
|
SiddAjmera/Instagram
|
/src/app/models/gender.enum.ts
| 2.578125
| 3
|
export enum Gender {
Male = 'Male',
Female = 'Female',
NotSpecified = 'Not Specified'
}
|
5e5bbf51ba314706f749c6314b6c75f421748d38
|
TypeScript
|
nghiepdev/prevent-orientation
|
/index.ts
| 2.6875
| 3
|
export class PreventOrientation {
private text: string;
private color: string;
private background: string;
private fontSize: string;
private angle: string | number = 0;
private readonly className: string = 'wrapper-prevent-orientation';
constructor({
text = 'Sorry, this device orientation is not supported',
color = 'rgb(90, 90, 90)',
background = 'linear-gradient(to right, rgb(255, 175, 189), rgb(255, 195, 160))',
fontSize = '1.2rem',
} = {}) {
this.text = text;
this.color = color;
this.background = background;
this.fontSize = fontSize;
}
protected get currentAngle() {
try {
return screen.orientation.angle;
} catch (e) {
return window.orientation;
}
}
protected get supportsOrientationChange() {
return 'onorientationchange' in window ? 'orientationchange' : 'resize';
}
protected handlePrevent = () => {
const container = document.createElement('div');
const text = document.createElement('p');
container.className = this.className;
if (this.angle === this.currentAngle) {
Object.assign(container.style, {
position: 'fixed',
width: '100%',
height: '100%',
left: 0,
top: 0,
zIndex: 99999998,
color: this.color,
background: this.background,
});
Object.assign(text.style, {
position: 'absolute',
width: '100%',
textAlign: 'center',
top: '50%',
fontSize: this.fontSize,
transform: 'translateY(-50%)',
padding: '0 5px',
});
text.innerText = this.text;
container.appendChild(text);
document.body.appendChild(container);
} else {
try {
Array.prototype.forEach.call(
document.querySelectorAll('.' + this.className),
node => {
node.parentNode.removeChild(node);
}
);
} catch (e) {}
}
};
preventOrientationToAngle = (angle: string | number) => {
this.angle = angle;
this.handlePrevent();
window.addEventListener(this.supportsOrientationChange, this.handlePrevent);
};
preventPortrait = () => this.preventOrientationToAngle(0);
preventLandscape = () => this.preventOrientationToAngle(90);
}
if (typeof window !== 'undefined') {
window.PreventOrientation = PreventOrientation;
}
declare global {
interface Window {
PreventOrientation: typeof PreventOrientation;
}
}
|
8fd179c3fd503d54059966c35f9b7ccb8597efde
|
TypeScript
|
jamilur-r/skill-mask
|
/apps/api/src/controller/Category.ts
| 2.59375
| 3
|
import { Request, RequestHandler, Response } from 'express';
import Category from '../model/Category';
import * as fs from 'fs';
import * as path from 'path';
export const getAllCategories: RequestHandler = async (_, res: Response) => {
try {
const data = await Category.find();
return res.status(200).json(data);
} catch (error) {
return res.status(400).json({ msg: 'Not found any' });
}
};
export const getCategoryById: RequestHandler = async (
req: Request,
res: Response
) => {
try {
const id = req.params;
const data = await Category.findOne({ _id: id });
return res.status(200).json(data);
} catch (error) {
return res.status(400).json({ msg: 'Not found any' });
}
};
export const createCategory: RequestHandler = async (
req: Request,
res: Response
) => {
try {
const { name, description } = req.body;
const image_url = '/media/' + req.file?.filename;
const category = new Category({
name: name,
description: description,
image_url: image_url,
});
await category.save();
return res.status(200).json(category);
} catch (error) {
console.log(error);
return res.status(400).json({ msg: 'Failed to create' });
}
};
export const updateCategory: RequestHandler = async (
req: Request,
res: Response
) => {
try {
const { id, name, description } = req.body;
if (req.file) {
const image_url = '/media/' + req.file?.filename;
const category = await Category.findOneAndUpdate(
{ _id: id },
{ name: name, description: description, image_url: image_url }
);
return res.status(200).json(category);
} else {
const category = await Category.findOneAndUpdate(
{ _id: id },
{ name: name, description: description }
);
return res.status(200).json(category);
}
} catch (error) {
return res.status(400).json({ msg: 'Failed to update' });
}
};
export const deleteCategory: RequestHandler = async (
req: Request,
res: Response
) => {
try {
const { id, } = req.body;
const category = await Category.findOne({ _id: id });
await category.deleteOne();
// const loc = path.join(__dirname, image_url);
// fs.unlinkSync(loc);
return res.status(200).json({ msg: 'Category deleted' });
} catch (error) {
console.log(error);
return res.status(400).json({ msg: 'Failed to delete' });
}
};
export const getCategoryCount: RequestHandler = async (
req: Request,
res: Response
) => {
try {
const count = await Category.count();
return res.status(200).json({ count });
} catch (error) {
return res.status(400).json({ msg: 'Failed to get count' });
}
};
|
1e4d8d959ad40145ecb7de6ad463fe0a64c45f72
|
TypeScript
|
mariatrojo/MEAN-TypeScript-Bikes-OOP
|
/tsBikesOOP.ts
| 3.765625
| 4
|
class Bike {
miles: number = 0;
allInfo: string;
constructor(
public price: number,
public max_speed: string) { }
//ISSUE: arrow is needed since this function is called by another function.
ride = () => {
for (var i = 0; i < 10; i++) {
this.miles++;
}
console.log('Riding');
return this;
}
reverse = () => {
for (var i = 0; i < 5; i++) {
this.miles--;
}
console.log('Reversing');
return this;
}
displayInfo = () => {
console.log('Price: ' + this.price + ', Max speed: ' + this.max_speed, ' Miles: ' + this.miles);
}
}
const bike1 = new Bike(10, "140");
bike1.ride().ride().ride().reverse();
bike1.displayInfo();
|
6839dabd7a7e7b0135870a1bff600dbef40c8ab5
|
TypeScript
|
ziponia/oauth2orize-examples
|
/src/routes/oauth2.ts
| 2.609375
| 3
|
"use strict";
import oauth2orize from "@poziworld/oauth2orize";
import passport from "passport";
import login from "connect-ensure-login";
import db from "../db";
import * as utils from "../utils";
// Create OAuth 2.0 server
const server = oauth2orize.createServer();
// Register serialization and deserialization functions.
//
// When a client redirects a user to user authorization endpoint, an
// authorization transaction is initiated. To complete the transaction, the
// user must authenticate and approve the authorization request. Because this
// may involve multiple HTTP request/response exchanges, the transaction is
// stored in the session.
//
// An application must supply serialization functions, which determine how the
// client object is serialized into the session. Typically this will be a
// simple matter of serializing the client's ID, and deserializing by finding
// the client by ID from the database.
server.serializeClient((client, done) => done(null, client.id));
server.deserializeClient((id, done) => {
db.clients.findById(id, (error, client) => {
if (error) return done(error);
return done(null, client);
});
});
function issueTokens(userId, clientId, done) {
db.users.findById(userId, (error, user) => {
const accessToken = utils.getUid(256);
const refreshToken = utils.getUid(256);
db.accessTokens.save(accessToken, userId, clientId, (error) => {
if (error) return done(error);
db.refreshTokens.save(refreshToken, userId, clientId, (error) => {
if (error) return done(error);
// Add custom params, e.g. the username
const params = { username: user.name };
return done(null, accessToken, refreshToken, params);
});
});
});
}
// Register supported grant types.
//
// OAuth 2.0 specifies a framework that allows users to grant client
// applications limited access to their protected resources. It does this
// through a process of the user granting access, and the client exchanging
// the grant for an access token.
// Grant authorization codes. The callback takes the `client` requesting
// authorization, the `redirectUri` (which is used as a verifier in the
// subsequent exchange), the authenticated `user` granting access, and
// their response, which contains approved scope, duration, etc. as parsed by
// the application. The application issues a code, which is bound to these
// values, and will be exchanged for an access token.
server.grant(
oauth2orize.grant.code((client, redirectUri, user, ares, done) => {
const code = utils.getUid(16);
db.authorizationCodes.save(code, client.id, redirectUri, user.id, user.username, (error) => {
if (error) return done(error);
return done(null, code);
});
})
);
// Grant implicit authorization. The callback takes the `client` requesting
// authorization, the authenticated `user` granting access, and
// their response, which contains approved scope, duration, etc. as parsed by
// the application. The application issues a token, which is bound to these
// values.
server.grant(
oauth2orize.grant.token((client, user, ares, done) => {
issueTokens(user.id, client.clientId, done);
})
);
// Exchange authorization codes for access tokens. The callback accepts the
// `client`, which is exchanging `code` and any `redirectUri` from the
// authorization request for verification. If these values are validated, the
// application issues an access token on behalf of the user who authorized the
// code. The issued access token response can include a refresh token and
// custom parameters by adding these to the `done()` call
server.exchange(
oauth2orize.exchange.code((client, code, redirectUri, done) => {
db.authorizationCodes.find(code, (error, authCode) => {
if (error) return done(error);
if (client.id !== authCode.clientId) return done(null, false);
if (redirectUri !== authCode.redirectUri) return done(null, false);
issueTokens(authCode.userId, client.clientId, done);
});
})
);
// Exchange user id and password for access tokens. The callback accepts the
// `client`, which is exchanging the user's name and password from the
// authorization request for verification. If these values are validated, the
// application issues an access token on behalf of the user who authorized the code.
server.exchange(
oauth2orize.exchange.password((client, username, password, scope, done) => {
// Validate the client
db.clients.findByClientId(client.clientId, (error, localClient) => {
if (error) return done(error);
if (!localClient) return done(null, false);
if (localClient.clientSecret !== client.clientSecret) return done(null, false);
// Validate the user
db.users.findByUsername(username, (error, user) => {
if (error) return done(error);
if (!user) return done(null, false);
if (password !== user.password) return done(null, false);
// Everything validated, return the token
issueTokens(user.id, client.clientId, done);
});
});
})
);
// Exchange the client id and password/secret for an access token. The callback accepts the
// `client`, which is exchanging the client's id and password/secret from the
// authorization request for verification. If these values are validated, the
// application issues an access token on behalf of the client who authorized the code.
server.exchange(
oauth2orize.exchange.clientCredentials((client, scope, done) => {
// Validate the client
db.clients.findByClientId(client.clientId, (error, localClient) => {
if (error) return done(error);
if (!localClient) return done(null, false);
if (localClient.clientSecret !== client.clientSecret) return done(null, false);
// Everything validated, return the token
// Pass in a null for user id since there is no user with this grant type
issueTokens(null, client.clientId, done);
});
})
);
// issue new tokens and remove the old ones
server.exchange(
oauth2orize.exchange.refreshToken((client, refreshToken, scope, done) => {
db.refreshTokens.find(refreshToken, (error, token) => {
if (error) return done(error);
issueTokens(token.id, client.id, (err, accessToken, refreshToken) => {
if (err) {
done(err, null, null);
}
db.accessTokens.removeByUserIdAndClientId(token.userId, token.clientId, (err) => {
if (err) {
done(err, null, null);
}
db.refreshTokens.removeByUserIdAndClientId(token.userId, token.clientId, (err) => {
if (err) {
done(err, null, null);
}
done(null, accessToken, refreshToken);
});
});
});
});
})
);
// User authorization endpoint.
//
// `authorization` middleware accepts a `validate` callback which is
// responsible for validating the client making the authorization request. In
// doing so, is recommended that the `redirectUri` be checked against a
// registered value, although security requirements may vary across
// implementations. Once validated, the `done` callback must be invoked with
// a `client` instance, as well as the `redirectUri` to which the user will be
// redirected after an authorization decision is obtained.
//
// This middleware simply initializes a new authorization transaction. It is
// the application's responsibility to authenticate the user and render a dialog
// to obtain their approval (displaying details about the client requesting
// authorization). We accomplish that here by routing through `ensureLoggedIn()`
// first, and rendering the `dialog` view.
const authorization = [
login.ensureLoggedIn(),
server.authorization(
(clientId, redirectUri, done) => {
db.clients.findByClientId(clientId, (error, client) => {
if (error) return done(error);
// WARNING: For security purposes, it is highly advisable to check that
// redirectUri provided by the client matches one registered with
// the server. For simplicity, this example does not. You have
// been warned.
return done(null, client, redirectUri);
});
},
(client, user, done) => {
// Check if grant request qualifies for immediate approval
// Auto-approve
if (client.isTrusted) return done(null, true);
db.accessTokens.findByUserIdAndClientId(user.id, client.clientId, (error, token) => {
// Auto-approve
if (token) return done(null, true);
// Otherwise ask user
return done(null, false);
});
}
),
(request, response) => {
response.render("dialog", {
transactionId: request.oauth2.transactionID,
user: request.user,
client: request.oauth2.client,
});
},
];
// User decision endpoint.
//
// `decision` middleware processes a user's decision to allow or deny access
// requested by a client application. Based on the grant type requested by the
// client, the above grant middleware configured above will be invoked to send
// a response.
const decision = [login.ensureLoggedIn(), server.decision()];
// Token endpoint.
//
// `token` middleware handles client requests to exchange authorization grants
// for access tokens. Based on the grant type being exchanged, the above
// exchange middleware will be invoked to handle the request. Clients must
// authenticate when making requests to this endpoint.
const token = [
passport.authenticate(["basic", "oauth2-client-password"], { session: false }),
server.token(),
server.errorHandler(),
];
export default {
decision,
token,
authorization,
};
|
aff5292129b74e7cdb6436ff8e9ced79b3f67996
|
TypeScript
|
suraj-dev/PayrollManager-
|
/SB-Admin-BS4-Angular-5-master/src/app/layout/list-of-employees/list-of-employees.component.ts
| 2.515625
| 3
|
import { Component, OnInit } from '@angular/core';
import {NgbModal, NgbModalRef} from '@ng-bootstrap/ng-bootstrap';
import {EmployeeService} from "../../services/employee.service";
import {IEmployee} from "../../interfaces/IEmployee";
/**
* This component serves data to the list of employees view and interacts with the employee service
* to retrieve employee information and delete employees.
*/
@Component({
selector: 'app-dashboard',
templateUrl: './list-of-employees.component.html',
styleUrls: ['./list-of-employees.component.scss'],
})
export class ListOfEmployeesComponent implements OnInit {
employeeList: Array<IEmployee>;
selectedEmployee: IEmployee;
selectedEmployeeIndex: number;
employeeModalReference: NgbModalRef;
deleteDialogModalReference: NgbModalRef;
constructor(private modalService: NgbModal, private employeeService: EmployeeService) {
}
/**
* This function fetches the list of employees and their information using the employee service
* on initialization of this component.
*/
ngOnInit() {
this.employeeService.getEmployees().subscribe(result => {
this.employeeList = JSON.parse(result["_body"]);
console.log(this.employeeList);
}, error => {
console.log("Could not retrieve employees: " + error);
})
}
/**
* This function accepts the name of the modal to be triggered, opens the modal and sets the selected employee using
* the index.
* @param content - string containing the name of the modal
* @param index - number containing the index of the employee object inside the array
*/
open(content: string, index: number) {
this.selectedEmployeeIndex = index;
this.employeeModalReference= this.modalService.open(content);
this.selectedEmployee = this.employeeList[index];
}
/**
* This function deletes the employee from the list of employees using the employeeId and the
* employee service
*/
deleteEmployee() {
let employeeId = this.employeeList[this.selectedEmployeeIndex].empSalary.EmployeeId;
this.employeeService.deleteEmployee(employeeId).subscribe(result => {
this.employeeList.splice(this.selectedEmployeeIndex, 1);
this.deleteDialogModalReference.close();
this.employeeModalReference.close();
console.log("Employee deleted successfully");
}, error => {
console.log("Failed to delete employee");
})
}
/**
* This function accepts the name of the modal and triggers it.
* @param content - string containing the name of the modal to be opened
*/
openDeleteDialog(content) {
this.deleteDialogModalReference = this.modalService.open(content);
}
}
|
5c70ccd2859ec5e05c3bf3a0064ab3bb76970d21
|
TypeScript
|
future4code/Noh-Ah-Jeong
|
/semana19/labook/src/data/userDatabase.ts
| 2.515625
| 3
|
import { User } from "../business/entities/user"
import { connection } from "./connection"
const usersTableName = "labook_users"
export const insertUser = async (user: User) => {
await connection.raw(`
INSERT INTO ${usersTableName} (id, name, email, password)
VALUES ("${user.id}", "${user.name}", "${user.email}", "${user.password}");
`)
}
export const selectUserByEmail = async (email: string) => {
const result = await connection.raw(`
SELECT * FROM ${usersTableName}
WHERE email = "${email}";
`)
return result[0]
}
|
10a2d51019b50261490c5e64536857c9410fc301
|
TypeScript
|
Hendrik6/Nasa-Deno
|
/models/planets.test.ts
| 2.609375
| 3
|
//Deno Includes
import {
assertEquals,
assertNotEquals,
} from "../test_deps.ts";
import * as log from "https://deno.land/std/log/mod.ts";
import { filtersHabitablePlanets } from "./planets.ts";
//Test runner in the CLI
//Built in text fixtures with Deno.test().
//Assertion statements
const HABITABLE_PLANET = {
koi_disposition: "CONFIRMED",
koi_prad: "1",
koi_srad: "1",
koi_smass: "1",
};
const NOT_CONFIRMED = {
koi_disposition: "FALSE POSITIVE",
};
const TOO_LARGE_PLANETARY_RADIUS = {
koi_disposition: "CONFIRMED",
koi_prad: "1.5",
koi_srad: "1",
koi_smass: "1",
};
const TOO_LARGE_SOLAR_RADIUS = {
koi_disposition: "CONFIRMED",
koi_prad: "1",
koi_srad: "1.01",
koi_smass: "1",
};
const TOO_LARGE_SOLAR_MASS = {
koi_disposition: "CONFIRMED",
koi_prad: "1",
koi_srad: "1",
koi_smass: "1.04",
};
Deno.test("filter only habitable planets", () => {
const filtered = filtersHabitablePlanets([
HABITABLE_PLANET,
NOT_CONFIRMED,
TOO_LARGE_PLANETARY_RADIUS,
TOO_LARGE_SOLAR_RADIUS,
TOO_LARGE_SOLAR_MASS,
]);
assertEquals(filtered, [
HABITABLE_PLANET,
]);
});
//Random testing, showing what Deno can do =>
//Shorter and better
Deno.test("short example test", () => {
assertEquals("deno", "deno");
assertNotEquals({
runtime: "deno",
}, {
runtime: "node",
});
});
//Too verbose
Deno.test({
name: "example test",
//Ignore if os is windows
ignore: Deno.build.os === "windows",
fn() {
assertEquals("deno", "deno");
assertNotEquals({
runtime: "deno",
}, {
runtime: "node",
});
},
});
Deno.test({
//Test case is leaking async ops.
name: "ops",
sanitizeOps: false,
fn() {
setTimeout(log.info, 10);
},
});
Deno.test({
name: "resource leak",
sanitizeResources: false,
//Make sure to close all open resource handles returned from Deno APIs before to prevent this -> AssertionError: Test case is leaking resources.
async fn() {
await Deno.open("./models/planets.ts");
},
});
|
c62fafc1fddc1f31a866f7e2f437e8c344d85c80
|
TypeScript
|
brady-miller/todo-api
|
/src/middlewares/auth.ts
| 2.609375
| 3
|
import { Response, NextFunction } from "express";
import { IUserRequest } from "../interfaces/IUserRequest";
import jwt from "jsonwebtoken";
import dotenv from "dotenv";
import { User } from "../models/user";
dotenv.config()
let {
JWT_SECRET
}: NodeJS.ProcessEnv = process.env;
if (!JWT_SECRET) throw new Error('Environment variables not found')
interface objID {
[_id: string]: string
}
export const auth = async function(req: IUserRequest, res: Response, next: NextFunction): Promise<void> {
try {
if (!JWT_SECRET) throw new Error('No secret provided')
const reqHeader: string | undefined = req.header('Authorization');
if (!reqHeader) throw new Error('User is not logged in');
const token: string = await reqHeader.replace('Bearer ', '');
const decoded: objID = await jwt.verify(token, JWT_SECRET) as objID
const user = await User.findOne({ _id: decoded._id, 'tokens.token': token})
if (!user) throw new Error('No user found')
req.token = token;
req.user = user;
next()
} catch(error) {
res.status(401).send({ error: 'User is not logged in' })
}
}
|
310724c7096bec6efc253f3c76f7cdbd5d2a2977
|
TypeScript
|
SuperVK/RLBotVK
|
/src/states/Orient.ts
| 2.65625
| 3
|
import BaseState from "./BaseState";
import Agent from '../Agent'
import { Vector3 } from "../utils/misc";
export default class Orient extends BaseState {
localTarget: Vector3;
target: Vector3;
hasJumped: Boolean;
constructor(agent: Agent, target: Vector3) {
super(agent, 'ORIENT')
this.target = target
this.hasJumped = false
}
run() {
if(this.agent.game.myCar.velocity.z >= 0) this.agent.controller.jump = true
if(!this.agent.game.myCar.hasWheelContact) {
this.hasJumped = true
this.localTarget = this.agent.getLocal(this.target)
this.agent.controller.yaw = this.localTarget.y/3000
} else if(this.hasJumped) {
this.finished = true;
}
}
}
|
34622804a9dea27dde6a997be5d4b2fd6e46df34
|
TypeScript
|
serhat2806/hrms-etiya
|
/src/app/features/candidate/candidate-sign/candidate-sign.component.ts
| 2.609375
| 3
|
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ToastrService } from 'ngx-toastr';
import { CandidateService } from 'src/app/services/candidate.service';
import { UserService } from 'src/app/services/user.service';
@Component({
selector: 'app-candidate-sign',
templateUrl: './candidate-sign.component.html',
styleUrls: ['./candidate-sign.component.css']
})
export class CandidateSignComponent implements OnInit {
checkNationalityId: boolean
checkEmail: boolean
password:string=""
verifyPassword:string=""
candidateSignForm: FormGroup
constructor(private formBuilder: FormBuilder,
private toastrService: ToastrService, private candidateService: CandidateService, private userService: UserService) { }
ngOnInit(): void {
this.createCandidateAddForm()
}
createCandidateAddForm() {
this.candidateSignForm = this.formBuilder.group({
firstName: ["", Validators.required],
lastName: ["", Validators.required],
email: ["", Validators.required],
password: ["", Validators.required],
verifyPassword:["",Validators.required],
nationalityId: ["", [Validators.required,Validators.maxLength(11),Validators.minLength(11)]],
birthYear: ["", Validators.required],
})
}
addCandidate() {
this.checkByNationalityId();
this.checkByEmail();
if (this.candidateSignForm.valid) {
if ( !this.checkEmail && !this.checkNationalityId && this.checkPassword() ) {
let candidateModel = Object.assign({}, this.candidateSignForm.value);
this.candidateService.add(candidateModel).subscribe((response) => {
console.log(candidateModel)
this.toastrService.success("Kaydınız yapıldı.", candidateModel.firstName)
})
}
}
}
checkByNationalityId(){
this.candidateService.getCandidatesByNationalityId(this.candidateSignForm.value["nationalityId"]).subscribe((data: any) => {
if (data.data == false) {
this.checkNationalityId = false
} else {
this.checkNationalityId = true
this.toastrService.error("bu natinality id kullanılıyor")
}
})
}
checkByEmail() {
this.userService.getByEmail(this.candidateSignForm.value["email"]).subscribe((data: any) => {
if (data.data == false) {
this.checkEmail = false
} else {
this.checkEmail = true
this.toastrService.error("bu e posta kullanılıyor")
}
})
}
checkPassword(){
if(this.password===this.verifyPassword){
return true;
}else{
this.toastrService.error("şifreler uyuşmuyor")
return false;
}
}
}
|
bfab8264307661f6e9fc6e3e386f8ff7697edb01
|
TypeScript
|
Bash360/premier-league-api
|
/src/models/user.ts
| 2.609375
| 3
|
import { Schema, model } from 'mongoose';
import Iuser from '../typings/user';
import uuid from 'uuid/v4';
import jwt from 'jsonwebtoken';
import bcrypt from 'bcrypt';
require('dotenv/config');
import uniqueValidate from 'mongoose-unique-validator';
let secret: string = `${process.env.SECRET}`;
import toLower from './to-lower';
let UserSchema = new Schema(
{
id: String,
firstName: { type: String, required: true, trim: true, set: toLower },
lastName: { type: String, required: true, trim: true, set: toLower },
email: {
type: String,
required: true,
unique: true,
trim: true,
lowercase: true,
},
password: { type: String, required: true, trim: true },
gender: {
type: String,
enum: ['male', 'female'],
required: true,
trim: true,
lowercase: true,
},
isAdmin: { type: Boolean, default: false },
},
{ timestamps: true, id: false },
);
UserSchema.pre('save', async function(this: any) {
if (this.isNew) {
this.id = uuid();
this.password = await bcrypt.hash(this.password, 10);
}
});
UserSchema.methods.generateToken = function(): string {
const token: string = jwt.sign(
{ isAdmin: this.isAdmin, id: this.id },
secret,
{ expiresIn: 1800 }, //expires after 30 minutes
);
return token;
};
UserSchema.plugin(uniqueValidate, {
message: 'Error, {VALUE} is already a registered account',
});
export default model<Iuser>('user', UserSchema);
|
99fcdfcb2dc8ee495bb4239fb4e03b98924b4540
|
TypeScript
|
frosit/odata-edm-generator
|
/tests/templates.spec.ts
| 2.5625
| 3
|
import { assert } from 'chai';
import mockFs from 'mock-fs';
import { join } from 'path';
import { v4 as uuid } from 'uuid';
import { Configuration } from '../src/cli/configuration';
import { ClassInfo, EdmInfo, EnumInfo, ComplexTypeInfo, PropertyInfo, ComplexTypeInfoSet } from '../src/cli/shared';
import { EdmTemplate, EndpointTemplate } from '../src/cli/templates';
import { standardEndpoints } from './data';
describe('templates', function () {
describe('EndpointTemplate', function () {
it('Renders correctly', function () {
try {
Configuration.createFromCLIArgs(['--quoteStyle', 'single']);
const actual = new EndpointTemplate().render(standardEndpoints);
assert.strictEqual(actual,
`/**
* This is a generated file. Please don't change this manually.
*/
export const enum Endpoints {
People = 'People',
Foos = 'Foos',
Bar = 'fizzbazz',
}`
);
} finally {
Configuration.dispose();
}
});
it('Respects the given template', function () {
try {
Configuration.createFromCLIArgs(['--quoteStyle', 'single']);
const template = 'export const enum Endpoints {<% for(const endpoint of it.endpoints) { %> <%= endpoint.name %> = "<%= endpoint.url %>",<% } %>}';
const actual = new EndpointTemplate(template).render(standardEndpoints);
assert.strictEqual(actual, 'export const enum Endpoints { People = "People", Foos = "Foos", Bar = "fizzbazz",}');
} finally {
Configuration.dispose();
}
});
});
describe('EdmTemplate', function () {
it('Renders correctly', function () {
try {
const basePath = join(process.cwd(), uuid());
mockFs({ [basePath]: {} }, { createCwd: true });
const config = Configuration.createFromCLIArgs(['--outputDir', basePath, '--endpoint', 'https://api.example.com']);
const base1 = new ClassInfo(
'BaseOne',
[
new PropertyInfo('name', 'string', false, false),
],
);
const interface1 = new ComplexTypeInfo(
'ComplexType1',
[
new PropertyInfo('prop11', 'number', false, false),
new PropertyInfo('prop12', 'string', false, false),
],
false,
null
);
const info = new EdmInfo(
'Awesome.Possum',
// [],
[
new ClassInfo(
'Foo',
[
new PropertyInfo('id', 'number', false, true),
new PropertyInfo('name', 'string', false, false),
new PropertyInfo('isActive', 'boolean', false, false),
new PropertyInfo('optional', 'string', true, false),
],
'foos'
),
new ClassInfo(
'Bar',
[
new PropertyInfo('id', 'number', false, true),
new PropertyInfo('boolProp', 'boolean', false, false),
new PropertyInfo('strProp', 'string', false, false),
new PropertyInfo('optionalProp', 'number', true, false),
],
),
base1,
new ClassInfo(
'Child',
[
new PropertyInfo('id', 'number', false, true),
new PropertyInfo('strProp', 'string', false, false),
new PropertyInfo('optionalProp', 'number', true, false),
],
'Children',
base1,
),
],
new ComplexTypeInfoSet(
interface1,
new ComplexTypeInfo(
'ComplexType2',
[
new PropertyInfo('prop21', 'number', false, false),
new PropertyInfo('prop22', 'string', false, false),
new PropertyInfo('prop23', 'boolean', false, false),
],
false,
null
),
new ComplexTypeInfo(
'ChildComplexType',
[
new PropertyInfo('prop31', 'number', false, false),
new PropertyInfo('prop32', 'string', false, false),
new PropertyInfo('prop33', 'boolean', false, false),
],
false,
interface1,
),
),
[
new EnumInfo(
'EnumOne',
['member11', 'member12']
),
new EnumInfo(
'EnumTwo',
['member21', 'member22']
),
],
config.endpoints[0],
);
const actual = new EdmTemplate().render(info);
assert.strictEqual(
actual,
`/**
* This is a generated file. Please don't change this manually.
*/
import {
Class,
odataEndpoint,
odataType,
odataTypeKey,
} from '@netatwork/odata-edm-generator';
import {
Endpoints,
} from '../../Endpoints';
@odataEndpoint(Endpoints.foos)
export class Foo {
public static create<TFoo extends Foo = Foo>(this: Class<TFoo>, raw: Partial<TFoo>): TFoo {
if (raw === undefined || raw === null || raw instanceof this) { return raw as TFoo; }
return new this(
raw.id,
raw.name,
raw.isActive,
raw.optional,
);
}
public constructor(
public id: number,
public name: string,
public isActive: boolean,
public optional?: string,
) { }
}
export class Bar {
public static create<TBar extends Bar = Bar>(this: Class<TBar>, raw: Partial<TBar>): TBar {
if (raw === undefined || raw === null || raw instanceof this) { return raw as TBar; }
return new this(
raw.id,
raw.boolProp,
raw.strProp,
raw.optionalProp,
);
}
public constructor(
public id: number,
public boolProp: boolean,
public strProp: string,
public optionalProp?: number,
) { }
}
export class BaseOne {
public static create<TBaseOne extends BaseOne = BaseOne>(this: Class<TBaseOne>, raw: Partial<TBaseOne>): TBaseOne {
if (raw === undefined || raw === null || raw instanceof this) { return raw as TBaseOne; }
return new this(
raw.name,
);
}
public constructor(
public name: string,
) { }
}
@odataEndpoint(Endpoints.Children)
// @ts-ignore needed to avoid this issue: https://github.com/microsoft/TypeScript/issues/4628
export class Child extends BaseOne {
public static create<TChild extends Child = Child>(this: Class<TChild>, raw: Partial<TChild>): TChild {
if (raw === undefined || raw === null || raw instanceof this) { return raw as TChild; }
return new this(
raw.id,
raw.name,
raw.strProp,
raw.optionalProp,
);
}
public constructor(
public id: number,
public name: string,
public strProp: string,
public optionalProp?: number,
) {
super(
name,
);
}
}
export enum $$ComplexType1Types {
ChildComplexType = 'ChildComplexType',
}
export class ComplexType1 {
protected static get derivedTypes(): typeof ComplexType1[] {
return [
ChildComplexType,
] as unknown as typeof ComplexType1[];
}
public static create(raw: Partial<ComplexType1>): ComplexType1 {
if (raw === undefined || raw === null || raw instanceof this) { return raw as ComplexType1; }
const edmType = raw[odataTypeKey];
const ctor = this.derivedTypes.find((f) => f.canHandle(edmType));
if (!ctor) {
return raw as ComplexType1;
}
return ctor.create(raw);
}
protected static canHandle(_odataType: string): boolean { return false; }
public readonly $$type: $$ComplexType1Types;
public constructor(
public prop11: number,
public prop12: string,
) { }
}
export interface ComplexType2 {
prop21: number;
prop22: string;
prop23: boolean;
}
@odataType('#Awesome.Possum.ChildComplexType', $$ComplexType1Types.ChildComplexType, '$$type')
export class ChildComplexType extends ComplexType1 {
public constructor(
public prop11: number,
public prop12: string,
public prop31: number,
public prop32: string,
public prop33: boolean,
) {
super(
prop11,
prop12,
);
}
public static create(raw: Partial<ChildComplexType>): ChildComplexType {
return new ChildComplexType(
raw.prop11,
raw.prop12,
raw.prop31,
raw.prop32,
raw.prop33,
);
}
}
export enum EnumOne {
member11 = 'member11',
member12 = 'member12',
}
export enum EnumTwo {
member21 = 'member21',
member22 = 'member22',
}
` );
} finally {
Configuration.dispose();
mockFs.restore();
}
});
});
});
|
921a59919a35732a3315d552eb71d1eeba4c8cc6
|
TypeScript
|
g-plane/TypeCake
|
/tests/compiler/snapshots/if-expression/else-if/output.ts
| 2.765625
| 3
|
type Check<T> = T extends string ? 'a string' : T extends number ? 'a number' : 'something else';
|
b950427700e254ec87b7f91ff001dc9512377c25
|
TypeScript
|
maertz/ngx-uploadx
|
/src/uploadx/lib/uploader.spec.ts
| 2.625
| 3
|
// noinspection ES6PreferShortImport
import { ErrorHandler } from './error-handler';
import { Uploader } from './uploader';
// tslint:disable: no-any
function getFile(): File {
return new File(['-'], 'filename.mp4', { type: 'video/mp4', lastModified: Date.now() });
}
const file = getFile();
const snip = { file, size: 1, name: 'filename.mp4' };
let code = 0;
function shouldReject(): boolean {
return code >= 400 || !code;
}
ErrorHandler.maxAttempts = 2;
export class MockUploader extends Uploader {
async getFileUrl(): Promise<string> {
this.responseStatus = code;
return shouldReject() ? Promise.reject() : Promise.resolve('');
}
async getOffset(): Promise<number> {
this.responseStatus = code;
return shouldReject() ? Promise.reject() : Promise.resolve(1);
}
async sendFileContent(): Promise<number> {
this.responseStatus = code;
return shouldReject() ? Promise.reject() : Promise.resolve(1);
}
}
describe('constructor()', () => {
it('should new()', () => {
const uploader = new MockUploader(file, {});
expect(uploader).toEqual(jasmine.objectContaining(snip));
});
});
describe('configure', () => {
let uploader: MockUploader;
beforeEach(() => {
uploader = new MockUploader(file, {});
});
it('should abort on pause', () => {
const abort = spyOn<any>(uploader, 'abort').and.callThrough();
const stateChange = spyOn<any>(uploader, 'stateChange').and.callThrough();
uploader.configure({ action: 'pause' });
expect(abort).toHaveBeenCalled();
expect(stateChange).toHaveBeenCalled();
});
it('should onCancel on cancel', () => {
const abort = spyOn<any>(uploader, 'abort').and.callThrough();
const onCancel = spyOn<any>(uploader, 'onCancel').and.callThrough();
const cleanup = spyOn<any>(uploader, 'cleanup').and.callThrough();
uploader.configure({ action: 'cancel' });
expect(abort).toHaveBeenCalled();
expect(cleanup).toHaveBeenCalled();
expect(onCancel).toHaveBeenCalled();
});
});
describe('chunkSize', () => {
let uploader: MockUploader;
it('should use adaptive chunkSize if not specified', async () => {
uploader = new MockUploader(getFile(), {});
(uploader as any).getChunk();
expect(uploader.chunkSize).toEqual(4096 * 256);
});
it('should set fixed chunkSize', async () => {
uploader = new MockUploader(file, { chunkSize: 4_194_304 });
(uploader as any).getChunk();
expect(uploader.chunkSize).toEqual(4_194_304);
});
it('should disable chunks', async () => {
uploader = new MockUploader(file, { chunkSize: 0 });
(uploader as any).getChunk();
expect(uploader.chunkSize).toEqual(1);
});
});
describe('upload()', () => {
let uploader: MockUploader;
beforeEach(() => {
uploader = new MockUploader(file, {});
(uploader as any).offset = undefined;
uploader.url = '';
});
it('should queue on 0', async () => {
code = 0;
await uploader.upload();
expect(uploader.status).toEqual('queue');
});
it('should error on 400', async () => {
code = 400;
await uploader.upload();
expect(uploader.status).toEqual('error');
});
it('should queue on 401', async () => {
code = 401;
const getToken = spyOn<any>(uploader, 'getToken').and.callThrough();
await uploader.upload();
expect(getToken).toHaveBeenCalled();
expect(uploader.status).toEqual('queue');
});
it('should queue on 500', async () => {
code = 500;
await uploader.upload();
expect(uploader.status).toEqual('queue');
});
it('should complete on 200', async () => {
code = 200;
const start = spyOn(uploader, 'start').and.callThrough();
const getOffset = spyOn(uploader, 'getOffset').and.callThrough();
const cleanup = spyOn<any>(uploader, 'cleanup').and.callThrough();
await uploader.upload();
expect(start).toHaveBeenCalledTimes(1);
expect(getOffset).toHaveBeenCalledTimes(1);
expect(cleanup).toHaveBeenCalled();
expect(uploader.status).toEqual('complete');
});
it('should complete on 201', async () => {
code = 201;
const start = spyOn(uploader, 'start').and.callThrough();
const cleanup = spyOn<any>(uploader, 'cleanup').and.callThrough();
await uploader.upload();
expect(start).toHaveBeenCalledTimes(1);
expect(cleanup).toHaveBeenCalled();
expect(uploader.status).toEqual('complete');
});
});
describe('start()', () => {
let uploader: MockUploader;
beforeEach(() => {
uploader = new MockUploader(file, {});
(uploader as any).offset = undefined;
uploader.status = 'uploading';
});
it('should error on 400', async () => {
code = 400;
const getOffset = spyOn(uploader, 'getOffset').and.callThrough();
await uploader.start();
expect(getOffset).toHaveBeenCalledTimes(1);
expect(uploader.status).toEqual('error');
});
it('should queue on 404', async () => {
code = 404;
const getOffset = spyOn(uploader, 'getOffset').and.callThrough();
await uploader.start();
expect(getOffset).toHaveBeenCalledTimes(1);
expect(uploader.status).toEqual('queue');
});
it('should retry on 0', async () => {
code = 0;
const getOffset = spyOn(uploader, 'getOffset').and.callThrough();
await uploader.start();
expect(getOffset).toHaveBeenCalledTimes(3);
expect(uploader.status).toEqual('error');
});
it('should retry on 500', async () => {
code = 500;
const getOffset = spyOn(uploader, 'getOffset').and.callThrough();
await uploader.start();
expect(getOffset).toHaveBeenCalledTimes(3);
expect(uploader.status).toEqual('error');
});
it('should complete on 200', async () => {
code = 200;
await uploader.start();
expect((uploader as any).offset).toEqual(1);
expect(uploader.status).toEqual('complete');
});
});
describe('prerequest', () => {
let uploader: MockUploader;
const injected = { headers: { Auth: 'token' } };
it('sync', async () => {
uploader = new MockUploader(file, { prerequest: req => ({ ...req, ...injected }) });
const _request = spyOn<any>(uploader, '_request').and.callThrough();
await uploader.request({ method: 'POST' });
expect(_request).toHaveBeenCalledWith({ method: 'POST', headers: { Auth: 'token' } });
});
it('async', async () => {
uploader = new MockUploader(file, {
prerequest: req => Promise.resolve({ ...req, ...injected })
});
const _request = spyOn<any>(uploader, '_request').and.callThrough();
await uploader.request({ method: 'POST' });
expect(_request).toHaveBeenCalledWith({ method: 'POST', headers: { Auth: 'token' } });
});
it('void', async () => {
uploader = new MockUploader(file, { prerequest: (() => {}) as any });
const _request = spyOn<any>(uploader, '_request').and.callThrough();
await uploader.request({ method: 'POST' });
expect(_request).toHaveBeenCalledWith({ method: 'POST' });
});
});
|
06c952effdbb953eff76922641754cf603954f48
|
TypeScript
|
gecosys/cso-client-typescript
|
/src/messages/ticket/ticket.ts
| 3.515625
| 4
|
export class Ticket {
ID: number;
Token: Uint8Array;
// ParseBytes converts bytes to Ticket
// ID: 2 bytes
// Token: next 32 bytes
public ParseBytes(buffer: Uint8Array) {
if (buffer.byteLength != 34) {
return null;
}
let temp = new Uint16Array(1);
temp[0] = (buffer[1] << 8) | buffer[0];
this.ID = temp[0];
this.Token = buffer.slice(2);
}
// BuildBytes returns bytes of Ticket
public BuildBytes(id: Uint16Array[0], token: Uint8Array) {
if (token.byteLength != 32) {
return null;
}
let buffer = new Uint8Array(34);
buffer[0] = id[0];
buffer[1] = id[0] >> 8;
for (let i = 0; i < 32; i++) {
buffer[i + 2] = token[i];
}
return buffer;
}
}
|
e053ecdf4d67ba1a44476a367f36d6414d8156b4
|
TypeScript
|
brendy/Incredibots-2-HTML5-Open-Source
|
/src/Actions/MultiOutlineAction.ts
| 2.59375
| 3
|
import { Action } from "../imports";
export class MultiOutlineAction extends Action
{
private outline:boolean;
private partsAffected:Array<any>;
constructor(parts:Array<any>, outlineVal:boolean)
{
super(parts[0]);
this.partsAffected = parts;
this.outline = outlineVal;
}
public UndoAction():void {
for (var i:number = 0; i < this.partsAffected.length; i++) {
this.partsAffected[i].outline = !this.outline;
}
}
public RedoAction():void {
for (var i:number = 0; i < this.partsAffected.length; i++) {
this.partsAffected[i].outline = this.outline;
}
}
}
|
1a8af2895ce6349d0923e1784df2b26da597e232
|
TypeScript
|
MtyldZ/node-app
|
/src/errors/forbidden.error.ts
| 2.640625
| 3
|
import {HttpError} from './http-error';
export class ForbiddenError<T> extends HttpError<{ error_body_message: string, details: T }> {
constructor(message: string, details?: T) {
super(403, {error_body_message: message, details});
}
}
|
ac07a3a5cb6d5874363cab94e744a88fe1fdc0fa
|
TypeScript
|
munxar/quarto
|
/frontend/src/app/toast/toast.ts
| 2.578125
| 3
|
///<reference path="../../../../mithril.d.ts"/>
import * as m from "mithril";
import {LoggerService, LogLevel} from "../service/LoggerService";
import "./toast.css!css";
class Toast {
constructor(public message: string, public level: LogLevel) {
}
}
class ToastController {
toasts: Toast[] = [];
constructor(private logger: LoggerService) {
logger.on((message, level) => this.addToast(message, level));
}
addToast(message: string, level: LogLevel) {
var toast = new Toast(message, level);
this.toasts.push(toast);
setTimeout(() => {
this.removeToast(toast);
m.redraw();
}, 5000);
};
removeToast(toast: Toast) {
var idx = this.toasts.indexOf(toast);
this.toasts.splice(idx, 1);
};
}
function toastView(ctrl: ToastController) {
return m(".toast-container", ctrl.toasts.map(renderToast));
}
function renderToast(toast: Toast) {
return m(".toast", { "class": levelToClass(toast.level)}, toast.message);
}
function levelToClass(level: LogLevel) {
return LogLevel[level].toLowerCase();
}
export function toast(logger: LoggerService) {
return {
controller: function() {
return new ToastController(logger);
},
view: toastView
};
}
|
c0a834daa3affb5e14418b5603566f2c42377679
|
TypeScript
|
zhf/typescript-rest-starter
|
/src/App.ts
| 2.515625
| 3
|
import * as express from 'express'
import * as bodyParser from 'body-parser'
import { test } from './test'
class App {
public express
constructor () {
this.express = express()
this.mountRoutes()
}
private mountRoutes (): void {
const router = express.Router()
router.get('/', (req, res) => {
res.json({
status: 'online'
})
})
router.post('/test', (req, res) => {
const contentType = req.headers['content-type'];
if (!contentType || contentType.indexOf('text/plain') !== 0) return res.sendStatus(400)
const message = req.body
res.json(test(message))
})
this.express.use(bodyParser.text())
this.express.use('/', router)
}
}
export default new App().express
|
6e086e914df84eb4fce3f781a5ff8d6c2b35e4c8
|
TypeScript
|
kml1990/products-listing
|
/src/provider/mocky/MockyProductParser.ts
| 2.71875
| 3
|
import Product from '../../product/Product';
import ProductPrice from '../../product/ProductPrice';
import { ProductsParser } from '../ProductParser';
import { MockyProduct } from './MockyTypes';
export default class MockyProductParser implements ProductsParser<MockyProduct> {
parse(products: MockyProduct[]): Product[] {
return products.map(product => {
const {
productId: id,
name,
price: current,
priceWas: old,
available,
quantity,
lowOnStock,
promotionBadge,
imageUrl: thumbnail,
} = product;
return new Product({
id,
name,
price: new ProductPrice({ current, old }),
available: this.isProductAvailable(available),
quantity,
lowOnStock: this.isLowOnStock(lowOnStock),
promotionBadge,
thumbnail,
});
});
}
private isProductAvailable(available: string): boolean {
return available === 'TRUE';
}
private isLowOnStock(lowOnStock: string): boolean {
return lowOnStock === 'TRUE';
}
}
|
9243be216d0acf3cff8eecc8b7cce9aacfc748cd
|
TypeScript
|
minhtrung2606-work/my-first-ng4-app
|
/Inventory/src/app/components/product-list/product-list.component.ts
| 2.796875
| 3
|
import { Component, OnInit, Input, Output, EventEmitter, HostBinding } from '@angular/core';
import { Product } from './../../product';
@Component({
selector: 'product-list',
templateUrl: './product-list.component.html',
styleUrls: ['./product-list.component.css']
})
export class ProductListComponent implements OnInit {
// An array of type Product passed in this component
@Input() productList: Array<Product>;
// Pass out the current product whenever a product is selected
// Selected is done by clicked and marked selected
@Output() onProductSelected: EventEmitter<Product>;
@HostBinding('attr.class') cssClass = 'product-list';
// Private property of this component to keep the current selected product
private currentProduct: Product;
constructor() {
this.onProductSelected = new EventEmitter();
}
ngOnInit() {
}
onProductClicked(product: Product): void {
this.currentProduct = product;
this.onProductSelected.emit(this.currentProduct);
}
isProductSelected(product: Product): boolean {
// Use equals function of the type Product to make it easy to test
return product && this.currentProduct && this.currentProduct.equals(product);
}
}
|
4321726efffa653212a00a3dfb3ba123712dc5e7
|
TypeScript
|
fun4wut/mltd-zh-functions
|
/lib/capture/magic.ts
| 2.609375
| 3
|
import CryptoJS from 'crypto-js'
import tmpUtil from 'tmp'
import { gzip } from 'compressing'
import { promises as fs } from 'fs'
const secretKey = process.env.MLTD_KEY!
const secretKeyHash = CryptoJS.enc.Utf8.parse(secretKey)
const decBase = (str: string) => {
const s = str.replace(/-/g, '+').replace(/_/g, '/')
const b64 = CryptoJS.enc.Base64.parse(s)
const res = CryptoJS.AES.decrypt(
{
ciphertext: b64,
} as any, // bad d.ts file sucks
secretKeyHash,
{
iv: CryptoJS.lib.WordArray.create(),
}
)
return Buffer.from(res.toString(), 'hex').subarray(16)
}
export async function decRes(str: string) {
const tmpFile = tmpUtil.tmpNameSync()
await gzip.uncompress(decBase(str), tmpFile).catch(console.error)
const json = await fs.readFile(tmpFile, 'utf-8')
return JSON.parse(json)
}
export async function decReq(str: string) {
const json = decBase(str).toString('utf-8')
return JSON.parse(json)
}
export function encReq(obj: unknown) {
let arr = CryptoJS.enc.Utf8.parse(JSON.stringify(obj))
arr = CryptoJS.lib.WordArray.random(16).concat(arr) // 填充前16个Bytes
const res = CryptoJS.AES.encrypt(arr, secretKeyHash, {
iv: CryptoJS.lib.WordArray.create(),
format: CryptoJS.format.Hex,
}).toString()
return Buffer.from(res, 'hex')
.toString('base64')
.replace(/\+/g, '-')
.replace(/\//g, '_')
}
|
dafbde288027b35ec780a913d7e5124b32f495ce
|
TypeScript
|
kavusiks/SellPoint
|
/sellpoint_frontend/src/models/ad.ts
| 3.046875
| 3
|
import User from "./user";
/**
* An image belonging to a specific Ad
*/
export interface AdImage {
/**
* The unique ID of this image
*/
id: number;
/**
* URL pointing to the image file
*/
url: string;
/**
* Textual description of this image
*/
description: string;
}
/**
* A posted ad
*/
export interface Ad {
/**
* The user that posted the ad
*/
readonly owner?: User;
/**
* The unique id of the ad
*/
readonly id?: number;
/**
* The title of the ad
*/
title: string;
/**
* The price
*/
price: number;
/**
* Description of the ad
*/
description: string;
/**
* When the ad was created
*/
created_at?: Date;
/**
* When the ad was last updated
*/
last_modified?: Date;
/**
* If the item has been sold
*/
is_sold?: boolean;
/**
* The image that is the thumbnail for this ad, will be
* displayed first
*/
thumbnail?: AdImage;
/**
* All images uploaded for this ad
*/
images?: AdImage[];
/**
* The category this ad is in
*/
category?: number;
/**
* The distance to this ad's owner
*/
distance?: number;
}
export interface Category {
id: number;
name: string;
}
export interface FavoriteAd {
user: number;
favorite_ad: number;
}
|
c4736fc7542d6bae5bdb63af32385c74ed967ddc
|
TypeScript
|
caioguilherme10/projectthree-server
|
/src/resolvers/pasciente.ts
| 2.71875
| 3
|
import { Query, Resolver, Arg, Int, Mutation } from "type-graphql";
import { getConnection } from "typeorm";
import { Pasciente } from "../entities/Pasciente";
import { PascienteInput } from "./types/pasciente-input";
@Resolver(Pasciente)
export class PascienteResolver {
//ADMINISTRADOR
@Query(() => [Pasciente])
async pascientes(): Promise<Pasciente[]> {
const result = await getConnection()
.createQueryBuilder()
.select("pasciente")
.from(Pasciente, "pasciente")
.getMany();
return result;
}
//ADMINISTRADOR, ANALISTA, AUDITOR, DIGITADOR
@Query(() => Pasciente, { nullable: true })
async getPasciente(@Arg('id', () => Int) id: number): Promise<Pasciente | undefined> {
const result = await getConnection()
.createQueryBuilder()
.select("pasciente")
.from(Pasciente, "pasciente")
.where("pasciente.id = :id", { id })
.getOne();
return result;
}
//ADMINISTRADOR, ANALISTA, AUDITOR, DIGITADOR
@Query(() => Pasciente, { nullable: true })
async getPascienteNome(@Arg('nome', () => String) nome: string): Promise<Pasciente | undefined> {
const result = await getConnection()
.createQueryBuilder()
.select("pasciente")
.from(Pasciente, "pasciente")
.where("pasciente.nome = :nome", { nome })
.getOne();
return result;
}
//ADMINISTRADOR
@Mutation(() => Pasciente)
async createPasciente(@Arg("input") input: PascienteInput): Promise<Pasciente> {
const result = await getConnection()
.createQueryBuilder()
.insert()
.into(Pasciente)
.values(input)
.returning("*")
.execute();
return result.raw[0];
}
//ADMINISTRADOR
@Mutation(() => Pasciente, {nullable: true})
async updatePasciente(
@Arg('id', () => Int) id: number,
@Arg("input") input: PascienteInput
)
: Promise<Pasciente | null>
{
const result = await getConnection()
.createQueryBuilder()
.update(Pasciente)
.set(input)
.where('id = :id', {
id,
})
.returning("*")
.execute();
return result.raw[0];
}
//ADMINISTRADOR
@Mutation(() => Boolean)
async deletePasciente(@Arg("id", () => Int) id: number): Promise<boolean> {
await getConnection()
.createQueryBuilder()
.delete()
.from(Pasciente)
.where("id = :id", { id })
.execute();
return true;
}
}
|
4a119bc7ec86dc8f7f78c490eb2613ff4196f628
|
TypeScript
|
heatherwenzel/angular-recipe-api
|
/src/app/search-criteria/search-criteria.component.ts
| 2.65625
| 3
|
import { Component, OnInit } from '@angular/core';
import { RecipeService } from '../recipe.service'; //added
@Component({
selector: 'search-criteria', //deleted app
templateUrl: './search-criteria.component.html',
styleUrls: ['./search-criteria.component.css']
})
export class SearchCriteriaComponent implements OnInit {
// this array stores all of our search results as queried on the search-criteria component
results: any[] = [];
constructor(private recipeService: RecipeService) { }
ngOnInit() {
}
// this method takes in the user input from the form and returns the appropriate recipe data, as returned from the recipe service
searchRecipe(form) {
this.recipeService.getRecipeData(form.value.userSearch, this.selectedDiet, this.selectedCalories).then(response => {
this.results = response;
});
}
// this variable sets the user's selectedDiet choice to an empty string
selectedDiet: string = '';
// this method takes in the the user's input for the selectedDiet and reassigns the variable to that value
selectDiet (event: any) {
this.selectedDiet = event.target.value;
console.log(this.selectedDiet);
}
// this variable sets the user's selectedCalories choice to an empty string
selectedCalories: string = '';
// this method takes in the the user's input for the selectedCalories and reassigns the variable to that value
selectCalories (event: any) {
this.selectedCalories = event.target.value;
console.log(this.selectedCalories);
}
// this method takes in the actual result and its index number, then sends it to the service to be run through the addToFavorites method, as well as sets the favorited property of the result to true
addFavorite(result: string, index: number): void {
this.recipeService.addToFavorites(result, index);
this.results[index].favorited = true;
}
}
|
a790613a88a61b1f54f7d5bb6d750dad57d3b290
|
TypeScript
|
glazar/ts-jest-enum-issue
|
/src/files/file1.ts
| 2.765625
| 3
|
import { ColorEnum, consoleLog } from "./file4";
export const square = (x: number) => x * x;
export const cube = (x: number) => x * x * x;
export const consoleLogSquare = (x: number) => consoleLog(square(x));
export const consoleLogCube = (x: number) => consoleLog(cube(x));
export enum NumberEnum {
Zero = 0,
One = 1,
Two = 2
}
export const blue: ColorEnum = ColorEnum.Blue;
|
99b0bfac257bcde595055e7a0b71532dfecf117c
|
TypeScript
|
fyfey/tic-tac-toe
|
/lib/dist/logger.d.ts
| 2.578125
| 3
|
export interface Logger {
info(...messages: string[]): void;
error(...messages: string[]): void;
}
export declare class NullLogger implements Logger {
info(...messages: string[]): void;
error(...messages: string[]): void;
}
export declare class ConsoleLogger implements Logger {
info(...messages: string[]): void;
error(...message: string[]): void;
private log;
}
|
a709bea4769e277160f2ca1b99d418da0f317d99
|
TypeScript
|
titiksha07/Assignment12.3
|
/src/app/capital.pipe.ts
| 2.71875
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'capital',
pure: false
})
export class CapitalPipe implements PipeTransform {
transform(value: string): string {
let fStr:string='';
let restStr:string='';
let newStr:string='';
if (value.length !== 0) {
fStr= value.charAt(0);
restStr=value.slice(1);
newStr=fStr.toUpperCase()+restStr;
};
return newStr;
}
}
|
aa5e651d3dd02aac235586b1cecd6647017367df
|
TypeScript
|
mvfsillva/find-quebec-montreal-bus
|
/src/hooks/use-click-away.ts
| 2.53125
| 3
|
// Packages
import { useRef, useEffect } from 'react'
const useClickAway = (effect: () => void) => {
const node = useRef<HTMLInputElement>(null)
const handler = (event: Event) => {
const { target } = event
if (node && node.current) {
if (node.current.contains(target as Node)) return
effect()
}
}
useEffect(() => {
document.addEventListener('mousedown', handler)
return () => {
document.removeEventListener('mousedown', handler)
}
}, [])
return node
}
export default useClickAway
|
d9bbc485936a8ef6ace5ae1e2b6c4839346ad0b0
|
TypeScript
|
uparlange/msdb-ts
|
/src/app/common/managers/favorites-manager.ts
| 2.640625
| 3
|
import { AbstractManager } from '../../fwk/abstract-manager';
import { CacheManager } from '../../fwk/managers/cache-manager';
import { EventEmitter, Injectable } from '@angular/core';
@Injectable({ providedIn: "root" })
export class FavoritesManager extends AbstractManager {
private _favorites: Array<string> = new Array();;
constructor(
private _cacheManager: CacheManager) {
super();
}
override init(): void {
super.init();
this._cacheManager.getItem("favorites", []).subscribe((value: Array<any>) => {
this._favorites = value;
});
}
add(name: string): void {
if (!this.has(name)) {
this._favorites.push(name);
this._save();
this.emit("change", {
action: "add",
value: name
});
}
}
remove(name: string): void {
const index = this._favorites.indexOf(name);
if (index !== -1) {
this._favorites.splice(index, 1);
this._save();
this.emit("change", {
action: "remove",
value: name
});
}
}
has(name: string): boolean {
return (this._favorites.indexOf(name) !== -1);
}
getList(): EventEmitter<any> {
const eventEmitter: EventEmitter<any> = new EventEmitter();
setTimeout(() => {
eventEmitter.emit(this._favorites);
}, 0);
return eventEmitter;
}
private _save(): void {
this._cacheManager.setItem("favorites", this._favorites, "favorites");
}
}
|
2e40d04cfb2653b533ad51383beb738c7678fae7
|
TypeScript
|
flyrootmedia/udemy-typescript
|
/01-features/classes.ts
| 4.28125
| 4
|
class Vehicle {
// properties CAN be initialized when declared here
// public color: string;
// public weight: number;
// to set properties as args when creating an instance, they must be set in
// the constructor method. Note now all args will be required by instances
// constructor(color: string, weight: number) {
// this.color = color;
// this.weight = weight;
// }
// shorthand syntax for creating/setting public properties as args:
constructor(
public color: string,
private weight: number,
protected numOfWheels: number
) {}
// private can only be accessed from inside this class
private getWeight(): number {
return this.weight;
}
// protected can be accessed by child classes
protected honk(): void {
console.log('beep');
}
// public accessible from anywhere
// public keyword is not required since this is default
public tellMeTheWeight(): void {
console.log(this.getWeight());
}
public tellMeHowManyWheels(): number {
return this.numOfWheels;
}
}
// car inherits from vehicle
class Car extends Vehicle {
// when adding properties to the constructor of a child class, you must still
// accept all the properties defined in the parent class as args and pass them
// to the super() method. NOTE: do not add access modifiers to the properties
// coming from the parent because you don't want to create new property definitions
// in the child.
constructor(
public engine: string,
color: string,
weight: number,
numOfWheels: number
) {
super(color, weight, numOfWheels);
}
// override the inherited drive method
private drive(): void {
console.log('vroom');
}
public startDrivingProcess(): void {
this.drive();
this.honk();
this.tellMeTheWeight();
}
}
// Vehicle has 3 required args as defined in the constructor
const vehicle = new Vehicle('black', 850, 2);
vehicle.tellMeTheWeight();
// Car has the required "engine" arg defined in the constructor, PLUS the
// additional "color", "weight" and "numOfWheels" args required in the parent Vehicle class
const car = new Car('v8', 'blue', 3000, 6);
car.startDrivingProcess();
console.log(car.tellMeHowManyWheels());
|
d35dd8529037873b20351bf1e3bbec26db5c89ed
|
TypeScript
|
johniyere/offroads-web-v1
|
/src/app/account/shared/time-view.pipe.ts
| 2.640625
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'timeView'
})
export class TimeViewPipe implements PipeTransform {
transform(value: number, args?: any): any {
const hours = Math.round(value / 3600);
const hoursRem = Math.round(value % 3600);
const min = Math.round(hoursRem / 60);
const secs = Math.round(hoursRem % 60);
return `${hours}h ${min}m ${secs}s`;
}
}
|
d8cd63ed26b1abfcdb8ec26aa1f43c18c8ed332e
|
TypeScript
|
Renddslow/y
|
/src/types.ts
| 2.515625
| 3
|
export type Character = {
age: number;
birthday: number;
tribe: string;
name: string;
};
export type State = {
day: number;
playRate: 1 | 2 | 3;
paused: boolean;
character: Character;
};
export type Game = {
stop: number;
lastTick: number;
tickLength: number;
lastRender: number;
gameStart: number;
dayClock: number;
};
|
1ded8567fe53e911c79b5f7a63c1f1482a9992ce
|
TypeScript
|
wasabi-io/tdd-suite
|
/src/renderer/electron/Browser.ts
| 2.53125
| 3
|
import BrowserWindowOptions = Electron.BrowserWindowOptions;
import Window, {WindowProps} from "./Window";
export interface BrowserProps extends WindowProps {
onDestroy();
}
export default class Browser extends Window {
public constructor(props: BrowserProps) {
super(props);
}
public destroy(){
}
}
|
a7701336352e00985d09bd2b30104fc1cdf991f7
|
TypeScript
|
nodegui/nodegui
|
/src/examples/modelview_3_changingmodel.ts
| 2.546875
| 3
|
import { ItemDataRole, QAbstractTableModel, QModelIndex, QTableView, QVariant } from '..';
function main(): void {
const tableView = new QTableView();
const model = new MyModel();
tableView.setModel(model);
tableView.show();
setInterval(() => {
model.timerHit();
}, 1000);
(global as any).win = tableView;
}
class MyModel extends QAbstractTableModel {
rowCount(parent = new QModelIndex()): number {
return 2;
}
columnCount(parent = new QModelIndex()): number {
return 3;
}
data(index: QModelIndex, role = ItemDataRole.DisplayRole): QVariant {
const row = index.row();
const col = index.column();
if (role == ItemDataRole.DisplayRole && row == 0 && col == 0) {
return new QVariant('' + new Date().toTimeString());
}
return new QVariant();
}
timerHit(): void {
const topLeft = this.createIndex(0, 0);
this.emitDataChanged(topLeft, topLeft, [ItemDataRole.DisplayRole]);
}
}
main();
|
72070778b698dddac84a444fe2ad29c5f41de30a
|
TypeScript
|
m8r1x/sakilagql
|
/src/schema/__tests__/customer.test.ts
| 2.921875
| 3
|
import test from 'ava';
import { api } from './api';
function getDocument(query: string) {
return `${query}
fragment AllCustomerProperties on Customer {
firstName
lastName
email
active
createdDate
lastUpdate
address { addressName }
}
`;
}
test('gets an object by api ID', async t => {
const query = '{ customer(customerID: 1) { firstName } }';
const { data } = await api(query);
t.is(data!['customer']['firstName'], 'MARY');
});
test('Gets an object by global ID', async t => {
const query = '{ customer(customerID: 1) { id firstName } }';
const { data } = await api(query);
const nextQuery = `{ customer(id: "${data!['customer']['id']}") { id firstName } }`;
const nextResult = await api(nextQuery);
t.is(data!['customer']['firstName'], 'MARY');
t.is(data!['customer']['firstName'], nextResult.data!['customer']['firstName']);
t.is(data!['customer']['id'], nextResult.data!['customer']['id']);
});
test('Gets an object by global ID with node', async t => {
const query = '{ customer(customerID: 1) { id firstName } }';
const { data } = await api(query);
const nextQuery = `{
node(id: "${data!['customer']['id']}") {
... on Customer { id firstName }
}
}`;
const nextResult = await api(nextQuery);
t.is(data!['customer']['firstName'], 'MARY');
t.is(data!['customer']['firstName'], nextResult.data!['node']['firstName']);
t.is(data!['customer']['id'], nextResult.data!['node']['id']);
});
test('Gets all properties', async t => {
const query = getDocument('{ customer(customerID: 1) { ...AllCustomerProperties } }');
const { data } = await api(query);
const expected = {
firstName: 'MARY',
lastName: 'SMITH',
email: 'MARY.SMITH@sakilacustomer.org',
active: 1,
createdDate: '2006-02-14T22:04:36Z',
lastUpdate: '2006-02-15T04:57:20Z',
address: { addressName: '1913 Hanoi Way' }
};
t.deepEqual(data!['customer'], expected);
});
test('all objects query', async t => {
const query = getDocument('{ allCustomers { edges { node { ...AllCustomerProperties } } } }');
const { data } = await api(query);
t.is(data!['allCustomers']['edges'].length, 599);
});
test('Pagination query', async t => {
const query = `{ allCustomers(first: 2) { edges { cursor node { firstName } } } }`;
const { data } = await api(query);
t.deepEqual(data!.allCustomers.edges.map((e: { [key: string]: any }) => e.node.firstName), [
'MARY',
'PATRICIA'
]);
const nextCursor: string = data!.allCustomers.edges[1].cursor;
const nextQuery = `{
allCustomers(first: 2, after: "${nextCursor}") {
edges { cursor node { firstName } }
}
}`;
const nextResult = await api(nextQuery);
t.deepEqual(nextResult.data!.allCustomers.edges.map((e: { [key: string]: any }) => e.node.firstName), [
'LINDA',
'BARBARA'
]);
});
|
3ef9ef5b0b282e51739f1c04e973ef1f0efbca8c
|
TypeScript
|
rheehot/metaflow-ui
|
/src/components/Timeline/taskdataUtils.ts
| 2.921875
| 3
|
import { Step, Task, TaskStatus } from '../../types';
import { RowDataModel } from './useTaskData';
//
// Counts rows
//
export type RowCounts = {
all: number;
completed: number;
running: number;
pending: number;
failed: number;
unknown: number;
};
export function countTaskRowsByStatus(rows: RowDataModel): RowCounts {
const counts = {
all: 0,
completed: 0,
running: 0,
failed: 0,
pending: 0,
unknown: 0,
};
const keys: Array<keyof typeof counts> = Object.keys(counts) as Array<keyof typeof counts>;
// Iterate steps
for (const stepName of Object.keys(rows)) {
// ...Wihtout steps that start with underscore because user is not interested on them
if (!stepName.startsWith('_')) {
const stepRow = rows[stepName];
// Iterate all task rows on step
for (const taskId of Object.keys(stepRow.data)) {
const taskRow = stepRow.data[taskId];
if (taskRow.length > 0) {
const task = taskRow[taskRow.length - 1];
// Every task adds one to all count
counts.all++;
// Increment specific count
const status = task.status as keyof typeof counts;
if (keys.indexOf(status) > -1) {
counts[status]++;
}
}
}
}
}
return counts;
}
//
// Make step line data for minimap
//
export type StepLineData = {
started_at: number;
finished_at: number;
status: TaskStatus;
step_name: string;
original?: Step;
};
export function makeStepLineData(rows: RowDataModel): StepLineData[] {
return Object.keys(rows).reduce((arr: StepLineData[], key) => {
if (key.startsWith('_')) return arr;
const row = rows[key];
return arr.concat([
{
started_at: row.step?.ts_epoch || 0,
finished_at: row.finished_at,
status: row.status,
original: row.step,
step_name: key,
},
]);
}, []);
}
//
// Find earliest and latest point from list of tasks
//
export function timepointsOfTasks(tasks: Task[]): [number | null, number] {
return tasks.reduce(
(val, task) => {
const taskStartTime = task.started_at;
const highpoint: number =
task.finished_at && task.finished_at > val[1]
? task.finished_at
: taskStartTime && taskStartTime > val[1]
? taskStartTime
: val[1];
const lowpoint: number | null =
taskStartTime && val[0] === null
? taskStartTime
: taskStartTime && val[0] !== null
? taskStartTime < val[0]
? taskStartTime
: val[0]
: val[0];
return [lowpoint, highpoint];
},
[tasks[0] ? tasks[0].started_at || null : 0, 0],
);
}
//
// Check if step is failure. Only checks new tasks we just got from server. This might cause an issue
// though if we get successful tasks after getting failed ones (should not really happen).
//
export function getStepStatus(stepTaskData: Record<string, Task[]>): TaskStatus {
for (const data of Object.entries(stepTaskData)) {
const statuses = data[1].map((item) => item.status);
const statusOfLastItem = statuses[statuses.length - 1];
if (statusOfLastItem === 'running') {
return 'running';
}
if (statusOfLastItem === 'failed') {
return 'failed';
}
}
return 'completed';
}
//
// Merge or add new data to row information.
// If there is already data about smae task, with same attempt_id we want to replace
// that data. Else we add new task
//
export function makeTasksForStep(currentData: Record<string, Task[]>, item: Task): Task[] {
if (currentData[item.task_id]) {
const newtasks = currentData[item.task_id];
// Process duration and start time for task since they are somewhat uncertain from API
// NOTE: WE ARE MUTATING TASK VALUES HERE BECAUSE VALUES GIVEN BY BACKEND MIGHT NOT BE CORRECT
// SINCE STARTED AT AND DURATION MIGHT BE INCORRECT IN SOME SITUATIONS!!!
if (!item.started_at) {
if (item.attempt_id === 0) {
item.started_at = item.ts_epoch;
item.duration = item.duration || (item.finished_at ? item.finished_at - item.ts_epoch : undefined);
} else {
const prevTask = currentData[item.task_id].find((t) => t.attempt_id === item.attempt_id - 1);
item.started_at = item.started_at || prevTask?.finished_at || undefined;
item.duration = item.started_at && item.finished_at ? item.finished_at - item.started_at : undefined;
}
}
// Track if we replaced old data...
let added = false;
for (const index in newtasks) {
if (newtasks[index].attempt_id === item.attempt_id) {
added = true;
newtasks[index] = item;
}
}
// ...else add as new task
if (!added) {
newtasks.push(item);
}
return newtasks.sort((a, b) => a.attempt_id - b.attempt_id);
} else {
return [item];
}
}
|
54fd9855e43f5944ff33605cd7e3841ada8f25cf
|
TypeScript
|
mweels/aphajs
|
/src/test/Exception.spec.ts
| 2.953125
| 3
|
import {expect} from "chai";
import {Exception} from "../main/Exception";
describe("Exception", () => {
it("should be filled with sense-making values", () => {
const e = new SomeDerivedException("my message");
expect(e).to.be.an.instanceOf(SomeDerivedException);
expect(e).to.be.an.instanceOf(Exception);
expect(e.name).to.equal("SomeDerivedException");
expect(e.message).to.equal("my message");
});
});
class SomeDerivedException extends Exception {
}
|
439c17fa52d01c1d72f9997d6e1862f8a272d94d
|
TypeScript
|
NicolasFkm/BankApp
|
/src/controllers/AccountController.ts
| 2.515625
| 3
|
import { HttpStatus } from '@enumerators/HttpStatus';
import { DataNotFoundException } from '@helpers/errors/DataNotFoundException';
import { InvalidArgumentException } from '@helpers/errors/InvalidArgumentException';
import { IAccount } from '@models/Account';
import EntityCollectionResponse from '@models/responses/EntityCollectionResponse';
import EntityResponse from '@models/responses/EntityResponse';
import ErrorResponse from '@models/responses/ErrorResponse';
import AccountService from '@services/AccountService';
import { Response, Request } from 'express';
import { Types } from 'mongoose';
export default class AccountController {
public accountService: AccountService;
constructor(){
this.accountService = new AccountService();;
}
public postCreate = async(req: Request, res: Response) : Promise<Response> => {
try{
let { name, password, balance }: { name: string, password: string, balance: number} = req.body;
const account = {name, password, balance} as IAccount;
const createdAccount = await this.accountService.create(account);
let response = new EntityResponse(createdAccount, req.url);
let status = HttpStatus.SUCCESS;
return res.status(status).send(response);
}
catch(error){
let status = HttpStatus.INTERNAL_SERVER_ERROR;
let errorResponse = new ErrorResponse(req.url);
if(error instanceof InvalidArgumentException){
status = HttpStatus.BAD_REQUEST;
errorResponse.message = error.message;
}
return res.status(status).send(errorResponse);
}
}
public getAll = async(req: Request, res: Response) : Promise<Response> => {
try{
const createdAccount = await this.accountService.getAll();
let response = new EntityCollectionResponse(createdAccount, req.url);
let status = HttpStatus.SUCCESS;
return res.status(status).send(response);
}
catch(error){
console.log("ERROR get All: " + error);
let status = HttpStatus.INTERNAL_SERVER_ERROR;
let errorResponse = new ErrorResponse(req.url);
if(error instanceof InvalidArgumentException){
status = HttpStatus.BAD_REQUEST;
errorResponse.message = error.message;
}
return res.status(status).send(errorResponse);
}
}
public getById = async(req: Request, res: Response) : Promise<Response> => {
try{
let { id } = req.params;
const account = await this.accountService.getById(id);
if(account == null){
throw new DataNotFoundException();
}
let response = new EntityResponse(account, req.url);
let status = HttpStatus.SUCCESS;
return res.status(status).send(response);
}
catch(error){
let status = HttpStatus.INTERNAL_SERVER_ERROR;
let errorResponse = new ErrorResponse(req.url);
if(error instanceof InvalidArgumentException){
status = HttpStatus.BAD_REQUEST;
errorResponse.message = error.message;
}
if(error instanceof DataNotFoundException){
status = HttpStatus.NOT_FOUND;
errorResponse.message = error.message;
}
return res.status(status).send(errorResponse);
}
}
public getPayments = async(req: Request, res: Response) : Promise<Response> => {
try{
let { id } = req.params;
const payments = await this.accountService.getAccountPaymentsById(id);
if(payments == undefined || payments.length == 0){
throw new DataNotFoundException();
}
let response = new EntityCollectionResponse(payments, req.url);
let status = HttpStatus.SUCCESS;
return res.status(status).send(response);
}
catch(error){
let status = HttpStatus.INTERNAL_SERVER_ERROR;
let errorResponse = new ErrorResponse(req.url);
if(error instanceof InvalidArgumentException){
status = HttpStatus.BAD_REQUEST;
errorResponse.message = error.message;
}
if(error instanceof DataNotFoundException){
status = HttpStatus.NOT_FOUND;
errorResponse.message = error.message;
}
return res.status(status).send(errorResponse);
}
}
public getDeposits = async(req: Request, res: Response) : Promise<Response> => {
try{
let { id } = req.params;
const deposits = await this.accountService.getAccountDepositsById(id);
if(deposits == undefined || deposits.length == 0 ){
throw new DataNotFoundException();
}
let response = new EntityCollectionResponse(deposits, req.url);
let status = HttpStatus.SUCCESS;
return res.status(status).send(response);
}
catch(error){
let status = HttpStatus.INTERNAL_SERVER_ERROR;
let errorResponse = new ErrorResponse(req.url);
if(error instanceof InvalidArgumentException){
status = HttpStatus.BAD_REQUEST;
errorResponse.message = error.message;
}
if(error instanceof DataNotFoundException){
status = HttpStatus.NOT_FOUND;
errorResponse.message = error.message;
}
return res.status(status).send(errorResponse);
}
}
public getWithdrawals = async(req: Request, res: Response) : Promise<Response> => {
try{
let { id } = req.params;
const withdrawals = await this.accountService.getAccountWithdrawalsById(id);
if(withdrawals == undefined || withdrawals.length == 0){
throw new DataNotFoundException();
}
let response = new EntityCollectionResponse(withdrawals, req.url);
let status = HttpStatus.SUCCESS;
return res.status(status).send(response);
}
catch(error){
let status = HttpStatus.INTERNAL_SERVER_ERROR;
let errorResponse = new ErrorResponse(req.url);
if(error instanceof InvalidArgumentException){
status = HttpStatus.BAD_REQUEST;
errorResponse.message = error.message;
}
if(error instanceof DataNotFoundException){
status = HttpStatus.NOT_FOUND;
errorResponse.message = error.message;
}
return res.status(status).send(errorResponse);
}
}
}
|
c98f863c055d0b2381772760ff61fdfb627f743a
|
TypeScript
|
Badaboom1995/mining
|
/server/src/app/workers/miner-stats/currency-api/currency-transaction.ts
| 2.65625
| 3
|
export interface ICurrencyTransaction {
/**
* Transaction type
* @type {string}
* @memberof ICurrencyTransaction
*/
type? : string;
/**
* Transaction value
*/
value : number;
/**
* Transaction time
* @type {number}
* @memberof ICurrencyTransaction
*/
timestamp : number;
/**
* Transaction index
* @type {number}
* @memberof ICurrencyTransaction
*/
index : number;
/**
* Transaction blockhain hash
*/
hash ? : string;
}
|
5699240b314f8d29131516d44a393432aaf5c466
|
TypeScript
|
JingYang0521/permission-management-system
|
/src/utils/storage.ts
| 2.765625
| 3
|
export const rmLocalStorageItem = (key: string) => {
localStorage.removeItem(key);
};
export const getLocalStorageItem = (key: string): string | null => {
return localStorage.getItem(key);
};
export const setLocalStorageItem = (key: string, value: string) => {
return localStorage.setItem(key, value);
};
export const clearLocalStorage = () => {
return localStorage.clear();
};
|
e9b0fc1e1bb6374442aaa48cd8f089cd133cf6bc
|
TypeScript
|
ZanovelloAlberto/PixiRPG
|
/src/game/map/Player.ts
| 2.796875
| 3
|
/*
*/
import { BaseTexture, Rectangle, Sprite, Texture } from 'pixi.js';
import { textSpanIntersectsWithPosition } from 'typescript';
import { Res } from '../../Res';
import { Map } from '../map/Map'
export class Player extends Sprite {
textures: Array<Texture>;
running: boolean = false;
direction: number = 0;
// front
// left
// right
// back
state: number = 0;
// right
// idle
// left
speed: number = 2;
static char:number = 0;
constructor() {
super();
this.textures = Res.getChar(Player.char)
this.x = 50;
this.y = 50;
this.anchor.set(0.5,0.8)
this.texture = this.textures[0]
document.addEventListener("keydown", (ev: KeyboardEvent) => {
const n = Player.getKey(ev.keyCode);
if (n != -1) {
this.direction = n;
this.running = true;
}
});
document.addEventListener("keyup", (ev: KeyboardEvent) => {
const n = Player.getKey(ev.keyCode);
if (n != -1) {
if (n == this.direction) {
this.running = false;
}
}
});
}
setState = ()=>{
if(this.running){
this.state = ((Math.floor(Date.now()/150))%3)
}else{
this.state = 1;
}
// console.log(this.state)
}
setTexture() {
this.texture = this.textures[this.direction * 3 + this.state];
//console.log(this.x,this.y)
}
update = ()=> {
//console.log("iter")
const x = this.x
const y = this.y
if (this.running) {
switch (this.direction) {
case 0:
this.y += this.speed;
break;
case 1:
this.x -= this.speed;
break;
case 2:
this.x += this.speed;
break;
case 3:
this.y -= this.speed;
break;
}
}
if(!Map.tiles.getTile(Math.floor(this.x/16),Math.floor(this.y/16)).walk ){
this.x = x
this.y = y
}
this.setState()
this.setTexture()
}
static getKey(n: number): number {
const KeyPair = [40, 37, 39, 38];
for (let i = 0; i < KeyPair.length; i++) {
if (KeyPair[i] == n) {
console.log("changed dir")
return i;
}
}
return -1;
}
}
|
64ff033918a3d364aaeb61c3ce31cef5f1f44829
|
TypeScript
|
Ericki/chronicler
|
/src/app/shared/services/crud-data.service.ts
| 2.625
| 3
|
import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireList } from '@angular/fire/database';
import * as firebase from 'firebase/app';
import 'firebase/storage';
import { FileUpload } from '../models/image';
@Injectable({
providedIn: 'root'
})
export class CrudDataService {
private basePath = '/uploads';
constructor(private db: AngularFireDatabase,
private path:string ) { }
//const listRef =
//booksRef: AngularFireList<any>; // Reference to Student data list, its an Observable
//bookRef: AngularFireObject<any>; // Reference to Student object, its an Observable too
// Create Student
create(source) {
this.db.list(this.path).push(source);
}
update(key,source) {
this.db.list(this.path).update(key,source);
}
delete(key){
this.db.list(this.path).remove(key);
}
getAll(){
return this.db.list(this.path).snapshotChanges();
}
get(productId) {
return this.db.object(this.path+ '/' + productId).snapshotChanges();
}
/* create(product) {
return this.db.list('/products').push(product);
}
getAll() {
return this.db.list('/products');
}
get(productId) {
return this.db.object('/products/' + productId);
}
update(productId, product) {
return this.db.object('/products/' + productId).update(product);
}
delete(productId) {
return this.db.object('/products/' + productId).remove();
}
*/
pushFileToStorage(fileUpload: FileUpload, progress: { percentage: number }) {
const storageRef = firebase.storage().ref();
const uploadTask = storageRef.child(`${this.path}/${fileUpload.file.name}`).put(fileUpload.file);
uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
(snapshot) => {
// in progress
const snap = snapshot as firebase.storage.UploadTaskSnapshot;
progress.percentage = Math.round((snap.bytesTransferred / snap.totalBytes) * 100);
},
(error) => {
// fail
console.log(error);
},
() => {
// success
uploadTask.snapshot.ref.getDownloadURL().then(downloadURL => {
console.log('File available at', downloadURL);
fileUpload.url = downloadURL;
fileUpload.name = fileUpload.file.name;
this.saveFileData(fileUpload);
});
}
);
}
private saveFileData(fileUpload: FileUpload) {
this.db.list(`${this.path}/`).push(fileUpload);
}
getFileUploads(numberItems): AngularFireList<FileUpload> {
return this.db.list(this.path, ref =>
ref.limitToLast(numberItems));
}
deleteFileUpload(fileUpload: FileUpload) {
this.deleteFileDatabase(fileUpload.key)
.then(() => {
this.deleteFileStorage(fileUpload.name);
})
.catch(error => console.log(error));
}
private deleteFileDatabase(key: string) {
return this.db.list(`${this.path}/`).remove(key);
}
private deleteFileStorage(name: string) {
const storageRef = firebase.storage().ref();
storageRef.child(`${this.path}/${name}`).delete();
}
downloadFileSotrage(fileUpload: FileUpload){
const storage = firebase.storage();
const httpsReference = storage.refFromURL(fileUpload.url);
httpsReference.getDownloadURL().then(function(url) {
// `url` is the download URL for 'images/stars.jpg'
// This can be downloaded directly:
const xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
const blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
}).catch(function(error) {
// Handle any errors
console.log('no funca');
});
}
}
|
6f1a216a76e697cc40a7fdb2e49f986fda0e04e9
|
TypeScript
|
sutherlanda/hire-or-fire
|
/src/app/components/employee-list/employee-list.component.ts
| 2.765625
| 3
|
import { Component, OnInit, Input } from '@angular/core';
import { Employee } from 'src/app/models/employee.model';
import { Category } from 'src/app/models/category.model';
@Component({
selector: 'app-employee-list',
templateUrl: './employee-list.component.html',
styleUrls: ['./employee-list.component.scss']
})
export class EmployeeListComponent implements OnInit {
@Input() categories: Category[] = [];
@Input() isActiveList: boolean;
selectedEmployees: Employee[];
textFilter: string = '';
constructor() { }
ngOnInit() { }
// Returns a count of the number of employees in this list
getEmployeeCount(): number {
let count = 0;
this.categories.forEach(category => {
count += category.employees.filter(employee => employee.isActive === this.isActiveList).length;
});
return count;
}
// Toggles the active status of the selected employees
toggleSelectedEmployees(): void {
this.selectedEmployees.forEach(employee => {
employee.toggleActiveStatus();
});
}
// Moves all employees to other list by setting their active status to the opposite of this list status.
// Respects the current filter.
toggleAllEmployees(): void {
this.categories.forEach(category => {
category.employees.filter(employee => employee.name.toLowerCase().includes(this.textFilter.toLowerCase()))
.forEach(employee => {
employee.isActive = !this.isActiveList;
});
});
}
}
|
875992af6e71cba42bf4c8b9c7df64c7bddc8ab0
|
TypeScript
|
RickvanB/Avans-Projects
|
/mobile-dev-hybrid/src/app/services/pokemon.service.ts
| 2.515625
| 3
|
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environments/environment';
import { Observable } from 'rxjs';
import { Pokemon, PokemonWrapper } from '../models/API_model';
@Injectable({
providedIn: 'root'
})
export class PokemonService {
private GET_POKEMON = `${environment.api_base}/pokemon`
constructor(private http: HttpClient) {
}
/**
* This method will return a list of pokemons
* @param limit
* @param offset
*/
getPokemons(limit: number, offset: number) : Observable<PokemonWrapper> {
return this.http.get<PokemonWrapper>(this.GET_POKEMON + `?offset=${offset}&limit=${limit}` );
}
/**
* This method will return a pokemon by searching on name
* @param name
*/
getPokemonDetails(identifier: string) : Observable<Pokemon> {
return this.http.get<Pokemon>(this.GET_POKEMON + `/${identifier}`);
}
}
|
5d734d86f1a6fc6de45de9227f3bd6876e83e7b7
|
TypeScript
|
bowen-wu/ts
|
/ts-demo/min.ts
| 4.46875
| 4
|
// 重载
function add (a: string, b: string): string;
function add (a: number, b: number): number;
function add (a: any, b: any): any{
return a + b;
}
// 返回值 类型
function min(a: number, b: number): number {
if(a > b) {
return b;
} else {
return a;
}
}
// 枚举
enum Gender {
Male,
Female
}
interface Person{
gender: Gender
}
// 数组 -> number[] | Array<number>
function marry(a: Person, b: Person): [Person, Person] {
if(a.gender !== b.gender) {
return [a, b];
} else {
throw new Error('性别相同!');
}
}
let man = {gender: Gender.Male};
let woman = {gender: Gender.Female};
console.log(marry(man, woman));
console.log('min', min(1, 2));
console.log('add -> number', add(1, 2));
console.log('add -> string', add('1', '2'));
|
0bb77ba1bb00b18a348d78f69b58da9c7c4543a1
|
TypeScript
|
lorefnon/vulcyn
|
/src/expr/Update.ts
| 3.296875
| 3
|
import { Expr, PickExpr } from "./Expr";
import { Infix } from "./Infix";
import { ReductionContext } from "./ReductionContext";
import { SQLFragment } from "./SQLFragment";
import { Where } from "./Where";
/**
* An array of updates.
*
* This type requires that at least one update be defined (since
* `UPDATE ... SET WHERE ...` is not a valid query).
*/
export type UpdatesArray = [Infix<"=">, ...Array<Infix<"=">>];
export class Update extends Expr<"update"> {
// NOTE: These need to be public have non-null assertions to allow PickExpr to work.
readonly tableName!: SQLFragment;
readonly updates!: UpdatesArray;
readonly where!: Where;
constructor(args: PickExpr<Update>) {
super("update");
Object.assign(this, args);
if (this.updates.length === 0) {
throw new Error(`Cannot construct an Update Expr with zero updates.`);
}
}
toSQL(context: ReductionContext): string {
return (
"UPDATE" +
this.tableNameSQL(context) +
this.updatesSQL(context) +
this.whereSQL(context) +
";"
);
}
private tableNameSQL(rc: ReductionContext) {
return " " + this.tableName.toSQL(rc);
}
private updatesSQL(rc: ReductionContext) {
return " SET " + this.updates.map((infix) => infix.toSQL(rc)).join(", ");
}
private whereSQL(rc: ReductionContext): string {
if (this.where) {
return " " + this.where.toSQL(rc);
}
return "";
}
}
|
6c4e17742cabc7964662001a8cfe87a0d334504d
|
TypeScript
|
piotrszyma/studies-system-security-2
|
/server/crypto/hash.ts
| 3.03125
| 3
|
import * as crypto from 'crypto';
const R = '0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001';
/**
* Creates a string of int modulo R of BigInt from sha3-512 hash.
*/
export function stringifiedIntHashOf(value: string): string {
const hasher = crypto.createHash('sha3-512');
hasher.update(value);
const msgHash = hasher.digest('hex');
const r = BigInt(R);
const hashInt = BigInt('0x' + msgHash);
const stringifiedIntValue = (hashInt % r).toString();
return stringifiedIntValue;
}
export function hashOf(value: string, mode = 'sha3-256') {
const hasher = crypto.createHash(mode);
hasher.update(value);
return hasher.digest();
}
|
af4c1fd46d1cca190dc22804f18d8fc39c0775a9
|
TypeScript
|
zsiegel92/mitzvah_scheduler
|
/mitzvah/src/app/DoubleDate.ts
| 2.96875
| 3
|
import * as Hebcal from 'hebcal';
import {NgbDateStruct} from '@ng-bootstrap/ng-bootstrap';
const now = new Date();
export class DoubleDate {
greg: NgbDateStruct;
hyear: number;
hmonth: number;
hdate: number;
hday: number;
hdays_in_month: number;
hgregorian: Date;
hgregorian_eve: Date;
hdate_str: string;
hdate_str_heb: string;
holidays: any[];
// selfdict: {"Gregorian Date": NgbDateStruct,
// "Hebrew Date (Roman)": string,
// "Hebrew Date (Hebrew)": string,
// "Number of days in (Hebrew) month": number,
// "Gregorian Date (backconverted)": string,
// "Gregorian Date Eve (backconverted)": string};
getGreg(){
return this.greg;
}
update() {
var heb = new Hebcal.HDate(new Date(this.greg.year, this.greg.month-1, this.greg.day));
this.hyear = heb.getFullYear();
this.hmonth = heb.getMonth();
this.hdate = heb.getDate();
this.hday = heb.getDay();
this.hdays_in_month = heb.daysInMonth();
this.hgregorian = heb.greg();
this.hgregorian_eve = heb.gregEve();
this.hdate_str = heb.toString();
this.hdate_str_heb= heb.toString('h');
this.holidays= heb.holidays(); //Try holidays(all)
// this.to_dict();
}
to_dict(){
return {"Gregorian Date":this.greg,
"Hebrew Date (Roman)":this.hdate_str,
"Hebrew Date (Hebrew)":this.hdate_str_heb,
"Number of days in (Hebrew) month":this.hdays_in_month,
"Gregorian Date (backconverted)":this.hgregorian.toString(),
"Gregorian Date Eve (backconverted)": this.hgregorian_eve.toString()}
}
thirteen_ago(){
this.greg = {year: now.getFullYear()-13,month: now.getMonth()+1,day:now.getDate()}
this.update();
}
//"If any values are out of range, e.g. the 31st of Nisan, convert them to proper values, i.e. 1st of Iyyar."
thirteen_from_h(gdate: NgbDateStruct){
var heb = new Hebcal.HDate(new Date(gdate.year, gdate.month-1, gdate.day));
var future = new Hebcal.HDate(heb.getDate(),heb.getMonth(),heb.getFullYear() + 13).onOrAfter(6).greg();
this.greg={year: future.getFullYear(),month: future.getMonth()+1,day:future.getDate()}
this.update();
}
thirteen_from_now(){
var heb = new Hebcal.HDate(new Date(this.greg.year, this.greg.month-1, this.greg.day));
var future = new Hebcal.HDate(heb.getDate(),heb.getMonth(),heb.getFullYear() + 13).onOrAfter(6).greg();
this.greg={year: future.getFullYear(),month: future.getMonth()+1,day:future.getDate()}
this.update();
}
copy_dd(other: DoubleDate){
this.greg={...other.greg};
// this.greg = JSON.parse(JSON.stringify(other.greg));
this.update();
}
copy_ngb(other: NgbDateStruct){
this.greg={year: other.year,month: other.month,day:other.day}
this.update();
}
copy_ngb_ducktype(other: any){
this.greg={year: other.year,month: other.month,day:other.day}
this.update();
}
selectThisWeek() {
this.greg = {year: now.getFullYear(), month: now.getMonth()+1, day: now.getDate() + 6 - (now.getDay() % 7)};
this.update();
}
constructor(){
this.selectThisWeek();
}
}
|
98f4d1b3b55d67f1f5b77adea74fbdf7fb431187
|
TypeScript
|
AkramiPro/persian-tools
|
/src/helpers/index.ts
| 2.90625
| 3
|
export const trim = (str: string): string => str.replace(/^\s+|\s+$/g, "");
interface ReplaceArrayDictionary {
[key: string]: string;
}
export const replaceArray = (string: string, find: ReplaceArrayDictionary): string => {
const pattern = new RegExp(Object.keys(find).join("|"), "gi");
return string.replace(pattern, (matched) => find[matched] as string);
};
|
6ccef4f0e559016b22bc76f6f295c4ea7db3b678
|
TypeScript
|
jsalazar7/react-class-project
|
/vote-app/src/models/elections/Election.ts
| 2.6875
| 3
|
export type Election = {
id: number,
title: string,
questions: QuestionEntry[],
voters: number[],
}
export type QuestionEntry = {
id: number,
question: string,
yes: number, // Total number of 'yes' responses
}
export type ElectionKeys = 'id' | 'title' | 'questions';
export type NewElection = Omit<Election, 'id'>;
|
e09289df48b763f34ada678f8b2babb82d195bc3
|
TypeScript
|
ceefour/webiny-js
|
/packages/api-security-tenancy/src/crud/paginateBatch.ts
| 2.859375
| 3
|
type TItem = Record<string, any>;
export const paginateBatch = async <T = TItem>(
items: T[],
perPage: number,
execute: (items: T[]) => Promise<any>
) => {
const pages = Math.ceil(items.length / perPage);
for (let i = 0; i < pages; i++) {
await execute(items.slice(i * perPage, i * perPage + perPage));
}
};
|
9715d405bafdfed76ea56a67194cb877c5f54f44
|
TypeScript
|
fc7/astronomia
|
/src/node.d.ts
| 2.6875
| 3
|
/**
* @copyright 2013 Sonia Keys
* @copyright 2016 commenthol
* @license MIT
* @module node
*/
export = node;
export as namespace node;
declare module node {
/**
* EllipticAscending computes time and distance of passage through the ascending node of a body in an elliptical orbit.
* Argument axis is semimajor axis in AU, ecc is eccentricity, argP is argument
* of perihelion in radians, timeP is time of perihelion as a jd.
* Result is jde of the event and distance from the sun in AU.
*/
function ellipticAscending(axis: number, ecc: number, argP: number, timeP: number): [number, number];
/**
* EllipticAscending computes time and distance of passage through the descending node of a body in an elliptical orbit.
* Argument axis is semimajor axis in AU, ecc is eccentricity, argP is argument
* of perihelion in radians, timeP is time of perihelion as a jd.
* Result is jde of the event and distance from the sun in AU.
*/
function ellipticDescending(axis: number, ecc: number, argP: number, timeP: number): [number, number];
/**
* ParabolicAscending computes time and distance of passage through the ascending node of a body in a parabolic orbit.
* Argument q is perihelion distance in AU, argP is argument of perihelion
* in radians, timeP is time of perihelion as a jd.
* Result is jde of the event and distance from the sun in AU.
*/
function parabolicAscending(q: number, argP: number, timeP: number): [number, number];
/**
* ParabolicDescending computes time and distance of passage through the descending node of a body in a parabolic orbit.
* Argument q is perihelion distance in AU, argP is argument of perihelion
* in radians, timeP is time of perihelion as a jd.
* Result is jde of the event and distance from the sun in AU.
*/
function parabolicDescending(q: number, argP: number, timeP: number): [number, number];
}
|
808bda891a58ade508b9bdffd56caa32a4965dc6
|
TypeScript
|
ILovePug/udemy-express-ts
|
/src/controllers/decorators/controller.ts
| 2.828125
| 3
|
import 'reflect-metadata'
import { AppRouter } from '../../utili/AppRouter'
import { Methods } from './Methods'
import { MetadataKeys } from './MetadataKeys'
import {Request, Response, RequestHandler, NextFunction } from 'express';
function bodyValidators(keys: string):RequestHandler{
return function(req: Request, res: Response, next: NextFunction){
console.log(req.body)
if(!req.body){
return res.status(422).send('Invalid request');
}
for (const key of keys) {
if(!req.body[key]){
return res.status(422).send(`${key} is required`);
}
}
next();
}
}
function errorHandlerWrapper(route: RequestHandler){
return function(req: Request, res: Response, next: NextFunction){
try {
route(req, res,next)
} catch (error) {
const { url, method, body, params, headers } = req;
console.log({ url, method, body, params, headers })
console.log('error end, make sure implement error log')
next(error);
}
}
}
export function controller(routePrefix:string){
return function(target: Function){
const router= AppRouter.getInstance();
for (const key in target.prototype) {
const routeHandler = target.prototype[key];
const path: string = Reflect.getMetadata(MetadataKeys.path,target.prototype,key)
const method: Methods = Reflect.getMetadata(MetadataKeys.method,target.prototype,key)
//array of middlewares
const middlewares = Reflect.getMetadata(MetadataKeys.middleware,target.prototype,key) || []
const requiredBodyProps = Reflect.getMetadata(MetadataKeys.validator,target.prototype,key)
let validator:RequestHandler[]= [];
if(requiredBodyProps) validator.push(bodyValidators(requiredBodyProps)) ;
if(path){
//spread the middlewares so it can be all applied before the final router handler
router[method](`${routePrefix}${path}`, ...middlewares,...validator, errorHandlerWrapper(routeHandler))
}
}
}
}
|
7a90767729cc7dee364980419cf6ab12dc48afe6
|
TypeScript
|
theLAZYmd/election
|
/src/Voter.ts
| 3.015625
| 3
|
import { Vote } from "./VoteInterfaces";
import Race from './Race';
import { Threshold } from "./ElectionInterfaces";
export default class Voter {
static properties: string[] = [];
static thresholds: Threshold<Voter>[] = []
public id: string = '';
public name: string = '';
public votes: {
[key: string]: Vote
} = {};
public races?: string[];
public active?: boolean;
[key: string]: any;
constructor(voter: Voter) {
this.id = voter.id;
this.name = voter.name;
for (let p of Voter.properties) {
this[p] = voter[p];
}
}
static setTransferredProperties(properties: string[]) {
Voter.properties = properties;
}
static setThresholds(thresholds: Threshold<Voter>[]) {
Voter.thresholds = thresholds;
}
public registerEligible(race: Race): boolean {
for (let threshold of Voter.thresholds) {
if (!threshold.validate(this, race)) {
if (this.votes[race.id]) delete this.votes[race.id];
return false;
};
}
this.votes[race.id] = null as unknown as Vote;
return true;
}
public deregisterEligible(raceID: string): void {
if (this.votes[raceID]) delete this.votes[raceID];
}
public isEligible(raceID: string) {
return raceID in this.votes;
}
public disqualify(raceID?: string) {
if (raceID) {
if (!(raceID in this.votes)) throw `Voter ${name} was not eligible for race ${raceID}`;
delete this.votes[raceID];
} else {
for (let race of Object.keys(this.votes)) {
delete this.votes[race];
}
}
}
public addVote(raceID: string, vote: Vote) {
if (!(raceID in this.votes)) throw `Voter ${name} is not eligible for race ${raceID}`;
this.votes[raceID] = vote;
}
}
|
a0cb502e176c05d69af1be0ecd5d6e8d366a3d6f
|
TypeScript
|
jamalashraf0406/Angular
|
/my-account/src/app/logging.service.ts
| 2.734375
| 3
|
/**
* Here we didn't use @Injectable() decorator because
* we are not going to inject any service into this service.
*
* */
export class LoggingService {
logStatusChanged(status: string) {
console.log("A server status changed, new status: "+ status);
}
}
|
5db73c6341c851c72a1eb65c219f7be91832e12a
|
TypeScript
|
michael-dean-haynie/rtmpg
|
/api/src/utilities/logger.ts
| 3.15625
| 3
|
import config from '../config';
export class Logger {
private static logLevelMatches(level: LogLevel): boolean {
const levelPriority = LogLevelMapping.get(level) || 0;
const configuredPriority = LogLevelMapping.get(config.app.logLevel) || 0;
return levelPriority <= configuredPriority;
}
private static log(message: string) {
console.log(`${new Date().toLocaleTimeString()} ${message}`);
}
static error(message: string) {
if (this.logLevelMatches('error')) {
this.log(`<app-error> ${message}`);
}
}
static warning(message: string) {
if (this.logLevelMatches('warning')) {
this.log(`<app-warning> ${message}`);
}
}
static info(message: string) {
if (this.logLevelMatches('info')) {
this.log(`<app-info> ${message}`);
}
}
static debug(message: string) {
if (this.logLevelMatches('debug')) {
this.log(`<app-debug> ${message}`);
}
}
static trace(message: string) {
if (this.logLevelMatches('trace')) {
this.log(`<app-trace> ${message}`);
}
}
}
export type LogLevel = 'error' | 'warning' | 'info' | 'debug' | 'trace';
export const LogLevelMapping: Map<LogLevel, number> = new Map([
['error', 1],
['warning', 2],
['info', 3],
['debug', 4],
['trace', 5]
]);
|
9b480566262a0f9f0d93ee879ac069169de6d8be
|
TypeScript
|
gungunfebrianza/Belajar-Dengan-Jenius-DenoTheWKWKLand
|
/src/ch3-subchapter5/check-type/typeof.ts
| 3.1875
| 3
|
const map1 = new Map();
const array = ["Hi", "Maudy"];
const object1 = {};
function reflect(param: any): any {
return param;
}
console.log(typeof map1);
console.log(typeof array);
console.log(typeof object1);
console.log(typeof reflect(() => {}));
/*
object
object
object
function
*/
|
60ae30365588325961ff468b0c3861aeed66a91e
|
TypeScript
|
webdonalds/jmt-server
|
/src/services/socket.ts
| 2.6875
| 3
|
import WebSocket from 'ws';
import { Event } from '../events';
import logger from '../logger';
export class SocketService {
private sockets = new Map<string, WebSocket>();
register(clientId: string, socket: WebSocket): void {
logger.info(`socket registered: ${clientId}`);
this.sockets.set(clientId, socket);
}
unregister(clientId: string): void {
logger.info(`socket unregistered: ${clientId}`);
this.sockets.delete(clientId);
}
publishEvent(socketId: string, event: Event): void {
this.sockets.get(socketId)?.send(event.toMessage());
}
broadcastEvent(event: Event): void {
const message = event.toMessage();
this.sockets.forEach((socket) => { socket.send(message); });
}
}
|
bb22fb1b9e9366e9c7197a38c2fb38e1447a7fe5
|
TypeScript
|
pmdartus/shader-experiments
|
/shader-preview/src/core/graph/GraphNode.ts
| 3.109375
| 3
|
import { uuid } from "../../utils/uuid";
import { Vec2 } from "../types";
import Graph from "./Graph";
import Input from "./Input";
import Output from "./Output";
import Property from "./Property";
import Connection from "./Connection";
export default class GraphNode {
id: string;
graph: Graph;
title: string;
position: Vec2 = [0, 0];
inputs = new Map<string, Input>();
outputs = new Map<string, Output>();
properties = new Map<string, Property>();
constructor({ graph, title }: { graph: Graph; title: string }) {
this.id = uuid();
this.graph = graph;
this.title = title;
}
setPosition(position: Vec2) {
this.position = position;
}
getConnections(): Connection[] {
const inputConnections = [...this.inputs.values()]
.map((input) => input.getConnection())
.filter((connection) => connection !== null) as Connection[];
const outputConnections = [...this.outputs.values()].flatMap((output) =>
output.getConnections()
);
return [...inputConnections, ...outputConnections];
}
addInput(input: Input) {
const { name } = input;
if (this.inputs.has(name)) {
throw new Error(`Input with name "${name}" already exists.`);
}
this.inputs.set(name, input);
}
getInput<T = unknown>(name: string): Input<T> | undefined {
return this.inputs.get(name) as Input<T> | undefined;
}
removeInput(input: Input) {
const { name } = input;
const actualInput = this.inputs.get(name);
if (input !== actualInput) {
throw new Error(
`Invalid input parameter, input with name ${name} maps to another Input instance.`
);
}
input.removeConnection();
this.inputs.delete(name);
}
addOutput(output: Output) {
const { name } = output;
if (this.inputs.has(name)) {
throw new Error(`Output with name "${name}" already exists.`);
}
this.outputs.set(name, output);
}
getOutput<T>(name: string): Output<T> | undefined {
return this.outputs.get(name) as Output<T> | undefined;
}
removeOutput(output: Output) {
const { name } = output;
const actualOutput = this.outputs.get(name);
if (output !== actualOutput) {
throw new Error(
`Invalid output parameter, output with name ${name} maps to another Output instance.`
);
}
output.removeConnections();
this.outputs.delete(output.name);
}
}
|
4fd5063bc186ad90eb2ec7feb86e06a0266e1953
|
TypeScript
|
gaaoge/GGCat
|
/src/game/Cat.ts
| 2.671875
| 3
|
/**
*
* @author GG on 15-06-30
*
*/
module game {
export class Cat extends egret.Sprite {
public node: Node;
private isWeizhu: boolean;
private staymc: egret.MovieClip;
private weizhumc: egret.MovieClip;
public constructor() {
super();
this.staymc = Utils.createMC('stay');
this.weizhumc = Utils.createMC('weizhu');
this.anchorX = 0.5;
this.anchorY = 1;
this.stay();
}
/*站定*/
public stay() {
this.isWeizhu = false;
this.removeChildren();
this.addChild(this.staymc);
this.staymc.play(-1);
}
/*围住*/
public weizhu() {
this.isWeizhu = true;
this.removeChildren();
this.addChild(this.weizhumc);
this.weizhumc.play(-1);
}
/*行走*/
public run(node:Node) {
this.node = node;
this.x = node.x;
this.y = node.y;
}
}
}
|
c949e4d557f19c0274855d639d648b9476dddd2b
|
TypeScript
|
Skatteetaten/frontend-components
|
/src/components/OpenClose/OpenClose.types.ts
| 2.9375
| 3
|
export interface OpenCloseProps {
/** If the content aria should be open/visible */
isOpen?: boolean;
/** Callback when opened (not when closed) */
onClick?: (...args: any[]) => any;
/** Button title */
title?: string;
/** If the title should be a wrapped in a heading tag, value 1-7 .*/
headingLevel?: number;
/** By default er ikonet for åpning til venstre. Kan overstyres med iconRight: true. */
iconRight?: boolean;
/**
* If true, onClick is fired only on open. If false, onClick is fired both on open and close
* @default true
*/
isOnClickOnlyFiredOnOpen?: boolean;
/** Display as a compact version with smaller font size and margins */
compact?: boolean;
/** Custom classNames for å overskrive styling */
customClassNames?: {
wrapper?: string;
button?: string;
content?: string;
};
/** Show text underline or not */
underline?: boolean;
/** Elements that are shown/hidden.*/
children?: JSX.Element;
}
|
3b65dc39d5b9bcd7bc2863c40dc9a712740ffbf4
|
TypeScript
|
dpinol/botonic
|
/packages/botonic-plugin-contentful/src/util/objects.ts
| 3.546875
| 4
|
// eslint-disable-next-line @typescript-eslint/ban-types
export function shallowClone<T extends object>(obj: T): T {
if (obj == undefined) {
return obj
}
//https://stackoverflow.com/a/28152032/145289 create copies the methods
const clone = Object.create(obj)
// without copying prototype, some fields (maybe the enums?) are not available in object
// TODO try this let clone = Object.assign( Object.create( Object.getPrototypeOf(orig)), orig)
// from https://stackoverflow.com/a/44782052/145289
for (const prop in Object.getPrototypeOf(clone)) {
clone[prop] = Object.getPrototypeOf(clone)[prop]
}
return clone as T
}
/**
* Deep copy function for TypeScript.
* @param T Generic type of target/copied value.
* @param target Target value to be copied.
* @see Source project, ts-deepcopy https://github.com/ykdr2017/ts-deepcopy
* @see Code pen https://codepen.io/erikvullings/pen/ejyBYg
*/
// eslint-disable-next-line @typescript-eslint/ban-types
export const deepClone = <T>(target: T, alreadyCloned: object[] = []): T => {
if (alreadyCloned.includes(target as any)) {
return target
}
alreadyCloned.push(target as any)
if (target === undefined) {
return target
}
if (target instanceof Date) {
return new Date(target.getTime()) as any
}
if (target instanceof Array) {
const cp = [] as any[]
;(target as any[]).forEach(v => {
cp.push(v)
})
return cp.map((n: any) => deepClone<any>(n, alreadyCloned)) as any
}
if (typeof target === 'object' && target !== {}) {
const cp = { ...(target as { [key: string]: any }) } as {
[key: string]: any
}
Object.keys(cp).forEach(k => {
cp[k] = deepClone<any>(cp[k], alreadyCloned)
})
return cp as T
}
return target
}
export interface Equatable {
equals(other: Equatable): boolean
}
export interface Stringable {
toString(): string
}
export interface ValueObject extends Equatable, Stringable {}
|
35ca9e9ae07f97a36457fe3ffd63a80084fc1f90
|
TypeScript
|
michaelcoxon/utilities
|
/src/Enumerators/AggregateEnumerator.spec.ts
| 3.328125
| 3
|
import { Collection } from '../../src/Enumerables';
import AggregateEnumerator from '../../src/Enumerators/AggregateEnumerator';
import isNumber from '../../src/TypeHelpers/isNumber';
describe("AggregateEnumerator.constructor", () =>
{
it("should return an enumerator from a collection", () =>
{
const array1 = [1, 2, 3, 4];
const expected = [1, 3, 6, 10];
const coll1 = new Collection<number>(array1);
const en = new AggregateEnumerator(coll1.getEnumerator(), (a, c) => a + c, 0);
let count = 0;
while (en.moveNext())
{
expect(expected[count]).toEqual(en.current);
count++;
}
});
it("should return an enumerator from a collection dev should handle nulls or use initialValue", () =>
{
const array1 = [1, 2, 3, 4];
const expected = [1, 3, 6, 10];
const coll1 = new Collection<number>(array1);
const en = new AggregateEnumerator(coll1.getEnumerator(), (a, c) => isNumber(a) ? a + c : c);
let count = 0;
while (en.moveNext())
{
expect(expected[count]).toEqual(en.current);
count++;
}
});
});
describe("AggregateEnumerator.peek", () =>
{
it("should return the next item in the enumerator without advancing", () =>
{
const array1 = [1, 2, 3, 4];
const expected = [1, 3, 6, 10];
const coll1 = new Collection<number>(array1);
const en = new AggregateEnumerator(coll1.getEnumerator(), (a, c) => a + c, 0);
let count = 0;
expect(1).toEqual(en.peek());
while (en.moveNext())
{
expect(expected[count]).toEqual(en.current);
count++;
}
});
it("should throw an execption when cannot peek", () =>
{
const array1 = [1, 2, 3, 4];
const expected = [1, 3, 6, 10];
const coll1 = new Collection<number>(array1);
const en = new AggregateEnumerator(coll1.getEnumerator(), (a, c) => a + c, 0);
let count = 0;
while (en.moveNext())
{
expect(expected[count]).toEqual(en.current);
count++;
}
try
{
en.peek();
fail(); //assert.fail(undefined, undefined, "Should not be able to see past end of enumerable");
} catch (ex) {
//do nothing
}
});
});
describe("AggregateEnumerator.reset", () =>
{
it("should move to the start of the enumerator", () =>
{
const array1 = [1, 2, 3, 4];
const expected = [1, 3, 6, 10];
const coll1 = new Collection<number>(array1);
const en = new AggregateEnumerator(coll1.getEnumerator(), (a, c) => a + c, 0);
let count = 0;
while (en.moveNext())
{
expect(expected[count]).toEqual(en.current);
count++;
}
en.reset();
count = 0;
while (en.moveNext())
{
expect(expected[count]).toEqual(en.current);
count++;
}
});
});
|
88ec70b8deef0edcfe2023de806c474e5cc968da
|
TypeScript
|
danidre14/char
|
/tests/isControl.test.ts
| 2.546875
| 3
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// https://github.com/dotnet/runtime/blob/master/src/libraries/System.Runtime/tests/System/CharTests.cs
import { isControl, UnicodeCategory } from '../src';
import { display, getTestChars, getTestCharsNotInCategory } from './lib/common';
describe('isControl', () => {
const categories = [UnicodeCategory.Control];
for (const code of getTestChars(...categories)) {
test(`GIVEN ${display(code)} THEN shows true`, () => {
expect(isControl(code)).toBe(true);
});
}
for (const code of getTestCharsNotInCategory(...categories)) {
test(`GIVEN ${display(code)} THEN shows false`, () => {
expect(isControl(code)).toBe(false);
});
}
});
|
83484bc014ea006b80ab84ee344a095e8a2dcecf
|
TypeScript
|
benwainwright/hue-build-status
|
/client.spec.ts
| 2.609375
| 3
|
import { HueClient, DEVICE_TYPE } from "./client";
import nock from "nock";
beforeEach(() => {
nock.disableNetConnect();
});
afterEach(() => {
nock.cleanAll();
nock.enableNetConnect();
});
describe("the hue client", () => {
describe("get", () => {
it("if no password is passed in, it gets one from the bridge and uses it in the request, then returns the response", async () => {
const testUsername = "foo-username";
const bridge = nock("http://123.123.123.123");
bridge.post("/api", `{"devicetype":"${DEVICE_TYPE}"}`).reply(200, [
{
success: {
username: testUsername
}
}
]);
const expectedResult = { foo: "bar" };
bridge.get(`/api/${testUsername}/foo-bar`).reply(200, expectedResult);
const client = new HueClient("123.123.123.123");
const actual = await client.get("/foo-bar");
expect(actual).toEqual(expectedResult);
});
});
describe("post", () => {
it("if no password is passed in, it gets one from the bridge and uses it in the request, then returns the response", async () => {
const testUsername = "foo-username";
const bridge = nock("http://123.123.123.123");
bridge.post("/api", `{"deviceType":"${DEVICE_TYPE}"}`).reply(200, [
{
success: {
username: testUsername
}
}
]);
const expectedResult = { foo: "bar" };
bridge
.post(`/api/${testUsername}/foo-bar`, { foo: "bar" })
.reply(200, expectedResult);
const client = new HueClient("123.123.123.123");
const actual = await client.post("/foo-bar", { foo: "bar" });
expect(actual).toEqual(expectedResult);
});
});
});
|
8a6b74c1399b2aa2e9bb6a28a5d7eb5403b09645
|
TypeScript
|
Nikpds/Gamerules
|
/src/app/order/order.ts
| 2.515625
| 3
|
export class Filter {
sortOrder: boolean;
sortField: string;
search: string;
searchField: string;
results = 20;
orderStatus: number[];
constructor() {
this.orderStatus = new Array<number>();
}
}
export class FilteredData<T> {
filters: Filter;
data: Array<T>;
constructor() {
this.data = new Array<T>();
this.filters = new Filter();
}
}
|