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
|
|---|---|---|---|---|---|---|
1bd263c250a943620f400a7de1f54f2d646d67f7
|
TypeScript
|
mysticatea/bre
|
/test/utils/get-data-view.ts
| 2.59375
| 3
|
import assert from "assert"
import { defineObjectRecord, getDataView } from "../../src/index"
describe("getDataView", () => {
it("should return DataView object.", () => {
const TestRecord = defineObjectRecord("TestRecord", {
a: "int8",
b: "int8",
})
const buffer = Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05])
const record = TestRecord.view(buffer, 1)
const dv = getDataView(record)
assert.strictEqual(dv.byteLength, 2)
assert.strictEqual(dv.getInt8(0), 2)
assert.strictEqual(dv.getInt8(1), 3)
})
})
|
470f5e31f62b697a63b940bc1c750338db06f9b3
|
TypeScript
|
Marissa99/GIS-SoSe-2021
|
/2.3DomEvents/script2.ts
| 3.09375
| 3
|
namespace Aufgabe2_3 {
//Aufgabe 3
//a)Startsteite.html und Waffel.html Datei hart gecodet und style.css
//b) Daten in der data.ts (canvas) und style.css
//--> da die verschiedenen Auswahlmöglichkeiten in canvas gespeichert werden, ist die Anzahl variabel
//c) script2.ts Datei
//Ich weiß dass die drei Funktionen 'Save' so sicher nicht gedacht waren, jedoch bin ich einfach auf keine einfachere Lösung gekommen.
//Ich speichere zwar meine Auswahl in einem Array kann, dies aber dann nur ganz am Ende ausgeben, wenn ich mein ganzes Interface Eis übergeben kann.
let button1: HTMLCanvasElement = <HTMLCanvasElement> document.getElementById("Auswahl1");
button1.addEventListener("click", Save1);
let button2: HTMLCanvasElement = <HTMLCanvasElement> document.getElementById("Auswahl2");
button2.addEventListener("click", Save2);
let button3: HTMLCanvasElement = <HTMLCanvasElement> document.getElementById("Auswahl3");
button3.addEventListener("click", Save3);
function Save1 (_speichern: Event): void {
//console.log(_speichern); //hier würde die Auswahl in Objekt Waffel und dann in das gesamte Objekt Eis gespeichert werden
zeigeInfos((0));
}
function Save2 (_speichern: Event): void {
//console.log(_speicher); //hier würde die Auswahl in das Objekt Eis gespeichert werden
zeigeInfos((1));
}
function Save3 (_speichern: Event): void {
//console.log(_speichern); //hier würde die Auswahl in das Objekt Eis gespeichert werden
zeigeInfos((2));
}
function zeigeInfos (_index: number): void {
console.log("Gewählte Waffel:" + alleWaffeln[_index].farbe);
}
}
|
41a681094899167bb8dbc72687c06f33d4ca0eb0
|
TypeScript
|
arthurgehrke/shopify-clean-microservice
|
/src/data/usecases/client-get-products.spec.ts
| 2.75
| 3
|
import { ClientGetProducts } from '@/data/usecases/client-get-products';
import {
HttpClient,
HttpRequest,
HttpResponse,
HttpStatusCode
} from '@/data/protocols/http/http-client';
// import { ProductModel } from '@/domain/models/product';
// import { mockClientGetProducts } from '@/data/tests/mocks/client-get-products';
import { ShopifyProductsResponse } from '@/data/helpers/serializers/shopify-products-serializer';
import faker from 'faker';
class HttpClientSpy<R = any> implements HttpClient<R> {
url?: string;
method?: string;
body?: any;
headers?: any;
response: HttpResponse<R> = {
statusCode: HttpStatusCode.ok
};
async request(data: HttpRequest): Promise<HttpResponse<R>> {
this.url = data.url;
this.method = data.method;
this.body = data.body;
this.headers = data.headers;
return this.response;
}
}
type SutTypes = {
sut: ClientGetProducts;
httpClientSpy: HttpClientSpy<ShopifyProductsResponse>;
};
const makeSut = (url: string): SutTypes => {
const httpClientSpy = new HttpClientSpy<ShopifyProductsResponse>();
const sut = new ClientGetProducts(url, httpClientSpy);
return {
sut,
httpClientSpy
};
};
describe('ClientGetProducts', () => {
test('Should call HttpClient with correct url and method', async () => {
const url = faker.internet.url();
const { sut, httpClientSpy } = makeSut(url);
await sut.get();
expect(httpClientSpy.url).toBe(url);
expect(httpClientSpy.method).toBe('GET');
});
test('Should return an empty array if HttpClient returns 204', async () => {
const url = faker.internet.url();
const { sut, httpClientSpy } = makeSut(url);
httpClientSpy.response = {
statusCode: HttpStatusCode.noContent
};
const products = await sut.get();
expect(products).toEqual([]);
});
// test('Should return at least one ProductModel if HttpClient returns 200', async () => {
// const url = faker.internet.url();
// const { sut, httpClientSpy } = makeSut(url);
// const httpResult = mockClientGetProducts();
// httpClientSpy.response = {
// statusCode: HttpStatusCode.ok,
// body: {
// products: httpResult
// }
// };
// const products = await sut.get();
// expect(products.length).toBeGreaterThanOrEqual(1);
// expect(products[0]).toHaveProperty('id');
// expect(products[0]).toHaveProperty('name');
// expect(products[0]).toHaveProperty('price');
// expect(products[0]).toHaveProperty('showcaseImage');
// expect(products[0]).toHaveProperty('galleryImages');
// });
});
|
ebb8a22f91322d532ecdf6008f706d0b18cb58d6
|
TypeScript
|
massimocode/Pizza-website
|
/back-end/payment-gateways/factory.ts
| 2.578125
| 3
|
import { IRequest } from "../router/router-utils";
import PayPal, { IsPayPalEnabled } from "./paypal";
import BarclaysEPDQ, { IsBarclaysEPDQEnabled } from "./barclays-epdq";
import { PaymentGateway } from "./interfaces";
import Cash from "./cash";
import { PlaceOrderRequest, PaymentMethod } from "../../shared/dtos";
import CreditDebitCardInPerson, {
IsCreditDebitCardInPersonEnabled
} from "./credit-debit-card-in-person";
export function getPaymentGateway(
req: IRequest<PlaceOrderRequest>
): PaymentGateway {
let baseReturnAddress = req.protocol + "://" + req.get("host");
if (req.body.paymentMethod === "PayPal") {
return new PayPal(baseReturnAddress);
}
if (req.body.paymentMethod === "Credit / Debit Card") {
return new BarclaysEPDQ(baseReturnAddress);
}
if (req.body.paymentMethod === "Credit / Debit card (in person)") {
return new CreditDebitCardInPerson();
}
if (req.body.paymentMethod === "Cash") {
return new Cash();
}
throw new Error(
`No payment gateway registered for payment method ${req.body.paymentMethod}`
);
}
export function getAvailablePaymentMethods(): PaymentMethod[] {
let paymentMethods: PaymentMethod[] = ["Cash"];
if (IsPayPalEnabled) {
paymentMethods.push("PayPal");
}
if (IsCreditDebitCardInPersonEnabled) {
paymentMethods.push("Credit / Debit card (in person)");
}
if (IsBarclaysEPDQEnabled) {
paymentMethods.push("Credit / Debit Card");
}
return paymentMethods;
}
|
6d5b9d91ccfa2c2a18213d5d1053c6add144f1fe
|
TypeScript
|
whthT/deno-graphql-quickstart
|
/tests/cases/libUcwords.test.ts
| 2.625
| 3
|
import ucwords from "../../src/lib/ucwords.ts";
import {assertEquals} from "https://deno.land/std@0.92.0/testing/asserts.ts";
Deno.test("libUcwords works", () => {
const str = "musa kurt";
assertEquals(ucwords(str), "Musa Kurt");
});
Deno.test("libUcwords works with no string", () => {
const str = "";
assertEquals(ucwords(str), "");
});
|
b76bef372e3824e838fbb1e98d9483bf3c85e6bb
|
TypeScript
|
bakuzan/ayaka
|
/lib/createListeners.ts
| 2.53125
| 3
|
const createListeners =
(t: string, f: EventListenerOrEventListenerObject) =>
(el: HTMLElement | Document = document) => ({
listen: () => el.addEventListener(t, f),
remove: () => el.removeEventListener(t, f)
});
export default createListeners;
|
15ee836a479d1e42953320ba78024330f83b2138
|
TypeScript
|
vitorKogawa/backend_hackatran
|
/src/controllers/PerguntaController.ts
| 2.515625
| 3
|
import { Request, Response } from 'express'
import { getRepository } from 'typeorm'
import { Perguntas } from '../database/entity/Perguntas'
class PerguntaController {
async store(request: Request, response: Response){
const repository = getRepository(Perguntas)
const {
texto_pergunta,
infracao
} = request.body
const data = {
texto_pergunta,
infracao
}
const new_pergunta = repository.create(data)
await repository.save(new_pergunta)
return response.json(new_pergunta)
}
async index(request: Request, response: Response){
const repository = getRepository(Perguntas)
const all_perguntas = await repository.find()
if(all_perguntas.length <= 0)
return response.json({
message: 'Nenhuma pergunta cadastrada na base de dados.'
})
return response.json(all_perguntas)
}
}
export default new PerguntaController()
|
ee2b1ff84c3769d0167dd16a2b3bc816acb2916c
|
TypeScript
|
AllenFang/node-commander-pattern
|
/src/commandHandler/base.ts
| 2.703125
| 3
|
import * as EventEmitter from 'events';
import { injectable, decorate } from 'inversify';
type Handler = <T>(t: T) => void;
decorate(injectable(), EventEmitter);
@injectable()
class Base extends EventEmitter {
on(name: string, handler: Handler): this {
return this.addListener(name, handler);
}
}
export default Base;
|
d86f555ac8c309d0dc4bda908ebe84c53426c221
|
TypeScript
|
tedchoward/advent-of-code-2018
|
/src/10/interactive-visual.ts
| 2.9375
| 3
|
import readline from 'readline';
import { parseInput } from './parse-input';
import { Grid } from './grid';
function question(rl: readline.Interface, prompt: string): Promise<string> {
return new Promise((res, rej) => {
try {
rl.question(prompt, answer => {
res(answer);
});
} catch (err) {
rej(err);
}
});
}
export async function interactiveVisual(input: string) {
const points = parseInput(input);
const numPoints = points.length;
const grid = new Grid(points);
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
let char = '';
let count = 0;
while (char !== 'q') {
const touchingCount = grid.countTouching();
if (touchingCount >= numPoints / 2) {
grid.print();
console.log();
char = await question(rl, `Second: ${count}, Enter 'q' to quit: `);
} else {
if (count % 1000 === 0) {
console.log(count, touchingCount);
}
}
count += 1;
grid.move();
}
rl.close();
}
|
26e0eeacb0099b19ba324e79ebd90325cfeba82d
|
TypeScript
|
DeveloperFromUkraine/car-info-app
|
/src/components/filter/actions.ts
| 2.65625
| 3
|
import { Dispatch } from "redux";
import {
IActionGETFilters,
IActionSETSelectedFilters,
IFilterData,
ISetFilterData
} from "./types";
import { fetchColor, fetchManufacturers } from '../../api/filter-api/fetchFilters';
import { GET_FILTERS, SET_SELECTED_FILTERS } from '../../constants/actions';
export const getFilters = () => async (dispatch: Dispatch) => {
const [colors, manufacturers] = await Promise.all([ fetchColor(), fetchManufacturers() ]);
dispatch(filterData({ colors: colors.data.colors, manufacturers: manufacturers.data.manufacturers }))
}
const filterData = ({ colors, manufacturers }: IFilterData):IActionGETFilters => {
return {
type: GET_FILTERS,
payload: {
colors: colors.map((color: string) => color.charAt(0).toUpperCase() + color.slice(1)),
manufacturers: manufacturers.map(({ name }) => name)
}
}
}
export const setSelectedFilters = ({color, manufacturer}: ISetFilterData): IActionSETSelectedFilters => {
return {
type: SET_SELECTED_FILTERS,
payload: {
colorFilter: color,
manufacturerFilter: manufacturer
}
}
}
|
3b825e8fd1eb36d870797c54bf67446fc737a9f8
|
TypeScript
|
Samour/js-playground
|
/src/sudoku/board/service.ts
| 2.734375
| 3
|
import { Store } from 'redux';
import { SudokuState, SudokuCell } from './model';
import {
clearBoardEvent,
resetGameEvent,
focusCellEvent,
setCellValueEvent,
setCellFixedEvent,
lockAllValuesEvent,
setNoteModeEvent,
addCellPossibleEvent,
removeCellPossibleEvent,
setBoardStateEvent,
} from './events';
const proto = require('sudoku/protoc/board_pb');
export default class BoardService {
private store: Store<SudokuState>;
constructor(store: Store<SudokuState>) {
this.store = store;
}
public clearBoard() {
this.store.dispatch(clearBoardEvent());
}
public resetGame() {
this.store.dispatch(resetGameEvent());
}
public focusCell(x: number, y: number) {
this.store.dispatch(focusCellEvent(x, y));
}
public setCellVaue(x: number, y: number, value: number | null) {
this.store.dispatch(setCellValueEvent(x, y, value));
}
public setCellFixed(x: number, y: number, fixed: boolean) {
this.store.dispatch(setCellFixedEvent(x, y, fixed));
}
public lockAllValues() {
this.store.dispatch(lockAllValuesEvent());
}
public setNoteMode(mode: boolean) {
this.store.dispatch(setNoteModeEvent(mode));
}
public addCellPossible(x: number, y: number, value: number) {
this.store.dispatch(addCellPossibleEvent(x, y, value));
}
public removeCellPossible(x: number, y: number, value: number) {
this.store.dispatch(removeCellPossibleEvent(x, y, value));
}
public seralise(): Uint8Array {
const board = this.store.getState().board;
const boardPb = new proto.Board();
for (let x = 0; x < board.length; x++) {
for (let y = 0; y < board[x].length; y++) {
const cell = new proto.Cell();
cell.setValue(board[x][y].value);
cell.setFixed(board[x][y].fixed);
board[x][y].possible.forEach((i) => cell.addPossible(i));
boardPb.addCell(cell);
}
}
return boardPb.serializeBinary();
}
public deserialise(data: ArrayBuffer) {
const boardPb = proto.Board.deserializeBinary(data);
if (!boardPb.getCellList()?.length) {
return;
}
const board: SudokuCell[][] = [];
for (let x = 0; x < 9; x++) {
const col: SudokuCell[] = [];
board.push(col);
for (let y = 0; y < 9; y++) {
const cellPb = boardPb.getCellList()[x * 9 + y];
const cell = new SudokuCell();
cell.value = cellPb.getValue() || null;
cell.fixed = cellPb.getFixed();
cell.possible = new Set(cellPb.getPossibleList());
col.push(cell);
}
}
this.store.dispatch(setBoardStateEvent(board));
}
}
|
e1f580993782a68750e4546184c49a953d7d6892
|
TypeScript
|
Miczeq22/brainflash-api
|
/src/core/decks/deck/rules/user-should-assessed-deck.rule.ts
| 2.6875
| 3
|
import { BusinessRule } from '@core/shared/business-rule';
import { UniqueEntityID } from '@core/shared/unique-entity-id';
export interface DeckRateChecker {
isRatedByUser(userId: UniqueEntityID, deckId: UniqueEntityID): Promise<boolean>;
}
export class UserShouldAssessedDeckRule extends BusinessRule {
message = 'The Deck has not been assessed.';
constructor(
private readonly deckRateChecker: DeckRateChecker,
private readonly userId: UniqueEntityID,
private readonly deckId: UniqueEntityID,
) {
super();
}
public async isBroken() {
return !(await this.deckRateChecker.isRatedByUser(this.userId, this.deckId));
}
}
|
c67db202628a38b5d566e2606574ed1f82d36b4d
|
TypeScript
|
johnwschneider96/Project2
|
/AndreStuff/P2/src/app/PostModel.ts
| 2.71875
| 3
|
//postid, content, numoflikes, useremail
export class Posting{
postid: number;
content: string;
numoflikes: number;
useremail: string;
constructor(postid: number = 0, content: string = '',
numoflikes: number = 0, useremail: string = ''){
this.postid = postid;
this.content = content;
this.numoflikes = numoflikes;
this.useremail = useremail;
}
}
|
393924cee9c31d713d3aad805e8110d088a871b2
|
TypeScript
|
jeiea/autopilot-deno
|
/autopilot_deno/utils/wmic_data_parser.ts
| 2.546875
| 3
|
// Copyright 2020-present Divy Srivastava and friends. All rights reserved. MIT license.
function parse(yml: string) {
let arr = yml.split("\n");
let obj: any[] = [];
arr.forEach((element) => {
obj.push(element.split(":")[1]);
});
return obj;
}
export default function parseMonitorsWin(
info: string,
): string {
let result = parse(info);
let displayLength = 0;
// @ts-ignore
for (var i in result) {
// @ts-ignore
if (result[i]) {
// @ts-ignore
if (result[i].trim() == "") continue;
else displayLength++;
}
}
return makeParseableString(displayLength);
}
function makeParseableString(len: number) {
return `Monitors: ${len}`;
}
|
a8082e7b364b082d8c0d2a1bbeb1bcc0ec405e5f
|
TypeScript
|
djoepramono/ads-checkout-system
|
/src/services/adService.spec.ts
| 3.03125
| 3
|
import { getAdPriceFromSource, Ad, Advertisement } from './adService';
describe('getAdPriceFromSource', () => {
it('gets the first available price', () => {
const ad = Ad.PREMIUM;
const availableAds: Advertisement[] = [
{ ad: Ad.PREMIUM, name: 'Premium Level', description: 'Best in class with all known feature', retailPrice: 1000 },
{ ad: Ad.PREMIUM, name: 'Premium Level', description: 'Accidentally entered again', retailPrice: 999 },
];
const result = getAdPriceFromSource(ad, availableAds);
expect(result).toStrictEqual(1000);
});
// I don't really like handling error cases with Exception, but since we don't know what we need to do with edge
// cases, throwing Exception makes sense in this case
it('throws an exception if cannot find the price', () => {
const ad = Ad.CLASSIC;
const availableAds: Advertisement[] = [
{ ad: Ad.PREMIUM, name: 'Premium Level', description: 'Best in class with all known feature', retailPrice: 1000 },
{ ad: Ad.STANDOUT, name: 'Standout Level', description: 'Accidentally entered again', retailPrice: 999 },
];
expect(() => getAdPriceFromSource(ad, availableAds)).toThrowError('error: getAdPriceFromSource - Cannot read property \'retailPrice\' of undefined');
});
});
|
85f905d9b3fa1a5d2c7a4e97c17cb5d01ccb8941
|
TypeScript
|
dubanzl/e-evolution-prueba
|
/api/controllers/index.controller.ts
| 2.546875
| 3
|
import { Request, Response } from 'express'; // eslint-disable-line no-unused-vars
import { ObjectId } from 'mongodb';
import TaskModel from '../models/task.model';
class IndexController {
public async getTasks(req: Request, res: Response) {
const task: any = await TaskModel.getTasks(req.params.userId);
res.json(task);
}
public async registerTask(req: Request, res: Response) {
const { task } = req.body;
const data = {
name: task.name,
priority: task.priority,
description: task.description,
expirationDate: new Date(task.expirationDate),
status: 'Pendiente',
userId: new ObjectId(task.userId),
};
const result = await TaskModel.registerTask(data);
res.json(result);
}
public async updateTask(req: Request, res: Response) {
const { _id, name, priority, expirationDate, description } = req.body;
const result = await TaskModel.updateTask(
_id, name, priority, new Date(expirationDate), description,
);
res.json(result);
}
public async updateStatusTask(req: Request, res: Response) {
const { _id, status } = req.body;
const result = await TaskModel.updateStatusTask(_id, status);
res.json(result);
}
public async removeTask(req: Request, res: Response) {
const { _id } = req.body;
const result = await TaskModel.removeTask(_id);
res.json(result);
}
}
export default IndexController;
|
4f08f95b3238d1b3c4eb4b963e1587e647a2e96a
|
TypeScript
|
damiankoper/pipg
|
/src/core/models/Sokrates.model.ts
| 2.578125
| 3
|
import { Vector, Body, Engine } from "matter-js";
import * as PIXI from "pixi.js";
import AnimatedSprite from "./base/AnimatedSprite";
enum CharacterState {
Idle,
MovingLeft,
MovingRight,
}
export default class Sokrates extends AnimatedSprite {
private runSprite: PIXI.AnimatedSprite;
private idleSprite: PIXI.AnimatedSprite;
private jumpSprite: PIXI.AnimatedSprite;
private walkSprite: PIXI.AnimatedSprite;
private state: CharacterState;
private isInTheAir: boolean;
private stableCollTimeout?: number;
readonly runSpeed: number;
readonly walkSpeed: number;
private isShift: boolean;
constructor(position: Vector, scale: number) {
const runSprite = AnimatedSprite.createSprite(
"assets/spritesheets/b1_run.json"
);
const idleSprite = AnimatedSprite.createSprite(
"assets/spritesheets/b1_idle.json"
);
const jumpSprite = AnimatedSprite.createSprite(
"assets/spritesheets/b1_jump.json"
);
const walkSprite = AnimatedSprite.createSprite(
"assets/spritesheets/b1_walk.json"
);
super(position, scale, idleSprite, [
idleSprite,
runSprite,
jumpSprite,
walkSprite,
]);
Body.setInertia(this.body, Infinity);
this.body.sleepThreshold = -1;
this.state = CharacterState.Idle;
this.isInTheAir = false;
this.runSpeed = 6;
this.walkSpeed = 3;
this.isShift = false;
this.runSprite = runSprite;
this.idleSprite = idleSprite;
this.jumpSprite = jumpSprite;
this.walkSprite = walkSprite;
this.runSprite.animationSpeed = 0.25;
this.walkSprite.animationSpeed = 0.13;
this.idleSprite.loop = false;
this.jumpSprite.animationSpeed = 0.1;
this.jumpSprite.loop = false;
runSprite.pivot.x += 25 / scale;
walkSprite.pivot.x += 25 / scale;
walkSprite.pivot.y += 5 / scale;
walkSprite.scale.y *= 0.9;
jumpSprite.pivot.x += 25 / scale;
jumpSprite.pivot.y += 15 / scale;
jumpSprite.scale.x *= 0.9;
jumpSprite.scale.y *= 0.9;
}
setup(container: PIXI.Container, engine: Engine) {
super.setup(container, engine);
this.setEvents();
}
update() {
super.update();
switch (this.state) {
case CharacterState.Idle:
Body.setVelocity(
this.body,
Vector.create(
Math.min(this.body.velocity.x, this.runSpeed),
this.body.velocity.y
)
);
break;
case CharacterState.MovingRight:
Body.setVelocity(
this.body,
Vector.create(this.getSpeed(), this.body.velocity.y)
);
break;
case CharacterState.MovingLeft:
Body.setVelocity(
this.body,
Vector.create(-this.getSpeed(), this.body.velocity.y)
);
break;
}
this.updateDirection();
}
private getSpeed() {
return this.isShift ? this.runSpeed : this.walkSpeed;
}
private updateDirection() {
if (
Math.sign(this.body.velocity.x) != Math.sign(this.mainSprite.scale.x) &&
Math.round(Math.abs(this.body.velocity.x)) > 0
) {
this.sprites.forEach((s) => (s.scale.x *= -1));
}
}
setEvents() {
window.addEventListener("keydown", (e) => {
switch (e.key) {
case "Shift":
this.isShift = true;
break;
case "D":
case "d":
this.state = CharacterState.MovingRight;
break;
case "A":
case "a":
this.state = CharacterState.MovingLeft;
break;
case " ":
if (!this.isInTheAir) {
this.jumpSprite.gotoAndStop(0);
this.setMainSprite(this.jumpSprite);
setTimeout(() => {
Body.setVelocity(
this.body,
Vector.create(this.body.velocity.x, -10)
);
}, 100);
}
break;
}
this.changeSprite();
});
window.addEventListener("keyup", (e) => {
switch (e.key) {
case "Shift":
this.isShift = false;
break;
case "D":
case "d":
if (this.state == CharacterState.MovingRight)
this.state = CharacterState.Idle;
break;
case "A":
case "a":
if (this.state == CharacterState.MovingLeft) {
this.state = CharacterState.Idle;
}
break;
}
this.changeSprite();
});
}
onCollisionActive(body: Body) {
this.setInTheAir(body);
}
onCollisionStart(body: Body) {
this.setInTheAir(body);
}
private setInTheAir(body: Body) {
if (
Math.abs(this.body.bounds.max.y - body.bounds.max.y) > 10 &&
body.isSensor == false
) {
clearTimeout(this.stableCollTimeout);
this.isInTheAir = false;
this.changeSprite();
}
}
onCollisionEnd(body: Body) {
if (
Math.abs(this.body.bounds.max.y - body.bounds.max.y) > 10 &&
body.isSensor == false
) {
this.stableCollTimeout = setTimeout(() => {
this.isInTheAir = true;
this.changeSprite();
}, 50);
}
}
private changeSprite() {
if (this.isInTheAir) {
this.setMainSprite(this.jumpSprite);
} else
switch (this.state) {
case CharacterState.Idle:
this.setMainSprite(this.idleSprite);
break;
case CharacterState.MovingLeft:
case CharacterState.MovingRight:
if (this.isShift) this.setMainSprite(this.runSprite);
else this.setMainSprite(this.walkSprite);
break;
}
}
}
|
2dd001dec8f61bb57c4ded7db2cd10d5e93060c8
|
TypeScript
|
isaac-allef/e-terapias
|
/back-end/tests/presentation/controllers/Login.spec.ts
| 2.59375
| 3
|
import { LoginController } from '../../../src/presentation/controllers/LoginController';
import { MissingParamError } from '../../../src/presentation/erros/missingParamError';
import { HttpRequest } from '../../../src/presentation/protocols/http';
import AuthenticationService from '../../../src/core/services/AuthenticationService';
import {
LoadUserByEmailRepositoryStub,
UpdateAccessTokenRepositoryStub,
} from '../../core/mocks/mockUser';
import { HashCompareStub } from '../../core/mocks/mockCryptography';
import { TokenGeneraterStub } from '../../core/mocks/mockToken';
import {
ok,
serverError,
unauthorized,
} from '../../../src/presentation/helpers/httpHelder';
const makeFakeRequest = (): HttpRequest => ({
body: {
email: 'any_email@email.com',
password: 'any_password',
},
});
const makeAuthenticationService = (): AuthenticationService => {
const loadUserByEmailRepository = new LoadUserByEmailRepositoryStub();
const hashComparer = new HashCompareStub();
const tokenGenerater = new TokenGeneraterStub();
const updateAccessTokenRepository = new UpdateAccessTokenRepositoryStub();
return new AuthenticationService(
loadUserByEmailRepository,
hashComparer,
tokenGenerater,
updateAccessTokenRepository,
);
};
interface SutTypes {
sut: LoginController;
authenticationServiceStub: AuthenticationService;
}
const makeSut = (): SutTypes => {
const authenticationServiceStub = makeAuthenticationService();
const sut = new LoginController(authenticationServiceStub);
return {
sut,
authenticationServiceStub,
};
};
describe('Login controller', () => {
test('Should return 400 if no email is provided', async () => {
const { sut } = makeSut();
const httpRequest = {
body: {
password: 'any_password',
},
};
const httpResponse = await sut.handle(httpRequest);
expect(httpResponse.statusCode).toBe(400);
expect(httpResponse.body).toEqual(new MissingParamError('email'));
});
test('Should return 400 if no password is provided', async () => {
const { sut } = makeSut();
const httpRequest = {
body: {
email: 'any_email',
},
};
const httpResponse = await sut.handle(httpRequest);
expect(httpResponse.statusCode).toBe(400);
expect(httpResponse.body).toEqual(new MissingParamError('password'));
});
test('Should call Authentication with corret values', async () => {
const { sut, authenticationServiceStub } = makeSut();
const authSpy = jest.spyOn(authenticationServiceStub, 'execute');
await sut.handle(makeFakeRequest());
expect(authSpy).toHaveBeenCalledWith(
'any_email@email.com',
'any_password',
);
});
test('Should return 500 if AuthenticationService throws', async () => {
const { sut, authenticationServiceStub } = makeSut();
jest.spyOn(authenticationServiceStub, 'execute').mockImplementationOnce(
() => {
throw new Error('any error');
},
);
const httpResponse = await sut.handle(makeFakeRequest());
expect(httpResponse).toEqual(serverError(new Error()));
});
test('Should return 401 if invalid credentials are provided', async () => {
const { sut, authenticationServiceStub } = makeSut();
jest.spyOn(authenticationServiceStub, 'execute').mockReturnValueOnce(
new Promise(resolve => resolve(null)),
);
const httpResponse = await sut.handle(makeFakeRequest());
expect(httpResponse).toEqual(unauthorized());
});
test('Should return 200 if valid credentials are provided', async () => {
const { sut } = makeSut();
const httpResponse = await sut.handle(makeFakeRequest());
expect(httpResponse).toEqual(
ok({ id: 'randomIdUser', token: 'randomToken' }),
);
});
});
|
a7b09517d0adefa7cc4d086bce7f9d28109d5333
|
TypeScript
|
pictasses/beluga-v2-api-server
|
/app/model/user/update_last_activity_date.ts
| 2.59375
| 3
|
import { ModelRuntimeError } from "../error"
import mongoose from "mongoose"
import * as vs from "../../validation"
import { get as get_user } from "../user/get"
export const ErrorCodes = {
InvalidUserId: "invalid_user_id",
InvalidDate: "invalid_date",
}
type Argument = {
user_id: mongoose.Types.ObjectId
date: Date
}
export const update_last_activity_date = async ({
user_id,
date,
}: Argument): Promise<void> => {
if (vs.object_id().ok(user_id) === false) {
throw new ModelRuntimeError(ErrorCodes.InvalidUserId)
}
if (date instanceof Date === false) {
throw new ModelRuntimeError(ErrorCodes.InvalidDate)
}
const user = await get_user({ user_id })
if (user == null) {
throw new ModelRuntimeError(ErrorCodes.InvalidUserId)
}
user.last_activity_date = date
await user.save()
}
|
440bc7edd92de51a36c9531664fc0ed2ef9910ef
|
TypeScript
|
bernzdevo/SampleFiles
|
/SampleApp/src/app/pipes/filter.pipe.ts
| 2.6875
| 3
|
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(value: any[], args?: string, filterBy?: string): any {
if (!args) { return value; }
args = args.toLowerCase();
return value.filter(prod => {
if (filterBy == "ID") {
return prod.id == args;
} else if (filterBy == "Name") {
return prod.productName.toLowerCase().includes(args);
} else if (filterBy == "Price") {
return (prod.productPrice) == parseInt(args);
} else {
return prod.productName.toLowerCase().includes(args);
}
});
}
}
|
04370964aeb16e4b7a12c08395594a826d945242
|
TypeScript
|
callstack/linaria
|
/packages/babel/src/transform/generators/processEntrypoint.ts
| 2.765625
| 3
|
import { isAborted } from '../actions/AbortError';
import type { ITransformResult } from '../actions/types';
import type { IProcessEntrypointAction, SyncScenarioForAction } from '../types';
/**
* The first stage of processing an entrypoint.
* This stage is responsible for:
* - scheduling the explodeReexports action
* - scheduling the transform action
* - rescheduling itself if the entrypoint is superseded
*/
export function* processEntrypoint(
this: IProcessEntrypointAction<'sync'>
): SyncScenarioForAction<IProcessEntrypointAction<'sync'>> {
const { only, log } = this.entrypoint;
log('start processing (only: %s)', only);
const abortController = new AbortController();
const onParentAbort = () => {
abortController.abort();
};
if (this.abortSignal) {
this.abortSignal.addEventListener('abort', onParentAbort);
}
const unsubscribe = this.entrypoint.onSupersede(() => {
abortController.abort();
});
let result: ITransformResult | null = null;
try {
yield [
'explodeReexports',
this.entrypoint,
undefined,
abortController.signal,
];
result = yield* this.getNext(
'transform',
this.entrypoint,
undefined,
abortController.signal
);
} catch (e) {
if (isAborted(e)) {
log('aborting processing');
} else {
throw e;
}
}
this.abortSignal?.removeEventListener('abort', onParentAbort);
unsubscribe();
const { supersededWith } = this.entrypoint;
if (supersededWith) {
log('entrypoint superseded, rescheduling processing');
result = yield* this.getNext(
'processEntrypoint',
supersededWith,
undefined,
null
);
}
log('entrypoint processing finished');
return result;
}
|
7785476f5ccf6bcb240b3ff39c31328b70ab2c77
|
TypeScript
|
nonoroazoro/typescript-react-boilerplate
|
/src/utils/fp.ts
| 3.515625
| 4
|
export type ArityFunction = (...args: any) => any;
export type UnaryFunction = (arg: any) => any;
export function compose(...fns: [...unary: UnaryFunction[], arity: ArityFunction])
{
if (fns.length === 0)
{
throw new Error("compose requires at least one argument");
}
const fn = fns.pop() as ArityFunction;
return (...args: Parameters<ArityFunction>) =>
{
return fns.reduceRight((v, f) => f(v), fn(...args));
};
}
export function pipe(...fns: [arity: ArityFunction, ...unary: UnaryFunction[]])
{
if (fns.length === 0)
{
throw new Error("pipe requires at least one argument");
}
const [f0, ...rest] = fns;
return (...args: Parameters<ArityFunction>) =>
{
return rest.reduce((v, f) => f(v), f0(...args));
};
}
|
31c7ef5cfa8c433372cfdeb7161bd77dba4b78cc
|
TypeScript
|
rike422/kirinuki-core
|
/src/scraper/browser/create-dom.ts
| 2.78125
| 3
|
import { isString } from '../../util';
export function createDom(
node: string | HTMLElement,
root?: string
): HTMLElement | Document | Element {
const target: HTMLElement | Document = isString(node) ? parseDom(node) : node;
if (root == undefined) {
return target;
}
const selectRoot = target.querySelector(root);
if (selectRoot === null) {
throw `Can't match root selector ${root}`;
}
return selectRoot;
}
function parseDom(html: string): Document {
const parser = new DOMParser();
return parser.parseFromString(html, 'text/html');
}
|
c9006c7db6c288d44fb84aaf4658f3c3b7c91a9e
|
TypeScript
|
vima91/SmartChurch
|
/SmartChurch.Angular/src/app/errors-handler/errors-handler.ts
| 2.515625
| 3
|
import { Injectable, ErrorHandler, Injector } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { Router } from '@angular/router';
@Injectable()
export class ErrorsHandler implements ErrorHandler {
// Because the ErrorHandler is created before the providers,
// we’ll have to use the Injector to get them.
constructor(private injector: Injector) {}
handleError(error: Error | HttpErrorResponse) {
enum ERROR_TYPE {
BAD_REQUEST = 400,
UNAUTHORIZED = 401,
FORBIDDEN = 403,
NOT_FOUND = 404,
INTERNAL_SERVER_ERROR = 500
}
const toaster = this.injector.get(ToastrService);
const router = this.injector.get(Router);
if (error instanceof HttpErrorResponse) {
// Server or connection error happened
if (!navigator.onLine) {
// Handle offline error
toaster.error('No Internet Connection', 'Error');
} else {
const errorMsg = ', ' + error['error']['message'];
// Handle Http Error (error.status === 403, 404...)
switch (error.status) {
case ERROR_TYPE.BAD_REQUEST:
toaster.error(`Bad Request ${errorMsg}`, 'Error');
break;
case ERROR_TYPE.UNAUTHORIZED:
router.navigate(['/login']);
toaster.error(`Unauthorized ${errorMsg}`, 'Error');
break;
case ERROR_TYPE.NOT_FOUND:
toaster.error(`Not Found ${errorMsg}`, 'Error');
break;
case ERROR_TYPE.FORBIDDEN:
toaster.error(`Forbidden ${errorMsg}`, 'Error');
break;
case ERROR_TYPE.INTERNAL_SERVER_ERROR:
toaster.error(`Internal Server Error ${errorMsg}`, 'Error');
break;
}
}
} else {
// Handle Client Error (Angular Error, ReferenceError...)
router.navigate(['/error'], { queryParams: { error: error } });
}
// Log the error anyway
console.error('ChurchOrganizer Error happens: ', error);
}
}
|
6505c85b379537c4b78ddf24d84a37cc90c2cfb5
|
TypeScript
|
aerophile/pigi
|
/packages/watch-eth/src/models/event-filter.ts
| 3.015625
| 3
|
import { hash } from '../utils'
export interface EventFilterOptions {
event: string
indexed?: { [key: string]: any }
}
/**
* Represents an event filter.
*/
export class EventFilter {
public options: EventFilterOptions
constructor(options: EventFilterOptions) {
this.options = options
}
/**
* @returns the unique hash for this filter.
*/
get hash(): string {
return hash(JSON.stringify(this.options))
}
}
|
5b12ec4f118aa742ffa9da72825405c7476f18be
|
TypeScript
|
chaveshigor/nlwValoriza
|
/src/services/CreateComplimentService.ts
| 2.828125
| 3
|
import { getCustomRepository, Repository } from "typeorm"
import { User } from "../entities/User"
import { ComplimentRepositories } from "../repositories/ComplimentRepositories"
import { UserRepositories } from "../repositories/UserRepositories"
import { TagRepositories } from "../repositories/TagRepositories"
import { ErrorHandler } from "./HandlingErrors"
interface ICompliment {
tag_id: string,
user_sender: string,
user_receiver: string,
message: string
}
class CreateComplimentService {
async execute({tag_id, user_sender, user_receiver, message}: ICompliment) {
const complimentRepository = getCustomRepository(ComplimentRepositories)
const userRepository = getCustomRepository(UserRepositories)
const tagRepository = getCustomRepository(TagRepositories)
const checkVariableContent = (param: string, errorMessage: string) => {
if(!param) {
throw new ErrorHandler(errorMessage, 400)
}
}
checkVariableContent(tag_id, "A tag must be provided")
checkVariableContent(user_sender, "An user sender must be provided")
checkVariableContent(user_receiver, "An user receiver must be provided")
checkVariableContent(message, "A message must be provided")
if(user_receiver === user_sender) {
throw new ErrorHandler("You cannot give to yourself a compliment", 400)
}
const checkIfUserItsValid = async(repo: Repository<User>, id: string, errorMessage: string) => {
const user = await repo.findOne(id)
if(!user) {
throw new ErrorHandler(errorMessage, 400)
}
}
await checkIfUserItsValid(userRepository, user_sender, "Invalid user sender")
await checkIfUserItsValid(userRepository, user_receiver, "Invalid user receiver")
const validTag = await tagRepository.findOne(tag_id)
if(!validTag) {
throw new ErrorHandler("Invalid tag", 400)
}
const newComplement = complimentRepository.create({
tag_id,
user_sender,
user_receiver,
message
})
await complimentRepository.save(newComplement)
return newComplement
}
}
export { CreateComplimentService }
|
774eee2aaf3d195e3d3d649f60619358a1b52bf2
|
TypeScript
|
NakedObjectsGroup/NakedObjectsFramework
|
/Client/nakedobjects-client/services/src/mask.service.ts
| 2.640625
| 3
|
import { CurrencyPipe, DecimalPipe } from '@angular/common';
import { Injectable } from '@angular/core';
import * as Ro from '@nakedobjects/restful-objects';
import forEach from 'lodash-es/forEach';
import { DateTime } from 'luxon';
import { ConfigService } from './config.service';
import { defaultDateFormat, defaultShortTimeFormat, defaultTimeFormat } from './date-constants';
export interface IMaskServiceConfigurator {
setNumberMaskMapping: (customMask: string, format: Ro.FormatType, digits?: string, locale?: string) => void;
// date masks now use luxon mask conventions https://moment.github.io/luxon/#/formatting
setDateMaskMapping: (customMask: string, format: Ro.FormatType, mask: string, tz?: string, locale?: string) => void;
setCurrencyMaskMapping: (customMask: string, format: Ro.FormatType, symbol?: string, digits?: string, locale?: string) => void;
}
export interface ILocalFilter {
filter(val: unknown): string;
}
export interface IMaskMap {
[index: string]: { [index: string]: ILocalFilter };
}
class LocalStringFilter implements ILocalFilter {
filter(val: unknown): string {
return val ? val.toString() : '';
}
}
function transform(tfm: () => string | null) {
try {
return tfm();
} catch (e) {
return '';
}
}
class LocalCurrencyFilter implements ILocalFilter {
constructor(
private readonly locale: string,
private readonly symbol?: string,
private readonly digits?: string,
) { }
filter(val: unknown): string {
if (val == null || val === '') {
return '';
}
if (typeof val == 'string' || typeof val == 'number') {
const pipe = new CurrencyPipe(this.locale);
return transform(() => pipe.transform(val, this.symbol, 'symbol', this.digits)) || '';
}
return '';
}
}
class LocalDateFilter implements ILocalFilter {
constructor(
private readonly locale: string,
private readonly mask?: string,
private readonly tz?: string,
) { }
filter(val: string): string {
if (!val) {
return '';
}
// Angular date pipes no longer support timezones so we need to use luxon here
// date or time
let mmt = val.length > 8 ? DateTime.fromISO(val) : DateTime.fromFormat(val, defaultTimeFormat);
if (mmt.isValid) {
if (this.tz) {
mmt = mmt.setZone(this.tz);
}
return this.mask ? mmt.toFormat(this.mask) : mmt.toLocaleString();
}
return '';
}
}
class LocalNumberFilter implements ILocalFilter {
constructor(
private readonly locale: string,
private readonly digits?: string
) { }
filter(val: unknown): string {
if (val == null || val === '') {
return '';
}
if (typeof val == 'string' || typeof val == 'number') {
const pipe = new DecimalPipe(this.locale);
const result = transform(() => pipe.transform(val, this.digits));
return result == null ? '' : result;
}
return '';
}
}
@Injectable()
export class MaskService implements IMaskServiceConfigurator {
private maskMap: IMaskMap = {
string: {},
'date-time': {},
date: {},
time: {},
'utc-millisec': {},
'big-integer': {},
'big-decimal': {},
blob: {},
clob: {},
decimal: {},
int: {}
};
constructor(
private readonly appConfig: ConfigService
) {
this.defaultLocale = appConfig.config.defaultLocale;
this.configureFromConfig();
}
private readonly defaultLocale: string;
defaultLocalFilter(format: Ro.FormatType): ILocalFilter {
switch (format) {
case ('string'):
return new LocalStringFilter();
case ('date-time'):
return new LocalDateFilter(this.defaultLocale, `${defaultDateFormat} ${defaultTimeFormat}`, 'utc');
case ('date'):
return new LocalDateFilter(this.defaultLocale, defaultDateFormat);
case ('time'):
return new LocalDateFilter(this.defaultLocale, defaultShortTimeFormat);
case ('utc-millisec'):
return new LocalNumberFilter(this.defaultLocale);
case ('big-integer'):
return new LocalNumberFilter(this.defaultLocale);
case ('big-decimal'):
return new LocalNumberFilter(this.defaultLocale);
case ('blob'):
return new LocalStringFilter();
case ('clob'):
return new LocalStringFilter();
case ('decimal'):
return new LocalNumberFilter(this.defaultLocale);
case ('int'):
return new LocalNumberFilter(this.defaultLocale);
default:
return new LocalStringFilter();
}
}
private customFilter(format: Ro.FormatType, remoteMask: string | null) {
if (remoteMask && this.maskMap[format]) {
return this.maskMap[format][remoteMask];
}
return undefined;
}
toLocalFilter(remoteMask: string | null, format: Ro.FormatType) {
return this.customFilter(format, remoteMask) || this.defaultLocalFilter(format);
}
setNumberMaskMapping(customMask: string, format: Ro.FormatType, digits?: string, locale?: string) {
this.maskMap[format!][customMask] = new LocalNumberFilter(locale || this.defaultLocale, digits);
}
setDateMaskMapping(customMask: string, format: Ro.FormatType, mask: string, tz?: string, locale?: string) {
this.maskMap[format!][customMask] = new LocalDateFilter(locale || this.defaultLocale, mask, tz);
}
setCurrencyMaskMapping(customMask: string, format: Ro.FormatType, symbol?: string, digits?: string, locale?: string) {
this.maskMap[format!][customMask] = new LocalCurrencyFilter(locale || this.defaultLocale, symbol, digits);
}
private configureFromConfig() {
const maskConfig = this.appConfig.config.masks;
if (maskConfig) {
const currencyMasks = maskConfig.currencyMasks;
const dateMasks = maskConfig.dateMasks;
const numberMasks = maskConfig.numberMasks;
if (currencyMasks) {
forEach(currencyMasks, (v, k) => this.setCurrencyMaskMapping(k!, v.format, v.symbol, v.digits, v.locale));
}
if (dateMasks) {
forEach(dateMasks, (v, k) => this.setDateMaskMapping(k!, v.format, v.mask, v.tz, v.locale));
}
if (numberMasks) {
forEach(numberMasks, (v, k) => this.setNumberMaskMapping(k!, v.format, v.digits, v.locale));
}
}
}
}
|
7bfa2f1c5555566d1629a10b3ddd3792c57d7b90
|
TypeScript
|
webern-unibas-ch/awg-app
|
/src/app/shared/toast/toast.service.spec.ts
| 2.578125
| 3
|
import { Component, TemplateRef, ViewChild } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { Toast, ToastService } from './toast.service';
// Mock component to get templateRef
@Component({
template: ` <ng-template #template><h1>Test template</h1></ng-template> `,
})
class MockTemplateComponent {
@ViewChild('template', { static: true }) public template: TemplateRef<any>;
}
describe('ToastService (DONE)', () => {
let toastService: ToastService;
let expectedTextMessage1: string;
let expectedTextMessage2: string;
let expectedTplMessage: TemplateRef<any>;
let expectedOptions: any = {};
let expectedToast1: Toast;
let expectedToast2: Toast;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ToastService],
declarations: [MockTemplateComponent],
});
// Inject service
toastService = TestBed.inject(ToastService);
// Test data
expectedTextMessage1 = 'Test message 1';
expectedTextMessage2 = 'Test message 2';
expectedOptions = { header: 'Test error name', classname: 'bg-danger text-light', delay: 7000 };
expectedToast1 = new Toast(expectedTextMessage1);
expectedToast2 = new Toast(expectedTextMessage2, expectedOptions);
});
it('... should create', () => {
expect(toastService).toBeTruthy();
});
it('... should have empty toast array', () => {
expect(toastService.toasts).toBeTruthy();
expect(toastService.toasts).withContext('should equal empty array []').toEqual([]);
});
describe('#add()', () => {
it('... should have a method `add`', () => {
expect(toastService.add).toBeDefined();
});
it('... should add given string to toast array', () => {
// Call service method
toastService.add(expectedToast1);
expect(toastService.toasts).toBeTruthy();
expect(toastService.toasts.length).withContext('should have one entry').toBe(1);
expect(toastService.toasts[0]).withContext(`should equal ${expectedToast1}`).toEqual(expectedToast1);
});
it('... should add given template to toast array', () => {
const fixture = TestBed.createComponent(MockTemplateComponent);
const mockComponent = fixture.componentInstance;
expectedTplMessage = mockComponent.template;
const expectedTplToast = new Toast(expectedTplMessage);
// Call service method
toastService.add(expectedTplToast);
expect(toastService.toasts).toBeTruthy();
expect(toastService.toasts.length).withContext('should have one entry').toBe(1);
expect(toastService.toasts[0]).withContext(`should equal ${expectedTplToast}`).toEqual(expectedTplToast);
});
it('... should only add textOrTpl if options not given', () => {
// Call service method
toastService.add(expectedToast1);
expect(toastService.toasts).toBeTruthy();
expect(toastService.toasts.length).withContext('should have one entry').toBe(1);
expect(toastService.toasts[0]).withContext(`should equal ${expectedToast1}`).toEqual(expectedToast1);
});
it('... should add options if given with text message', () => {
// Call service method
toastService.add(expectedToast2);
expect(toastService.toasts).toBeTruthy();
expect(toastService.toasts.length).withContext('should have one entry').toBe(1);
expect(toastService.toasts[0]).withContext(`should equal ${expectedToast2}`).toEqual(expectedToast2);
});
it('... should add options if given with template message', () => {
const fixture = TestBed.createComponent(MockTemplateComponent);
const mockComponent = fixture.componentInstance;
expectedTplMessage = mockComponent.template;
const expectedTplToast = new Toast(expectedTplMessage, expectedOptions);
// Call service method
toastService.add(expectedTplToast);
expect(toastService.toasts).toBeTruthy();
expect(toastService.toasts.length).withContext('should have one entry').toBe(1);
expect(toastService.toasts[0]).withContext(`should equal ${expectedTplToast}`).toEqual(expectedTplToast);
});
});
describe('#remove()', () => {
beforeEach(() => {
toastService.add(expectedToast1);
toastService.add(expectedToast2);
});
it('... should have a method `remove`', () => {
expect(toastService.remove).toBeDefined();
});
it('... should do nothing if toast does not exist', () => {
const expectedOtherToast = new Toast('Test message 3');
// Call service method
toastService.remove(expectedOtherToast);
expect(toastService.toasts).toBeTruthy();
expect(toastService.toasts.length).withContext('should have two entries').toBe(2);
expect(toastService.toasts[0]).withContext(`should equal ${expectedToast1}`).toEqual(expectedToast1);
expect(toastService.toasts[1]).withContext(`should equal ${expectedToast2}`).toEqual(expectedToast2);
});
it('... should do nothing if options do not match', () => {
const otherOptionsToast = new Toast(expectedTextMessage1, expectedOptions);
// Call service method
toastService.remove(otherOptionsToast);
expect(toastService.toasts).toBeTruthy();
expect(toastService.toasts.length).withContext('should have two entries').toBe(2);
expect(toastService.toasts[0]).withContext(`should equal ${expectedToast1}`).toEqual(expectedToast1);
expect(toastService.toasts[1]).withContext(`should equal ${expectedToast2}`).toEqual(expectedToast2);
});
it('... should remove existing toast from toast array (without options)', () => {
// Call service method
toastService.remove(expectedToast1);
expect(toastService.toasts).toBeTruthy();
expect(toastService.toasts.length).withContext('should have one entry').toBe(1);
expect(toastService.toasts[0])
.withContext(`should not equal ${expectedToast1}`)
.not.toEqual(expectedToast1);
expect(toastService.toasts[0]).withContext(`should equal ${expectedToast2}`).toEqual(expectedToast2);
});
it('... should remove existing toast from toast array (with options)', () => {
// Call service method
toastService.remove(expectedToast2);
expect(toastService.toasts).toBeTruthy();
expect(toastService.toasts.length).withContext('should have one entry').toBe(1);
expect(toastService.toasts[0]).withContext(`should equal ${expectedToast1}`).toEqual(expectedToast1);
expect(toastService.toasts[1])
.withContext(`should not equal ${expectedToast2}`)
.not.toEqual(expectedToast2);
});
});
});
|
60cac70b004e392f8264500cf4e74765d04a8335
|
TypeScript
|
jhonkoan110/qpd-learn
|
/Тема5/todolist/src/redux/tasks/reducer.ts
| 3.078125
| 3
|
import { CategoryType } from '../categories/reducer';
import {
ADD_TASK,
DELETE_TASK,
EDIT_TASK,
SET_TASKS,
TASKS_IS_LOADING,
TASKS_INCREMENT_ID,
DELETE_CATEGORY_ID,
} from './actionTypes';
export interface ITask {
id: number;
title: string;
description: string;
categoryId?: number;
categoryTitle?: string;
}
const initialState = {
currentId: 0,
isLoading: false,
hasErrored: false,
tasks: [] as Array<ITask>,
categories: [] as Array<CategoryType>,
};
export type InitialStateType = typeof initialState;
const tasksReducer = (state: InitialStateType = initialState, action: any): InitialStateType => {
switch (action.type) {
case TASKS_IS_LOADING: {
return { ...state, isLoading: action.isLoading };
}
case SET_TASKS: {
return {
...state,
tasks: action.tasks,
currentId: action.tasks.length ? action.tasks[action.tasks.length - 1].id : 0,
};
}
case DELETE_TASK: {
return {
...state,
tasks: state.tasks.filter((task) => task.id !== action.id),
};
}
case ADD_TASK: {
return { ...state, tasks: [...state.tasks, action.payload] };
}
case TASKS_INCREMENT_ID: {
return { ...state, currentId: state.currentId + 1 };
}
case EDIT_TASK: {
const newTasks: Array<ITask> = state.tasks.map((item) => {
if (item.id === action.updatedTask.id) {
item = action.updatedTask;
}
return item;
});
return { ...state, tasks: newTasks };
}
case DELETE_CATEGORY_ID: {
const newTasks: Array<ITask> = state.tasks.map((task) => {
if (task.categoryId === action.id) {
task.categoryId = undefined;
task.categoryTitle = undefined;
}
return task;
});
return { ...state, tasks: newTasks };
}
default:
return state;
}
};
export default tasksReducer;
|
dd67c9bebcb7925f08d98d726bfba54820a465c8
|
TypeScript
|
wwwK/node-hariko
|
/src/hariko-parser/structure/http-request.ts
| 2.671875
| 3
|
import { ProtagonistHttpRequest } from 'protagonist'
import { HttpTransaction } from './http-transaction'
export type HttpRequestMethod = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'OPTIONS'
export class HttpRequest {
constructor(
public readonly http_transaction: HttpTransaction,
public method: HttpRequestMethod,
private orig_uri_template: string | null
) {}
get uri_template() {
return this.orig_uri_template
? this.orig_uri_template
: this.http_transaction.transition.resource.uri_template
}
clone() {
return new HttpRequest(
this.http_transaction,
this.method,
this.orig_uri_template
)
}
hasSpecificUri() {
return this.orig_uri_template !== null
}
static create(
http_transaction: HttpTransaction,
data: ProtagonistHttpRequest
) {
let method = data.attributes.method.content
let uri_template = data.meta ? data.meta.title.content : null
// split method and path from `GET /path/to`
if (
uri_template &&
uri_template.match(/^(GET|POST|PUT|DELETE|OPTIONS)\s*(.+)$/)
) {
method = RegExp.$1 as HttpRequestMethod
uri_template = RegExp.$2
}
return new HttpRequest(http_transaction, method, uri_template)
}
}
|
e9c35844fb6c0880006b2fcf170cbc9b4ae33fb5
|
TypeScript
|
giraffesyo/dynamic-form-generator
|
/lib/reviveJSON.ts
| 3.03125
| 3
|
import { DateTime } from 'luxon'
import type { TJSONValue } from '../typings'
// convert strings to dates ( used by JSON.parse() )
const JSONReviver = (key: string, value: TJSONValue) => {
if (typeof value !== 'string') return value
const ISODateTime = DateTime.fromISO(value)
const SQLDateTime = DateTime.fromSQL(value)
const AmericanDateTime = DateTime.fromFormat(value, 'MM/dd/yyyy')
// Store false or the date time if its a valid date
const validDateTime =
(ISODateTime.isValid && ISODateTime) ||
(SQLDateTime.isValid && SQLDateTime) ||
(AmericanDateTime.isValid && AmericanDateTime)
return validDateTime || value
}
export default JSONReviver
|
3c18228740458046d6bad8a0e5d524a7e23d2145
|
TypeScript
|
gustavo-hillesheim/proxer
|
/server/src/websocket_server.ts
| 2.921875
| 3
|
import { websocket } from "./dependencies.ts";
const { WebSocketServer } = websocket;
export function startWebsocketServer({ port = 10001 }): WebSocketServerAdapter {
const server = new WebSocketServer(port);
server.on("connection", handleClientConnection);
console.log(`Started WebSocket server at port: ${port}`);
return new WebSocketServerAdapter(server);
}
function handleClientConnection(client: websocket.WebSocket): void {}
interface WebSocketMessage {
type: string;
content: object;
}
export interface WebSocketTargetedMessage extends WebSocketMessage {
receiver: string | undefined;
}
export class WebSocketServerAdapter {
constructor(private server: websocket.WebSocketServer) {}
send({ type, receiver, content }: WebSocketTargetedMessage): void {
if (receiver) {
this.sendTo(receiver, { type, content });
} else {
this.sendAll({ type, content });
}
}
private sendTo(receiver: string, message: WebSocketMessage): void {
this.activeClients().forEach((client) => {
if (this.isClient(receiver, client)) {
client.send(JSON.stringify(message));
}
});
}
private sendAll(message: WebSocketMessage): void {
this.activeClients().forEach((client) => {
client.send(JSON.stringify(message));
});
}
private activeClients(): websocket.WebSocket[] {
return Array.from(this.server.clients).filter((client) => !client.isClosed);
}
private isClient(receiver: string, client: websocket.WebSocket): boolean {
return true; // TODO: Adicionar validação de IP do client === receiver
}
}
|
5a1b787071534cc3d751df14099de8a632a5786b
|
TypeScript
|
Messiviski/push-notifications-firebase
|
/src/useCases/sendNotifications/SendNotificationsUseCase.ts
| 2.578125
| 3
|
import * as admin from "firebase-admin";
import { inject, injectable } from "tsyringe";
import { INotificationsRepository } from "../../repositories/INotificationsRepository";
interface INotificationMessage {
tokens: string[];
data: {
title: string;
body: string;
};
}
@injectable()
class SendNotificationsUseCase {
constructor(
@inject("NotificationsRepository")
private notificationRepository: INotificationsRepository
) {}
execute({ data, tokens }: INotificationMessage): void {
const failedTokens = [];
const message = {
data,
tokens,
};
admin
.messaging()
.sendMulticast(message)
.then((response) => {
if (response.failureCount > 0) {
response.responses.forEach((response, index) => {
if (!response.success) {
failedTokens.push(tokens[index]);
}
});
}
});
if (failedTokens.length === tokens.length) {
throw new Error("The messages were not sent!");
}
this.notificationRepository.create({ data, tokens });
}
}
export { SendNotificationsUseCase };
|
b46d0565ed0c5e8bd1d96dd26aeca97176122e3e
|
TypeScript
|
KellyLMaud/TSOS-2015
|
/source/host/cpu.ts
| 2.671875
| 3
|
///<reference path="../globals.ts" />
/* ------------
CPU.ts
Requires global.ts.
Routines for the host CPU simulation, NOT for the OS itself.
In this manner, it's A LITTLE BIT like a hypervisor,
in that the Document environment inside a browser is the "bare metal" (so to speak) for which we write code
that hosts our client OS. But that analogy only goes so far, and the lines are blurred, because we are using
TypeScript/JavaScript in both the host and client environments.
This code references page numbers in the text book:
Operating System Concepts 8th edition by Silberschatz, Galvin, and Gagne. ISBN 978-0-470-12872-5
------------ */
module TSOS {
export class Cpu {
constructor(public PC: number = 0,
public Acc: number = 0,
public Xreg: number = 0,
public Yreg: number = 0,
public Zflag: number = 0,
public isExecuting: boolean = false,
public code: String = '0') {
}
public init(): void {
this.PC = 0;
this.Acc = 0;
this.Xreg = 0;
this.Yreg = 0;
this.Zflag = 0;
this.isExecuting = false;
}
public printPCB(PID, PC, Accum, Xreg, Yreg, Zflag): void {
_StdOut.putText("PID: " + PID );
_StdOut.putText(", PC: " + (PC - 1));
_StdOut.putText(", ACC: " + Accum);
_StdOut.putText(", XReg: " + Xreg);
_StdOut.putText(", YReg: " + Yreg);
_StdOut.putText(", ZFlag: " + Zflag);
_StdOut.advanceLine();
}
public clearProgram(){
this.code = "0";
this.PC = 0;
this.Acc = 0;
this.Xreg = 0;
this.Yreg = 0;
this.Zflag = 0;
this.isExecuting = false;
}
public opCodes(input): void {
//this.code = input.toUpperCase();
this.PC++;
switch (input) {
case "A9": //load accumulator with a constant
this.loadAccumConst();
break;
case "AD": //load the accumulator from memory
this.loadAccumMem();
break;
case "8D": //store the accumulator in memory
this.storeAccumMem();
break;
case "6D": //add with carry
this.addCarry();
break;
case "A2": //load the x register with a constant
this.loadXRegConst();
break;
case "AE": //load the x register from memory
this.loadXRegMem();
break;
case "A0": //load the y register with a constant
this.loadYRegConst();
break;
case "AC": //load the y register from memory
this.loadYRegMem();
break;
case "EA": //no operation
this.noOperation();
break;
case "00": //break
this.break();
break;
case "EC": //compare a byte in memory to the x reg
this.compareXReg();
break;
case "D0": //branch n bytes if Zflag = 0
this.branchNBytes();
break;
case "EE": //increment the value of a byte
this.incrementByte();
break;
case "FF": //system call
this.systemCall();
break;
default:
_StdOut.putText("Undefined OP Code " + input + ".");
_StdOut.advanceLine();
_CPU.isExecuting = false;
}
}
public loadAccumConst(){
//load the accumulator with a constant
this.Acc = _MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, this.PC));
this.PC++;
}
public loadAccumMem(){
//load the accumulator from memory
this.Acc = _MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, this.PC));
this.PC++;
this.PC++;
}
public storeAccumMem(){
//store the accumulator in memory
var location = _MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, this.PC));
_MM.writeToMemory(_CurrPartitionOfMem, location, _MM.dec2Hex(this.Acc));
this.PC++;
this.PC++;
}
public addCarry(){
//add with carry
var location = _MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, this.PC));
this.Acc += _MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, location));
this.PC++;
this.PC++;
}
public loadXRegConst(){
//load the x register with a constant
this.Xreg = _MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, this.PC));
this.PC++;
}
public loadXRegMem(){
//load the x register from memory
var location = _MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, this.PC));
this.Xreg = _MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, location));
this.PC++;
this.PC++;
}
public loadYRegConst(){
//load the y register with a constant
this.Yreg = _MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, this.PC));
this.PC++;
}
public loadYRegMem(){
//load the y register from memory
var adr = _MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, this.PC));
this.Yreg = _MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, adr));
this.PC++;
this.PC++;
}
public noOperation(){
//no operation
this.isExecuting = false;
_Kernel.krnTrace("break");
}
public break(){
//break
this.isExecuting = false;
this.finishProgram();
_CPUScheduler.breakContextSwitch();
_OsShell.putPrompt();
}
public compareXReg(){
//compare a byte in memory to the x reg
var location = _MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, this.PC));
var memoryValue = _MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, location));
this.Zflag = (memoryValue === this.Xreg) ? 1 : 0;
this.PC++;
this.PC++;
}
public branchNBytes(){
if (this.Zflag===0){
this.PC +=_MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, this.PC++))+1 ;
if (this.PC>=256){
this.PC-=256
}
}
else {
this.PC++;
}
_Kernel.krnTrace("branch");
}
public incrementByte(){
//increment the value of a byte
var location = _MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, this.PC));
var value = 1 + _MM.hex2Dec(_MM.readFromMemory(_CurrPartitionOfMem, location));
_MM.writeToMemory(_CurrPartitionOfMem, location, value);
this.PC++;
this.PC++;
}
public systemCall(){
//system call
if(this.Xreg == 1){
_StdOut.putText(this.Yreg.toString());
}
else if(this.Xreg == 2){
var adr = this.Yreg;
var char = _MM.readFromMemory(_CurrPartitionOfMem, adr);
while(char != "00"){
_StdOut.putText(String.fromCharCode(_MM.hex2Dec(char)));
adr ++;
char = _MM.readFromMemory(_CurrPartitionOfMem, adr);
}
}else{
_StdOut.putText("XReg is supposed to be a 1 or a 2");
_CPU.isExecuting = false;
}
}
public finishProgram(): void{
_StdOut.advanceLine();
_CurrentPCB.PC = this.PC;
_CurrentPCB.Accum = this.Acc;
_CurrentPCB.Xreg = this.Xreg;
_CurrentPCB.Yreg = this.Yreg;
_CurrentPCB.Zflag = this.Zflag;
_CurrentPCB.printPCB();
}
public printCPUElements(): void {
document.getElementById("tdPC").innerHTML = this.PC.toString();
document.getElementById("tdIR").innerHTML = _MM.readFromMemory(_CurrPartitionOfMem, this.PC);
document.getElementById("tdAccum").innerHTML = this.Acc.toString();
document.getElementById("tdXReg").innerHTML = this.Xreg.toString();
document.getElementById("tdYReg").innerHTML = this.Yreg.toString();
document.getElementById("tdZFlag").innerHTML = this.Zflag.toString();
}
public updateCPUElements(_CurrentPCB: PCB): void {
this.PC = _CurrentPCB.PC;
this.Acc = _CurrentPCB.Acc;
this.Xreg = _CurrentPCB.Xreg;
this.Yreg = _CurrentPCB.Yreg;
this.Zflag = _CurrentPCB.Zflag;
}
public cycle(): void {
_Kernel.krnTrace('CPU cycle');
var opCode = _MM.readFromMemory(_CurrPartitionOfMem, this.PC);
this.printCPUElements();
if(this.Yreg >= _CurrentPCB.baseRegister + 256){
this.break();
_Kernel.krnTrace('invalid memory access');
}else{
this.opCodes(opCode);
}
if (_SingleStep){
this.isExecuting = false;
}
}
}
}
|
330a9320743abe76d911e4bd37fa694dc1da6dc3
|
TypeScript
|
M1ST4KE/giphy-react-native-sdk
|
/src/GiphyContent.ts
| 2.71875
| 3
|
import { GiphyContentRequest, GiphyContentRequestType, GiphyMediaType } from './native/types'
export type GiphyContentSearchOptions = {
searchQuery: string
mediaType?: GiphyMediaType
}
export type GiphyContentTrendingOptions = {
mediaType?: GiphyMediaType
}
export type GiphyContentAnimateOptions = {
searchQuery: string
}
function makeGiphyContentRequest(
options: Required<Pick<GiphyContentRequest, 'requestType'>> & Partial<GiphyContentRequest>
): GiphyContentRequest {
return {
searchQuery: '',
mediaType: GiphyMediaType.Gif,
...options,
}
}
export class GiphyContent {
static search(options: GiphyContentSearchOptions): GiphyContentRequest {
return makeGiphyContentRequest({
...options,
requestType: GiphyContentRequestType.Search,
})
}
static trending(options: GiphyContentTrendingOptions): GiphyContentRequest {
return makeGiphyContentRequest({
...options,
requestType: GiphyContentRequestType.Trending,
})
}
static trendingGifs(): GiphyContentRequest {
return makeGiphyContentRequest({
mediaType: GiphyMediaType.Gif,
requestType: GiphyContentRequestType.Trending,
})
}
static trendingStickers(): GiphyContentRequest {
return makeGiphyContentRequest({
mediaType: GiphyMediaType.Sticker,
requestType: GiphyContentRequestType.Trending,
})
}
static trendingText(): GiphyContentRequest {
return makeGiphyContentRequest({
mediaType: GiphyMediaType.Text,
requestType: GiphyContentRequestType.Trending,
})
}
static recents(): GiphyContentRequest {
return makeGiphyContentRequest({
mediaType: GiphyMediaType.Gif,
requestType: GiphyContentRequestType.Recents,
})
}
static emoji(): GiphyContentRequest {
return makeGiphyContentRequest({
mediaType: GiphyMediaType.Sticker,
requestType: GiphyContentRequestType.Emoji,
})
}
static animate(options: GiphyContentAnimateOptions): GiphyContentRequest {
return makeGiphyContentRequest({
...options,
requestType: GiphyContentRequestType.Animate,
})
}
}
|
1e72817593048b2711c0b9f8be4e13060ec79111
|
TypeScript
|
dpayonk/payonk-jama
|
/src/app/models/AccountProfile.ts
| 2.875
| 3
|
import { ISerializableObject, SerializationMixin, Logger } from 'payonkjs';
class AccountProfile extends SerializationMixin implements ISerializableObject {
key: string = "";
createdAt: string = "";
emailAddress: string = ""; // need to define default to implement fillFromJSON
currentRole: string = "";
friendlyName: string = "Guest";
authenticated: boolean = false;
static validateJsonResponse: (json_data: any) => boolean;
static fromJson: (jsonResponse: any) => AccountProfile | null;
constructor(props: Object = {}) {
super();
this.fillFromJSON(props);
}
toJson(){
return {
'emailAddress': this.emailAddress,
'currentRole': this.currentRole
}
}
fromJson(jsonResponse: any){
return AccountProfile.fromJson(jsonResponse);
}
}
AccountProfile.validateJsonResponse = function(json_data): boolean{
// test all required values are populated
if(json_data['email_address'] !== undefined){
return true;
}
return false;
}
AccountProfile.fromJson = function(jsonResponse: Object): AccountProfile | null {
try{
if(AccountProfile.validateJsonResponse(jsonResponse)){
let jsonData = AccountProfile.convertToCamelCase(jsonResponse);
return new AccountProfile(jsonData);
}
}catch(exc){
Logger.warn(`AccountProfile.fromJson: ${exc.toString()}`, exc);
Logger.alert(`AccountProfile.fromJson: Could not serialize response:`, jsonResponse);
}
return null;
}
export default AccountProfile;
|
3c9c5053bb865a97dcc49b544264b85618606893
|
TypeScript
|
ferrumnet/totp-lambda
|
/src/server/SecureKeyValueStore.ts
| 2.625
| 3
|
import {SecretHanlder} from './SecretsHandler';
import {KmsCryptor} from "aws-lambda-helper";
import { SecretInterface } from './Types';
export class SecureKeyValueStore {
constructor(
private secretsHandler: SecretHanlder,
private cryptor: KmsCryptor,
) {
}
__name__(): string { return 'SecureKeyValueStore'; }
async getItem<T>(secretId: string): Promise<any> {
const secret = await this.secretsHandler.get(secretId);
if(secret === undefined){
return null
} else {
const skHex = await this.cryptor.decryptToHex(secret.secret);
const response = {...secret, secret: Buffer.from(skHex, 'hex').toString('utf-8')}
return response;
}
}
async removeItem<T>(k: string): Promise<void> {
const response = this.secretsHandler.remove(k);
return;
}
async setItem(k: { userId: string, secretId: string }, v: string): Promise<SecretInterface> {
const encSk = await this.cryptor.encryptHex(Buffer.from(v, 'utf-8').toString('hex'));
const dataToStore = {
'secret': encSk,
'userId': k.userId,
'secretId': k.secretId,
'createdAt': Date.now()
}
const data = await this.secretsHandler.save(dataToStore);
return data;
}
}
|
6b9e8a6eb0bd216970e82572ce10881cb8036070
|
TypeScript
|
project-cemetery/pick-by-lang
|
/lib/pickByLang.ts
| 2.96875
| 3
|
import isPlainObject from 'lodash.isplainobject'
import mapValues from 'lodash.mapvalues'
import { isEmpty } from './helpers/isEmpty'
import { isString } from './helpers/isString'
export const pickByLang = (lang: string, content?: any) => {
const checkString = (v: any) => isString(v) && v === lang
const checkArray = (v: any) => Array.isArray(v) && v.includes(lang)
const transformArray = (arr: any[]) =>
arr
.filter(
({ onlyFor }) =>
isEmpty(onlyFor) || checkString(onlyFor) || checkArray(onlyFor),
)
.map(pick) // eslint-disable-line no-use-before-define
const pick = (data: any) => {
if (Array.isArray(data)) {
return transformArray(data)
}
if (!isPlainObject(data)) {
return data
}
if (Object.keys(data).includes(lang)) {
return data[lang]
}
return mapValues(data, pick)
}
if (!content) {
return pick
}
return pick(content)
}
|
5fcb604fdec3b73421d85b1a6e079c832dde3506
|
TypeScript
|
mohism-framework/utils
|
/src/libs/logs/console-log.ts
| 2.609375
| 3
|
import { blue, grey, yellow, red } from 'colors';
import rp from '../rightpad';
import dayjs from 'dayjs';
const stringify = (input: any): string => {
return (typeof input === 'string' ? input : JSON.stringify(input));
};
const LEVEL_MAP: { [key: string]: number } = {
debug: 0,
info: 1,
warn: 2,
error: 3,
ultra: 99,
}
export class ConsoleLogger {
info(ctx: any): void {
if (process.env.LOG_LEVEL && LEVEL_MAP[process.env.LOG_LEVEL] > LEVEL_MAP.info) {
return;
}
console.log(`${blue(rp('[INFO]', 6))} ${grey(dayjs().format('YYYY-MM-DD HH:mm:ss'))} ${grey(stringify(ctx))}`);
}
warn(ctx: any): void {
if (process.env.LOG_LEVEL && LEVEL_MAP[process.env.LOG_LEVEL] > LEVEL_MAP.warn) {
return;
}
console.log(`${yellow(rp('[WARN]', 6))} ${grey(dayjs().format('YYYY-MM-DD HH:mm:ss'))} ${grey(stringify(ctx))}`);
}
// 为对下兼容而重复
err(ctx: any): void {
if (process.env.LOG_LEVEL && LEVEL_MAP[process.env.LOG_LEVEL] > LEVEL_MAP.error) {
return;
}
console.error(`${red(rp('[ERR]', 6))} ${grey(dayjs().format('YYYY-MM-DD HH:mm:ss'))} ${grey(stringify(ctx))}`);
}
error(ctx: any): void {
if (process.env.LOG_LEVEL && LEVEL_MAP[process.env.LOG_LEVEL] > LEVEL_MAP.error) {
return;
}
console.error(`${red(rp('[ERR]', 6))} ${grey(dayjs().format('YYYY-MM-DD HH:mm:ss'))} ${grey(stringify(ctx))}`);
}
}
export default new ConsoleLogger();
|
d24c819a0d427176e396fc15f588a12c0b5929c8
|
TypeScript
|
iota-pi/crossangles
|
/src/state/Events.spec.ts
| 2.921875
| 3
|
import { getAutoSelectedEvents, getEvents, getEventId } from './Events';
import { CourseMap, CourseId, CourseData } from './Course';
import { ClassTime } from './Stream';
describe('getEventId', () => {
it('gives expected result', () => {
const course: CourseData = {
code: 'RING1379',
name: 'Ring Theory 1A',
streams: [
{ component: 'Secret Forging', times: [{ time: 'M8', location: 'Mount Doom' }] },
],
isAdditional: true,
};
const result = getEventId(course, 'Secret Forging');
expect(result).toBe('RING1379~Secret Forging');
});
});
describe('getEvents', () => {
const baseCourse: CourseData = {
code: 'code',
name: '',
streams: [
{ component: 'a', times: [] },
{ component: 'b', times: [] },
],
};
it('gets events from additional course', () => {
const course: CourseData = { ...baseCourse, isAdditional: true };
const result = getEvents(course);
expect(result).toEqual([
{ id: 'code~a', name: 'a' },
{ id: 'code~b', name: 'b' },
]);
});
it('gives no events for non-additional courses', () => {
expect(getEvents(baseCourse)).toEqual([]);
expect(getEvents({ ...baseCourse, isAdditional: false })).toEqual([]);
});
it('doesn\'t give duplicate events', () => {
const course: CourseData = {
code: 'code',
name: '',
isAdditional: true,
streams: [
{ component: 'a', times: [] },
{ component: 'a', times: [] },
],
};
const result = getEvents(course);
expect(result).toEqual([
{ id: 'code~a', name: 'a' },
]);
});
});
describe('getAutoSelectedEvents', () => {
it('gets events from auto-selected courses', () => {
const times: ClassTime[] = [];
const courseMap: CourseMap = {
a: {
code: 'a',
name: '',
isAdditional: true,
autoSelect: true,
streams: [
{ component: 'a', times },
{ component: 'b', times },
],
},
b: {
code: 'b',
name: '',
autoSelect: true,
streams: [
{ component: 'c', times },
],
},
d: {
code: 'd',
name: '',
isAdditional: true,
streams: [
{ component: 'd', times },
],
},
};
const additional: CourseId[] = ['a', 'd'];
const result = getAutoSelectedEvents(courseMap, additional);
expect(result).toEqual([
{ id: 'a~a', name: 'a' },
{ id: 'a~b', name: 'b' },
]);
});
});
|
1ce738b5045ff6ca8fcdbc0e919bde18615d6596
|
TypeScript
|
kouji-dev/auth-boilerplate
|
/client/src/features/auth/auth.slice.ts
| 2.609375
| 3
|
import { AsyncThunkPayloadCreator, createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { RootState } from '../../config/store';
import API from '../../api'
type UserType = {
username: string;
lastName: string;
firstName: string;
email: string;
}
interface authState {
user: any;
loading: string;
error: any;
}
const initialState: authState = {
user: null,
loading: 'idle',
error: null
};
export const login = createAsyncThunk(
'auth/login',
async ({username, password}: any, {rejectWithValue} ) => {
const response = await API.post(
'auth/login',
{username, password}
)
return response.data;
}
)
export const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
},
extraReducers: (builder) => {
builder.addCase(
login.pending,
(state, action) => {
console.log(action);
state.loading = 'pending';
}
).addCase(
login.fulfilled,
(state, action) => {
console.log(action);
}
).addCase(
login.rejected,
(state, action) => {
console.log(action);
}
)
},
});
export const selectAuth = (state: RootState) => state.auth;
export default authSlice.reducer;
|
7027e55ad4935ba3b5381c210d320c0d8731dbd7
|
TypeScript
|
Erick2280/spoticards-discord-bot
|
/spoticards-bot/commands/sendcards.ts
| 2.734375
| 3
|
import { Message } from 'discord.js';
import { Server } from '../../spoticards/server';
import * as interfaceUtils from '../interface-utils';
import { ClassicGame } from '../../spoticards/game-types/classic-game';
export const data = {
name: 'sendcards',
aliases: ['sendmydeck', 'mydeck', 'mycards'],
description: 'Envia as suas cartas para sua DM.',
args: false,
usage: '<used (opcional caso queira filtrar as cartas utilizadas)>'
};
export function execute(message: Message, args: string[], server: Server, client) {
const identifier = server.findGameIdentifierByUser(message.author.id);
if (identifier == null) {
throw new Error('UserNotFound');
}
const targetGame = server.findGameByIdentifier(identifier);
if (targetGame instanceof ClassicGame) {
let filterUsed = false;
if (args[0] != null && args[0] === 'used') {
filterUsed = true;
}
message.reply('enviei suas cartas na sua DM.');
let index = 0;
const targetPlayer = targetGame.players.find(player => player.userName === message.author.id);
message.author.send(`Estas são as suas cartas do jogo ${targetGame.identifier}:`);
for (const card of targetPlayer.deck) {
if (!filterUsed || filterUsed && !card.used) {
message.author.send({embed: interfaceUtils.createCardEmbed(card, index)});
}
index += 1;
}
}
}
|
a65c679f4486df66e234122a0f1864e5d5582834
|
TypeScript
|
echappee/FranceServ
|
/FranceServ/store/geolocalisation.ts
| 2.84375
| 3
|
import { GetterTree, MutationTree } from 'vuex'
// ici ce sont les datas globales
export const state = () => ({
geolocalisation: '' as any,
})
export type RootState = ReturnType<typeof state>
// getters ceux qu'on recupere
export const getters: GetterTree<RootState, RootState> = {
getGeolocalisation: (state) => state.geolocalisation,
}
// méthodes qui permettent de modifier les datas globales
export const mutations: MutationTree<RootState> = {
setGeolocalisation: (state, newValue: any) =>
(state.geolocalisation = newValue),
}
|
33553e2d3212f3d9b9fe6ca0852fa8b5b5ab8f80
|
TypeScript
|
Marcelo8173/E-learning_server
|
/src/controller/LessonController.ts
| 2.75
| 3
|
import {Request,Response} from 'express';
import { getRepository } from 'typeorm';
import Lesson from '../model/LessonModel';
import Courser from '../model/CourserModel';
class LessonController{
public async indexLesson(request: Request, response: Response):Promise<Response> {
try {
const {id} = request.params;
const ormRepository = getRepository(Lesson);
const lesson = await ormRepository.query(`select * from lesson where (course_id = '${id}')`);
return response.json(lesson);
} catch (error) {
return response.status(400).json(error);
}
}
public async createLesson(request: Request, response: Response): Promise<Response> {
try {
const {id} = request.params;
const { name, duration, description } = request.body;
const ormRepository = getRepository(Lesson);
const lesson = await ormRepository.query(`insert into lesson (name,duration,description,course_id)
values ('${name}','${duration}','${description}','${id}')`);
return response.json(lesson);
} catch (error) {
return response.status(400).json(error);
}
};
public async listLessonByCourse(request: Request, response: Response): Promise<Response>{
try {
const {id} = request.params;
const ormRepository = getRepository(Courser);
// const course = await ormRepository.query(`select * from courses where(id = '${id}')`);
const course = await ormRepository.query(`select
l.id,
l.name as lessonName,
l.duration,
l.description,
c.name as couseName,
c.image
from lesson l inner join courses c on l.course_id = c.id where(c.id = '${id}')
order by l.created_at;`)
const count = await ormRepository.query(`select count (id) as lessonQtd from lesson;`)
return response.json({
courses: course,
countLesson: count[0].lessonqtd
})
} catch (error) {
return response.status(404).json({error:'Course id not found'});
}
}
}
export default LessonController;
|
d9289f36a6c8e708f9f0bc89bccbe8bf1ea955ab
|
TypeScript
|
d4rkr00t/opaline
|
/packages/core/commands/compiler/__tests__/commands-parser.test.ts
| 2.765625
| 3
|
import test from "ava";
import * as path from "path";
import {
parseCommands,
getCommandJSDoc,
getMetaFromJSDoc,
verify$InputsType,
} from "../commands-parser";
import { ProjectInfo } from "../project-info";
test("parseCommands should be able to parse jsdoc from a command file", async (t) => {
let project = {
commandsDirPath: path.join(
__dirname,
"..",
"..",
"..",
"..",
"..",
"examples",
"singlecli",
"commands"
),
cliName: "example",
} as ProjectInfo;
let commands = ["index.js"];
let parsedCommands = await parseCommands(project, commands);
t.snapshot(parsedCommands);
});
test("parseCommands should be able to parse jsdoc from multiple files file", async (t) => {
let project = {
commandsDirPath: path.join(
__dirname,
"..",
"..",
"..",
"..",
"..",
"examples",
"multicli",
"commands"
),
cliName: "example",
} as ProjectInfo;
let commands = ["index.js", "hello-world.js", "runner.js"];
let parsedCommands = await parseCommands(project, commands);
t.snapshot(parsedCommands);
});
test("getMetaFromJSDoc should support aliases", (t) => {
let source = `
/**
* @param {string} name Name
* @short name=n
*
* @param {number} age Age
* @short age=a
*/
export default function cli(){}
`;
let meta = getMetaFromJSDoc({
jsdocComment: getCommandJSDoc(source),
cliName: "cli",
commandPath: "",
});
t.is(meta.options.name.alias, "n");
t.is(meta.options.age.alias, "a");
});
test("getCommandJSDoc should support module.exports", (t) => {
let source = `
/**
* @param {string} name Name
* @short name=n
*
* @param {number} age Age
* @short age=a
*/
module.exports = function cli(){}
`;
let jsdoc = getCommandJSDoc(source);
t.true(!!jsdoc);
});
test("getCommandJSDoc should support export default", (t) => {
let source = `
/**
* @param {string} name Name
* @short name=n
*
* @param {number} age Age
* @short age=a
*/
export default function cli(){}
`;
let jsdoc = getCommandJSDoc(source);
t.true(!!jsdoc);
});
test("getCommandJSDoc should support return undefined if non of the supported formats found", (t) => {
let source = `
/**
* @param {string} name Name
* @short name=n
*
* @param {number} age Age
* @short age=a
*/
module.whatever = function cli(){}
`;
let jsdoc = getCommandJSDoc(source);
t.true(jsdoc === undefined);
});
test("verify$InputsType should return true if a type is `string`", (t) => {
t.true(
verify$InputsType(
{
name: "$inputs",
tag: "param",
type: "string",
optional: true,
description: "",
line: 0,
source: "",
},
"command.ts"
)
);
});
test("verify$InputsType should return true if a type is `string[]`", (t) => {
t.true(
verify$InputsType(
{
name: "$inputs",
tag: "param",
type: "string[]",
optional: true,
description: "",
line: 0,
source: "",
},
"command.ts"
)
);
});
test("verify$InputsType should return true if a type is `Array<string>`", (t) => {
t.true(
verify$InputsType(
{
name: "$inputs",
tag: "param",
type: "Array<string>",
optional: true,
description: "",
line: 0,
source: "",
},
"command.ts"
)
);
});
test("verify$InputsType should return false if a type is not `string` or `string[]` or `Array<string>`", (t) => {
t.false(
verify$InputsType(
{
name: "$inputs",
tag: "param",
type: "Array<number>",
optional: true,
description: "",
line: 0,
source: "",
},
"command.ts"
)
);
});
|
039a56e65cf312c59dcbaab97a7ee2ad1bd40af5
|
TypeScript
|
datavisyn/tdp_core
|
/dist/base/rest.d.ts
| 2.546875
| 3
|
import { IDTypeLike } from 'visyn_core/idtype';
import { IRow, IServerColumn } from 'visyn_core/base';
import { IScoreRow } from './interfaces';
/**
* Describes the properties returned for each database connector
*/
export interface IDatabaseDesc {
/**
* name of the db connector (defined for a connector in the __init__.py function)
*/
readonly name: string;
/**
* Description of the connector. Empty string if not set server-side.
*/
readonly description: string;
}
export interface IServerColumnDesc {
/**
* idType of the DBView, can be null
*/
idType: IDTypeLike | null;
/**
* list of columns within this view, can be empty
*/
columns: IServerColumn[];
}
export interface IDatabaseViewDesc extends IServerColumnDesc {
name: string;
description: string;
arguments: string[];
query: string;
filters?: string[];
queries?: {
[name: string]: string;
};
}
export interface IParams {
[key: string]: string | number | boolean | string[] | number[] | boolean[];
}
/**
* Interface that contains all possible filters for the database API
*/
export interface IAllFilters {
/**
* column values have to be equal to the filter value (string, numerical)
*/
normal: IParams;
/**
* less than filter, column values have to be lower than the filter value (numerical only)
*/
lt: IParams;
/**
* less than equlas filter, column values have to be lower or equal to the filter value (numerical only)
*/
lte: IParams;
/**
* greater than filter, column values have to be higher than the filter value (numerical only)
*/
gt: IParams;
/**
* greater than equals filter, column values have to be higher or equal to the filter value (numerical only)
*/
gte: IParams;
}
export interface ILookupItem {
_id?: never;
id: string;
text: string;
}
export interface ILookupResult {
items: ILookupItem[];
more: boolean;
}
export declare class RestBaseUtils {
static readonly REST_NAMESPACE = "/tdp";
static readonly REST_DB_NAMESPACE: string;
private static getTDPDataImpl;
/**
* Add a prefix to the keys of all given URL parameters
* @param params URL parameter
* @param prefix The prefix for the parameter keys (default is `filter`)
*/
private static prefixFilter;
/**
* Merges the "regular" parameters with filter parameters for the URL.
* Filter parameters are prefixed accordingly to be accepted by the backend.
*
* @param params URL parameters
* @param filters URL filter parameters
*/
private static mergeParamAndAllFilters;
/**
* queries the server side column information of the given view
* @param {string} database
* @param {string} view
* @returns {Promise<Readonly<IDatabaseViewDesc>>}
*/
static getTDPDesc(database: string, view: string): Promise<Readonly<IDatabaseViewDesc>>;
static getTDPDatabases(): Promise<IDatabaseDesc[]>;
static getTDPViews(database: string): Promise<Readonly<IDatabaseViewDesc>[]>;
/**
* return the website url based on the registered proxy page
* @param {string} proxy proxy page identifier
* @param args additional arguments
* @returns {string} the url to the used for iframes
*/
static getProxyUrl(proxy: string, args: any): string;
static getTDPProxyData(proxy: string, args: any, type?: string): Promise<any>;
/**
* query the TDP rest api to read data
* @param {string} database the database connector key
* @param {string} view the view id
* @param {IParams} params additional parameters
* @returns {Promise<T[]>}
*/
static getTDPData<T>(database: string, view: string, params?: IParams): Promise<T[]>;
/**
* query the TDP rest api to read data
* @param {string} database the database connector key
* @param {string} view the view id
* @param {IParams} params additional parameters
* @returns {Promise<IRow[]>}
*/
static getTDPRows(database: string, view: string, params?: IParams): Promise<IRow[]>;
/**
* Merges the "regular" parameters with filter parameters for the URL.
* Filter parameters are prefixed accordingly to be accepted by the backend.
*
* @param params URL parameters
* @param filters URL filter parameters
*/
static mergeParamAndFilters(params: IParams, filters: IParams): {
[x: string]: string | number | boolean | string[] | number[] | boolean[];
};
/**
* query the TDP rest api to read data with additional given filters
* @param {string} database the database connector key
* @param {string} view the view id
* @param {IParams} params additional parameters
* @param {IParams} filters filters to use
* @returns {Promise<IRow[]>}
*/
static getTDPFilteredRows(database: string, view: string, params: IParams, filters: IParams): Promise<IRow[]>;
/**
* query the TDP rest api to read data with additional given filters
* @param {string} database the database connector key
* @param {string} view the view id
* @param {IParams} params additional parameters
* @param {IAllFilters} filters object that contains all filter options
* @returns {Promise<IRow[]>}
*/
static getTDPFilteredRowsWithLessGreater(database: string, view: string, params: IParams, filters?: IAllFilters): Promise<IRow[]>;
/**
* query the TDP rest api to read a score
* @param {string} database the database connector key
* @param {string} view the view id
* @param {IParams} params additional parameters
* @param {IParams} filters filters to use
* @returns {Promise<IScoreRow<T>[]>}
*/
static getTDPScore<T>(database: string, view: string, params?: IParams, filters?: IParams): Promise<IScoreRow<T>[]>;
/**
* query the TDP rest api to read a score
* @param {string} database the database connector key
* @param {string} view the view id
* @param {IParams} params additional parameters
* @param {IAllFilters} filters object that contains all filter options
* @returns {Promise<IScoreRow<T>[]>}
*/
static getTDPScoreWithLessGreater<T>(database: string, view: string, params?: IParams, filters?: IAllFilters): Promise<IScoreRow<T>[]>;
/**
* query the TDP rest api to compute the number of rows matching this query
* @param {string} database the database connector key
* @param {string} view the view id
* @param {IParams} params additional parameters
* @param {IParams} filters filters to use
* @returns {Promise<number>}
*/
static getTDPCount(database: string, view: string, params?: IParams, filters?: IParams): Promise<number>;
/**
* query the TDP rest api to compute the number of rows matching this query
* @param {string} database the database connector key
* @param {string} view the view id
* @param {IParams} params additional parameters
* @param {IAllFilters} filters object that contains all filter options
* @returns {Promise<number>}
*/
static getTDPCountWithLessGreater(database: string, view: string, params?: IParams, filters?: IAllFilters): Promise<number>;
static getTDPLookupUrl(database: string, view: string, params?: IParams): string;
/**
* lookup utility function as used for auto completion within select2 form elements
* @param {string} database the database connector key
* @param {string} view the view id
* @param {IParams} params additional parameters
* @returns {Promise<Readonly<ILookupResult>>}
*/
static getTDPLookup(database: string, view: string, params?: IParams): Promise<Readonly<ILookupResult>>;
}
//# sourceMappingURL=rest.d.ts.map
|
6ecd3636fbb82bd2eef0c02f6668dc3ad872581c
|
TypeScript
|
HearTao/typei18n
|
/src/types.ts
| 3.078125
| 3
|
export type YamlNode = string | number | { [v: string]: YamlNode }
export const enum ArgKind {
literal = 'literal',
param = 'param'
}
export interface LiteralArg {
kind: ArgKind.literal
value: string
}
export interface ParamArg {
kind: ArgKind.param
name: string
}
export type ArgType = LiteralArg | ParamArg
export const enum TypeDescriptorKind {
string = 'String',
call = 'Function',
record = 'Record'
}
export interface StringTypeDescriptor {
kind: TypeDescriptorKind.string
value: string
}
export interface CallTypeDescriptor {
kind: TypeDescriptorKind.call
body: ArgType[]
}
export interface RecordTypeDescriptor {
kind: TypeDescriptorKind.record
value: Record<string, TypeDescriptor>
}
export interface MissingRecordTypeDescriptor extends RecordTypeDescriptor {
missing: true
}
export type TypeDescriptor =
| StringTypeDescriptor
| CallTypeDescriptor
| RecordTypeDescriptor
| MissingRecordTypeDescriptor
export const enum Target {
resource = 'resource',
provider = 'provider',
type = 'type'
}
export const enum MismatchedKeyType { LHS, RHS }
export const enum ErrorType {
UnexpectedValueType = 'Unexpected type',
NotFoundKey = 'Not found key',
MismatchedKind = 'Mismatched kind',
MismatchedArguments = 'Mismatched arguments'
}
export type ErrorRecord =
| { type: ErrorType.UnexpectedValueType, path: string, payload: [ string, string ] }
| { type: ErrorType.MismatchedKind, path: string }
| { type: ErrorType.MismatchedArguments, path: string }
| { type: ErrorType.NotFoundKey, path: string, payload: [ MismatchedKeyType, Set<string> ] }
export interface Context {
errors: Map<string, ErrorRecord>
paths: string[]
}
export interface NamedValue<T = string> {
name: string
value: T
}
|
881d66e0d1677b0d88d2bbfe7ad6b18a88a9a0b4
|
TypeScript
|
canrozanes/turnouter-api
|
/src/utils/get-winner.ts
| 3.1875
| 3
|
const getWinner = (votes: string[]): { winner: string; count: number } => {
const counts: { [key: string]: number } = {}
votes.forEach((vote) => {
if (!(vote in counts)) {
counts[vote] = 1
} else {
counts[vote] += 1
}
})
let maxCount = 0
let winner: string
const entries = Object.entries(counts)
for (let i = 0; i < entries.length; i++) {
const candidate = entries[i][0]
const voteCount = entries[i][1]
if (voteCount > maxCount) {
maxCount = voteCount
winner = candidate
}
}
return {
winner,
count: maxCount,
}
}
export default getWinner
|
b55ac6299e8225856031b7b0f777e9419bbda9c7
|
TypeScript
|
diroussel/orgtomate-js
|
/src/org.ts
| 2.59375
| 3
|
#!/usr/bin/env node
/** vim: set syntax=typescript tabstop=2 softtabstop=2 shiftwidth=2 expandtab smarttab : */
/**
* A command-line interface as a replacement for, or supplement to, the AWS CLI
* that is not only faster than the AWS CLI, but also allows the execution of operations
* in multiple AWS Accounts and Regions in parallel using Orgtomate.
*
* @module
*/
'use strict';
/**
* We're not actually using the AWS-SDK to make API calls,
* we leave that to getAwsResults, but we use this to validate
* the options we've passed as the object keys on clients/all
* gives us a list of all currently supported clients
*/
import * as AWSClients from 'aws-sdk/clients/all';
/** Yargs is our command line argument parser */
import yargs = require('yargs');
import {
/**
* A type definition that extends AwsOrgNode that represents the object
* passed to our callback function from orgtomate
*/
ProcessableAccount,
/**
* A type definition that represents the credentials object passed
* to our callback function from orgtomate that we will pass on
* into the getAwsResults client parameters
*/
RoleCredentials,
/**
* A type definition representing the Role Information we need to
* pass into orgtomate for it to assume in each account
*/
RoleInfo,
/** The orgtomate function */
orgtomate,
} from './orgtomate';
/** The getAwsResults function that will do all of our AWS API calls */
import { getAwsResults } from './get-aws-results';
/**
* The results of our regionalPayload function that we will process
* after Orgtomate executes it everywhere
*
* @remarks
* If we use Orgtomate, We are going to create a custom query that we
* will execute in every region in every AWS account, and pass that
* to Orgtomate. Orgtomate will return the results of our callback to
* us in the same way we created it, just wrapped in Arrays.
* This type lets us define what we are creating so that we process it
* the same way when it comes back to us, even though Orgtomate
* can only process it as an any.
*
* If we are not using Orgtomate, we still generate results using the
* same basic structure, just without the information we don't know
* as we can't get the account name without AWS Organizations and
* we can't get the account ID without an unnecessary API call
*/
type RegionalPayloadResult = {
/** String indexable */
[index: string]: any;
/** The AWS Account ID of the payload execution */
accountId?: string;
/** The AWS Account Name of payload execution */
accountName?: string;
/** The region of the payload execution */
region: string;
/** The results block that we get from getAwsResults */
results: any;
};
/**
* Respect the AWS approach for region definition from the environment
* if it's not set, respect the AWS default selection of us-east-1 for SDKs
* This can still be overridden by command line options
*/
const awsRegion = process.env.AWS_REGION;
const awsDefaultRegion = process.env.AWS_DEFAULT_REGION;
const defaultRegion = awsDefaultRegion || awsRegion || 'us-east-1';
/**
* If we're invoking orgtomate, we need all of these set
* these represent defaults for AWS Organizations, but ought
* to be customised in a correctly secured Organization
*/
const roleDurationSeconds = process.env.ROLE_DURATION_SECONDS || 900;
const roleExternalId = process.env.ROLE_EXTERNAL_ID || undefined;
const roleName = process.env.ROLE_NAME || 'OrganizationAccountAccessRole';
const roleSessionName = process.env.ROLE_SESSION_NAME || 'orgtomate-cli';
/**
* The Arguments we will get from Yargs
*
* @internal
*/
interface Arguments {
[index: string]: unknown;
r: Array<string | number> | undefined;
regions?: Array<string | number>;
f: string | undefined;
format?: string;
c: Array<string | number> | undefined;
'client-args'?: Array<string | number>;
a: Array<string | number> | undefined;
'operation-args'?: Array<string | number>;
j: boolean;
'args-as-json'?: boolean;
k: string | undefined;
'result-key'?: string;
o: string | undefined;
orgtomate?: string;
y: boolean;
recurse?: boolean;
n: string | undefined;
'role-name'?: string;
e: string | undefined;
'external-id'?: string;
s: string | number | undefined;
'session-duration'?: string | number;
x: string | undefined;
'session-name'?: string;
d: boolean;
debug?: boolean;
_: (string | number)[];
$0: string;
}
/** The implementation of Arguments by Yargs */
const options: Arguments = yargs
.usage(
'Usage: org <service> <operation> -c <service key=val> <service key=val> -a <operation key=val> <operation key=val> -o <orgtomate target> -r <region> <region> -k <result key>',
)
.option('r', {
alias: 'regions',
type: 'array',
default: [defaultRegion],
describe: 'List of regions to execute queries against. Defaults to AWS_DEFAULT_REGION/AWS_REGION from environment',
demandOption: true,
})
.option('f', {
alias: 'format',
type: 'string',
default: 'flat',
describe: "Output format. Can be: 'flat', 'full', 'regions', 'accountids', 'accountnames'",
choices: ['flat', 'full', 'regions', 'accountids', 'accountnames'],
})
.option('c', {
alias: 'client-args',
type: 'array',
describe: 'Arguments for the API Client Constructor: key1=value1 key2=value2',
})
.option('a', {
alias: 'operation-args',
type: 'array',
describe: 'Arguments for the API Client Operation: key1=value1 key2=value2',
})
.option('j', {
alias: 'args-as-json',
type: 'boolean',
default: false,
describe: 'Whether to parse client and constructor arguments as JSON',
})
.option('k', {
alias: 'result-key',
type: 'string',
describe: 'Optional Result Key from the API Response',
})
.option('o', {
alias: 'orgtomate',
type: 'string',
describe: '"Root" or ID of an Organizations Object (Root, Organizational Unit or Account)',
})
.option('y', {
alias: 'recurse',
type: 'boolean',
default: true,
describe:
'Whether to recursively apply to all accounts in the tree below the orgtomate target, or only the accounts directly beneath the target node',
})
.option('n', {
alias: 'role-name',
type: 'string',
default: roleName,
describe: 'Orgtomation Cross Account Role Name',
})
.option('e', {
alias: 'external-id',
type: 'string',
default: roleExternalId,
describe: 'Orgtomation Cross Account Role External ID',
})
.option('s', {
alias: 'session-duration',
type: 'number',
default: roleDurationSeconds,
describe: 'Orgtomation Cross Account Role Session Duration',
})
.option('x', {
alias: 'session-name',
type: 'string',
default: roleSessionName,
describe: 'Orgtomation Cross Account Role Session Name',
})
.option('d', {
alias: 'debug',
type: 'boolean',
default: false,
describe: 'Debug Output (to STDERR)',
})
.check((argv) => {
if (argv._.length !== 2) {
return `Two positional arguments are required: service and operation, i.e. Route53 listHostedZones or EC2 describeInstances. You provided: ${argv._}`;
}
if (argv.f) {
if (!argv.o && (argv.f === 'accountids' || argv.f === 'accountnames' || argv.f === 'regions')) {
return "Output formats other than 'flat' and 'full' can only be used in conjuction with --orgtomate/-o";
}
}
return true;
})
.parseSync();
const { debug } = options;
if (debug) {
console.error(options);
}
/**
* A function to handle the errors in the command line execution.
*
* @remarks
* When an error is thrown it is caught and signals an abnormal
* process exit, printing the error to the console
*
* @param error - A thrown Exception or error string
* @internal
*/
const _die = (error: unknown): void => {
console.error(error);
process.exit(1);
};
/**
* The main async execution function for the CLI
*
* @returns An empty promise
* @internal
*/
const execute = async () => {
if (!options._[0]) {
throw new Error('No Service Provided!');
}
const service = options._[0].toString();
if (debug) {
console.error(`Service: ${service}`);
}
if (!options._[1]) {
throw new Error('No Operation Provided!');
}
const operation = options._[1].toString();
if (debug) {
console.error(`Operation: ${operation}`);
}
/**
* Use aws-sdk/client/all to find out all services supported by
* the version of the aws-sdk we're using, so we can validate
* if the service requested is supported or not
*/
if (!Object.keys(AWSClients).includes(service)) {
console.error('Invalid AWS Service');
process.exit(1);
}
if (debug) {
console.error(`Service is available in the AWS JS SDK`);
}
/** -j/--args-as-json or --no-j/--no-args-as-json */
const argsAsJson = options['args-as-json'];
if (debug) {
console.error(`Client and Operation Arguments parsed as JSON?: ${argsAsJson}`);
}
/**
* Create the parameters that will be fed to the Service Constructor
* We can't have any idea what type of object this will be, we only
* know that it will be string indexed
*/
const clientParams: { [index: string]: any } = {};
if (options['client-args']) {
options['client-args'].forEach((element) => {
const arr = element.toString().split('=');
if (arr && arr.length === 2) {
const [clientParamKey, clientParamValue] = arr;
if (argsAsJson) {
try {
clientParams[clientParamKey] = JSON.parse(clientParamValue);
} catch (error: unknown) {
if (error instanceof SyntaxError) {
throw new Error(
`Operation Argument ${clientParamKey} value is not valid JSON: ${clientParamValue} :: Don't forget to escape string quotes or single-quote your input when using -j/--args-as-json`,
);
} else {
throw error;
}
}
} else {
clientParams[clientParamKey] = clientParamValue;
}
} else {
throw new Error(`Client Argument parsing error. ${element} should be key=value`);
}
});
}
if (debug) {
console.error(`Custom Parameters to the AWS Service constructor: ${JSON.stringify(clientParams, null, 2)}`);
}
/**
* This is probably the worst bit of fudgery in this code.
* It is how we can determine which operations the AWS Service
* requested supports, but the Clients object has to be force-casted
* to any in order for us to instantiate an unknown service from it
* and we have to create an instance of the service object so as to
* query the supported services as they are only available from the
* instantiated object, not from the service object interface
*/
if (!(operation in new (<any>AWSClients)[service]()['api']['operations'])) {
throw new Error(`Service ${service} does not support operation ${operation}`);
}
if (debug) {
console.error(`Service ${service} supports operation ${operation}`);
}
/**
* If the user has passed additional arguments for the operation
* construct the map that will be passed to the API function call
* As with client params, we can't know anything about this object
* other than it's string-indexable
*/
const operationParams: { [index: string]: any } = {};
if (options['operation-args']) {
options['operation-args'].forEach((element) => {
const arr = element.toString().split('=');
if (arr && arr.length === 2) {
const [operationParamKey, operationParamValue] = arr;
if (argsAsJson) {
try {
operationParams[operationParamKey] = JSON.parse(operationParamValue);
} catch (error: unknown) {
if (error instanceof SyntaxError) {
throw new Error(
`Operation Argument ${operationParamKey} value is not valid JSON: ${operationParamValue} :: Don't forget to escape string quotes or single-quote your input when using -j/--args-as-json`,
);
} else {
throw error;
}
}
} else {
operationParams[operationParamKey] = operationParamValue;
}
} else {
throw new Error(`Operation Argument parsing error. ${element} should be key=value`);
}
});
}
if (debug) {
console.error(`Custom Parameters to the ${operation} operation: ${JSON.stringify(operationParams, null, 2)}`);
}
/** If we have been passed a resultKey it will get passed directly into getAwsResults */
const resultKey: string | undefined = options['result-key'] || undefined;
if (debug) {
console.error(`Result Key: ${resultKey}`);
}
/**
* By default, do not use Orgtomate - just run on the local account
* but do it much more quickly than the Python AWS CLI ;-)
*/
let useOrgtomate = false;
let targetId;
/**
* Oooo we *are* going to Orgtomate!
* Let's pass in our target AWS Organizations node
* which by default is the ROOT node
*/
if (options.orgtomate) {
useOrgtomate = true;
if (options.orgtomate !== 'Root') {
targetId = options.orgtomate;
}
}
/**
* Get our regions from the user. If the user didn't
* specify one or more regions, we'll just work in the one we have
*/
if (!options.regions) {
throw new Error('Regions not Defined');
}
const regions: Array<string> = [];
options.regions.forEach((region) => {
regions.push(region.toString());
});
if (debug) {
console.error(`Regions: ${regions}`);
}
/** Get our console output format preference from options */
if (!options.format) {
throw new Error('Format not Defined');
}
const outputFormat = options.format;
if (debug) {
console.error(`Output Format: ${outputFormat}`);
}
/** Here we go! */
let results: Array<RegionalPayloadResult>;
/**
* Using Orgtomate means a completely different approach that without it
* with orgtomate we need to configure our callback. Without, all we need
* is a getAwsResults call
*/
if (useOrgtomate) {
if (debug) {
console.error(`Using Orgtomate`);
}
/**
* Set up the Cross Account Role configuration for Orgtomation
* Even though we would like everyone to follow best practice and
* use an ExternalId, the default AWS Organizations setup doesn't
* have one, an we can't hold that against users by requiring it
*/
if (!options['session-duration'] || !options['role-name'] || !options['session-name']) {
throw new Error('Role Info is incomplete');
}
const roleInfo: RoleInfo = {
durationSeconds: parseInt(options['session-duration'].toString(), 10),
externalId: options['external-id'] || undefined,
name: options['role-name'],
sessionName: options['session-name'],
};
if (debug) {
console.error(`Role Information: ${JSON.stringify(roleInfo, null, 2)}`);
}
/** -y/--recurse or --no-y/--no-recurse */
const { recurse } = options;
if (debug) {
console.error(`Recurse?: ${recurse}`);
}
/**
* This is the async callback function we are going to run in parallel
* against every AWS Account we are targeting
*
* @remarks
* Orgtomate will send us a creds object and an awsOrgNode object
* for the cross account role credentials to use and the
* account we are going to operate on. We don't have to use
* the awsAccount object, but it's the only way for our callback
* to know where it is executing if we want that information for
* any reason in our code. The credentials object must be passed
* into any API call we make, whether via getAwsResults or not
* so that our call will be made in the correct target account
*
* *NOTE:* Any errors thrown inside this callback will not
* be treated as fatal. The error will be logged to the console
* and the output will be chomped from the final result inside
* Orgtomate.procesAccount. This allows one account to fail
* without affecting the availability of results from the others.
*
* @param credentials - A RoleCredentials object passed in from orgtomate
* @param awsAccounts - A ProcessableAccount object passed in from orgtomate
* @returns A promise to return an array of RegionalPayloadResult objects
* from our regional payload function
* @internal
*/
const orgtomateCallback = async (
credentials: RoleCredentials,
awsAccount: ProcessableAccount,
): Promise<Array<RegionalPayloadResult>> => {
/**
* The function block to be executed in every region in every account
*
* @remarks
* Because we're greedy, let's set up another function payload
* so that we can run the command in multiple regions in parallel
* as well as multiple accounts in parallel.A
*
* This is where the actual code we're going to run in each account
* is going to sit. While it is orgtomate's responsibility to execute
* a block of code in every account, it's not orgtomate's responsibility
* to do it across regions. We do that ourselves here.
*
* @param region - The region we're operating in inside this payload
* @returns A promise to return an instance of Our custom type definition
* of a Regional Payload Result that standardises how we will create and
* then process the results we are getting from each region in each account
* @internal
*/
const regionalPayload = async (region: string): Promise<RegionalPayloadResult> => {
if (debug) {
console.error(`Processing Account: ${awsAccount.Name} (${awsAccount.Id}) in region: ${region}`);
}
/*
* Set up the parameters that will be sent to the AWS Service constructor in getAwsResults
* Precedence is critical here, so that the caller can override the region or credentials
* the constructor uses with a custom client parameter of their own
*/
const regionalClientParams = { credentials, region, ...clientParams };
/** FINALLY execute our AWS API call */
const awsResults = await getAwsResults(
service,
operation,
regionalClientParams,
operationParams,
resultKey,
).catch((error: unknown) => {
throw error;
});
/**
* We have to return all of this information here. All of the function executions
* down to this level are parallelised asynchronous Promises, and the results
* are all just lists of result objects. Once all of the results have been collated
* the contents of this object are all that determine which results belong to which
* account and region. We technically could look up the name later from the ID
* but adding the name here, since we have it in the AwsOrgNode object makes parsing
* the output so much easier.
*/
const regionalPayloadResult: RegionalPayloadResult = {
accountId: awsAccount.Id,
accountName: awsAccount.Name,
region,
results: awsResults,
};
return regionalPayloadResult;
};
/**
* Map one regionalPayload function to each region
* we have been configured to run against in this account
*/
const regionalTasks = regions.map(regionalPayload);
/**
* Execute the regional payloads on all regions in parallel
* for the account we are running against
*/
const regionalTaskResults: Array<RegionalPayloadResult> = await Promise.all(regionalTasks).catch(
(error: unknown) => {
throw error;
},
);
/** Return our Array of RegionalPayloadResult objects */
return regionalTaskResults;
};
/**
* FINALLY execute orgtomate, passing in our callback, role information and the target
* accounts we want orgtomate to operate on, and have it return to us the results we asked for
* as the RegionalPayloadResult type we created them as, buried in an Array per AWS Account
* containing an Array per region
*/
if (debug) {
console.error(`Invoking Orgtomate...`);
}
const allResults: Array<Array<RegionalPayloadResult>> = await orgtomate(
orgtomateCallback,
roleInfo,
targetId,
recurse,
).catch((error: unknown) => {
throw error;
});
if (debug) {
console.error(`Orgtomation complete. Processing results...`);
}
/** Flatten the results for processing into a single Array<RegionalPayloadResult> */
results = allResults.flat();
} else {
/** No Orgtomate, Denied! */
if (debug) {
console.error(`Not using Orgtomate`);
}
/**
* The regionalPayload for the call we are parallelising across all requested regions
*
* @remarks
* We're still going to allow for parallelisation of a local CLI call across
* multiple regions at once, just another benefit we have over the AWS CLI
* Use the same regionalPayload approach as if we had orgtomated.
*
* @param region - The region the payload will execute in
* @returns A promise to return a Regional Payload Result
* @internal
*/
const regionalPayload = async (region: string): Promise<RegionalPayloadResult> => {
if (debug) {
console.error(`Processing region: ${region}`);
}
/**
* Set up the parameters that will be sent to the AWS Service constructor in getAwsResults
* Precedence is critical here, so that the caller can override the region
* the constructor uses with a custom client parameter of their own
*/
const regionalClientParams = { region, ...clientParams };
/** FINALLY execute our AWS API call */
const awsResults = await getAwsResults(
service,
operation,
regionalClientParams,
operationParams,
resultKey,
).catch((error: unknown) => {
/**
* We could maybe be a little more chill here, and instead of throwing an error
* for a failure in one region, just drop the error on the console and
* still try to return the results for the other regions like Orgtomate
* does for each account, but this is an executive decision that if you
* are running a call in one account, any exceptions you're going to cause
* in one region you are probably going to cause in another region
* and it's reasonable to assume that anyone making a multi-region
* call in a single account needs all the regional results to succeed
* for the output to be correct and useful.
*
* Change my mind.
*/
throw error;
});
const regionalPayloadResult: RegionalPayloadResult = {
region,
results: awsResults,
};
if (debug) {
console.error(`Operation complete. Processing results...`);
console.error(regionalPayloadResult);
}
return regionalPayloadResult;
};
/** Parallelise the payload execution across each requested region */
const regionalTasks = regions.map(regionalPayload);
results = await Promise.all(regionalTasks).catch((error: unknown) => {
throw error;
});
}
/**
* BOOM. We have our results. Now if only we knew what to do with them(!)
*/
/**
* A function to rearrange an Array of RegionalPayloadResults into an output
* format that suits the needs of the user
*
* @param resultsToArrange - The Array of RegionalPayloadResult objects to arrange
* @param arrangementMethod - The method to use to rearrange the results
* @param resultsResultKey - The resultKey that was sent into the getAwsResults calls, if defined
* which makes a significant difference to what the results objects look like
* and therefore how we can process them. Technically we could access this directly
* in scope as resultKey, but it just feels saner to let this function manage
* its own scope and send a value into it. Especially if we move this function.
* @returns A string-indexed Object that contains our rearranged results
* @internal
*/
const arrangeResultsBy = (
resultsToArrange: Array<RegionalPayloadResult>,
arrangementMethod: string,
resultsResultKey: string | undefined,
): { [index: string]: any } => {
if (debug) {
console.error(`Arranging results by: ${arrangementMethod}...`);
}
/**
* Set up the returnable object to fill in with results
*
* This would be a const except for the Unexpected Single Item Instead of Array condition
*/
let arrangedOutput: { [index: string]: any } = {};
/**
* Iterate each of the RegionalPayloadResult objects and
* inject a formatted version into the output object
*/
resultsToArrange.forEach((regionalPayloadResult) => {
/** Typescript-enforced safety and did we get any results anyway? */
if (regionalPayloadResult && regionalPayloadResult.results) {
/** Flattening the results is completely different to rearranging them */
if (arrangementMethod === 'flat') {
/** If a resultKey was used, the results are easier to flatten as we have no metadata to merge */
if (resultsResultKey) {
if (!arrangedOutput[resultsResultKey]) {
arrangedOutput[resultsResultKey] = [];
}
if (regionalPayloadResult.results instanceof Array) {
/**
* We know we have only one key in our results blocks, and it contains an Array
* so we can just merge all the values from all the blocks into one single block
* of the same key. Nice and neat.
*/
regionalPayloadResult.results.forEach((regionalPayloadResultValue: any) => {
arrangedOutput[resultsResultKey] = arrangedOutput[resultsResultKey].concat(regionalPayloadResultValue);
});
} else {
/** The regionalPayloadResult results key was not an Array of objects just a single solitary object obtained with a resultKey */
arrangedOutput[resultsResultKey].push(regionalPayloadResult.results);
}
} else if (regionalPayloadResult.results instanceof Array) {
/**
* resultKey was not used; therefore there's potentially lots of keys in the object
* including potentially multiple keys from the AWS API (especially if we're dealing with
* S3 objects, but also metadata about the call such as getAwsResults's custom PaginationMetadata
* key and operation parameters, and pagination tokens.
*
* Since the user didn't ask for a specific key, lets give them everything, just merge
* all object values for each key that exists into one array of the same key name
*/
Object.entries(regionalPayloadResult.results).forEach(([key, value]) => {
if (!arrangedOutput[key]) {
arrangedOutput[key] = [];
}
arrangedOutput[key] = arrangedOutput[key].concat(value);
});
} else {
if (Object.keys(arrangedOutput).length === 0) {
arrangedOutput = new Array<any>();
}
arrangedOutput.push(regionalPayloadResult.results);
}
} else {
/** So we are definitely re-arranging these results, not just flattening them */
/** Let's check the key we've been asked to index results by exists in the first result we have */
if (arrangementMethod in Object.keys(regionalPayloadResult)) {
throw new Error(`Account did not have key ${arrangementMethod} to arrange by: ${regionalPayloadResult}`);
}
const arrangementKey = regionalPayloadResult[arrangementMethod];
/** As with the flattening operation, it's a lot easier if a resultKey was used */
if (resultsResultKey) {
if (!arrangedOutput[arrangementKey]) {
arrangedOutput[arrangementKey] = { [resultsResultKey]: [] };
}
if (regionalPayloadResult.results instanceof Array) {
/**
* For each regionalPayloadResult, we are going to ensure there is a top level
* index for each value we find for that key, i.e. each region we have results
* for it if the key is regions. Then in each one, concatenate all the results values
* for each regionalPayloadResult's resultKey into one object which will
* give us one result key per index containing all of the results that
* match that index
*/
regionalPayloadResult.results.forEach((regionalPayloadResultValue: any) => {
arrangedOutput[arrangementKey][resultsResultKey] =
arrangedOutput[arrangementKey][resultsResultKey].concat(regionalPayloadResultValue);
});
} else {
arrangedOutput[arrangementKey][resultsResultKey].push(regionalPayloadResult.results);
}
} else {
/**
* No resultKey, just splattergun all of the result values for all of the keys
* into a single array of the same key for each of the indices we're arranging by
*/
Object.entries(regionalPayloadResult.results).forEach(([key, value]) => {
if (!arrangedOutput[arrangementKey]) {
arrangedOutput[arrangementKey] = { [key]: [] };
} else if (!arrangedOutput[arrangementKey][key]) {
arrangedOutput[arrangementKey][key] = [];
}
arrangedOutput[arrangementKey][key].push(value);
});
}
}
}
});
if (debug) {
console.error(`Output arranged`);
}
/** Phew! */
return arrangedOutput;
};
/**
* We have our results. We can do whatever we want with them.
* If we're asked to arrange them, arrange them, or we can
* just return them as is.
*/
let consoleOutput: any;
switch (outputFormat) {
case 'flat':
consoleOutput = arrangeResultsBy(results, 'flat', resultKey);
break;
case 'regions':
consoleOutput = arrangeResultsBy(results, 'region', resultKey);
break;
case 'accountids':
consoleOutput = arrangeResultsBy(results, 'accountId', resultKey);
break;
case 'accountnames':
consoleOutput = arrangeResultsBy(results, 'accountName', resultKey);
break;
case 'full':
consoleOutput = results;
break;
default:
throw new Error('Invalid output format');
}
if (debug) {
console.error(`Printing Output to STDOUT as JSON.stringify(consoleOutput, null, 2)`);
}
/** This is how I like my results. Give me a reason to make this customisable */
console.log(JSON.stringify(consoleOutput, null, 2));
};
/**
* If executing from the CLI, run the execute function.
* I mean, this *is* a CLI so I don't know why you wouldn't
* but we still need to call execute() from here because
* it's async.
*/
if (require.main === module) {
execute().catch((error: unknown) => {
_die(error);
});
}
|
bdd09879e0c0b6bc86e956b94e8917443005a804
|
TypeScript
|
Iru89/geometric-app
|
/src/redux/types/profileTypes.ts
| 2.59375
| 3
|
import {Action} from "redux";
import {IProfile} from "../../types";
export const PROFILE_REQUEST = 'PROFILE_REQUEST';
export const PROFILE_SUCCESS = 'PROFILE_SUCCESS';
export const PROFILE_ERROR = 'PROFILE_ERROR';
export interface IProfileRequest extends Action{
type: typeof PROFILE_REQUEST,
isFetching: boolean,
}
export interface IProfileSuccess extends Action{
type: typeof PROFILE_SUCCESS,
isFetching: boolean,
profile: IProfile,
}
export interface IProfileError extends Action{
type: typeof PROFILE_ERROR,
isFetching: boolean,
message: string,
}
export type ProfileActions = IProfileRequest | IProfileSuccess | IProfileError;
|
a59fab6a87c66a60cb41e2c933215a9b08b7bffe
|
TypeScript
|
Dtrust/social_network
|
/frontend/src/store/ducks/post/reducer.ts
| 2.671875
| 3
|
import produce, {Draft} from "immer";
import {PostState} from "./contracts/state";
import {PostActions} from "./actions/actionCreators";
import { PostActionsType } from "./actions/actionTypes";
import { LoadingStatus } from "../../types";
const initialPostState: PostState = {
data: undefined,
loadingState: LoadingStatus.NEVER
};
export const postReducer = produce((draft: Draft<PostState>, action: PostActions) => {
switch (action.type) {
case PostActionsType.SET_POST_DATA:
draft.data = action.payload;
draft.loadingState = LoadingStatus.LOADED;
break;
case PostActionsType.FETCH_POST_DATA:
draft.data = undefined;
draft.loadingState = LoadingStatus.LOADING;
break;
case PostActionsType.SET_LOADING_STATE:
draft.loadingState = LoadingStatus.LOADED;
break;
default:
break;
}
}, initialPostState)
|
203310e0c7fcf3418ed863d4aa689cd4fff72642
|
TypeScript
|
dchesterton/nasa-image-and-video-library
|
/src/store/asset/reducer.ts
| 2.578125
| 3
|
import { Reducer } from "redux";
import {
AssetActionTypes,
AssetState,
FETCH_MANIFEST_REQUEST,
FETCH_MANIFEST_SUCCESS,
FETCH_MANIFEST_ERROR,
DISPLAY_ASSET,
CLOSE_ASSET
} from "./types";
import { RequestStatus } from "../../types";
export const initialState: AssetState = {};
export const assetReducer: Reducer<AssetState, AssetActionTypes> = (
state = initialState,
action
) => {
switch (action.type) {
case CLOSE_ASSET:
return { ...state, currentAsset: undefined };
case DISPLAY_ASSET:
return { ...state, currentAsset: action.asset };
case FETCH_MANIFEST_REQUEST:
return { ...state, status: RequestStatus.Loading };
case FETCH_MANIFEST_SUCCESS:
const manifest = action.response.collection.items.map(
item => item.href
);
return {
...state,
status: RequestStatus.Success,
manifest
};
case FETCH_MANIFEST_ERROR:
return { ...state, status: RequestStatus.Error };
default:
return state;
}
};
|
9a9aac765a1001ea06a620803f1035a9ec04dbaa
|
TypeScript
|
coffmanjrp/ts-double-heart-click
|
/src/ts/main.ts
| 2.84375
| 3
|
const loveMe = document.querySelector('.loveMe') as HTMLDivElement;
const times = document.querySelector('#times') as HTMLDivElement;
let clickTime = 0;
let timesClicked = 0;
const createHeart = (e: MouseEvent) => {
const heart = document.createElement('i');
heart.classList.add('fas');
heart.classList.add('fa-heart');
const x = e.clientX;
const y = e.clientY;
const leftOffset = (e.target as HTMLDivElement).offsetLeft;
const topOffset = (e.target as HTMLDivElement).offsetTop;
const xInside = x - leftOffset;
const yInside = y - topOffset;
heart.style.top = `${yInside}px`;
heart.style.left = `${xInside}px`;
loveMe.appendChild(heart);
const likes = ++timesClicked;
times.innerHTML = likes.toString();
setTimeout(() => heart.remove(), 1000);
};
loveMe.addEventListener('click', (e) => {
if (clickTime === 0) {
clickTime = new Date().getTime();
} else if (new Date().getTime() - clickTime < 800) {
createHeart(e);
clickTime = 0;
} else {
clickTime = new Date().getTime();
}
});
|
a6fbc58e8a27b8f22585b142807e6dd503d400cd
|
TypeScript
|
bve/telegraf-inline-menu
|
/source/buttons/align.test.ts
| 3.0625
| 3
|
import test from 'ava'
import {getRowsOfButtons, maximumButtonsPerPage} from './align'
function generateCharArray(charA: string, charZ: string): string[] {
// https://stackoverflow.com/questions/24597634/how-to-generate-an-array-of-alphabet-in-jquery/24597663#24597663
const a = []
let i = charA.charCodeAt(0)
const j = charZ.charCodeAt(0)
for (; i <= j; ++i) {
a.push(String.fromCharCode(i))
}
return a
}
const inputData = generateCharArray('A', 'E')
test('without arg in one line', t => {
const result = getRowsOfButtons(generateCharArray('A', 'E'))
t.deepEqual(result, [
inputData
])
})
test('without buttons', t => {
const result = getRowsOfButtons([])
t.deepEqual(result, [])
})
test('less columns that buttons', t => {
const result = getRowsOfButtons(generateCharArray('A', 'E'), 3)
t.deepEqual(result, [
['A', 'B', 'C'],
['D', 'E']
])
})
test('trim by maxRows', t => {
const result = getRowsOfButtons(generateCharArray('A', 'Z'), 1, 5)
t.deepEqual(result, [
['A'],
['B'],
['C'],
['D'],
['E']
])
})
test('second page', t => {
const result = getRowsOfButtons(generateCharArray('A', 'Z'), 1, 3, 2)
t.deepEqual(result, [
['D'],
['E'],
['F']
])
})
test('partial last page', t => {
const result = getRowsOfButtons(generateCharArray('A', 'E'), 1, 3, 2)
t.deepEqual(result, [
['D'],
['E']
])
})
test('last possible page instead of wanted', t => {
const result = getRowsOfButtons(generateCharArray('A', 'F'), 1, 3, 3)
t.deepEqual(result, [
['D'],
['E'],
['F']
])
})
test('maximumButtonsPerPage example', t => {
t.is(maximumButtonsPerPage(2, 3), 6)
t.is(maximumButtonsPerPage(4, 4), 16)
})
test('maximumButtonsPerPage default', t => {
t.is(maximumButtonsPerPage(), 60)
})
|
d8d0dcc1d277924b47e9a45df9ae2495728963d0
|
TypeScript
|
Yokotes/loop-frontend
|
/back/src/dtos/userDto.ts
| 2.703125
| 3
|
class UserDto {
name: string;
password: string;
img: string;
role: string;
groupAliases: string[];
constructor(
name: string,
password: string,
img: string,
role: string,
groupAliases: string[]
)
{
this.name = name;
this.password = password;
this.img = img;
this.role = role;
this.groupAliases = groupAliases;
}
}
export default UserDto;
|
028eb30ae14b66cee4afe4d7f4fe1ceca933bc50
|
TypeScript
|
mosfiqurRahmanJsd/typescript-basic
|
/first.ts
| 3.640625
| 4
|
let age: number;
age = 50;
let club: string = 'Real Madrid';
const isFamous: boolean = false;
let famous: boolean;
function add (num1: any, num2: number | string){
return num1 + num2;
}
add(3, 76);
add('Adam', 'Sand');
add(3, 'Someone');
function doubleItAndConsole(num: number): void {
const result = num * 2;
console.log(result);
}
const output = doubleItAndConsole(10);
console.log('output', output);
function fullName (firstName: string, lastName: string): string {
return firstName + ' ' + lastName;
}
const user: string = fullName('Mosfiqur', 'Rahman');
let multiply2: (x:number, y: number) => number;
multiply2 = (x, y) => x * y;
const multiply = (x: number, y: number): number => x * y;
console.log(multiply(25, 10));
const numbers: number[] = [2, 3, 4, 8, 12, 91, 34];
numbers.push(22);
const friends: string[] = ['George', 'Jeff', 'Bill', 'Abdul'];
let megaName: string = '';
for (let i = 0; i < friends.length; i++) {
const friend: string = friends[i];
if(friend.length > megaName.length) {
megaName = friend;
}
}
console.log('Friend with the largest name', megaName);
let player: {
club: string,
salary: number
}
player = {
club: 'Real Madrid',
salary: 450000
}
// object
const friend: {name: string, age: number} = {
name: 'Samuel David',
age: 61
}
friend.age = 57;
interface Player {
club: string,
name: string,
salary: number,
wife ?: string,
isPlaying: boolean
}
const messy: Player = {
name: 'Messy',
club: 'Real Madrid',
salary: 4500000,
wife: 'Some name',
isPlaying: true
}
const ronaldo:Player = {
name: 'Ronaldo',
club: 'Liverpool',
salary: 5100000,
isPlaying: true
}
function getBonus (player: Player, friends: string[]) {
return player.salary * 0.1;
}
const poorPlayer = {salary: 10000, age: 50};
getBonus(messy, ['shuvo'])
class Person {
name: string;
private _partner: string;
readonly fatherName: string;
constructor(name: string, father: string) {
this.name = name;
this._partner = name;
this.fatherName = father;
}
getName(): string {
return this.name + '' + this._partner;
}
}
const sam = new Person('Samuel', 'Devid')
console.log('name', sam.name, sam.fatherName)
const samName: string = sam.getName();
sam.name = 'Ben';
|
ab81be70d9ddb70ff05f901808dabff20d5bb0bd
|
TypeScript
|
sergiosanchezs/Recursion-Store
|
/server/src/utils/capitalizeWords.ts
| 2.65625
| 3
|
const capitalizeWords = (word: string) => {
return word.replace(/\b\w/g, char => char.toUpperCase());
};
export default capitalizeWords;
|
8c0ad8ed9d58615e5e5f8daf88cab604bc0a417a
|
TypeScript
|
sirJiggles/angular-2
|
/app/components/hero-details/index.ts
| 2.640625
| 3
|
import {Component, OnInit, Output, EventEmitter} from 'angular2/core';
import {NgForm} from 'angular2/common';
import {RouteParams} from 'angular2/router';
import {HeroesService} from '../../services/heroes/index';
import {Hero} from '../../interfaces/hero/index';
@Component({
selector: 'hero-details',
inputs: ['hero'],
templateUrl: 'app/components/hero-details/template.html',
styleUrls: ['app/components/hero-details/style.css']
})
export class HeroDetailsComponent {
public hero: Hero;
public powers: string[] = ['Really Smart', 'Super Flexible', 'Super Hot', 'Weather Changer'];
public submited: boolean = false;
// An emitter for sending things out of the component
@Output() customEvent = new EventEmitter<Hero>();
// could use the custom event on the directive if it was a child like this
// <hero-details (customEvent)="someParentFunction($event)"></hero-details>
// The hero would be passed in the event to the parent
constructor(
private _heroesService: HeroesService,
private _routeParams: RouteParams) {
}
ngOnInit(): void {
// convert the route param to a number using + in JS
let id = +this._routeParams.get('id');
this._heroesService.getHero(id).then(hero => this.hero = hero);
}
onSubmit() {
// emit the custom hero out (if we where using)
this.customEvent.emit(this.hero);
console.log('sending it out');
this.submited = true;
}
goBack(): void {
window.history.back();
}
}
|
2e07ffb204cdaf228f008e751343440015e2ef81
|
TypeScript
|
webdevproformation/angular-3wa-oct21
|
/jour1Reprise/src/app/start/verifLogin.ts
| 3.03125
| 3
|
// dans le dossier src/app/start/ verifLogin.ts
import { AbstractControl, ValidationErrors } from "@angular/forms";
export class VerifLogin{
static neContientPasDePoint(control : AbstractControl) : ValidationErrors | null{
// la condition est vérifiée (si la chaine de caractère contient le symbole .)
// assertion de type
// console.log(control.value.indexOf("."));
const verif = (control.value as string).indexOf(".") // -1 si la condition est fausse
// nombre > -1 si la condition est respectée
if(verif !== -1){
return {
message : "le champ ne peut contenir le symbole .",
neContientPasDePoint : true
}
}
// si la condition n'est pas respectée (ne contient pas de .)
return null ;
}
}
|
a9f4505deee0e98d98afbb32d735a1dd5f1ad070
|
TypeScript
|
hlhNicola/CICD
|
/src/features/Intake/reducer.ts
| 2.515625
| 3
|
import { createSlice, PayloadAction } from 'redux-starter-kit';
export interface intakeState {
data:any,
calorie: number
}
const initialState:intakeState = {
data:[],
calorie: 0
};
const slice = createSlice({
name: 'intake',
initialState,
reducers: {
addItem: (state, action: PayloadAction<any>) => {
state.data = state.data.concat(action.payload)
state.calorie = state.data.reduce((a: number, b: any) => {
return a + b.ENERC_KCAL
}, 0)
},
reduceItem: (state, action: PayloadAction<string>) => {
state.data.splice(action.payload, 1)
state.calorie = state.data.reduce((a: number, b: any) => {
return a + b.ENERC_KCAL
}, 0)
},
intakeApiErrorReceived: (state, action: PayloadAction<any>) => state,
},
});
export const reducer = slice.reducer;
export const actions = slice.actions;
|
9981f6e98286f3a857594826a774bad3087c190b
|
TypeScript
|
MarquisF/react-redux-ts-boilerplate
|
/src/reducers/index.ts
| 2.671875
| 3
|
import { combineReducers } from 'redux';
import ActionTypes from 'actions/ActionTypes';
import documents from './documents';
import { CompositionState } from 'store/ApplicationState';
interface ReducerItem {
stateKey: string;
initialState: CompositionState;
reducerFunctions: any;
}
interface CompositionReducer {
(state: CompositionState, action: ActionTypes): CompositionState;
}
interface Reducers {
[index: string]: CompositionReducer;
}
const reducerList = [documents];
const reducers: Reducers = {};
reducerList.forEach((reducerItem: ReducerItem) => {
const { stateKey, initialState, reducerFunctions } = reducerItem;
reducers[stateKey] = (
state: CompositionState = initialState,
action: ActionTypes
): CompositionState => {
if (reducerFunctions.hasOwnProperty(action.type)) {
return reducerFunctions[action.type](state, action);
} else {
return state;
}
};
});
const rootReducer = combineReducers(reducers);
export default rootReducer;
|
2021a6e410d5883c3bac80efbd50d899689b465f
|
TypeScript
|
CommunitySolidServer/CommunitySolidServer
|
/src/identity/interaction/email-password/storage/AccountStore.ts
| 3.21875
| 3
|
/**
* Options that can be set on an account.
*/
export interface AccountSettings {
/**
* If this account can be used to identify as the corresponding WebID in the IDP.
*/
useIdp: boolean;
/**
* The base URL of the pod associated with this account, if there is one.
*/
podBaseUrl?: string;
/**
* All credential tokens associated with this account.
*/
clientCredentials?: string[];
}
/**
* Storage needed for the email-password interaction
*/
export interface AccountStore {
/**
* Authenticate if the username and password are correct and return the WebID
* if it is. Throw an error if it is not.
* @param email - The user's email.
* @param password - This user's password.
* @returns The user's WebID.
*/
authenticate: (email: string, password: string) => Promise<string>;
/**
* Creates a new account.
* @param email - Account email.
* @param webId - Account WebID.
* @param password - Account password.
* @param settings - Specific settings for the account.
*/
create: (email: string, webId: string, password: string, settings: AccountSettings) => Promise<void>;
/**
* Verifies the account creation. This can be used with, for example, e-mail verification.
* The account can only be used after it is verified.
* In case verification is not required, this should be called immediately after the `create` call.
* @param email - The account email.
*/
verify: (email: string) => Promise<void>;
/**
* Changes the password.
* @param email - The user's email.
* @param password - The user's password.
*/
changePassword: (email: string, password: string) => Promise<void>;
/**
* Gets the settings associated with this account.
* Errors if there is no matching account.
* @param webId - The account WebID.
*/
getSettings: (webId: string) => Promise<AccountSettings>;
/**
* Updates the settings associated with this account.
* @param webId - The account WebID.
* @param settings - New settings for the account.
*/
updateSettings: (webId: string, settings: AccountSettings) => Promise<void>;
/**
* Delete the account.
* @param email - The user's email.
*/
deleteAccount: (email: string) => Promise<void>;
/**
* Creates a Forgot Password Confirmation Record. This will be to remember that
* a user has made a request to reset a password. Throws an error if the email doesn't
* exist
* @param email - The user's email.
* @returns The record id. This should be included in the reset password link.
*/
generateForgotPasswordRecord: (email: string) => Promise<string>;
/**
* Gets the email associated with the forgot password confirmation record or undefined
* if it's not present
* @param recordId - The record id retrieved from the link.
* @returns The user's email.
*/
getForgotPasswordRecord: (recordId: string) => Promise<string | undefined>;
/**
* Deletes the Forgot Password Confirmation Record
* @param recordId - The record id of the forgot password confirmation record.
*/
deleteForgotPasswordRecord: (recordId: string) => Promise<void>;
}
|
d2630cdb14e4518d42c3e2af7d990f7ac2de904d
|
TypeScript
|
dxprog/pigeon
|
/src/interfaces/IResponse.ts
| 2.578125
| 3
|
export interface IResponse {
xhr: XMLHttpRequest;
httpStatus?: number;
response?: any;
error?: any;
}
export type IResponseFn = () => IResponse;
|
875d41840b51cd48f26768f53dd1a18b048caeb2
|
TypeScript
|
hiphil2000/pixi-practices
|
/src/objects/polygon.ts
| 2.75
| 3
|
import { IHitArea, Polygon, RenderTexture } from "pixi.js";
import BaseObject, { IBaseObjectConfig } from "./object";
export interface IPolygonObjectConfig extends IBaseObjectConfig {
points: Array<number>;
}
export default class PloygonObject extends BaseObject {
constructor(config: IPolygonObjectConfig) {
super(config);
}
protected GetTexture(): RenderTexture {
const config = this.config as IPolygonObjectConfig;
this._g.clear();
this._g.beginFill(config.backgroundColor, 1.0, true);
this._g.lineStyle(1, config.backgroundColor);
this._g.drawPolygon(config.points);
this._g.endFill();
return this._app.app.renderer.generateTexture(this._g);
}
protected GetHitArea(): IHitArea {
return new Polygon((this.config as IPolygonObjectConfig).points);
}
}
|
0883392bfca3acac11fa20119263b0e845602b55
|
TypeScript
|
InSeong-So/IT-Note
|
/chapter06-디자인패턴/javascript/ES6/bridge/typescript/bridge.ts
| 3.453125
| 3
|
import { Logger } from '../../logger';
//Refined Abstraction
export class CircleShape {
x: number;
y: number;
radius: number;
drawingApi: DrawingAPI;
constructor(x: number, y: number, radius: number, drawingApi: DrawingAPI) {
this.x = x;
this.y = y;
this.radius = radius;
this.drawingApi = drawingApi;
}
//low-level i.e. Implementation specific
draw() {
this.drawingApi.drawCircle(this.x, this.y, this.radius);
}
//high-level i.e. Abstraction specific
scale(pct: number) {
this.radius *= pct;
}
}
export class DrawingAPI {
logger: Logger;
constructor() {
this.logger = new Logger();
}
drawCircle(...args: any[]) {
throw new Error('Abstract method!');
}
}
//ConcreteImplementor 1/2
export class DrawingAPI1 extends DrawingAPI {
drawCircle(x: number, y: number, radius: number) {
this.logger.log('API1.circle at ' + x + ':' + y + ' radius ' + radius);
}
}
// ConcreteImplementor 2/2
export class DrawingAPI2 extends DrawingAPI {
drawCircle(x: number, y: number, radius: number) {
this.logger.log('API2.circle at ' + x + ':' + y + ' radius ' + radius);
}
}
|
882743394772b459f3048a5a7fbfd1857ebffefe
|
TypeScript
|
orionjs/orionjs
|
/packages/graphql/src/resolversSchemas/getField.test.ts
| 2.8125
| 3
|
import {Prop, TypedModel} from '@orion-js/typed-model'
import getField from './getField'
describe('Field serialization', () => {
it('should return a valid serialization of the field', async () => {
const schema = {
name: {
type: String,
a: '1234'
}
}
const result = await getField(schema.name)
expect(result).toEqual({type: 'string', a: '1234', __graphQLType: 'String'})
})
it('should pass field options with simple array fields', async () => {
const schema = {
name: {
type: [String],
a: '1234'
}
}
const result = await getField(schema.name)
expect(result.a).toEqual(schema.name.a)
})
it('Should allow serialization of typed models', async () => {
@TypedModel()
class Point {
@Prop({label: 'Name'})
name: string
}
const schema = {
point: {
type: Point
}
}
const result = await getField(schema.point)
expect(result.type.name).toEqual({type: 'string', label: 'Name', __graphQLType: 'String'})
})
})
|
97e14b5d1ee59ef940a3c028b8ac9088bf35d112
|
TypeScript
|
ivor06/WebRTCHub
|
/client/src/containers/App/actions.ts
| 2.640625
| 3
|
import {USER_LOGIN_SUCCESS, USER_LOGOUT_SUCCESS} from "./actionTypes";
import {loginToken as loginTokenUser, logout as logoutUser} from "../../services/user.service";
const actionCreatorMapObject = {
loginToken,
logout
};
export {
actionCreatorMapObject
}
function loginSuccess(user) {
return {type: USER_LOGIN_SUCCESS, user};
}
function logoutSuccess() {
return {type: USER_LOGOUT_SUCCESS};
}
function loginToken() {
return (dispatch) => loginTokenUser().then(user => user ? dispatch(loginSuccess(user)) : null);
}
function logout() {
return (dispatch, getState) => logoutUser().then(() => dispatch(logoutSuccess()), () => dispatch(logoutSuccess()));
}
|
9387054681d578f68b0ea8d472597338c5c2e6d3
|
TypeScript
|
rainder/koa-basic-auth
|
/index.ts
| 2.65625
| 3
|
'use strict';
import { createHash } from 'crypto';
import { Context } from 'koa';
export namespace KoaBasicAuth {
export interface Credentials {
[user: string]: string;
}
export interface Options {
hashingAlgorithm: string;
}
export function middleware(credentials: Credentials, options?: Options) {
return async (ctx: Context, next: Function) => {
const headerValue = ctx.headers['authorization'];
if (!headerValue) {
return forbid(ctx);
}
const [type, value] = headerValue.split(' ');
if (type.toLowerCase() !== 'basic' || !value) {
return forbid(ctx);
}
const [user, pass] = new Buffer(value, 'base64').toString().split(':');
if (!user || !pass || !credentials[user]) {
return forbid(ctx);
}
const hashedPassword = options && options.hashingAlgorithm
? createHash(options.hashingAlgorithm)
.update(pass)
.digest('hex')
: pass;
if (hashedPassword !== credentials[user]) {
return forbid(ctx);
}
return next();
};
}
/**
*
* @param ctx
*/
function forbid(ctx: Context) {
ctx.set('WWW-Authenticate', 'Basic');
ctx.status = 401;
}
}
|
e1f834e8e8ae8bc8bc44e05b4017be95c3391d6b
|
TypeScript
|
BHatGuy/DasProjekt
|
/client/Background.ts
| 2.78125
| 3
|
import { Game } from "./Game";
export class Background {
protected imgSea: CanvasImageSource;
protected imgClouds: CanvasImageSource;
protected game: Game;
protected canvas: HTMLCanvasElement;
overlay: HTMLDivElement;
protected xfactor: number;
protected yfactor: number;
private offset = 0;
private speed = 0.03;
constructor(game: Game, canvas: HTMLCanvasElement, config: any) {
let img = document.createElement("img");
img.setAttribute("src", config.background.sea);
this.imgSea = img as CanvasImageSource;
img = document.createElement("img");
img.setAttribute("src", config.background.clouds);
this.imgClouds = img as CanvasImageSource;
this.game = game;
this.canvas = canvas;
this.overlay = document.getElementById("overlay") as HTMLDivElement;
this.canvas.height = window.innerHeight;
this.canvas.width = window.innerWidth;
this.yfactor = canvas.height / (this.imgSea.height as number);
this.xfactor = this.yfactor;
}
draw(): void {
let ctx = this.canvas.getContext("2d");
ctx?.drawImage(this.imgSea, 0, 0, this.imgSea.width as number * this.xfactor, this.imgSea.height as number * this.yfactor);
ctx?.drawImage(this.imgClouds, this.offset, 0, this.imgClouds.width as number * this.xfactor, this.imgClouds.height as number * this.yfactor);
ctx?.drawImage(this.imgClouds, this.offset - (this.imgClouds.width as number * this.xfactor), 0, this.imgClouds.width as number * this.xfactor, this.imgClouds.height as number * this.yfactor);
}
update(delta: number): void {
this.offset += this.speed * delta;
if (this.offset >= (this.imgClouds.width as number * this.xfactor)) {
this.offset = 0;
}
}
}
|
b930cdc380e17a3f19fdbe910e1b9087a84645b7
|
TypeScript
|
zwliew/std-algo
|
/lib/linkedList/linkedList.ts
| 3.875
| 4
|
import { List } from "./list";
class Node<T> {
next: Node<T> | null | undefined;
prev: Node<T> | null | undefined;
item: T | null;
constructor(
item: T | null,
prev: Node<T> | null | undefined,
next: Node<T> | null | undefined
) {
this.item = item;
this.next = next;
this.prev = prev;
}
}
export class LinkedList<T> implements List<T> {
private sz: number = 0;
private front: Node<T> = new Node<T>(null, null, null);
private back: Node<T> = new Node<T>(null, null, null);
/**
* Returns true if the list is empty.
*
* @returns {boolean} true if the list is empty; false otherwise.
*/
empty(): boolean {
return this.size() === 0;
}
/**
* Returns the number of elements in the list.
*
* @returns {number} the number of elements in the list.
*/
size(): number {
return this.sz;
}
/**
* Inserts the given element to the front of the list.
*
* @param item {T} The element to be inserted.
*
* @returns {void}
*/
pushFront(item: T): void {
const newNode = new Node(item, this.front, this.front.next);
this.front.next = newNode;
if (this.empty()) {
this.back.prev = newNode;
}
++this.sz;
}
/**
* Inserts the given element to the back of the list.
*
* @param item {T}
*
* @returns {void}
*/
pushBack(item: T): void {
const newNode = new Node(item, this.back.prev, this.back);
this.back.prev = newNode;
if (this.empty()) {
this.front.next = newNode;
}
++this.sz;
}
/**
* Removes and returns the first element in the list.
*
* @returns {T} The first element in the list.
*/
popFront(): T {
if (this.empty()) {
throw Error("List is empty.");
}
const item = this.front.next?.item;
this.front.next = this.front.next?.next;
--this.sz;
if (this.empty()) {
this.back.prev = this.back.prev?.prev;
}
return item!;
}
/**
* Removes and returns the last element in the list.
*
* @returns {T}
*/
popBack(): T {
if (this.empty()) {
throw Error("List is empty.");
}
const item = this.back.prev?.item;
this.back.prev = this.back.prev?.prev;
--this.sz;
if (this.empty()) {
this.front.next = this.front.next?.next;
}
return item!;
}
/**
* Removes all the elements in the list.
*
* @returns {void}
*/
clear(): void {
this.front.next = this.back.prev = null;
this.sz = 0;
}
/**
* Returns the first element in the list.
*
* @returns {T}
*/
getFront(): T {
if (this.empty()) {
throw Error("List is empty.");
}
return this.front.next?.item!;
}
/**
* Returns the last element in the list.
*
* @returns {T}
*/
getBack(): T {
if (this.empty()) {
throw Error("List is empty.");
}
return this.back.prev?.item!;
}
// TODO: Implement more linked list methods
// insertBefore(node: Node | null, item: T) {
// if (node === null) {
// throw Error("Can't insert before a null node");
// }
// const newNode = new Node(node.prev, item, node);
// node.prev = newNode;
// if (node.prev === null) {
// this.front = newNode;
// } else {
// node.prev.next = newNode;
// }
// ++this.size;
// }
// insert(idx: number, item: T) {
// if (idx < 0 || idx > this.size) {
// throw Error("Index out of bounds");
// }
// if (idx === this.size) {
// this.pushBack(item);
// return;
// }
// if (idx === 0) {
// this.pushFront(item);
// return;
// }
// let x = this.front;
// for (; idx > 0; --idx, x = x?.next || null);
// this.insertBefore(x, item);
// }
// }
}
|
d4f28c40eaadf7fb2f30e2d449f454d7f0520d64
|
TypeScript
|
madhavaxisrooms/billing-old
|
/src/app/shared/services/toaster.service.ts
| 2.6875
| 3
|
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
@Injectable()
export class ToasterService {
/**
* Creating a behaviour subject to broadcast to toaster details
*
* @private
* @memberof ToasterService
*/
private toasterHiddenSource = new BehaviorSubject<boolean>(true);
private toasterMessageSource = new BehaviorSubject<String>("Default Message");
private toasterMessageTypeSource = new BehaviorSubject<String>("success");
toasterHidden = this.toasterHiddenSource.asObservable();
toasterMessage = this.toasterMessageSource.asObservable();
toasterMessageType = this.toasterMessageTypeSource.asObservable();
constructor() { }
/**
* Displays the Toater
* hides the toaster in 5 seconds
*
* @param {string} message
* @param {string} messageType
* @memberof ToasterService
*/
displayToaster(message: string, messageType: string) {
this.toasterHiddenSource.next(false);
this.toasterMessageSource.next(message);
this.toasterMessageTypeSource.next(messageType);
setTimeout(() => { this.dismissToaster() }, 5000);
}
/**
* Dismisses the toaster.
*
* @memberof ToasterService
*/
dismissToaster() {
this.toasterHiddenSource.next(true);
}
}
|
f9e6a21d8d93974fb6efadb697865fa5ade91434
|
TypeScript
|
AmelineA/PokeApi
|
/src/app/api.service.ts
| 2.5625
| 3
|
import { Injectable } from '@angular/core';
import{ HttpClient } from '@angular/common/http';
import { Pokemon } from './pokemon';
@Injectable({
providedIn: 'root'
})
export class ApiService {
apiUrl: string = "https://pokeapi.co/api/v2/";
constructor(private http: HttpClient) { }
//récupère les infos d'un pokemon en particulier
getPoke(){
return this.http.get(this.apiUrl+"pokemon/1");
}
//récupère un pokemon par son nom
getPokeByName(name: string){
return this.http.get(this.apiUrl+"pokemon/"+name);
}
//récupère un liste de pokemons
getPokeList(){
return this.http.get(this.apiUrl+"pokemon/");
}
//récupérer les informations d'un pokemon à partir de son url depuis la liste
getPokeFromList(url: string){
return this.http.get(url);
}
//récupérer la couleur principale du pokemon à partir de l'url des species
getPokeColor(url: string){
return this.http.get(url);
}
}
|
f9bf6cc7baecf3e9e2488a68fe8302b3474d214c
|
TypeScript
|
tutous/lessons
|
/typescript/lessons-rxjs/src/transformers/columns.ts
| 3.140625
| 3
|
export { };
import { Observable, OperatorFunction } from 'rxjs';
import { finalize } from "rxjs/operators";
interface Person {
foreName: string;
name: string;
}
interface Column {
index: number;
}
interface ForeNameColumn extends Column {
foreName: string;
}
interface NameColumn extends Column {
name: string;
}
interface PersonColumns {
foreNames: ForeNameColumn[];
names: NameColumn[];
}
let persons: Person[] = [
{ foreName: 'Uwe', name: 'Sluga' },
{ foreName: 'Max', name: 'Mustermann' }
]
let toColumns: () => OperatorFunction<Person, Column[]> =
function (): OperatorFunction<Person, Column[]> {
let operatorFunction: OperatorFunction<Person, Column[]> = inputObservable => {
// return new output observable
return new Observable<Column[]>(columnsSubscriber => {
inputObservable.subscribe(person => {
let colForeName: ForeNameColumn = { index: 0, foreName: person.foreName };
let colName: NameColumn = { index: 1, name: person.name };
let columns: Column[] = [colForeName, colName];
columnsSubscriber.next(columns);
});
});
};
return operatorFunction;
};
let collectColumns: (personColumns: PersonColumns) => OperatorFunction<Column[], Column[]> =
function (personColumns: PersonColumns): OperatorFunction<Column[], Column[]> {
let operatorFunction: OperatorFunction<Column[], Column[]> = inputObservable => {
return new Observable<Column[]>(columnsSubscriber => {
inputObservable.subscribe(columns => {
columns.forEach(c => {
if (c.index == 0) {
personColumns.foreNames.push(c as ForeNameColumn);
}
else if (c.index == 1) {
personColumns.names.push(c as NameColumn);
}
});
columnsSubscriber.next(columns);
});
});
};
return operatorFunction;
}
let obsrv01: Observable<Person> = new Observable(subscriber => {
persons.forEach(p => subscriber.next(p));
subscriber.complete();
});
const columns: PersonColumns = { foreNames: new Array(), names: new Array() };
obsrv01.pipe(
toColumns(),
collectColumns(columns),
finalize(() => console.log('unsubscribe')
)
).subscribe().unsubscribe();
columns.foreNames.forEach(c => console.log(`${c.index} ${c.foreName}`));
columns.names.forEach(c => console.log(`${c.index} ${c.name}`));
|
551399bb867000e832fc6bf20ba182ba91e08011
|
TypeScript
|
AlexanderFromEarth/calconut
|
/src/calculation/functions/factory.ts
| 3.046875
| 3
|
import {Operation} from '../classes/operation';
import {Return} from '../classes/return';
import {Command} from '../interfaces/command';
/**
* Factory for Operation
* @param command Command that must be interpreted in future
* @returns Operation with provided command
*/
export const createOperation = <T>(command: Command<T>): Operation<T> => new Operation(command);
/**
* Factory for Return
* @param payload Data for storing in class
* @returns End of calculation with provided data
*/
export const createReturn = <T>(payload: T): Return<T> => new Return(payload);
|
6239669d306804f99332fe35a7b72f4717397c93
|
TypeScript
|
AndyDecker/fhir-ts
|
/packages/fhir-types/src/R4/OperationOutcome.ts
| 2.828125
| 3
|
/**
* OperationOutcome Module
*/
import * as primitives from "@tangdrew/primitives";
import * as t from "io-ts";
import { CodeableConcept } from "./CodeableConcept";
import { Element } from "./Element";
import { Extension } from "./Extension";
import { Meta } from "./Meta";
import { Narrative } from "./Narrative";
import { Resource } from "./Resource";
/**
* Information about the success/failure of an action
*/
export interface OperationOutcome {
/** The type of resource */
resourceType?: "OperationOutcome";
/** Logical id of this artifact */
id?: primitives.R4.id;
/** Extension of id element */
_id?: Element;
/** Metadata about the resource */
meta?: Meta;
/** A set of rules under which this content was created */
implicitRules?: primitives.R4.uri;
/** Extension of implicitRules element */
_implicitRules?: Element;
/** Language of the resource content */
language?: primitives.R4.code;
/** Extension of language element */
_language?: Element;
/** Text summary of the resource, for human interpretation */
text?: Narrative;
/** Contained, inline Resources */
contained?: Resource[];
/** Additional content defined by implementations */
extension?: Extension[];
/** Extensions that cannot be ignored */
modifierExtension?: Extension[];
}
/**
* Information about the success/failure of an action
*/
export const OperationOutcome: t.Type<OperationOutcome> = t.recursion<
OperationOutcome
>("OperationOutcome", () =>
t.intersection([
t.type({}),
t.partial({
/** The type of resource */
resourceType: t.literal("OperationOutcome"),
/** Logical id of this artifact */
id: primitives.R4.id,
/** Extension of id element */
_id: Element,
/** Metadata about the resource */
meta: Meta,
/** A set of rules under which this content was created */
implicitRules: primitives.R4.uri,
/** Extension of implicitRules element */
_implicitRules: Element,
/** Language of the resource content */
language: primitives.R4.code,
/** Extension of language element */
_language: Element,
/** Text summary of the resource, for human interpretation */
text: Narrative,
/** Contained, inline Resources */
contained: t.array(Resource),
/** Additional content defined by implementations */
extension: t.array(Extension),
/** Extensions that cannot be ignored */
modifierExtension: t.array(Extension)
})
])
);
/**
* A single issue associated with the action
*/
export interface OperationOutcomeIssue {
/** Unique id for inter-element referencing */
id?: string;
/** Extension of id element */
_id?: Element;
/** Additional content defined by implementations */
extension?: Extension[];
/** Extensions that cannot be ignored even if unrecognized */
modifierExtension?: Extension[];
/** fatal | error | warning | information */
severity: primitives.R4.code;
/** Extension of severity element */
_severity?: Element;
/** Error or warning code */
code: primitives.R4.code;
/** Extension of code element */
_code?: Element;
/** Additional details about the error */
details?: CodeableConcept;
/** Additional diagnostic information about the issue */
diagnostics?: string;
/** Extension of diagnostics element */
_diagnostics?: Element;
/** Deprecated: Path of element(s) related to issue */
location?: string[];
/** Extension of location element */
_location?: Element[];
/** FHIRPath of element(s) related to issue */
expression?: string[];
/** Extension of expression element */
_expression?: Element[];
}
/**
* A single issue associated with the action
*/
export const OperationOutcomeIssue: t.Type<OperationOutcomeIssue> = t.recursion<
OperationOutcomeIssue
>("OperationOutcomeIssue", () =>
t.intersection([
t.type({
/** fatal | error | warning | information */
severity: primitives.R4.code,
/** Error or warning code */
code: primitives.R4.code
}),
t.partial({
/** Unique id for inter-element referencing */
id: primitives.R4.string,
/** Extension of id element */
_id: Element,
/** Additional content defined by implementations */
extension: t.array(Extension),
/** Extensions that cannot be ignored even if unrecognized */
modifierExtension: t.array(Extension),
/** Extension of severity element */
_severity: Element,
/** Extension of code element */
_code: Element,
/** Additional details about the error */
details: CodeableConcept,
/** Additional diagnostic information about the issue */
diagnostics: primitives.R4.string,
/** Extension of diagnostics element */
_diagnostics: Element,
/** Deprecated: Path of element(s) related to issue */
location: t.array(primitives.R4.string),
/** Extension of location element */
_location: t.array(Element),
/** FHIRPath of element(s) related to issue */
expression: t.array(primitives.R4.string),
/** Extension of expression element */
_expression: t.array(Element)
})
])
);
|
f85947547cc5290f9c447ae4ae949b107b131728
|
TypeScript
|
dang1412/ccex-api
|
/src/exchanges/bitfinex/websocket/bitfinex-websocket-old.ts
| 2.640625
| 3
|
import { ExchangeWebsocket, SocketFactory } from '../../exchange-websocket.abstract';
import { ReplaySubject, Observable } from 'rxjs';
import { wsEndpoint } from '../bitfinex-common';
export class BitfinexWebsocket extends ExchangeWebsocket<WebsocketSubscribe | WebsocketUnSubscribe, WebsocketResponse | WebsocketData> {
private readonly keyStreamMap = new Map<string, ReplaySubject<any>>();
private readonly chanIdKeyMap = new Map<number, string>();
constructor(endPoint?: string, createSocket?: SocketFactory) {
super(endPoint || wsEndpoint, createSocket);
}
/**
* Subscribe channel
*
* @param request
*/
subscribe<T>(request: WebsocketRequestBase): Observable<T> {
const key = getKey(request);
let stream = this.keyStreamMap.get(key);
if (!stream) {
stream = new ReplaySubject<T>(1);
this.keyStreamMap.set(key, stream);
}
this.send({ ...request, event: 'subscribe' });
return stream.asObservable();
}
/**
* Unsubscribe channel
*
* @param request
*/
unsubscribe(request: WebsocketRequestBase): void {
const key = getKey(request);
const stream = this.keyStreamMap.get(key);
if (stream) {
stream.complete();
this.keyStreamMap.delete(key);
}
const chanId = Array.from(this.chanIdKeyMap.keys()).find((cid) => this.chanIdKeyMap.get(cid) === key);
if (chanId) {
this.chanIdKeyMap.delete(chanId);
this.send({ event: 'unsubscribe', chanId });
}
// TODO handle when unsubscribe complete
}
/**
* handle message
*
* @param message
*/
handleMessage(message: WebsocketResponse | WebsocketData): void {
// console.log('handleMessage ===>', message);
const response = message as WebsocketResponse;
if (response.event === 'subscribed') {
// save chanId => key, no need to forward message to stream
const key = getKey(response);
this.chanIdKeyMap.set(response.chanId, key);
return;
}
if (response.event === 'unsubscribed') {
// handle unsubcribe success
// console.log('unsubscribed', response);
return;
}
const messageData = message as WebsocketData;
if (messageData.length >= 2 && typeof messageData[0] === 'number' && messageData[1] !== 'hb') {
const chanId = messageData[0];
const key = this.chanIdKeyMap.get(chanId);
if (key) {
const stream = this.keyStreamMap.get(key);
// normally data is messageData[1], special 'trade' channel case: message is messageData[2]
const data = messageData[1] === 'tu' || messageData[1] === 'te' ? messageData[2] : messageData[1];
if (stream) {
stream.next(data);
}
}
}
}
onDestroy(): void {
// TODO complete all streams
// clear stream map and key map
this.keyStreamMap.clear();
this.chanIdKeyMap.clear();
}
}
export function getKey(request: WebsocketRequestBase): string {
return (
request.channel +
// (ticker, orderbook)
(request.symbol || '') +
// (orderbook)
(request.prec || '') +
(request.freq || '') +
(request.len || '') +
// (candle)
(request.key || '')
);
}
export interface WebsocketRequestBase {
channel: string;
// ex: tBTCUSD (ticker, orderbook)
symbol?: string;
// (orderbook)
// level of price aggregation (P0, P1, P2, P3)
// default: P0
prec?: string;
// (orderbook)
// Frequency of updates(F0, F1).
// F0 = realtime / F1=2sec.
freq?: string;
// (orderbook)
len?: string;
// (candles)
key?: string;
}
export interface WebsocketSubscribe extends WebsocketRequestBase {
event: 'subscribe';
}
export interface WebsocketUnSubscribe {
event: 'unsubscribe';
chanId: number;
}
export interface WebsocketResponse extends WebsocketRequestBase {
event: 'subscribed' | 'unsubscribed';
chanId: number;
// ex: BTCUSD
pair?: string;
}
export type WebsocketData = [number, any] | [number, string, any];
|
7b4e8391c9d5b337ea38b074c32f3a612da644ad
|
TypeScript
|
alekbobgd/smartthings-cli
|
/packages/lib/src/basic-io.ts
| 2.53125
| 3
|
import { CLIError } from '@oclif/errors'
import { flags } from '@oclif/command'
import { buildInputProcessor } from './input-builder'
import { IOFormat } from './io-util'
import { itemTableFormatter, listTableFormatter, writeOutput } from './output'
import { buildOutputFormatter } from './output-builder'
import { SmartThingsCommandInterface } from './smartthings-command'
import { TableFieldDefinition } from './table-generator'
export type GetDataFunction<O> = () => Promise<O>
export type ListDataFunction<L> = () => Promise<L[]>
export type LookupDataFunction<ID, O> = (id: ID) => Promise<O>
export type ExecuteCommandFunction<I, O> = (input: I) => Promise<O>
export interface TableCommonOutputProducer<O> {
tableFieldDefinitions: TableFieldDefinition<O>[]
}
export interface CustomCommonOutputProducer<O> {
buildTableOutput(data: O): string
}
export type CommonOutputProducer<O> = TableCommonOutputProducer<O> | CustomCommonOutputProducer<O>
export interface TableCommonListOutputProducer<L> {
listTableFieldDefinitions: TableFieldDefinition<L>[]
}
export interface CustomCommonListOutputProducer<L> {
buildListTableOutput(data: L[]): string
}
export type CommonListOutputProducer<L> = TableCommonListOutputProducer<L> | CustomCommonListOutputProducer<L>
export async function formatAndWriteItem<O>(command: SmartThingsCommandInterface & CommonOutputProducer<O>, item: O,
defaultIOFormat?: IOFormat): Promise<void> {
const commonFormatter = 'tableFieldDefinitions' in command
? itemTableFormatter<O>(command.tableGenerator, command.tableFieldDefinitions)
: (data: O) => command.buildTableOutput(data)
const outputFormatter = buildOutputFormatter(command, defaultIOFormat, commonFormatter)
await writeOutput(outputFormatter(item), command.flags.output)
}
export async function formatAndWriteList<L>(command: SmartThingsCommandInterface & CommonListOutputProducer<L>,
list: L[]): Promise<void> {
const commonFormatter = 'listTableFieldDefinitions' in command
? listTableFormatter<L>(command.tableGenerator, command.listTableFieldDefinitions)
: (data: L[]) => command.buildListTableOutput(data)
const outputFormatter = buildOutputFormatter(command, undefined, commonFormatter)
await writeOutput(outputFormatter(list), command.flags.output)
}
// TODO: inputItem<I>
export async function outputItem<O>(command: SmartThingsCommandInterface & CommonOutputProducer<O>,
getData: GetDataFunction<O>): Promise<void> {
const data = await getData()
await formatAndWriteItem(command, data)
}
outputItem.flags = buildOutputFormatter.flags
export async function outputList<L>(command: SmartThingsCommandInterface & CommonListOutputProducer<L>,
getData: GetDataFunction<L[]>): Promise<void> {
const list = await getData()
await formatAndWriteList(command, list)
}
outputList.flags = buildOutputFormatter.flags
export async function inputAndOutputItem<I, O>(command: SmartThingsCommandInterface & CommonOutputProducer<O>,
executeCommand: ExecuteCommandFunction<I, O>) : Promise<void> {
const inputProcessor = buildInputProcessor<I>(command)
if (inputProcessor.hasInput()) {
const defaultIOFormat = inputProcessor.ioFormat
if (command.flags['dry-run']) {
const outputFormatter = buildOutputFormatter(command, defaultIOFormat)
await writeOutput(outputFormatter(await inputProcessor.read()), command.flags.output)
} else {
const item = await executeCommand(await inputProcessor.read())
await formatAndWriteItem(command, item, defaultIOFormat)
}
} else {
throw new CLIError('input is required either via file specified with --input option or from stdin')
}
}
inputAndOutputItem.flags = {
...buildInputProcessor.flags,
...buildOutputFormatter.flags,
'dry-run': flags.boolean({
char: 'd',
description: "produce JSON but don't actually submit",
}),
}
|
bf55e804660b2907c088fb771f4a30dcbadac6fe
|
TypeScript
|
roaldpalaya/COMP397_A3
|
/Scripts/objects/bread.ts
| 2.703125
| 3
|
//Roald Palaya 300714999
//Last updated 11/24/2016
module objects {
export class Bread extends objects.GameObject {
private _move : objects.Vector2;
private _speed : number;
private _counter : number;
// public variables
public name:string;
public width:number;
public height:number;
public center:objects.Vector2;
private _spawn() :void{
}
constructor(imageString:string) {
super(imageString, "bread");
this.name = "bread";
this.position = new objects.Vector2(config.Screen.WIDTH, Math.floor(Math.random()*400));
this.regX = this.getBounds().width * 0.5;
this.regY = this.getBounds().height * 0.5;
this._speed = 5;
this._counter=1;
// while(this._counter<4){
// super(imageString, "cloud");
// this._counter ++;
// }
}
public update() : void {
super.update();
this.position.x -= this._speed;
if (this.position.x<0){
currentScene.removeChild(this);
// this._counter-=1;
}
}
}
}
|
b3979789ecc0a4daf38d3a3efbab8364ee9e7fb0
|
TypeScript
|
tpikh/natural-events
|
/client/src/actions/events.ts
| 2.6875
| 3
|
import { AnyAction, Dispatch } from "redux";
import { FilterData, updateFilters } from "./filters";
import { REQUEST_DETAIL, RECEIVE_DETAIL, RECEIVE_EVENTS, REQUEST_EVENTS, RECEIVE_EVENTS_FAILED } from "../constants/actionTypes";
const serviceUrl = process.env.REACT_APP_API_URL;
const appendParams = (url: URL, filterData: FilterData) => {
filterData.from && url.searchParams.append('from', filterData.from.toISOString());
filterData.to && url.searchParams.append('to', filterData.to.toISOString());
filterData.sources.length > 0 && url.searchParams.append('source', filterData.sources.join(','));
filterData.statuses.length > 0 && url.searchParams.append('status', filterData.statuses.join(','));
filterData.sort && url.searchParams.append('sort', filterData.sort);
}
export const fetchItems = (filterData: FilterData) => {
return (dispatch: Dispatch) => {
dispatch(updateFilters(filterData))
dispatch(requestItems());
var url = new URL(`${serviceUrl}/naturalevents`);
appendParams(url, filterData)
return fetch(url.toString())
.then(response => response.json())
.then(json => {
dispatch(receiveEvents(json));
})
.catch(()=> {
dispatch(receiveEventsFailed());
});
}
}
export const receiveEventsFailed = () => {
return {
type: RECEIVE_EVENTS_FAILED
}
}
export const fetchDetails = (id: string) => (dispatch: Dispatch) => {
dispatch(requestDetail());
return fetch(`${serviceUrl}/naturalevents/${id}`)
.then(response => response.json())
.then(json => {
dispatch(receiveDetail(json));
})
}
export const requestDetail = () => {
return { type: REQUEST_DETAIL }
}
export const receiveDetail = (json: any): AnyAction => {
return {
type: RECEIVE_DETAIL,
payload: json
}
}
const requestItems = (): AnyAction => {
return { type: REQUEST_EVENTS }
}
const receiveEvents = (json: any): AnyAction => {
return {
type: RECEIVE_EVENTS,
events: json,
}
}
|
eeced312c0b424c9340e5a4703f315ecfbeeb2e3
|
TypeScript
|
jasdevsidhu12/FeedService
|
/packages/angularDesign/src/trend_design/reducer/FIReducer.ts
| 2.75
| 3
|
import {
ADD_NEW_COMMENT,
ADD_NEW_FEED,
LOAD_INITIAL_FEED,
LOADING_COMPONENTS
} from '../api/FIUtils';
export interface IAppState {
feed: Array<any>;
isContentLoading: boolean
};
const initialState = { feed: [{}], isContentLoading: true };
export default function feedItemReducer(state: IAppState = initialState, action:any): IAppState {
let newState: IAppState;
switch(action.type) {
case ADD_NEW_FEED:
const feed = [ ...state.feed ];
feed.unshift(action.payload);
newState = { ...state, feed };
break;
case ADD_NEW_COMMENT:
const feedArray = [ ...state.feed ];
feedArray.forEach((obj: any) => {
if (obj.id === action.payload.id) {
obj.comment.unshift(action.payload.comment);
// obj.actor.displayName = 'Roshan';
}
});
newState = { ...state, feed: feedArray };
break;
case LOAD_INITIAL_FEED:
newState = { ...state, feed: action.payload, isContentLoading: false };
break;
case LOADING_COMPONENTS:
newState = { ...state, isContentLoading: true };
break;
default: newState = state; break;
}
console.log('--New State--');
console.log(newState);
return newState;
}
|
fca8bb6b3a26d785fe3bd18250f8060cebbb0a3f
|
TypeScript
|
FabianLauer/tsh
|
/src/ast/PrecedenceExpr.ts
| 3.25
| 3
|
import { assertAstNodeParam } from './utils/assert'
import Expr from './Expr'
/**
* Used to wrap expressions (that includes all kinds of operations) when they need to be
* evaluated with precedence over other expressions, just like parens in source code.
* Type parameter `TExpr` can be used to specify the wrapped expression's type.
*/
export class PrecedenceExpr<TExpr extends Expr> extends Expr {
public constructor(
/**
* The expression that should be evaluated with precedence.
*/
public readonly expr: TExpr
) {
super(expr)
assertAstNodeParam(expr instanceof Expr)
}
}
export default PrecedenceExpr
|
0eb8711344ee9cf9085b131b03122bf0a31eb9d8
|
TypeScript
|
paolotiu/blog_client
|
/src/functions/api.ts
| 2.53125
| 3
|
const url = 'https://blog-api-pt.herokuapp.com';
export const fetchAllBlogs = async () => {
const blogs = await fetch(url + '/blogs');
return blogs.json();
};
export const fetchBlogByID = async (id: string) => {
const blog = await fetch(url + '/blogs/' + id);
return blog.json();
};
export const postComment = async (id: string, author: string, text: string) => {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const res = await fetch(url + '/blogs/' + id + '/comment', {
method: 'POST',
headers: headers,
body: JSON.stringify({ author, text }),
});
return res.json();
};
export const loginUser = async (username: string, password: string) => {
const headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
const urlencoded = new URLSearchParams();
urlencoded.append('username', username);
urlencoded.append('password', password);
const requestOptions: RequestInit = {
method: 'POST',
headers: headers,
body: urlencoded,
};
try {
const res = await fetch(url + '/user/login', requestOptions);
const json = await res.json();
return json;
} catch (err) {
return Promise.reject(err);
}
};
export const signUpUser = async (
email: string,
username: string,
password: string
) => {
const res = await fetch(url + '/user/signup', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password, username }),
});
const json = await res.json();
return json;
};
export const getUser = async () => {
const token = localStorage.getItem('token');
if (!token) {
return { error: 'No token' };
}
const res = await fetch(url + '/user', {
headers: {
Authorization: 'Bearer ' + token,
},
});
const json = await res.json();
return json;
};
export const getOwnBlogs = async () => {
const token = localStorage.getItem('token');
if (!token) {
return { error: 'No token' };
}
const res = await fetch(url + '/user/blogs', {
headers: {
Authorization: 'Bearer ' + token,
},
});
const json = await res.json();
return json;
};
export const updateBlog = async (id: string, title: string, text: string) => {
const token = localStorage.getItem('token');
if (!token) {
return { error: 'No token' };
}
const res = await fetch(url + '/blogs/' + id, {
method: 'PUT',
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json',
},
body: JSON.stringify({ title, text }),
});
const json = await res.json();
return json;
};
export const deleteBlog = async (id: string) => {
const token = localStorage.getItem('token');
if (!token) {
return { error: 'No token' };
}
const res = await fetch(url + '/blogs/' + id, {
method: 'DELETE',
headers: {
Authorization: 'Bearer ' + token,
},
});
const json = await res.json();
return json;
};
export const createBlog = async (title: string, text: string) => {
const token = localStorage.getItem('token');
if (!token) {
return { error: 'No token' };
}
const res = await fetch(url + '/blogs', {
method: 'POST',
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json',
},
body: JSON.stringify({ title, text }),
});
const json = await res.json();
return json;
};
|
f71ec347d2f43649f29e0f6127759e7a8e8c5f6f
|
TypeScript
|
achung3071/booktogether-server
|
/src/__test__/controllers/review.test.ts
| 2.5625
| 3
|
import app from "../../../app";
import bcrypt from "bcrypt";
import Book from "../../models/Book";
import Curation from "../../models/Curation";
import Review from "../../models/Review";
import User from "../../models/User";
import request from "supertest";
import { Document, Types } from "mongoose";
describe("Reviews", () => {
// Set up all tests
const bookId: Types.ObjectId = new Types.ObjectId();
const curationId: Types.ObjectId = new Types.ObjectId();
const reviewId: Types.ObjectId = new Types.ObjectId();
const userId: Types.ObjectId = new Types.ObjectId();
beforeAll(async done => {
await Promise.all([
Book.deleteMany({}),
Curation.deleteMany({}),
Review.deleteMany({}),
User.deleteMany({})
]);
const book: Document = new Book({
_id: bookId,
title: "fake book"
});
const curation: Document = new Curation({
_id: curationId,
books: [bookId],
reviews: [reviewId],
title: "fake curation"
});
const review: Document = new Review({
_id: reviewId,
author: userId,
books: [bookId],
published: true,
title: "fake review"
});
const user: Document = new User({
_id: userId,
name: "jest",
email: "jest@gmail.com",
password: await bcrypt.hash("jest1234", 10)
});
await Promise.all([
book.save(),
curation.save(),
review.save(),
user.save()
]);
done();
});
describe("GET /reviews", () => {
it("should get a list of reviews by book id", done => {
request(app)
.get(`/reviews?book_id=${bookId}`)
.end((err: any, res: any) => {
expect(res.statusCode).toBe(200);
expect(res.body[0]).toHaveProperty("_id", reviewId.toHexString());
expect(res.body[0]).toHaveProperty("title", "fake review");
done();
});
});
it("should get a list of reviews by curation id", done => {
request(app)
.get(`/reviews?curation_id=${curationId}`)
.end((err: any, res: any) => {
expect(res.statusCode).toBe(200);
expect(res.body[0]).toHaveProperty("_id", reviewId.toHexString());
expect(res.body[0]).toHaveProperty("title", "fake review");
done();
});
});
it("should work on a combination of queries", async done => {
await request(app)
.get(`/reviews?book_id=${bookId}&curation_id=${curationId}`)
.then((res: any) => {
expect(res.statusCode).toBe(200);
expect(res.body[0]).toHaveProperty("_id", reviewId.toHexString());
expect(res.body[0]).toHaveProperty("title", "fake review");
});
const randomId = new Types.ObjectId();
request(app)
.get(`/reviews?curation_id=${curationId}&book_id=${randomId}`)
.then((res: any) => {
expect(res.statusCode).toBe(200);
expect(res.body.length).toEqual(0);
done();
});
});
});
describe("GET /reviews/:id", () => {
it("should get the information for a specific review", done => {
request(app)
.get(`/reviews/${reviewId}`)
.then((res: any) => {
expect(res.statusCode).toBe(200);
expect(res.body).toHaveProperty("_id", reviewId.toHexString());
expect(res.body).toHaveProperty("title", "fake review");
expect(res.body).toHaveProperty("published", true);
expect(res.body.author).toHaveProperty("_id");
expect(res.body.author).toHaveProperty("name");
expect(res.body.author).toHaveProperty("profile");
expect(res.body.author).toHaveProperty("image");
done();
});
});
it("should return 404 for an invalid id", done => {
request(app)
.get("/reviews/jest1")
.then((res: any) => {
expect(res.statusCode).toBe(404);
expect(res.body).toHaveProperty("error");
expect(res.body.error).toHaveProperty("type", "ReviewNotFound");
done();
});
});
});
});
|
3b7fbdd69f6e7e24fd8f06e7f40bc89382c08bf5
|
TypeScript
|
sergzaligin359/learn-typescript
|
/src/components/Learn/arrays.ts
| 3.359375
| 3
|
export default () => {
// Массив
type A = (number | string)[];
const arr: A = [1, 2, 'hi'];
console.log('arr', arr);
// Кортеж
// Может содержать необязательный элемент [number, string?]
const cortege: [number, string] = [1, 'string'];
console.log('cortege', cortege);
// Перечисления
enum G {
A,
B,
}
console.log('enum, G.A, G.B, G[0], G[1]', G.A, G.B, G[0], G[1]);
};
|
212b414a1710d8c1c185a3a6d76d3a7d6eecbab7
|
TypeScript
|
validatorjs/validator-deno
|
/src/lib/isEthereumAddress.ts
| 2.640625
| 3
|
const eth: RegExp = /^(0x)[0-9a-f]{40}$/i;
export default function isEthereumAddress(str: string): boolean {
return eth.test(str);
}
|
254802ef1a5c2f2b02ea629c4211c3242ebebbbb
|
TypeScript
|
cindy-alvarado/angular-pro-src
|
/50-resolves/app/mail/containers/mail-folder/mail-folder.component.ts
| 2.578125
| 3
|
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Mail } from '../../models/mail.interface';
import { Observable } from 'rxjs/Observable';
// pluck operator
import 'rxjs/add/operator/pluck';
@Component({
selector: 'mail-folder',
styleUrls: ['mail-folder.component.scss'],
template: `
<h2>{{ title | async }}</h2>
<!-- display the mail items : i.e.: inbox mail folder from a mail client -->
<!-- async pipe allows you to subscribe to the observable -->
<mail-item
*ngFor="let message of (messages | async)"
[message]="message">
</mail-item>
`
})
// injet the router and acces the resolve data
export class MailFolderComponent {
// .puck allows you to take part of the data property on the data object i.e.: messages
messages: Observable<Mail[]> = this.route.data.pluck('messages');
// .puck allows you to take part of the data property on the data object i.e.: name (inbox, trash)
title: Observable<string> = this.route.params.pluck('name');
constructor(private route: ActivatedRoute) {}
}
|
e15f57a022b800c1a05728696bda0fc79ab20308
|
TypeScript
|
acolytec3/permasnap-client
|
/src/providers/ArweaveProvider.ts
| 2.6875
| 3
|
import { JWKInterface } from 'arweave/web/lib/wallet'
import { IPsnapPhoto } from '../redux/reducers'
let Arweave
if(process.env.NODE_ENV === "test"){ Arweave = require('arweave/node') }
else{ Arweave = require('arweave/web').default } //hack for node-based testing to work
const HOST = process.env.REACT_APP_ARWEAVE_GW_HOST
const arweave = Arweave.init({
host: HOST,
port: 443,
protocol: 'https'
})
export const generateWallet = async ():Promise<JWKInterface> => {
return await arweave.wallets.generate()
}
export const getAddress = async (gWallet: JWKInterface):Promise<string> => {
return await arweave.wallets.jwkToAddress(gWallet)
}
export const getAddressPubkey = async (pubkey: string) => {
return await arweave.wallets.ownerToAddress(pubkey)
}
export const isInstanceofJwkInterface = (obj: object):boolean => {
let result = true;
['kty', 'n', 'e', 'd', 'p', 'q', 'dp', 'dq', 'qi'].forEach(keyname => {
if( obj.hasOwnProperty(keyname) === false){
result = false
}
})
// // You could go on: https://tools.ietf.org/html/rfc7518#section-6.3
return result
}
export const getAllTxsDefault = async ():Promise<IPsnapPhoto[]> => {
return getAllTxsByTag("psnap_context", "production")
}
export const getAllTxsByHashtag = async (hashtag: string):Promise<IPsnapPhoto[]> => {
return getAllTxsByTag("psnap_content_tag", hashtag)
}
export const getAllTxsByPubKey = async (pubkey: string):Promise<IPsnapPhoto[]> => {
return getAllTxsByTag("dpost_owner", pubkey)
}
const getAllTxsByTag = async (name: string, value: string):Promise<IPsnapPhoto[]> => {
let txDatas: IPsnapPhoto[] = []
//grab all wallets uploads. take id, description, and hashtags - psnap_content_tag (many), psnap_description
let gqlQuery = `{
transactions(tags: [{name: "${name}", value: "${value}"},{name: "App-Name", value: "${process.env.REACT_APP_APP_NAME}"}]){
id
tags { name, value }
}
}`
//let's just restate that interface in typescript
interface IQuery {
id: string;
tags: { name: string, value: string }[]
}
//grab the query results
let res = await arweave.api.post('arql', { query: gqlQuery })
let txs = res.data.data.transactions
if(!txs){
console.log('Unhandled Rejection (TypeError): res.data.data is null')
return []
}
// arweave.transactions.getStatus(txs[0]).then((status:any)=>{
// console.log('*************************************************************')
// console.log(status)
// console.log('*************************************************************')
// })
//loop over each tx object reformatting the data we need
txDatas = txs.map( (tx: IQuery):IPsnapPhoto => {
//grab tag data we want
let hashtags: string[] = []
let description = ''
let owner = ''
tx.tags.forEach((tag: {name:string, value:string}) => {
// console.log(tag.name+':'+tag.value)
switch (tag.name) {
case "psnap_content_tag":
hashtags.push(tag.value)
break
case "psnap_description":
description = tag.value
break
case "dpost_owner":
owner = tag.value
break
default:
break;
}
})
//return a ITxData object
return {
id: tx.id,
url: 'https://' + HOST + '/' + tx.id,
description: description,
completed: true,
hashtags: hashtags,
owner: owner,
}
})
return txDatas
}
export interface IArIdData {
address: string
name: string
}
export const getArweaveId = async (pubkey: string):Promise<IArIdData> => {
let address: string = await arweave.wallets.ownerToAddress(pubkey) //
/** We just want the txs with arweaveId "Type": "name" */
let gqlQuery = `{
transactions(from: "${address}", tags: [{name: "App-Name", value: "arweave-id"},{name: "Type", value: "name"}]){
id
}
}`
// let gqlQuery = `{
// transactions(from: "${address}", tags: [{name: "App-Name", value: "arweave-id"},{name: "Type", value: "name"}]){
// id
// }
// }`
//let's just restate that interface in typescript
interface IQuery {
id: string;
}
//grab the query results
let res = await arweave.api.post('arql', { query: gqlQuery })
let txids = res.data.data.transactions // returned from newest to oldest
if(txids.length > 0){
let name = await arweave.transactions.getData(txids[0].id, {decode: true, string: true}) //.then(console.log)
console.log('arweave-id txid: ')
console.log(txids[0].id)
return {
name,
address,
}
} else{
return {
name: address.substr(0,4) + '...' + address.substr( (address.length-4) ),
address: address,
}
}
}
|
96c24c22e9c43ecaf7cd2c16e994001aeb6a2265
|
TypeScript
|
jaryno/TypeScript-Design-Patterns
|
/src/behavioural/chain-of-responsibility/index.ts
| 2.734375
| 3
|
import Handler from "./Handler";
import CivilianVehicleHandler from "./CivilianVehicleHandler";
import FiretruckHandler from "./FiretruckHandler";
import AmbulanceHandler from "./AmbulanceHandler";
import PoliceSUVHandler from "./PoliceSUVHandler";
let civilianHandler = new CivilianVehicleHandler();
let firetruckHandler = new FiretruckHandler();
let ambulanceHandler = new AmbulanceHandler();
let policeSUVHandler = new PoliceSUVHandler();
civilianHandler.setNextHandler(firetruckHandler);
firetruckHandler.setNextHandler(ambulanceHandler);
ambulanceHandler.setNextHandler(policeSUVHandler);
function getVehicleHandler():Handler {
return civilianHandler;
}
export function run() {
let vehicleType = "POLICE_SUV";
let vehicleHandler = getVehicleHandler();
vehicleHandler.handle(vehicleType);
}
|
0a8609c8d900d482ed8a0138443eddaff5f95154
|
TypeScript
|
graemebrooks/waffl-archive-api
|
/src/services/statsheet/teamBrandingProvider.ts
| 2.5625
| 3
|
interface teamBranding {
logoUrl: string;
colors: {
primary: string;
secondary: string;
};
}
export function getTeamBranding(teamName: string): teamBranding {
switch (teamName) {
case 'Cartels':
return {
logoUrl: 'https://i.imgur.com/lIRYULG.png',
colors: {
primary: '#ee8a10',
secondary: '#dd366d'
}
};
case 'Beer':
return {
logoUrl: 'https://i.imgur.com/aTs50El.png',
colors: {
primary: '#00005b',
secondary: '#ffce00'
}
};
case 'Ice Babies':
return {
logoUrl: 'https://i.imgur.com/KE0cDMD.png',
colors: {
primary: '#7437bf',
secondary: '#ffffff'
}
};
case 'Islanders':
return {
logoUrl: 'https://i.imgur.com/bDpjNeF.png',
colors: {
primary: '#1e6b0e',
secondary: '#ff6d00'
}
};
case 'Wenches':
return {
logoUrl: 'https://i.imgur.com/qVAzfoj.png',
colors: {
primary: '#00205b',
secondary: '#fa6300'
}
};
case 'Toad Lickers':
return {
logoUrl: 'https://i.imgur.com/TpSQJZN.png',
colors: {
primary: '#206632',
secondary: '#e53841'
}
};
case 'Chili Peppers':
return {
logoUrl: 'https://i.imgur.com/a9jFlAW.png',
colors: {
primary: '#dd1919',
secondary: '#ffb600'
}
};
case 'Digital Rays':
return {
logoUrl: 'https://i.imgur.com/Je5Chs0.png',
colors: {
primary: '#00f1ee',
secondary: '#db00c9'
}
};
case 'Not The Jets':
return {
logoUrl: 'https://i.imgur.com/q4j1M2D.png',
colors: {
primary: '#000b6d',
secondary: '#ffe600'
}
};
case 'Nadoes':
return {
logoUrl: 'https://i.imgur.com/lLmmaih.png',
colors: {
primary: '#41b1f0',
secondary: '#a7a7a7'
}
};
case 'Librarians':
return {
logoUrl: 'https://i.imgur.com/znuRXVw.png',
colors: {
primary: '#007efe',
secondary: '#ffffff'
}
};
}
}
|
df995aa411628080bfbe38bdb97e61de9271fec8
|
TypeScript
|
whitesky0109/GOST-MSM
|
/src/MangaDownloader.ts
| 2.578125
| 3
|
import "reflect-metadata";
import {Service} from "typedi";
import * as http from "http";
import * as https from "https";
import * as fs from "fs";
import {Transform} from 'stream';
const archiver = require('archiver');
// child process
@Service()
class MangaDownloader {
downloadBasePath: string = "download";
downloadedBasePath: string = "."
constructor(private title: string, private urlList: any[]) {
this.createDownloadPath();
}
createDownloadPath() {
const { downloadBasePath } = this;
if (!fs.existsSync(downloadBasePath)) {
fs.mkdirSync(downloadBasePath);
}
}
async downloads() {
const { title, urlList } = this;
if (fs.existsSync(`${title}.zip`)) {
console.log("already downloaded file");
return true;
}
const pList: any[] = [];
for (const url of urlList) {
pList.push(this.download(url));
}
Promise.all(pList).then(async () => {
let zipInfo: any;
let baseInfo: any = {
title,
images: urlList.length,
};
try {
console.log(`try ${title} zipping...`);
zipInfo = await this.zip();
} catch (e) {
console.error(e);
}
process.send(Object.assign(baseInfo, zipInfo,));
}, (err) => {
console.error(err);
});
return true;
}
async getFile(url): Promise<any> {
const urlObj: URL = new URL(url);
const protocol: any = (urlObj.protocol === "https:") ? https : http;
return new Promise((resolve, reject) => {
protocol.request(url, async (response: any) => {
switch (response.statusCode) {
case 200: // success
let data: Transform = new Transform();
response.on('data', (chunk: any) => data.push(chunk) );
response.on('end', () => resolve(data) );
break;
case 301: // redirect
try {
resolve(await this.getFile(response.headers.location));
} catch (e) {
reject(e);
}
break;
default: // etc
reject(response.statusCode);
}
}).end();
})
}
async download(url: any) {
const { title, downloadBasePath } = this;
const path: string = `${downloadBasePath}/${title}`;
try {
const data: any = await this.getFile(url);
const filename: string = url.split("/").pop();
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
}
fs.writeFileSync(`${path}/${filename}`, data.read());
} catch (e) {
console.error(e);
}
}
zip(): Promise<any> {
return new Promise((resolve, reject) => {
const { title, downloadBasePath } = this;
const archive: any = archiver("zip");
const path: string = `${downloadBasePath}/${title}`;
const output: fs.WriteStream = fs.createWriteStream(`${path}.zip`);
output.on('close', function () {
resolve({
zipFile: `${title}.zip`,
bytes: archive.pointer(),
});
});
archive.on('error', (err) => reject(err) );
archive.pipe(output);
archive.directory(path, path);
archive.finalize();
})
}
}
process.on("message", ({ title, links }: {title: string, links: any[]}) => {
const md = new MangaDownloader(title, links);
md.downloads();
});
|
53ab9dc0ebfdf4fe8639c8c82fce0b22653a5c87
|
TypeScript
|
nvgiang2212/html_add_project
|
/src/app/model/task.ts
| 2.578125
| 3
|
export interface Task {
title: string;
status: boolean;
deadline: Date;
description: string;
}
|
5f592d8b913937d5188a3e84f3ffe659362873aa
|
TypeScript
|
thewindsword/stardust-ui-react
|
/build/gulp/tasks/stats.ts
| 2.515625
| 3
|
import * as fs from 'fs'
import { task, parallel, series } from 'gulp'
import * as _ from 'lodash'
import * as webpack from 'webpack'
import * as stableStringify from 'json-stable-stringify-without-jsonify'
import config from '../../../config'
const g = require('gulp-load-plugins')()
const { paths } = config
const { log, PluginError } = g.util
const UNRELEASED_VERSION_STRING = 'Unreleased'
const SEMVER_MATCHER = /(\d+)\.(\d+)\.(\d+)/
const semverCmp = (a, b) => {
const left = a.key
const right = b.key
// Unreleased first
if (left === UNRELEASED_VERSION_STRING) {
return -1
}
if (right === UNRELEASED_VERSION_STRING) {
return 1
}
// x.y.z semver DESC
const leftMatch = left.match(SEMVER_MATCHER)
const rightMatch = right.match(SEMVER_MATCHER)
if (leftMatch && rightMatch) {
for (let i = 1; i <= 3; i++) {
const partOfLeft = Number(leftMatch[i])
const partOfRight = Number(rightMatch[i])
if (partOfLeft > partOfRight) return -1
if (partOfRight > partOfLeft) return 1
}
}
// rest ASC
if (left < right) return -1
if (left > right) return 1
return 0
}
function webpackAsync(config): Promise<any> {
return new Promise((resolve, reject) => {
const compiler = webpack(config)
compiler.run((err, stats) => {
const statsJson = stats.toJson()
const { errors, warnings } = statsJson
if (err) {
log('Webpack compiler encountered a fatal error.')
reject(new PluginError('webpack', err.toString()))
}
if (errors.length > 0) {
log('Webpack compiler encountered errors.')
reject(new PluginError('webpack', errors.toString()))
}
if (warnings.length > 0) {
log('Webpack compiler encountered warnings.')
reject(new PluginError('webpack', warnings.toString()))
}
resolve(statsJson)
})
})
}
async function compileOneByOne(allConfigs) {
let assets = []
for (const config of allConfigs) {
log('Compiling', config.output.filename)
try {
const result = await webpackAsync(config)
assets = [...assets, ...result.assets]
log('Done', result.assets[0].name) // All builds should produce just single asset
} catch (err) {
log('Error', config.output.filename)
throw err
}
}
return assets
}
function updateStatsFile(filePath: string, currentBundleStats: any) {
const stats = fs.existsSync(filePath) ? require(filePath) : {}
stats[UNRELEASED_VERSION_STRING] = {
bundles: currentBundleStats,
}
fs.writeFileSync(
filePath,
stableStringify(stats, {
cmp: semverCmp,
space: 2,
}),
)
}
task('build:stats:bundle', async () => {
process.env.NODE_ENV = 'build'
const webpackStatsConfig = require('../../webpack.config.stats').default
const assets = await compileOneByOne(webpackStatsConfig)
const results = _(assets)
.map(({ name, size }) => ({ name, size }))
.sortBy('name')
.value()
updateStatsFile(paths.docsSrc('bundleStats.json'), results)
})
task(
'stats',
series(
parallel(series('clean:dist:es', 'build:dist:es'), 'build:docs:component-info'),
'build:stats:bundle',
),
)
|
27dfbad0c629b51c30627a89d79cd464bfaebae3
|
TypeScript
|
sunyanzhe/ts-demo
|
/类/protected.ts
| 3.53125
| 4
|
interface AInter {
a: string;
b: string;
}
class AA implements AInter {
protected constructor(public a: string, public b: string) {
this.a = a;
this.b = b
}
}
interface BInter extends AA {
c?: string;
[m: string]: any;
}
class BB extends AA implements BInter{
public c: string
constructor(a: string, b: string) {
super(a, b)
this.c = a + b
}
}
// let aa = new AA() 报错
let bb = new BB('a', 'b')
|
e69325371fbe13ee386368aabb39b758aa93bef7
|
TypeScript
|
alissonsouzaac/Ent.RITS
|
/Cliente/Helpers/response.ts
| 2.734375
| 3
|
export class Response {
code: string;
name: string;
message: string;
constructor(code: string, name: string, message: string) {
this.code = code;
this.name = name;
this.message = message;
}
}
|
04bd1047f8151335722b633bcc8701efa2c17f2c
|
TypeScript
|
MyAeroCode/PS-TypeScript-Programmers
|
/lessons/43164/solution.ts
| 3.578125
| 4
|
export function solution(tickets: string[][]): string[] {
//
// 목적지를 사전순으로 정렬하고,
// 차례차례로 isConnected[startAirport]에 push한다.
const isConnected = {} as { [key: string]: string[] };
tickets
.sort((a, b) => (a[1] < b[1] ? -1 : +1))
.forEach(([srt, end]) => {
if (isConnected[srt] === undefined) isConnected[srt] = [];
if (isConnected[end] === undefined) isConnected[end] = [];
isConnected[srt].push(end);
});
//
// 재귀적으로 답을 찾는다.
let answer: string[] = [];
function solve(untilNow: string[]) {
//
// 중간에 답을 찾았다면 중단한다.
if (answer.length) return;
//
// 최초 정답이 사전순으로 가장 빠른 정답이다.
if (untilNow.length === tickets.length + 1) {
answer = untilNow;
return;
}
//
// 사용되지 않은 다음 목적지로 이동한다.
const lastAirport = untilNow[untilNow.length - 1];
for (let i = 0; i < isConnected[lastAirport].length; i++) {
const nextAirport = isConnected[lastAirport][i];
if (nextAirport === "") continue;
isConnected[lastAirport][i] = "";
solve([...untilNow, nextAirport]);
isConnected[lastAirport][i] = nextAirport;
}
}
solve(["ICN"]);
return answer;
}
|
f7726968ea48398683d173432240d0fbc795ccea
|
TypeScript
|
amagovpt/admin-monitor-suite
|
/src/app/models/user.ts
| 2.78125
| 3
|
interface IUser {
UserId: number;
Email: string;
Type: string;
Register_Date: Date;
Last_Login: Date;
}
export class User implements IUser {
UserId: number;
Email: string;
Type: string;
Register_Date: Date;
Last_Login: Date;
constructor(UserId: number, Email: string, Type: string, Register_Date: Date, Last_Login: Date) {
this.UserId = UserId;
this.Email = Email;
this.Type = Type;
this.Register_Date = Register_Date;
this.Last_Login = Last_Login;
}
}
|
00fb0c072839bae9e6764c637427d401b5753d81
|
TypeScript
|
rimmugygr/Angular
|
/TypeScript/MultiMath/scoreboard.ts
| 2.953125
| 3
|
// import {Result} from "./result";
class Scoreboard {
private results: Result[] = [];
addResults(newResult: Result): void {
this.results.push(newResult);
}
updateScoreboard():void {
console.log(this.results);
let output: string = "<h2>Scoreboard</h2>\n";
for (let result of this.results){
output += '<h4>\n'+
result.playerName+" has socre "+
result.score+ "/"+
result.problemCount+" for factor "+
result.factor+'<h4>\n';
}
const scoresElement: HTMLElement | null = document.getElementById('scores');
scoresElement!.innerHTML = output;
}
}
|
24786748e75004feb3a46c0b4d2f0dbca47bf5eb
|
TypeScript
|
stuckupfool/def-ntf
|
/src/stores/CharacterStore.ts
| 2.734375
| 3
|
import {
action,
computed,
makeObservable,
observable,
runInAction,
} from "mobx";
import React from "react";
import fetch from "../Util/Fetch";
import * as _ from "lodash";
export interface CharacterResultItem {
id: string;
name: string;
status: "Alive" | "Dead" | "unknown";
species: string;
type: string;
gender: string;
origin: {
name: string;
url: string;
};
location: {
name: string;
url: string;
};
image: string;
episode: string[];
url: string;
created: string;
}
export interface InfoResult {
count: Number;
pages: Number;
next: string;
prev: string;
}
interface CharacterResult {
info: InfoResult;
results: CharacterResultItem[];
}
class CharacterStore {
public isLoading: boolean = false;
public characters: Map<string, CharacterResultItem> = new Map();
public get charactersOrderedById() {
return _.chain([...this.characters.values()])
.filter((val) => parseInt(val.id) <= this._endChunkId)
.orderBy("id")
.value();
}
private _nextPage?: string = "";
private _endChunkId: number = 0;
public totalCharacters: Number = 0;
public get loadedCharacters() {
return this.characters.size;
}
public get moreToLoad() {
return this.loadedCharacters < this.totalCharacters;
}
constructor() {
makeObservable(this, {
characters: observable,
charactersOrderedById: computed,
totalCharacters: observable,
loadedCharacters: computed,
isLoading: observable,
moreToLoad: computed,
});
this.loadNext();
}
@action public async loadRange(ids: string[]) {
if (ids.length > 0) {
const apiPath =
"https://rickandmortyapi.com/api/character/" + ids.join(",");
const results: CharacterResultItem[] = await fetch<CharacterResultItem[]>(
apiPath,
{}
);
runInAction(() => {
_.forEach(results, (result) =>
this.characters.set(result.id + "", result)
);
});
}
}
@action public async loadNext() {
if (this._nextPage !== null) {
runInAction(() => {
this.isLoading = true;
});
const nextPage =
this._nextPage || "https://rickandmortyapi.com/api/character";
const result: CharacterResult = await fetch<CharacterResult>(
nextPage,
{}
);
this._nextPage = result.info.next;
runInAction(() => {
_.forEach(result.results, (result) => {
this._endChunkId = Math.max(this._endChunkId, parseInt(result.id));
this.characters.set(result.id + "", result);
});
this.totalCharacters = result.info.count;
this.isLoading = false;
});
}
}
}
export const CharacterContext = React.createContext<CharacterStore>(
new CharacterStore()
);
export default CharacterStore;
|
5e965b7dd60af20afbb556a9d870fbec21c12df3
|
TypeScript
|
HealthML/StyleGAN2-Hypotheses-Explorer
|
/client/src/logic/tools/blobURL.ts
| 3.03125
| 3
|
export class BlobURLFake {
readonly url: string =
'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"/>';
increaseUses(_: number = 1) {}
decreaseUses(_: number = 1) {}
}
export class BlobURL extends BlobURLFake {
readonly url: string;
constructor(blob: Blob, private uses = 0) {
super();
this.url = URL.createObjectURL(blob);
}
increaseUses(amount: number = 1) {
this.uses += amount;
}
decreaseUses(amount: number = 1) {
this.uses -= amount;
if (this.uses <= 0) {
URL.revokeObjectURL(this.url);
}
}
}
export function createBlobURL(blob: Blob) {
return new BlobURL(blob);
}
|
8faccf2c0d1d63f0676dd3523a34a18360c2b839
|
TypeScript
|
xendke/bulma-native
|
/src/elements/Text/Text.styles.ts
| 2.515625
| 3
|
import { StyleSheet } from 'react-native';
import { getColor } from '../../theme/color';
import { getTextSize, getTextWeight } from '../../theme/text';
import { Theme } from '../../theme';
const createStyles = (
{
alignment,
color,
size,
transform,
weight,
}: {
alignment: TextAlignment;
color: Nullable<Color>;
size: TextSize;
transform: Nullable<TextTransform>;
weight: TextWeight;
},
theme: Theme,
) => {
const colorHex = getColor(color, theme);
const fontSize = getTextSize(size, theme);
const fontWeight = getTextWeight(weight, theme);
return StyleSheet.create({
text: {
color: colorHex || theme.text,
fontSize,
fontWeight,
textAlign: alignment,
textTransform: transform || 'none',
},
});
};
export default createStyles;
|