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 |
|---|---|---|---|---|---|---|
a7128b12432e7927a64d7086b1f11cd4679cd926 | TypeScript | GuilhermRodovalho/trainee-ascii | /backend/src/services/DeleteVideoService.ts | 2.5625 | 3 | import { getRepository } from 'typeorm';
import path from 'path';
import fs from 'fs';
import Video from '../models/Video';
export default class DeleteVideoService {
public async execute(id: string): Promise<void> {
const videoRepository = getRepository(Video);
const video = await videoRepository.findOne({
where: {
id,
},
});
if (!video) {
throw new Error("This video doesn't exist on database");
}
const videoFilePath = path.resolve(
__dirname,
'..',
'..',
'videos',
video.name,
);
const statusVideoFile = await fs.promises.stat(videoFilePath);
if (statusVideoFile) {
await fs.promises.unlink(videoFilePath);
}
await videoRepository.delete(video);
}
}
|
84af4bdd354361375d8506e9504ebdf1f1e455bc | TypeScript | fakenickels/es2077-nodebr | /slides/src/snippets/VariantDemoSwitch.ts | 3.140625 | 3 | let greeting = (person: Person) => {
switch (person.kind) {
case SchoolPersonEnum.Teacher:
return "Hey Professor!"
case SchoolPersonEnum.Director:
return "Hello Director."
case SchoolPersonEnum.Student:
if(person.name === "Richard") return "Still here Ricky?"
else return `Hey, ${person.name}.`
}
}
|
b6a8125e77fd8b1609c3a211dc53308bc25f6e8d | TypeScript | kahole/edamagit | /src/utils/commitCache.ts | 2.65625 | 3 | import { Commit, Repository } from '../typings/git';
const commitCache: { [hash: string]: Promise<Commit> | undefined; } = {};
export function getCommit(repository: Repository, hash: string): Promise<Commit> {
let cachedResult = commitCache[hash];
if (cachedResult !== undefined) {
return cachedResult;
}
const commitTask = repository.getCommit(hash);
commitCache[hash] = commitTask;
return commitTask;
} |
a06316fb01cbb086dd5f254de971c118ef5b39e6 | TypeScript | kuehnert/react-kakuro | /webapp/src/utils/checkPuzzle.ts | 3.25 | 3 | import { CellType, IGameData, IHintCell, INumberCell } from 'models/cellModels';
export function checkPuzzle(puzzle: IGameData) {
const { cells } = puzzle;
// TODO: Which clever checks should we implement?
// * are the sums possible?
let sumHorizontal = 0;
let sumVertical = 0;
// * are the values of rows and columns correct?
// * do all hint cells have all necessary hints?
const allHints = cells
.filter(c => c.type === CellType.HintCell)
.every(c => {
const hc = c as IHintCell;
if (hc.hints[0]?.sumSolved) {
sumHorizontal += hc.hints[0]?.sumSolved;
}
if (hc.hints[1]?.sumSolved) {
sumVertical += hc.hints[1]?.sumSolved;
}
return (
(!hc.hints[0]?.sumSolved || hc.hints[0]?.sumSolved > -1) &&
(!hc.hints[1]?.sumSolved || hc.hints[1]?.sumSolved > -1)
);
});
if (!allHints) {
return { valid: false, error: 'Not all hints provided.' };
}
if (sumHorizontal !== sumVertical) {
return {
valid: false,
error: `Hints across: ${sumHorizontal}, down: ${sumVertical}. Must be equal.`,
};
}
return { valid: true };
}
export function checkGuessesCorrect({ cells }: IGameData): boolean {
return cells
.filter(c => c.type === CellType.NumberCell)
.every(c => (c as INumberCell).guess === (c as INumberCell).solution);
}
export function checkAllSolved({ cells }: IGameData): boolean {
return cells
.filter(c => c.type === CellType.NumberCell)
.every(c => (c as INumberCell).solution > 0);
}
|
b0a7adfd64a25c8c99852851c374737551359cb6 | TypeScript | ahmadykhan555/data-structures-and-algorithms | /Code/slidingWindow.ts | 4.125 | 4 | /**
* Write a solution that finds a window that results in max sum
* Approach:
* get the sum of first three and store it somewhere
* start at index window + 1
* add index window + 1 to the temp sum and subtract index window - 1 and add window +1
* see if this results in a sum greater than the previous
* if so, update max sum and continue until we reach index == arr.length - window -1
* since there is only one loop the complexity is O(n)
*/
const maxSum = (arr, window) => {
if (!arr.length || (arr.length && arr.length < window)) {
return null;
}
if (window === 1) {
let temp = [...arr].sort((a, b) => a - b);
return temp[temp.length - 1];
}
let maxSum = 0;
for (let i = 0; i < window; i++) {
maxSum += arr[i];
}
for (let i = 1; i <= arr.length - window; i++) {
let temp = maxSum - arr[i - 1] + arr[window + i - 1];
if (temp >= maxSum) {
maxSum = temp;
}
}
return maxSum;
};
(() => {
console.log(maxSum([1, 2, 5, 2, 8, 1, 5], 2)); // 10
console.log(maxSum([1, 2, 5, 2, 8, 1, 5], 4)); // 17
console.log(maxSum([4, 2, 1, 6, 2], 4)); // 13
console.log(maxSum([4, 2, 1, 6], 1)); // 6
console.log(maxSum([], 4)); // null
})();
|
ae39e356414a82e999202e6951be9eac2a501103 | TypeScript | lfcd85/trading-api-browser | /openapi/ibkrweb/client/models/SecdefInfo.ts | 2.640625 | 3 | // @ts-nocheck
/* eslint-disable */
/**
* Client Portal Web API
* Client Poral Web API
*
* The version of the OpenAPI document: 1.0.0
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
import { exists, mapValues } from '../runtime'
/**
* Contains some basic info of contract
* @export
* @interface SecdefInfo
*/
export interface SecdefInfo {
/**
*
* @type {number}
* @memberof SecdefInfo
*/
conid?: number
/**
* Underlying symbol
* @type {string}
* @memberof SecdefInfo
*/
symbol?: string
/**
*
* @type {string}
* @memberof SecdefInfo
*/
secType?: string
/**
*
* @type {string}
* @memberof SecdefInfo
*/
exchange?: string
/**
*
* @type {string}
* @memberof SecdefInfo
*/
listingExchange?: string
/**
* C = Call Option, P = Put Option
* @type {string}
* @memberof SecdefInfo
*/
right?: string
/**
* The strike price also known as exercise price
* @type {string}
* @memberof SecdefInfo
*/
strike?: string
/**
* Currency the contract trades in
* @type {string}
* @memberof SecdefInfo
*/
currency?: string
/**
* Committee on Uniform Securities Identification Procedures number
* @type {string}
* @memberof SecdefInfo
*/
cusip?: string
/**
* Annual interest rate paid on a bond
* @type {string}
* @memberof SecdefInfo
*/
coupon?: string
/**
* Formatted symbol
* @type {string}
* @memberof SecdefInfo
*/
desc1?: string
/**
* Formatted expiration, strike and right
* @type {string}
* @memberof SecdefInfo
*/
desc2?: string
/**
* Format YYYYMMDD, the date on which the underlying transaction settles if the option is exercised
* @type {string}
* @memberof SecdefInfo
*/
maturityDate?: string
/**
* total premium paid or received for an option contract
* @type {string}
* @memberof SecdefInfo
*/
multiplier?: string
/**
*
* @type {string}
* @memberof SecdefInfo
*/
tradingClass?: string
/**
*
* @type {string}
* @memberof SecdefInfo
*/
validExchanges?: string
}
export function SecdefInfoFromJSON(json: any): SecdefInfo {
return SecdefInfoFromJSONTyped(json, false)
}
export function SecdefInfoFromJSONTyped(
json: any,
ignoreDiscriminator: boolean
): SecdefInfo {
if (json === undefined || json === null) {
return json
}
return {
conid: !exists(json, 'conid') ? undefined : json['conid'],
symbol: !exists(json, 'symbol') ? undefined : json['symbol'],
secType: !exists(json, 'secType') ? undefined : json['secType'],
exchange: !exists(json, 'exchange') ? undefined : json['exchange'],
listingExchange: !exists(json, 'listingExchange')
? undefined
: json['listingExchange'],
right: !exists(json, 'right') ? undefined : json['right'],
strike: !exists(json, 'strike') ? undefined : json['strike'],
currency: !exists(json, 'currency') ? undefined : json['currency'],
cusip: !exists(json, 'cusip') ? undefined : json['cusip'],
coupon: !exists(json, 'coupon') ? undefined : json['coupon'],
desc1: !exists(json, 'desc1') ? undefined : json['desc1'],
desc2: !exists(json, 'desc2') ? undefined : json['desc2'],
maturityDate: !exists(json, 'maturityDate')
? undefined
: json['maturityDate'],
multiplier: !exists(json, 'multiplier') ? undefined : json['multiplier'],
tradingClass: !exists(json, 'tradingClass')
? undefined
: json['tradingClass'],
validExchanges: !exists(json, 'validExchanges')
? undefined
: json['validExchanges'],
}
}
export function SecdefInfoToJSON(value?: SecdefInfo | null): any {
if (value === undefined) {
return undefined
}
if (value === null) {
return null
}
return {
conid: value.conid,
symbol: value.symbol,
secType: value.secType,
exchange: value.exchange,
listingExchange: value.listingExchange,
right: value.right,
strike: value.strike,
currency: value.currency,
cusip: value.cusip,
coupon: value.coupon,
desc1: value.desc1,
desc2: value.desc2,
maturityDate: value.maturityDate,
multiplier: value.multiplier,
tradingClass: value.tradingClass,
validExchanges: value.validExchanges,
}
}
|
b5bf909e40e1f52b2bdffe218142f3121671617f | TypeScript | OmarEQMS/Tlacubazar | /angular-mysql-crud/client/src/app/models/PaymentMethodEnum.ts | 2.84375 | 3 | export class PaymentMethodEnum {
idPaymentMethodEnum?: number;
paymentMethod?: _PaymentMethodEnum.PaymentMethodEnum;
constructor(paymentMethodEnum?: PaymentMethodEnum) {
if (paymentMethodEnum != null) {
this.idPaymentMethodEnum = paymentMethodEnum.idPaymentMethodEnum,
this.paymentMethod = paymentMethodEnum.paymentMethod;
}
}
}
export namespace _PaymentMethodEnum {
export type PaymentMethodEnum = 1 | 2 ;
export const PaymentMethodEnum = {
TARJETA: 1,
EFECTIVO: 2
};
}
|
3686ff4b92a864a94f4a567f5c6ee85bb6140400 | TypeScript | microsoftgraph/msgraph-sdk-javascript | /test/common/tasks/OneDriveLargeFileUploadTask.ts | 2.59375 | 3 | /**
* -------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License.
* See License in the project root for license information.
* -------------------------------------------------------------------------------------------
*/
import { assert } from "chai";
import { OneDriveLargeFileUploadTask } from "../../../src/tasks/OneDriveLargeFileUploadTask";
describe("OneDriveLargeFileUploadTask.ts", () => {
describe("constructCreateSessionUrl", () => {
const spaceFileName = " test.png ";
const fileName = "test.png";
const specialFileName = "test file.png";
const encodedFileName = "test%20file.png";
it("Should trim the extra spaces in the filename", () => {
assert.equal(`/me/drive/root:/${fileName}:/createUploadSession`, OneDriveLargeFileUploadTask["constructCreateSessionUrl"](spaceFileName));
});
it("Should encode space in the filename", () => {
assert.equal(`/me/drive/root:/${encodedFileName}:/createUploadSession`, OneDriveLargeFileUploadTask["constructCreateSessionUrl"](specialFileName));
});
it("Should return url with default root value", () => {
assert.equal(`/me/drive/root:/${fileName}:/createUploadSession`, OneDriveLargeFileUploadTask["constructCreateSessionUrl"](fileName));
});
it("Should return url with default root value for an empty path string", () => {
assert.equal(`/me/drive/root:/${fileName}:/createUploadSession`, OneDriveLargeFileUploadTask["constructCreateSessionUrl"](fileName, ""));
});
it("Should add / in front of the path", () => {
assert.equal(`/me/drive/root:/Documents/${fileName}:/createUploadSession`, OneDriveLargeFileUploadTask["constructCreateSessionUrl"](fileName, "Documents/"));
});
it("Should add / in back of the path", () => {
assert.equal(`/me/drive/root:/Documents/${fileName}:/createUploadSession`, OneDriveLargeFileUploadTask["constructCreateSessionUrl"](fileName, "/Documents"));
});
it("Should trim the extra spaces in the path", () => {
assert.equal(`/me/drive/root:/Documents/${fileName}:/createUploadSession`, OneDriveLargeFileUploadTask["constructCreateSessionUrl"](fileName, " /Documents/ "));
});
});
describe("getFileInfo", () => {
/* tslint:disable: no-string-literal */
it("Should return file content info for Buffer", () => {
const bytes = [1, 2, 3, 4, 5];
const buffer = Buffer.from(bytes);
const fileContent = OneDriveLargeFileUploadTask["getFileInfo"](buffer, "test.png");
const arrayBuffer = new ArrayBuffer(bytes.length);
const typedArray = new Uint8Array(arrayBuffer);
for (let i = 0; i < bytes.length; i++) {
typedArray[i] = bytes[i];
}
assert.deepEqual(fileContent, { content: arrayBuffer as Buffer, size: bytes.length });
});
/* tslint:enable: no-string-literal */
});
});
|
ca3dd066b086cf323d953c4fd4d22f8042f3a6ab | TypeScript | fork-archive-hub/deno-crdt | /logoot/internal/node.ts | 3.296875 | 3 | import { Id, IdJSON, Ordering } from "./id.ts";
export interface NodeJSON {
id?: IdJSON;
value?: string;
children: NodeJSON[];
size: number;
empty: boolean;
}
export class Node {
#id: Id | null;
#value: string | null;
#parent: Node | null = null;
#children: Node[] = [];
#size: number = 1;
#empty: boolean = false;
constructor(id: Id | null, value: string | null = null) {
this.#id = id;
this.#value = value;
}
get id(): Id | null {
return this.#id;
}
get length(): number {
return this.#size - 2;
}
get value(): string | null {
return this.#value;
}
set value(value: string | null) {
this.#value = value;
}
addChild(child: Node): Node {
child.#parent = this as any;
let index = this.#leftmostSearch(child);
this.#children.splice(index, 0, child);
this.adjustSize(child.#size);
return child;
}
adjustSize(amount: number): void {
this.#size += amount;
if (this.#parent) {
this.#parent.adjustSize(amount);
}
}
getChildById(id: Id): Node | null {
let index = this.#exactSearchById(id);
if (index == null) {
return null;
}
return this.#children[index] || null;
}
getChildByOrder(index: number): Node | null {
if (index === 0 && !this.#empty) {
return this as any;
}
let left = this.#empty ? 0 : 1;
let right = left;
for (let i = 0; i < this.#children.length; i++) {
right += this.#children[i].#size;
if (left <= index && right > index) {
return this.#children[i].getChildByOrder(index - left);
}
left = right;
}
return null;
}
getChildByPosition(position: Id[], build: boolean) {
let current: Node | null = this;
let next = null;
position.every((id) => {
next = current!.getChildById(id);
if (!next && !build) {
current = null;
return false;
}
if (!next && build) {
next = new Node(id);
current!.addChild(next);
next.setEmpty(true);
}
current = next;
return true;
});
return current;
}
getOrder(): number {
// -1 to discount the left end node
if (!this.#parent) {
return -1;
}
let order = this.#parent.getOrder();
if (!this.#parent.#empty) {
order += 1;
}
for (let i = 0; i < this.#parent.#children.length; i++) {
if (this.#parent.#children[i].id!.compare(this.id!) === Ordering.Equal) {
break;
}
order += this.#parent.#children[i].#size;
}
return order;
}
getPosition(): Id[] {
if (!this.#parent) {
return [];
}
return this.#parent.getPosition().concat([this.id!]);
}
isEmpty(): boolean {
return this.#empty;
}
removeChild(child: Node): Node | null {
let index = this.#exactSearch(child);
if (index === null) {
return null;
}
this.#children.splice(index, 1);
this.adjustSize(child.#size);
return child;
}
setEmpty(bool = true): void {
if (bool === this.#empty) {
return;
}
this.#empty = bool;
if (bool) {
this.adjustSize(-1);
} else {
this.adjustSize(1);
}
}
toJSON(): NodeJSON {
return {
id: this.#id?.toJSON(),
value: this.#value || undefined,
children: this.#children.map((c) => c.toJSON()),
size: this.#size,
empty: this.#empty,
};
}
trimEmpty(): void {
if (!this.#parent) {
return;
}
if (this.#empty && this.#children.length === 0) {
this.#parent.removeChild(this);
this.#parent.trimEmpty();
}
}
walk(fn: (node: Node) => void): void {
fn(this as any);
this.#children.forEach((child) => {
child.walk(fn);
});
}
#exactSearch = (child: Node): number | null => {
if (!child.id) {
return null;
}
return this.#exactSearchById(child.id);
};
#exactSearchById = (id: Id): number | null => {
let left: number = 0;
let right: number = this.#children.length - 1;
let middle: number;
while (left <= right) {
middle = Math.floor((left + right) / 2);
switch (this.#children[middle].id!.compare(id)) {
case Ordering.Lower: {
left = middle + 1;
break;
}
case Ordering.Greater: {
right = middle - 1;
break;
}
case Ordering.Equal: {
return middle;
}
}
}
return null;
};
#leftmostSearch = (child: Node): number => {
let left: number = 0;
let right: number = this.#children.length;
let middle: number;
while (left < right) {
middle = Math.floor((left + right) / 2);
if (this.#children[middle].id!.compare(child.id!) === Ordering.Lower) {
left = middle + 1;
} else {
right = middle;
}
}
return left;
};
}
|
02b7eaa32961cabc85b66e1a62a77d2e5fa0be8d | TypeScript | nivinjoseph/n-domain | /src/configurable-domain-context.ts | 2.59375 | 3 | import { given } from "@nivinjoseph/n-defensive";
import { DomainContext } from "./domain-context";
export class ConfigurableDomainContext implements DomainContext
{
private _userId: string;
public get userId(): string { return this._userId; }
public set userId(value: string) { this._userId = value; }
public constructor(userId: string)
{
given(userId, "userId").ensureHasValue().ensureIsString();
this._userId = userId;
}
}
|
b826830ea2947fde6262984d54cd32bb1a23598c | TypeScript | pipopotamasu/vue-function-tester | /src/result.ts | 2.859375 | 3 | class Result<returnValue> {
_returnVal: returnValue;
constructor(returnVal: returnValue, context: { [key: string]: any }) {
this._returnVal = returnVal;
Object.keys(context).forEach((key) => {
// FIXME: generate getter
(this as any)[key] = context[key];
});
}
get return() {
return this._returnVal;
}
}
export default Result;
|
3aefc6dadc7a96af4a13e687e59cfc8e3b1c00c8 | TypeScript | Ruddickmg/js-wars | /front/javascript/src/browser/menu/arrows/arrow.ts | 3.0625 | 3 | import {Position} from "../../../game/map/coordinates/position";
import curry from "../../../tools/function/curry";
import capitalizeFirstLetter from "../../../tools/stringManipulation/capitalizeFirstLetter";
import pixelStringConverter, {PixelStringConversion} from "../../../tools/stringManipulation/pixelStringConversion";
import validator, {Validator} from "../../../tools/validation/validator";
import createElement, {Element, ElementPosition} from "../../dom/element/element";
export interface Arrow extends Element<any> {
background: any;
direction: string;
outline: any;
setColor(color: string): Arrow;
setPosition(x: number, y: number): Arrow;
setSize(size: any): Arrow;
}
export default (function() {
const {validateString, validateNumber}: Validator = validator("arrow");
const {formatPixelString}: PixelStringConversion = pixelStringConverter();
const percentageOfScreenSize: number = 25;
const amountToAugmentBorderBy: number = 2;
const top = "borderTopWidth";
const bottom = "borderBottomWidth";
const left = "borderLeftWidth";
const right = "borderRightWidth";
const triangleShapeProperties = {
down: [left, right, bottom],
left: [left, bottom, top],
right: [bottom, right, top],
up: [bottom, right, top],
};
const side: any = {
down: "Top",
left: "Right",
right: "Left",
up: "Bottom",
};
const setSizeOfShape = curry((shapeProperties: string[], element: any, formattedPixelSize: string): any => {
shapeProperties.forEach((property: string) => {
element.style[property] = formattedPixelSize;
});
});
const setSizeOfUpwardFacingArrow = setSizeOfShape(triangleShapeProperties.up);
const setSizeOfDownwardFacingArrow = setSizeOfShape(triangleShapeProperties.down);
const setSizeOfLeftFacingArrow = setSizeOfShape(triangleShapeProperties.left);
const setSizeOfRightFacingArrow = setSizeOfShape(triangleShapeProperties.right);
const modifyArrowByDirection: any = {
down: setSizeOfDownwardFacingArrow,
left: setSizeOfLeftFacingArrow,
right: setSizeOfRightFacingArrow,
up: setSizeOfUpwardFacingArrow,
};
const offsetBorderForPositioning = (element: Element<any>, borderSize: string): any => {
element.setLeft(borderSize);
};
const percentage = (numericalValue: number): number => numericalValue / 100;
const isLeftOrRight = (direction: string): boolean => ["left", "right"].indexOf(direction) > -1;
const augmentBottomSizeForArrowShape = (element: Element<any>, formattedSize: string): any => {
element.element.style.borderBottomWidth = formattedSize;
};
const methods: any = {
setColor(color: string): Arrow {
const edge = capitalizeFirstLetter(side[this.direction]);
if (validateString(color, "setColor")) {
this.background.element.style[`border${edge}Color`] = color;
}
return this;
},
setPosition(position: Position | ElementPosition): Arrow {
const methodName: string = "setPosition";
const {x, y}: Position = position;
if (validateNumber(x, methodName) && validateNumber(y, methodName)) {
this.setLeft(x);
this.setTop(y);
}
return this;
},
setSize(size: number): Arrow {
const background = this.background;
const arrow = this.outline;
const type = this.direction;
const borderWidthAsPercentageOfSize = percentage(percentageOfScreenSize);
const borderWidth = size * borderWidthAsPercentageOfSize;
const formattedSize = formatPixelString(size);
const setSizeOfArrow = modifyArrowByDirection[type];
let formattedBackgroundSize: string;
let borderOffset: string;
let augmentedBottomSize: string;
if (validateNumber(size, "setSize")) {
formattedBackgroundSize = formatPixelString(size - borderWidth);
borderOffset = formatPixelString(borderWidth - size);
augmentedBottomSize = formatPixelString(size - amountToAugmentBorderBy);
this.setWidth(size);
offsetBorderForPositioning(background, borderOffset);
setSizeOfArrow(arrow, formattedSize);
setSizeOfArrow(background, formattedBackgroundSize);
if (isLeftOrRight(type)) {
augmentBottomSizeForArrowShape(background, augmentedBottomSize);
}
}
return this;
},
};
return function(direction: string): Arrow {
const arrowElementType: string = "div";
const arrowElementClass: string = `${direction}Arrow`;
const outline = createElement(`${direction}ArrowOutline`, arrowElementType).setClass(arrowElementClass);
const background: Element<any> = createElement(`${direction}ArrowBackground`, arrowElementType)
.setClass(arrowElementClass);
if (validateString(direction, "constructor")) {
outline.appendChild(background);
return Object.assign(outline, methods, {
background,
direction,
}) as Arrow;
}
};
}());
|
fe01835d22b6ef90501cf90e90df14fb6b3e2d08 | TypeScript | Rumec/pb138-project | /DB-server/src/dataAccess/ordersDataHandler.ts | 2.984375 | 3 | import { Order, PrismaClient } from '@prisma/client';
/**
* Gets all orders for specified user by user id
* Default ordering: by id descending
*/
export async function getByUser(db: PrismaClient, userId: number): Promise<Order[]> {
return db.order.findMany({
where: {
user_id: userId
},
orderBy: {
id: "desc"
}
});
}
/**
* Gets orders for specified user by user's id (@param userId)
* Takes only top n
* Default ordering: by id descending
*/
export async function getByUserTakeN(db: PrismaClient, userId: number, amount: number): Promise<Order[]> {
return db.order.findMany({
where: {
user_id: userId
},
orderBy: {
id: "desc"
},
take: amount
});
}
/**
* Gets an order by @param id
* @returns Order or null if no match for @param id
*/
export async function get(db: PrismaClient, id: number): Promise<Order | null> {
return db.order.findUnique({
where: {
id: id
},
});
}
/**
* Sets {@link Order.canceled} flag to true for an order if it exists
*/
export async function cancel(db: PrismaClient, id: number): Promise<void> {
db.order.update({
where: {
id: id
},
data: {
canceled: true
},
});
}
/**
* Gets an order by @param id with components included (except computer, computer is loaded separately {@link computersDataHandler})
* @returns Order or null if no match for @param id
*/
export async function getWithComponentsExceptComputer(db: PrismaClient, id: number): Promise<Order | null> {
return db.order.findUnique({
where: {
id: id
},
include: {
keyboard: true,
mouse: true,
user: true,
screen: true,
computers: false //to be loaded separately
},
});
}
/**
* Creates a new order
* The computer must be assigned to the order afterwards
* Cancelled and Paid flags are set to false by default
* @param db
* @param userId required
* @param computer required
* @param mouseId optional
* @param keyboardId optional
* @param screenId optional
* @param totalPrice required
* @returns
*/
export function createNewWithoutComputer(db: PrismaClient,
userId: number, mouseId: number | null, keyboardId: number | null, screenId: number | null,
totalPrice: number): Promise<Order> {
const newOrderData = {
canceled: false,
paid: false,
total_price: totalPrice,
user_id: userId,
screen_id: screenId,
mouse_id: mouseId,
keyboard_id: keyboardId
};
return db.order.create({data: newOrderData});
} |
ed91c44c598798bc3afc1a2ef3c6b4aa9a1d5336 | TypeScript | labs42io/itiriri-async | /lib/utils/isAsyncIterable.ts | 2.75 | 3 | export function isAsyncIterable<T>(item: any): item is AsyncIterable<T> {
return typeof (<AsyncIterable<T>>item)[Symbol.asyncIterator] === 'function';
}
|
fb9dc8214ff2f37db44b39e0a919c03ca4984ac6 | TypeScript | vagfsantos/challenge | /angular-chat/src/app/chat.service.ts | 2.625 | 3 | import { Injectable, EventEmitter } from '@angular/core';
import { Message } from './chat/Message';
@Injectable()
export class ChatService {
// event emitted when new messages comes from the user or server
onNewMessageIsAvaiable$: EventEmitter<Message[]> = new EventEmitter();
// list of the entire chat
conversationHistory: Message[] = [];
// returns a copy of the chat history
getAll(): Message[] {
return [].concat( this.conversationHistory );
}
// could be used to send data to server
sendAll() {
}
// add a new message to the stack and emit the tells everybody about it
addMessage(msg: Message) {
this.conversationHistory.push(msg);
this.onNewMessageIsAvaiable$.emit( this.conversationHistory );
}
cleanAll() {
this.conversationHistory = [];
this.onNewMessageIsAvaiable$.emit( this.conversationHistory );
}
}
|
d695bf819586d1f424ba7ef74d5c9568b1dc55d2 | TypeScript | fiveagency/node-seed | /server/src/shared/io/io-error.ts | 2.6875 | 3 | export class IoError extends Error {
public code: string;
public detail: string;
constructor(detail, code) {
super(detail);
this.code = code;
this.detail = detail;
Error.captureStackTrace(this, this.constructor);
}
}
export const ioErrorAdapter = {
serialize(err: Error) {
if (err instanceof IoError) {
const error = {
status: '400',
title: 'io error',
code: err.code,
detail: err.detail,
meta: {
trace: err.stack,
},
};
return error;
}
return null;
},
};
|
5688c2d427c7d618ffdc4668c2d4a93f99dceb63 | TypeScript | bave8672/leetcode | /src/merge-sorted-array/merge-sorted-array.ts | 3.53125 | 4 | /**
Do not return anything, modify nums1 in-place instead.
*/
function merge(nums1: number[], m: number, nums2: number[], n: number): void {
nums1.splice(m);
nums2.splice(n);
let i = 0;
for (const n of nums2) {
while (i < nums1.length && nums1[i] < n) {
i++;
}
nums1.splice(i, 0, n);
}
}
|
0b6f0d4d45d497f39a75bb94bd7aa2b69f59f2b0 | TypeScript | williangaspar/tic-tac-toe | /dist/core/grid.d.ts | 2.671875 | 3 | import ICell from "./i/iCell";
import IGrid from "./i/iGrid";
import { ILine } from "./i/iVictory";
export default class Grid implements IGrid {
private cellGrid;
private range;
private plays;
constructor(Cell: new () => ICell);
reset(): void;
setCell(x: number, y: number, play: number): boolean;
getCell(x: number, y: number): number;
getVictoryLine(play: number): ILine | null;
isFull(): boolean;
getGrid(): number[][];
private getUserGrid(play);
private isVerticallVictory(grid);
private isHorizontalVictory(grid);
private isDiagonalVictory(grid);
private runGrid(action);
}
|
f5f4a2ec0a0ec79859c0e91f526e015cfdd8c0dd | TypeScript | TimJentzsch/tor-user-stats | /tests/transcription.test.ts | 2.640625 | 3 | import RComment from '../src/comment';
import Transcription from '../src/transcription';
import { imageMD, imageMDApr1, imageMDBugged, imageMDOld } from './transcription-templates';
describe('Transcription', () => {
describe('fromComment', () => {
test('should create transcription from normal transcription comment', () => {
const comment: RComment = {
id: '1',
permalink: '',
body: imageMD,
body_html: '',
created_utc: new Date('2020-12-01').valueOf() / 1000,
score: 1,
subreddit_name_prefixed: 'r/CuratedTumblr',
};
const actual = Transcription.fromComment(comment);
expect(actual.contentMD)
.toEqual(`[*Description of anything that you think may be worth describing about the image itself aside from what the text says. For example, an unusual text font, background images or color, etc.*]
Text.
NOTE: if your post has text above an image, transcribe the text before describing the image. Templates show how to format things, not the order to follow.`);
expect(actual.format).toEqual('Image');
expect(actual.type).toEqual('Image');
});
test('should create transcription from April 1st comment', () => {
const comment: RComment = {
id: '1',
permalink: '',
body: imageMDApr1,
body_html: '',
created_utc: new Date('2020-04-01').valueOf() / 1000,
score: 1,
subreddit_name_prefixed: 'r/CuratedTumblr',
};
const actual = Transcription.fromComment(comment);
expect(actual.contentMD)
.toEqual(`[*Description of anything that you think may be worth describing about the image itself aside from what the text says. For example, an unusual text font, background images or color, etc.*]
Text.
NOTE: if your post has text above an image, transcribe the text before describing the image. Templates show how to format things, not the order to follow.`);
expect(actual.format).toEqual('Image');
expect(actual.type).toEqual('Image');
});
});
describe('isTranscription', () => {
test('should reject r/TranscribersOfReddit posts', () => {
const comment: RComment = {
id: '1',
permalink: '',
body: imageMD,
body_html: '',
created_utc: new Date('2020-12-01').valueOf() / 1000,
score: 1,
subreddit_name_prefixed: 'r/TranscribersOfReddit',
};
const actual = Transcription.isTranscription(comment);
expect(actual).toBe(false);
});
test('should reject r/kierra posts', () => {
const comment: RComment = {
id: '1',
permalink: '',
body: imageMD,
body_html: '',
created_utc: new Date('2020-12-01').valueOf() / 1000,
score: 1,
subreddit_name_prefixed: 'r/kierra',
};
const actual = Transcription.isTranscription(comment);
expect(actual).toBe(false);
});
test('should reject mod welcoming comment', () => {
const comment: RComment = {
id: '1',
permalink: '',
body: `Welcome, /u/username! We like to check in, welcome you to the team, and give you some feedback. Your first transcription is a great start -- there’s just one thing we need to clean up to make it top-notch.
You should have thematic breaks separating the transcription from the header and footer. You can write a thematic break in markdown as "---" with an empty line above and below, like so:
Header
---
Transcription
---
Footer
If you could clean that up for me, that'd be perfect. If you have any questions or issues, feel free to reach out to us through modmail (https://old.reddit.com/message/compose/?to=/r/TranscribersOfReddit), join our Discord (https://discord.gg/ZDDE3Pj) for instant feedback on transcriptions and such and to read our step-by-step tutorial (https://old.reddit.com/r/TranscribersOfReddit/wiki/tutorial), explaining how to transcribe in detail.
Cheers and welcome to the crew!`,
body_html: '',
created_utc: new Date('2020-12-01').valueOf() / 1000,
score: 1,
subreddit_name_prefixed: 'r/TranscribersOfReddit',
};
const actual = Transcription.isTranscription(comment);
expect(actual).toBe(false);
});
test('should accept post with standard footer', () => {
const comment: RComment = {
id: '1',
permalink: '',
body: imageMD,
body_html: '',
created_utc: new Date('2020-12-01').valueOf() / 1000,
score: 1,
subreddit_name_prefixed: 'r/CuratedTumblr',
};
const actual = Transcription.isTranscription(comment);
expect(actual).toBe(true);
});
test('should accept post with old footer', () => {
const comment: RComment = {
id: '1',
permalink: '',
body: imageMDOld,
body_html: '',
created_utc: new Date('2020-12-01').valueOf() / 1000,
score: 1,
subreddit_name_prefixed: 'r/CuratedTumblr',
};
const actual = Transcription.isTranscription(comment);
expect(actual).toBe(true);
});
test('should accept post with bugged footer', () => {
const comment: RComment = {
id: '1',
permalink: '',
body: imageMDBugged,
body_html: '',
created_utc: new Date('2020-12-01').valueOf() / 1000,
score: 1,
subreddit_name_prefixed: 'r/CuratedTumblr',
};
const actual = Transcription.isTranscription(comment);
expect(actual).toBe(true);
});
test('should reject post with relaxed footer', () => {
const comment: RComment = {
id: '1',
permalink: '',
body: imageMDApr1,
body_html: '',
created_utc: new Date('2020-12-01').valueOf() / 1000,
score: 1,
subreddit_name_prefixed: 'r/CuratedTumblr',
};
const actual = Transcription.isTranscription(comment);
expect(actual).toBe(false);
});
test('should accept post with relaxed footer on April 1st', () => {
const comment: RComment = {
id: '1',
permalink: '',
body: imageMDApr1,
body_html: '',
created_utc: new Date('2020-04-01').valueOf() / 1000,
score: 1,
subreddit_name_prefixed: 'r/CuratedTumblr',
};
const actual = Transcription.isTranscription(comment);
expect(actual).toBe(true);
});
});
});
|
ab8a7c28211c42532ec994166688d8433aa02022 | TypeScript | ricoarisandyw/garapin-education | /utils/LoadBase64Image.ts | 2.890625 | 3 | import axios from "axios";
// function LoadBase64Image(url: string) {
// return axios.get(url, { responseType: 'blob' })
// .then(response => Buffer.from(response.data, 'binary').toString('base64'))
// }
type Callback = (value: string) => void
function LoadBase64Image(url: string, callback: Callback) {
let canvas = document.createElement('canvas') as (HTMLCanvasElement | null);
let img = document.createElement('img');
//img.setAttribute('crossorigin', 'anonymous');
img.src = url;
img.crossOrigin = "anonymous"
img.onload = () => {
if (canvas) {
canvas.height = img.height;
canvas.width = img.width;
let context = canvas.getContext('2d') as CanvasRenderingContext2D;
context.drawImage(img, 0, 0);
let dataURL = canvas.toDataURL('image/png');
canvas = null;
callback(dataURL);
} else {
callback("")
}
};
}
export default LoadBase64Image |
2481793cf3a2cc79e598c3c8cd7e3a1b8db17023 | TypeScript | Edweis/bricabrac | /app/src/constants/types.ts | 2.5625 | 3 | import { NavigationScreenProp, NavigationRoute } from 'react-navigation';
import firebase from '../firebase';
type Timestamp = firebase.firestore.Timestamp;
export type NavigationProp = NavigationScreenProp<NavigationRoute>;
export type ConceptT = string;
export type ConceptDepSetT = {
name: ConceptT;
deps: ConceptT[];
id: string;
};
export type ConceptDepsT = {
datetime: Date;
} & ConceptDepSetT;
export enum CollectionE {
CONCEPT_DEPS = 'conceptDeps',
USERS = 'users',
BRICKS = 'bricks',
COMMENTS = 'comments',
READING_TIMES = 'readingTimes',
}
export type ComputedCollection = string;
export type LoadingT = {
shouldLoadAgain: boolean;
[keys: string]: boolean;
};
export type SourceT = string;
export type ProjectT = SourceT | null;
/**
* Represents bricks comming from the database.
*/
export type BrickT = {
id: string;
childrenConcepts: ConceptT[];
content: string;
submitTime: Timestamp;
datetime: Timestamp;
parentConcept: ConceptT;
source: string;
isDefinition: boolean;
author: string;
};
/**
* Brick used in the app.
*/
export type UserT = {
id: string;
email: string;
};
export type CommentT = {
id: string;
author: string;
text: string;
datetime: Timestamp;
};
export type ProjectSourceT = SourceT;
export type ProjectSetterT = [
ProjectSourceT,
(project: ProjectSourceT) => void,
];
export type ReadingTimeSetT = {
startTime: Timestamp;
endTime: Timestamp | null;
startPage: number;
endPage: number;
source: SourceT;
};
export type ReadingTimeT = ReadingTimeSetT & {
userId: string;
id: string;
};
export type ConceptAnalysisT = { deps: ConceptT[]; isCyclical: boolean };
export type RegistrationT = {
email: string;
password: string;
passwordConfirmation: string;
};
|
165e3609d190553c5bd5b924246ca3703f0c7f0b | TypeScript | Xan0C/curbl-gltf-viewer | /src/components/camera/lookAtCameraComponent.ts | 2.71875 | 3 | import { ECS, Component } from '@curbl/ecs';
import { vec3 } from 'gl-matrix';
export type LookAtCameraConfig = {
target?: vec3;
up?: vec3;
panning?: vec3;
zoom?: vec3;
};
@ECS.Component()
export class LookAtCameraComponent implements Component {
protected _target: vec3;
protected _up: vec3;
protected _panning: vec3;
protected _zooming: vec3;
protected _zoomPos: number;
constructor(config?: LookAtCameraConfig) {
this.init(config);
}
init(
config: LookAtCameraConfig = {
target: vec3.create(),
up: vec3.fromValues(0, 1, 0),
panning: vec3.create(),
zoom: vec3.create(),
}
): void {
this._target = config.target || vec3.create();
this._up = config.up || vec3.fromValues(0, 1, 0);
this._panning = config.panning || vec3.create();
this._zooming = config.zoom || vec3.create();
this._zoomPos = 0;
}
remove(): void {}
public get target(): vec3 {
return this._target;
}
public set target(value: vec3) {
this._target = value;
}
public get up(): vec3 {
return this._up;
}
public set up(value: vec3) {
this._up = value;
}
public get panning(): vec3 {
return this._panning;
}
public set panning(value: vec3) {
this._panning = value;
}
public get zooming(): vec3 {
return this._zooming;
}
public set zooming(value: vec3) {
this._zooming = value;
}
public get zoomPos(): number {
return this._zoomPos;
}
public set zoomPos(value: number) {
this._zoomPos = value;
}
}
|
67fce734a78d23d32524054b7d26631d7d192a29 | TypeScript | bernhardfritz/falldown | /src/index.ts | 2.53125 | 3 | import Constants from './constants';
import Game from './game';
import Utils from './utils';
import './assets/style.css';
(() => {
if (Utils.isMac()) {
document.getElementById('key1').textContent = '⌥';
document.getElementById('key2').textContent = '⌘';
}
if (navigator.userAgent.indexOf('Chrome') === -1) {
if (navigator.userAgent.indexOf('Firefox') !== -1) {
document.getElementById('key3').textContent = 'K';
} else if (navigator.userAgent.indexOf('Safari') !== -1) {
document.getElementById('key3').textContent = 'C';
}
}
const game = new Game();
game.fps = 24;
game.start();
document.addEventListener('keydown', event => {
if (event.key === 'ArrowLeft') {
game.state.ball.v[0] = -Constants.VX;
} else if (event.key === 'ArrowRight') {
game.state.ball.v[0] = Constants.VX;
}
});
document.addEventListener('keyup', event => {
if (event.key === 'ArrowLeft' || event.key === 'ArrowRight') {
game.state.ball.v[0] = 0;
}
});
window.addEventListener('blur', event => {
if (game.state.gameover || !game.isRunning()) {
return;
}
game.stop();
console.log('⏸ Paused. Click anywhere on the page to resume.')
});
document.addEventListener('click', event => {
if (game.state.gameover || game.isRunning()) {
return;
}
game.start();
});
})(); |
695fc7edcc34c98cb8f446a317ca3c48af631c65 | TypeScript | rxstack/platform-callbacks | /src/validate.ts | 2.515625 | 3 | import {
OperationCallback,
OperationEvent,
OperationEventsEnum,
} from '@rxstack/platform';
import {validate as _validate, ValidatorOptions} from 'class-validator';
import * as _ from 'lodash';
import {BadRequestException} from '@rxstack/exceptions';
import {classToPlain, plainToClass} from 'class-transformer';
import {restrictToOperations} from './utils';
import {Constructable} from '@rxstack/utils';
export const validate = <T>(type: Constructable<T> | string, options?: ValidatorOptions): OperationCallback => {
return async (event: OperationEvent): Promise<void> => {
restrictToOperations(event.eventType, [OperationEventsEnum.PRE_EXECUTE]);
event.request.body = await processData(event.request.body, type, resolveOptions(options));
};
};
const processData = async <T>(data: any, type: Constructable<T> | string,
options?: ValidatorOptions): Promise<any> => {
if (_.isArray(data)) {
for (let i = 0; i < data.length; i++) {
data[i] = await validateItem(data[i], type, options);
}
} else {
data = await validateItem(data, type, options);
}
return data;
};
const validateItem = async <T>(data: Record<string, any>, type: Constructable<T> | string,
options?: ValidatorOptions): Promise<Record<string, any>> => {
const input = _.isString(type) ? data : plainToClass(type, data);
await doValidate(type, input, options);
return classToPlain(input);
};
const resolveOptions = (options?: ValidatorOptions): ValidatorOptions => {
const defaults = {
validationError: { target: false },
whitelist: true,
skipMissingProperties: false
};
return options ? _.merge(defaults, options) : defaults;
};
const doValidate = async <T>(type: Constructable<T> | string,
input: Record<string, any>, options?: ValidatorOptions): Promise<void> => {
const errors = _.isString(type) ? await _validate(type, input, options)
: await _validate(input, options);
if (errors.length > 0) {
const exception = new BadRequestException('Validation Failed');
exception.data = {
errors: errors
};
throw exception;
}
};
|
7276efc649b6a38728db6bf6661eac28d35ffce7 | TypeScript | fanmingfei/ISEEU | /src/config.ts | 3.015625 | 3 | // 问题有之前问题的条件
// 剧情也有之前问题的条件
export enum ConfigType {
/** 旁白 */
dialogue = 'dialogue',
/** 对话 */
question = 'question',
/** 步骤 */
step = 'step',
/** 不展示 */
empty = 'empty'
}
export interface Next {
type: ConfigType,
id: string;
}
interface Condition {
id: string;
answer: string[]
}
export interface Question {
type: ConfigType;
/** 对话id */
id: string;
/** 问题内容 */
value: string;
/** 选项 */
answers: Array<{
/** 答案id */
id: string;
/** 答案内容 */
value: string;
/** 下一步行为 */
next: Array<Next>;
}>;
conditions: Array<Condition>
}
export interface Dialogue {
type: ConfigType;
/** 对话id */
id: string;
/** 对话列表 */
list: Array<{
/** 头像 */
avatar: string;
/** 称呼 */
name: string;
/** 内容 */
value: string;
seek: number;
duration: number
}>;
/** 下一步行为 */
next: Array<Next>;
conditions: Array<Condition>
}
export interface Step {
type: ConfigType;
id: string;
background: string;
player: string;
next: Array<Next>;
}
export interface Empty {
type: ConfigType;
id: string;
}
export type AllType = Question & Dialogue & Step & Empty;
export const dialogue: Dialogue[] = [{
type: ConfigType.dialogue,
id: 'school_choice_a',
list: [
{
avatar: './statics/haimianbaobao.png',
name: '',
value: '你背着书包冲进家门,高喊一声“我回来啦”,爸爸妈妈正在厨房做饭',
seek: 0.1,
duration: 9,
},
{
avatar: './statics/haimianbaobao.png',
name: '',
value: '你将书包甩到书桌上,打开电视准备看海绵宝宝',
seek: 11,
duration: 6
},
{
avatar: './statics/haimianbaobao.png',
name: '',
value: '还没看一会儿,妈妈就开吼:作业写完了么?就看电视!',
seek: 18,
duration: 6 // 24
},
{
avatar: './statics/haimianbaobao.png',
name: '',
value: '你悻悻地关上电视,回房写作业去了,但还是有些委屈。',
seek: 25,
duration: 8 // 33
},
],
next: [{
type: ConfigType.step,
id: 'youth'
}],
conditions: []
}, {
type: ConfigType.dialogue,
id: 'school_choice_b',
list: [
{
avatar: './statics/haimianbaobao.png',
name: '',
value: '店里新上海绵宝宝的玩具,让你很是眼馋,就是价格让你望而却步',
seek: 35,
duration: 10 // 45
},
{
avatar: './statics/haimianbaobao.png',
name: '',
value: '看着口袋里只有攒下的4块钱,叹了口气',
seek: 45,
duration: 7 // 52
},
{
avatar: './statics/haimianbaobao.png',
name: '',
value: '你有些不舍的离开了小店,临走前还看了一眼海绵宝宝',
seek: 53.5,
duration: 7 // 59.5
},
],
next: [{
type: ConfigType.step,
id: 'youth'
}],
conditions: []
}, {
type: ConfigType.dialogue,
id: 'youth_choice_a',
list: [
{
avatar: './statics/rongyao.png',
name: '',
value: '队友坑到不行,你觉得有点带不动',
seek: 61,
duration: 4 // 65
},
{
avatar: './statics/rongyao.png',
name: '',
value: '我方水晶被打爆的瞬间,有点不爽,对着死党说:再来',
seek: 66,
duration: 8 // 72
},
{
avatar: './statics/rongyao.png',
name: '',
value: '不知不觉已经凌晨1点了,自己晚上什么书都没有看,暗暗发誓明天一定要认真复习',
seek: 74,
duration: 8 // 82
},
],
next: [{
type: ConfigType.step,
id: 'adult'
}],
conditions: []
}, {
type: ConfigType.dialogue,
id: 'youth_choice_b',
list: [
{
avatar: './statics/sannian.png',
name: '',
value: '你翻开了五年高考三年模拟,准备开始做题',
seek: 83,
duration: 5 // 87
},
{
avatar: './statics/sannian.png',
name: '',
value: '然而,10分钟后,却开始打哈欠犯困了',
seek: 90,
duration: 5 // 94
},
{
avatar: './statics/sannian.png',
name: '',
value: '上下眼皮打架,最终还是趴在桌上睡着了',
seek: 96,
duration: 6 // 101
},
],
next: [{
type: ConfigType.step,
id: 'adult'
}],
conditions: []
}, {
type: ConfigType.dialogue,
id: 'adult_choice_a',
list: [
{
avatar: './statics/huatong.png',
name: '',
value: '你充分发挥出中华小曲库的能力,成为了场上的焦点,不知不觉很晚了,明天还要上班,大家各自回家了。',
seek: 102,
duration: 11 // 113
}
],
next: [{
type: ConfigType.empty,
id: ''
}],
conditions: []
}, {
type: ConfigType.dialogue,
id: 'adult_choice_b',
list: [
{
avatar: './statics/pijiu.png',
name: '',
value: '跟同事比摇骰子,也不知道今天怎么了,一次也没赢过',
seek: 114,
duration: 7 // 121
},
{
avatar: './statics/pijiu.png',
name: '',
value: '输的酒到是喝了不少,有点发晕,你靠在了沙发上睡了起来',
seek: 121,
duration: 6 // 127
},
{
avatar: './statics/pijiu.png',
name: '',
value: '醒来的时候已经是早上了,头发晕,却还要去上班。',
seek: 127,
duration: 7 // 143
},
],
next: [{
type: ConfigType.empty,
id: ''
}],
conditions: []
}]
export const question: Question[] = [{
type: ConfigType.question,
id: 'confirm_school_choice',
value: '放学后校门口特别热闹,门口小商贩的周围,总是会聚集很多学生,你决定:',
answers: [
{
id: 'confirm_school_choice_a',
value: '回家看海绵宝宝',
next: [{
type: ConfigType.dialogue,
id: 'school_choice_a'
}],
},
{
id: 'confirm_school_choice_b',
value: '冲进小卖部',
next: [{
type: ConfigType.dialogue,
id: 'school_choice_b'
}],
}
],
conditions: []
}, {
type: ConfigType.question,
id: 'confirm_youth_choice',
value: '不知不觉已经高三了,越来越临近高考了,父母的期望像座大山有点压着你喘不过气,死党约你上荣耀开黑,放松一下,你决定',
answers: [
{
id: 'confirm_youth_choice_a',
value: '来上一局',
next: [{
type: ConfigType.dialogue,
id: 'youth_choice_a'
}],
},
{
id: 'confirm_youth_choice_b',
value: '好好复习',
next: [{
type: ConfigType.dialogue,
id: 'youth_choice_b'
}],
}
],
conditions: []
}, {
type: ConfigType.question,
id: 'confirm_adult_choice',
value: '今天部门团建,大家一起去KTV唱歌,你决定:',
answers: [
{
id: 'confirm_adult_choice_a',
value: '麦霸本色出演',
next: [{
type: ConfigType.dialogue,
id: 'adult_choice_a'
}],
},
{
id: 'confirm_adult_choice_b',
value: '摇骰子喝啤酒',
next: [{
type: ConfigType.dialogue,
id: 'adult_choice_b'
}],
}
],
conditions: []
}]
export const step: Step[] = [
{
type: ConfigType.step,
id: 'child',
background: './statics/child.png',
player: './statics/player_child.png',
next: [{
type: ConfigType.question,
id: 'confirm_school_choice'
}]
},
{
type: ConfigType.step,
id: 'youth',
background: './statics/youth.png',
player: './statics/player_youth.png',
next: [{
type: ConfigType.question,
id: 'confirm_youth_choice'
}],
},
{
type: ConfigType.step,
id: 'adult',
background: './statics/adult.png',
player: './statics/player_adult.png',
next: [{
type: ConfigType.question,
id: 'confirm_adult_choice'
}]
},
]
const empty: Empty[] = [{ type: ConfigType.empty, id: '' }]
const config: { [propName: string]: AllType[] } = {
dialogue, question, step, empty
}
export default config
|
9e62812466c9cf79e88182788d4c716ccbc8ca3c | TypeScript | BroloPwnsU/jinx-shop-ext | /src/app/classes/notification.ts | 2.90625 | 3 | export class Notification {
message: string = '';
isError: boolean = false;
constructor (
message: string
, isError: boolean
) {
this.message = message;
this.isError = isError;
}
} |
7f0abfc8c0e023fb482b51ec836ed831a616f4b1 | TypeScript | SMazeikaite/eshop-angular-ui | /src/app/services/store.service.ts | 2.5625 | 3 | import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Product } from '../models/product.model';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class StoreService {
items$ = new BehaviorSubject<Product[]>([]);
productList: Product[];
url = 'http://localhost:3000/products';
constructor(private http: HttpClient) {
this.refreshItems();
}
getItem(id: number): Observable<Product> {
return this.http.get<Product>(`${this.url}/${id}`);
}
addItem(product: Product): void {
this.http.post<Product>(this.url, product).subscribe(() => {
this.refreshItems();
});
}
updateItem(product: Product, id: number): void {
this.http.put<Product>(`${this.url}/${id}`, JSON.stringify(product), { headers: { 'Content-Type': 'application/json' } }).subscribe(() => {
this.refreshItems();
});
}
removeItem(product: Product): void {
this.http.delete<Product>(`${this.url}/${product.id}`).subscribe(() => {
this.refreshItems();
});
}
refreshItems(): void {
this.getData().subscribe(data => this.items$.next(data));
}
getData(): Observable<Product[]> {
return this.http.get<Product[]>(this.url);
}
}
|
61d3bf420bb6d88ee21f205034996833184d92e0 | TypeScript | MedN-Dev/vue_typescript_starter_kit | /src/store/store.ts | 2.578125 | 3 | import Vue from 'vue'
import Vuex, {ActionTree, MutationTree} from 'vuex'
import * as T from '../types/common'
import {DaptinClient} from 'daptin-client'
Vue.use(Vuex);
export interface Todo {
title: String,
completed: Boolean
created_at: Date,
updated_at: Date,
}
const daptinClient = new DaptinClient("http://localhost:6336", false);
daptinClient.worldManager.loadModels().then(function () {
daptinClient.jsonApi.findAll("todo").then(function(res: any){
console.log("all todos", res.data)
})
});
interface State {
links: T.Link[],
todos: Todo[]
}
const mutations: MutationTree<State> = {
reverse: (state) => state.links.reverse(),
refreshTodos: (state) => {
daptinClient.worldManager.loadModel("todo").then(function (response) {
daptinClient.jsonApi.findAll("todo").then(function (todos: object[]) {
console.log("todos", todos);
});
})
}
}
const actions: ActionTree<State, any> = {}
const state: State = {
links: [
{url: "https://vuejs.org", description: "Core Docs"},
] as T.Link[],
todos: [] as Todo[],
}
export default new Vuex.Store<State>({
state,
mutations,
actions
});
|
d9df30e37c0073e56ddbecd539eb55572705712e | TypeScript | rockysims/handshakeTracker | /src/app/app.model.ts | 2.71875 | 3 | interface Entry {
id: string,
data: EntryData
}
interface EntryData {
name: string,
tags: string[],
note: string,
unixTimestamp: number,
location: LatLong
}
interface LatLong {
latitude: number,
longitude: number
}
interface MapBounds {
min: LatLong,
max: LatLong
}
interface DateRange {
min: Date,
max: Date
} |
5dc1c17b4627dbbd5a08fde7056eb87ce0689e02 | TypeScript | tolgaberk/iris_data_mining | /src/iris/main.ts | 2.6875 | 3 | import { model, resetModel } from "./model";
import * as tf from "@tensorflow/tfjs";
import {
testDataTensor,
testOutputTensor,
trainDataTensor,
trainOutputTensor,
} from "./data";
import { Tensor } from "../typings";
import {
drawAccuracy,
drawBoxPlot,
drawHistograms,
drawLossGraph,
drawSplom,
drawStatistics,
} from "./plotter";
import { createRandomDiv } from "../helpers";
////////////////////////////////////////////////////
///////////////////////////////////////////////////
// run the tensorflow model to fit itself to train data
function evaluateModel() {
tf.tidy(() => {
model
.fit(trainDataTensor, trainOutputTensor, {
epochs: 100, // how many times its going to pass over data
shuffle: true,
callbacks: {
onEpochEnd,
},
})
.then(({ history }) => {
drawLossGraph(history.loss as number[]);
//
predictAndReportAccuracy();
});
});
}
evaluateModel();
drawBoxPlot();
drawStatistics();
drawHistograms();
drawSplom();
//
const indicatorDiv = createRandomDiv();
indicatorDiv.style.textAlign = "center";
indicatorDiv.style.fontSize = "2rem";
//
function predictAndReportAccuracy() {
// predict species based on trained data and calculated weights
const predicted: Tensor = model.predict(testDataTensor) as Tensor;
// get most confident specie index
const softmaxedPrediction = predicted.argMax(1);
// compare it to labels
const accuracyTensor = softmaxedPrediction.equal(testOutputTensor.argMax(1));
// get tensor from gpu
const accuracyVector = accuracyTensor.arraySync() as number[];
// count true and false values
const counts = accuracyVector.reduce(
(acc, item) => {
item ? acc.truthies++ : acc.falsies++;
return acc;
},
{ truthies: 0, falsies: 0 }
);
// get accuracy by dividing true values by item count
const accuracy = counts.truthies / accuracyVector.length;
drawAccuracy(counts);
indicatorDiv.innerHTML = `Accuracy = ${(accuracy * 100).toFixed(2)}%`;
}
//
let sameLossCounter = 0;
let lastLoss = 0;
// epoch callback => i added a auto reset switch in case model stucks in a local minima for 30 epochs
function onEpochEnd(epoch: number, logs: tf.Logs | undefined): void {
indicatorDiv.innerHTML = `Model ${epoch + 1}% finished!`;
if (logs?.loss) {
lastLoss === logs.loss && sameLossCounter++;
lastLoss = logs.loss;
if (sameLossCounter > 30) {
console.log("Model Stuck in a local minima re-evaluating");
resetModel(model, evaluateModel);
}
} else {
sameLossCounter = 0;
}
}
|
01ca4968b2d26e8d00a06ab1ffebea554a11640f | TypeScript | LuizEduOML/FiapProjetoDevOps | /Front-End/GestaoDeEstoque/src/app/home/home.component.ts | 2.53125 | 3 | import { Component, OnInit, ViewChild } from '@angular/core';
import { MatPaginator, MatTableDataSource } from '@angular/material';
interface Category {
value: string;
viewValue: string;
}
export interface Product {
id: number;
descricao: string;
categoria: string;
quantidade: number;
ultimaAtualizacao: string;
}
const PRODUCT_DATA: Product[] = [
{id: 1, descricao: 'Notebook', categoria: 'Eletrônicos', quantidade: 3, ultimaAtualizacao: 'Ontem'},
{id: 1, descricao: 'Notebook', categoria: 'Eletrônicos', quantidade: 3, ultimaAtualizacao: 'Ontem'},
{id: 1, descricao: 'Notebook', categoria: 'Eletrônicos', quantidade: 3, ultimaAtualizacao: 'Ontem'},
{id: 1, descricao: 'Notebook', categoria: 'Eletrônicos', quantidade: 3, ultimaAtualizacao: 'Ontem'},
{id: 1, descricao: 'Notebook', categoria: 'Eletrônicos', quantidade: 3, ultimaAtualizacao: 'Ontem'},
{id: 1, descricao: 'Notebook', categoria: 'Eletrônicos', quantidade: 3, ultimaAtualizacao: 'Ontem'},
];
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor() { }
@ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
ngOnInit() {
this.dataSource.paginator = this.paginator;
}
categories: Category[] = [
{value: 'eletronico-0', viewValue: 'Eletrônicos'},
{value: 'limpeza-1', viewValue: 'Limpeza'},
];
displayedColumns: string[] = ['id', 'descricao', 'categoria', 'quantidade', 'ultimaAtualizacao'];
dataSource = new MatTableDataSource<Product>(PRODUCT_DATA);
}
|
26c26d5023776b11a5835a95f76f4f897aeed7f6 | TypeScript | Carleslc/IonicAI | /src/providers/utils/strings.ts | 3.046875 | 3 | export class StringUtils {
static capitalize(s: string) {
s = s.trim();
return s ? s[0].toUpperCase() + s.slice(1) : ''
}
}
|
02c0874e2670ecc1e913f0dc2b6dc38435742070 | TypeScript | koorosh/ui | /packages/cluster-ui/src/store/analytics/analytics.reducer.ts | 2.65625 | 3 | import { createAction } from "@reduxjs/toolkit";
type Page =
| "statements"
| "statementDetails"
| "transactions"
| "transactionDetails";
type PagePayload<T> = {
page: Page;
value: T;
};
type SortingPayload = {
tableName: string;
columnName: string;
ascending?: boolean;
};
const PREFIX = "adminUI/analytics";
/**
* actions accept payload with "page" field which specifies the page where
* action occurs and a value expected expected by specific action.
*/
export const actions = {
search: createAction<PagePayload<number>>(`${PREFIX}/search`),
pagination: createAction<PagePayload<number>>(`${PREFIX}/pagination`),
sorting: createAction<PagePayload<SortingPayload>>(`${PREFIX}/sorting`),
activateDiagnostics: createAction<PagePayload<string>>(
`${PREFIX}/activateStatementDiagnostics`,
),
downloadStatementDiagnostics: createAction<PagePayload<string>>(
`${PREFIX}/downloadStatementDiagnostics`,
),
subNavigationSelection: createAction<PagePayload<string>>(
`${PREFIX}/subNavigationSelection`,
),
};
|
db359233db1a828de8ef759904c5c3a2d697ac59 | TypeScript | jasperstafleu/ums-node | /app/spec/Templating/JsEngine.spec.ts | 2.984375 | 3 | import JsEngine from "$stafleu/Templating/JsEngine";
describe('JsEngine', () => {
let engine: JsEngine,
fileExists: (fileName: string) => boolean,
getContent: (fileName: string, encoding: string) => string;
beforeEach(() => {
engine = new JsEngine({
existsSync: (fileName) => fileExists(fileName),
readFileSync: (fileName, encoding) => getContent(fileName, encoding)
});
fileExists = () => true;
getContent = () => '';
});
describe('\b.supports', () => {
it('should support template names ending in .jstpl only', () => {
expect(engine.supports(Math.random().toString(36))).toBe(false);
expect(engine.supports('.jstpl')).toBe(true);
expect(engine.supports(Math.random().toString(36)+'.jstpl')).toBe(true);
});
it('should support existing templates only', () => {
fileExists = (fileName) => fileName === 'exists.jstpl';
expect(engine.supports('exists.jstpl')).toBe(true);
expect(engine.supports('does-not-exist.jstpl')).toBe(false);
});
});
describe('\b.render', () => {
it('should render .jstpl files', () => {
const fileName = Math.random().toString(36) + '.jstpl',
templ = Math.random().toString(36);
getContent = (fn) => fn === fileName ? templ : '';
expect(engine.render(fileName)).toBe(templ);
});
it('should render literals', () => {
const fileName = Math.random().toString(36) + '.jstpl',
literal = Math.random(),
templLiteral = 'success: ${lit}';
getContent = (fn) => fn === fileName ? templLiteral : '';
expect(engine.render(fileName, {lit: literal})).toBe('success: '+literal);
});
it('should throw if literals are used that were not passed in parameters', () => {
const fileName = Math.random().toString(36) + '.jstpl',
templLiteral = 'success: ${lit}';
getContent = (fn) => fn === fileName ? templLiteral : '';
expect(() => engine.render(fileName)).toThrow();
});
});
});
|
f5d8eacdcfa5e7c88d5e13084ef3e97d76fa80c9 | TypeScript | joker1u3/tiny-entity | /sqlite/test/entityObj_test.ts | 2.796875 | 3 | import { SqliteDataContext } from '../index';
import { EntityObject } from '../../entityObject';
import { Assert } from './assert';
class Account extends EntityObject<Account> {
UserName: string;
Password: string;
toString(): string { return "Account"; }
}
class Employee extends EntityObject<Employee> {
account: string;
employeeNumber: string;
joinTime: Date;
note: string;
password: string;
storeId: string;
userId: string;
roles: string;
toString(): string { return "Employee"; }
}
class TestDemoDataContext extends SqliteDataContext {
private _account: Account;
private _employee: Employee;
constructor() {
super("./clerkDB.db");
this._account = new Account(this);
this._employee = new Employee(this);
}
get Account() { return this._account; }
get Employee() { return this._employee; }
}
function query() {
let ctx = new TestDemoDataContext();
let nn = "001"
let r = ctx.Employee.Where(x => x.employeeNumber == nn, ["nn"], [nn]).ToList();
console.log("employee =====>", r);
// //ctx.Employee.Count();
// let count = ctx.Employee.Count(x=>x.employeeNumber == "001");
// console.log("count ====>" ,count);
// console.log("any ===>",ctx.Employee.Any(x=>x.employeeNumber == "002"));
// console.log("First ===>",ctx.Employee.First());
//ctx.Employee.OrderBy(x=>x.account).ToList();
// var r = ctx.Employee
// .Where(x => x.account == "lkc")
// .Select(x => x.account && x.password)
// .Count();
// console.log(r);
let employee = new Employee();
employee.account = "jhonlee";
employee.id = "6207b0fbff284730a1e536e0ebfefc14";
employee.joinTime = new Date("2016-6-14 17:22"); //"2016-6-14 17:22";
employee.password = "202cb962ac59075b964b07152d234b70";
employee.userId = "3";
employee.employeeNumber = "003";
ctx.BeginTranscation();
let rr = ctx.Create(employee);
console.log("create result:", rr);
ctx.Commit();
//ctx.Update()
// let ac = "lkc";
// var r = ctx.Employee.Where(x => x.account == "lkc").Select(x => x.account).ToList();
// console.log(r);
}
query();
|
65e6c341f6098ac2295ce3d18bccde4cffc19ad0 | TypeScript | maxcamp/sfdx-core | /test/unit/config/configStoreTest.ts | 2.640625 | 3 | /*
* Copyright (c) 2018, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
import { expect } from 'chai';
import { BaseConfigStore } from '../../../src/config/configStore';
class TestConfig extends BaseConfigStore<BaseConfigStore.Options> {
public async init(): Promise<void> {}
}
describe('ConfigStore', () => {
it('for each value', async () => {
const config = await TestConfig.create({});
config.set('1', 'a');
config.set('2', 'b');
let st = '';
config.forEach((key, val) => {
st += `${key}${val}`;
});
expect(st).to.equal('1a2b');
});
it('await each value', async () => {
const config = await TestConfig.create({});
config.set('1', 'a');
config.set('2', 'b');
let st = '';
await config.awaitEach(async (key, val) => {
st += `${key}${val}`;
});
expect(st).to.equal('1a2b');
});
});
|
bdd47ead9b222855519a71d30b1da5e73539c7b1 | TypeScript | 1905-javareact/project1-micheledexter | /src/actions/login.actions.ts | 2.59375 | 3 | import { History } from "history";
import { Dispatch } from "redux";
import { User } from "../models/user";
import { checkPermission } from "../utilities/handle";
import { apiClient } from "../axios/user-api-client";
export const loginTypes = {
INVALID_CREDENTIALS: 'LOGIN_INVALID_CREDENTIALS',
FAILED_LOGIN: 'LOGIN_FAILED_LOGIN',
SUCCESSFUL_LOGIN: 'LOGIN_SUCCESSFUL_LOGIN'
}
export const login = (username: string, password: string, history: History) => async (dispatch: Dispatch) => {
const credentials = {
username,
password
}
try {
const response = await apiClient.post('/login', credentials);
if (response.status === 401) {
dispatch({
type: loginTypes.INVALID_CREDENTIALS
});
} else if (response.status === 200) {
const user: User = await response.data;
dispatch({
payload: {
user: user
},
type: loginTypes.SUCCESSFUL_LOGIN
});
history.push('/dashboard/' + user.role.role);
} else {
dispatch({
type: loginTypes.FAILED_LOGIN
});
}
} catch(err) {
checkPermission(history, err);
}
};
|
9cf5bc533c387c247b7cebaafde7e24b26b46632 | TypeScript | msolvaag/redux-db | /src/models/__tests__/FieldSchemaModel.spec.ts | 2.859375 | 3 | // tslint:disable:object-literal-key-quotes
import { createDatabase } from "../..";
import { TYPE_MODIFIED, TYPE_PK } from "../../constants";
import errors from "../../errors";
import Database from "../Database";
import FieldSchemaModel from "../FieldSchemaModel";
const TABLE1 = "TABLE1";
const TABLE2 = "TABLE2";
const schema = {
[TABLE1]: {
id: { pk: true }
},
[TABLE2]: {
ref: { pk: true, references: TABLE1 }
}
};
const invalidTypes: Record<string, any> = {
"string": ["", null, 123, NaN, {}, new Date(), () => 0],
"function": ["", null, 123, NaN, {}, new Date()]
};
describe("constructor", () => {
test("throws if no table instance given", () => {
const model = FieldSchemaModel as any;
expect(() => new model())
.toThrow(errors.argument("table", "object"));
});
test("throws if no name given", () => {
const model = FieldSchemaModel as any;
expect(() => new model({}))
.toThrow(errors.argument("name", "string"));
});
test("throws if no field definition given", () => {
const model = FieldSchemaModel as any;
expect(() => new model({}, "field"))
.toThrow(errors.argument("schema", "object"));
});
describe("invalid field definition", () => {
const db = createDatabase(schema);
const table = db.getTableSchema(TABLE1);
test.each([
["fieldName", "string", {}],
["propName", "string", {}],
["value", "function", {}],
["references", "string", {}],
["relationName", "string", { references: "table2" }]
])('throws if "schema.%s" is given invalid %s', (field: string, type: string, def: any) => {
invalidTypes[type].forEach((val: any) => {
expect(() => new FieldSchemaModel(table, "field", { ...def, [field]: val }))
.toThrow(errors.argument(`schema.${field}`, type));
});
});
});
describe("assignment", () => {
const db = createDatabase(schema);
const table = db.getTableSchema(TABLE1);
const name = "FIELD";
const type = TYPE_MODIFIED;
const pk = true;
const relationName = "refs";
const cascade = true;
const unique = true;
const notNull = false;
const references = TABLE2;
const field = new FieldSchemaModel(table, name, { type });
test("field.type is set", () =>
expect(field.type).toEqual(type));
test("field.name is set", () =>
expect(field.name).toEqual(name));
test("field.name is set to def.fieldName", () => {
const fieldName = "Field";
const withFieldName = new FieldSchemaModel(table, name, { fieldName });
expect(withFieldName.name).toEqual(fieldName);
});
test("field.propName is defaulted to name", () =>
expect(field.propName).toEqual(name));
test("field.propName is set to def.propName", () => {
const propName = "Prop";
const withPropName = new FieldSchemaModel(table, name, { propName });
expect(withPropName.propName).toEqual(propName);
});
test("field.isPrimaryKey is set if def.pk is true", () => {
const pkField = new FieldSchemaModel(table, name, { pk: true });
expect(pkField.isPrimaryKey).toEqual(true);
});
test("field.isPrimaryKey is set if def.type is TYPE_PK", () => {
const pkField = new FieldSchemaModel(table, name, { type: TYPE_PK });
expect(pkField.isPrimaryKey).toEqual(true);
});
test("field.isStamp is set if def.stamp is true", () => {
const stampField = new FieldSchemaModel(table, name, { stamp: true });
expect(stampField.isStamp).toEqual(true);
});
test("field.isStamp is set if def.type is TYPE_MODIFIED", () => {
const stampField = new FieldSchemaModel(table, name, { type: TYPE_MODIFIED });
expect(stampField.isStamp).toEqual(true);
});
test("field._valueFactory is set if def.value is a function", () => {
const stampField: any = new FieldSchemaModel(table, name, { value: () => 0 });
expect(stampField._valueFactory).toBeInstanceOf(Function);
});
test("field.isForeignKey is set when def.references has value", () => {
const pkField = new FieldSchemaModel(table, name, { references: TABLE2 });
expect(pkField.isForeignKey).toEqual(true);
});
describe("field is a key", () => {
const key = new FieldSchemaModel(table, "field", {
pk,
relationName,
cascade,
unique,
notNull
});
test("field.relationName is set when field is foreign key and has value", () => {
const fkey = new FieldSchemaModel(table, "field", { references, relationName });
expect(fkey.relationName).toEqual(relationName);
});
test("field.relationName is not set when field is not a foreign key", () => {
const pkey = new FieldSchemaModel(table, "field", { pk, relationName });
expect(pkey.relationName).toBeUndefined();
});
test("field.cascade is set when def.cascade has value", () =>
expect(key.cascade).toEqual(cascade));
test("field.unique is set when def.unique has value", () =>
expect(key.unique).toEqual(unique));
test("field.notNull is set when def.notNull has value", () =>
expect(key.notNull).toEqual(notNull));
});
describe("field is not a key", () => {
const attr = new FieldSchemaModel(table, "field", {
relationName,
cascade,
unique,
notNull
});
test("field.isPrimaryKey is false", () =>
expect(attr.isPrimaryKey).toEqual(false));
test("field.isForeignKey is false", () =>
expect(attr.isForeignKey).toEqual(false));
test("field.relationName is undefined", () =>
expect(attr.relationName).toBeUndefined());
test("field.cascade is false", () =>
expect(attr.cascade).toEqual(false));
test("field.unique is false", () =>
expect(attr.unique).toEqual(false));
test("field.notNull is set when def.notNull has value", () =>
expect(attr.notNull).toEqual(notNull));
});
});
});
describe("connect", () => {
const db = createDatabase(schema);
const table = db.getTableSchema(TABLE1);
const refTable = db.getTableSchema(TABLE2);
const field = new FieldSchemaModel(table, "field", {
references: TABLE2
});
field.connect(db.tableMap);
test("assigns refTable to referenced table schema", () =>
expect(field.refTable).toStrictEqual(refTable));
test("throws if references unknown schema", () =>
expect(() => field.connect({}))
.toThrow(errors.fkInvalidReference(field.table.name, field.name, field.references as string)));
test("does not assign refTable", () => {
const attr = new FieldSchemaModel(table, "field", {});
attr.connect(db.tableMap);
expect(attr.refTable).toBeUndefined();
});
});
describe("getValue", () => {
const db = createDatabase(schema);
const table = db.getTableSchema(TABLE1);
const fieldName = "field";
const fieldValue = "value";
const field = new FieldSchemaModel(table, fieldName, {});
test("returns value of record field value", () =>
expect(field.getValue({ [fieldName]: fieldValue })).toEqual(fieldValue));
test("invokes valueFactory if defined", () => {
const customValue = "COMPOSITE";
const value = jest.fn(d => customValue);
const fieldWithFactory = new FieldSchemaModel(table, fieldName, { value });
const data = { [fieldName]: fieldValue };
const record = { value: data };
expect(fieldWithFactory.getValue(data, record)).toEqual(customValue);
expect(value).toHaveBeenCalledWith(data, { record, schema: fieldWithFactory });
});
});
describe("getRecordValue", () => {
const db = createDatabase(schema);
const table = db.getTableSchema(TABLE1);
const fieldName = "field";
const fieldValue = "value";
const field = new FieldSchemaModel(table, fieldName, {});
const data = { [fieldName]: fieldValue };
const record = { value: data };
const spy = jest.spyOn(field, "getValue");
test("returns value of record field value", () =>
expect(field.getRecordValue(record)).toEqual(fieldValue));
test("invokes field.getValue with record.value and record", () =>
expect(spy).toHaveBeenCalledWith(data, record));
});
|
d8ae94f57333e7129d457ad3e3d2dc0f17e2df73 | TypeScript | Aareksio/zombie-net | /src/resolvers/zombieItem.resolver.ts | 2.921875 | 3 | import { Zombie } from '../entities/Zombie';
import { Arg, Int, Mutation, Resolver } from 'type-graphql';
import { EntityManager, Repository } from 'typeorm';
import { InjectManager, InjectRepository } from 'typeorm-typedi-extensions';
import { Item } from '../entities/Item';
@Resolver()
export class ZombieItemResolver {
constructor(
@InjectRepository(Zombie) private readonly zombieRepository: Repository<Zombie>,
@InjectRepository(Item) private readonly itemRepository: Repository<Item>,
@InjectManager() private readonly entityManager: EntityManager
) {}
@Mutation(returns => Zombie, { description: 'Adds selected item to zombie\'s inventory. The item must be unique for given zombie, the inventory can have up to 5 items total.' })
async addZombieItem(@Arg('zombieId', type => Int) zombieId: number, @Arg('itemId', type => Int) itemId: number): Promise<Zombie> {
const item = await this.itemRepository.findOne(itemId);
if (!item) throw new Error('Invalid item ID');
return this.entityManager.transaction('SERIALIZABLE', async manager => {
const zombie = await manager.getRepository(Zombie).findOne(zombieId, { relations: ['items'] });
if (!zombie) throw new Error('Invalid zombie ID');
if (zombie.items.length >= 5) throw new Error(`Zombie can have up to ${5} items`);
if (zombie.items.find(zombieItem => zombieItem.id === item.id)) throw new Error(`Zombie is already equipped with ${item.name} (id: ${item.id})`);
await manager.getRepository(Zombie)
.createQueryBuilder()
.relation(Zombie, 'items')
.of(zombie)
.add(item);
return {
...zombie,
items: [...zombie.items, item]
};
});
}
@Mutation(returns => Zombie, { description: 'Removes selected item from zombie\'s inventory.' })
async removeZombieItem(@Arg('zombieId', type => Int) zombieId: number, @Arg('itemId', type => Int) itemId: number): Promise<Zombie> {
const zombie = await this.zombieRepository.findOne(zombieId, { relations: ['items'] });
if (!zombie) throw new Error('Invalid zombie ID');
const item = zombie.items.find(zombieItem => zombieItem.id === itemId);
if (!item) throw new Error(`Zombie is not equipped with item id ${itemId}`);
await this.zombieRepository
.createQueryBuilder()
.relation(Zombie, 'items')
.of(zombie)
.remove(item);
return {
...zombie,
items: zombie.items.filter(zombieItem => zombieItem.id !== item.id)
};
}
}
|
0df0906faac3e91fb93ad1eddd7cb97c9eb27d3e | TypeScript | rafaleal/cwbmess-delivery-mgmt-panel | /src/app/domain/enums.ts | 2.59375 | 3 | export enum ContractTypeEnum {
Billed,
Spontaneous
}
export enum CustomerTypeEnum {
Legal,
Natural
}
export enum DeliveryStatusEnum {
Registered,
Ongoing,
Completed,
Canceled
}
export enum PaymentStatusEnum {
Pending,
Paid
}
export enum PaymentTypeEnum {
Money,
Transfer
}
export enum PhoneTypeEnum {
LandLine,
Mobile
}
export const DeliveryStatus = Object.freeze([
'REGISTERED',
'ONGOING',
'COMPLETED',
'CANCELED'
]);
export const PaymentStatus = Object.freeze([
'PENDING',
'PAID'
]);
|
e1f09625a2262fd10de5972162d9cb28796fc381 | TypeScript | kdharani/protractor-ui-reference | /protractor-typescript-cucumber/pages/fedex.page.ts | 2.765625 | 3 | import {browser, element, ElementArrayFinder, ElementFinder, protractor} from 'protractor';
import { logger } from '../../utils/log4jsconfig'
export class Page {
protected route = '';
protected timeout = {
SHORT: 2000,
MEDIUM: 30000,
LONG: 60000
};
protected sels: {
/*
selectorName: selector
*/
};
constructor (sels:any, route:string){
if(typeof sels === 'object') {
this.sels = sels;
} else {
throw new Error('first argument is expected to be a selector object')
}
if(typeof route === 'string'){
this.route = route;
return this;
} else {
throw new Error('second argument is expected to be a route string')
}
}
public async pojo (...args: any[]): Promise<any> {
const members = args;
return function (...args: any[]) {
const obj = {}, j = members.length;
for (let i =0; i < j; ++i) {
obj[members[i]] = args[i];
}
return obj;
};
}
public log(message:string): void {
logger.log().info(message);
}
public logStep(message:string, context: any): void {
logger.log().info(message);
if(typeof context === 'object')
context.allure.logStep(message);
}
public async navigate (context?:any,waitFor?:string, timeout?:number): Promise<void>{
if(waitFor!==undefined) {
await browser.get(this.route);
await browser.wait(this.isElementPresent(waitFor), timeout, `Element ${waitFor} not found`);
} else {
await browser.get(this.route);
}
}
public async title (): Promise<string> {
return await browser.getTitle()
}
public async currentUrl (): Promise<string> {
return await browser.getCurrentUrl()
}
public element (selName:string):ElementFinder {
return element(this.sels[selName]);
}
public elements (selName:string):ElementArrayFinder {
return element.all(this.sels[selName]);
}
public async getSelector (selName) {
const elementSelector = this.sels[selName];
if (!elementSelector) {
throw new Error('Cannot find element "'+selName+'"');
}
return elementSelector;
}
public async waitForElementText (selName:string, text:string, timeout:number) {
return await browser.wait(protractor.ExpectedConditions.textToBePresentInElement(this.element(selName), text), timeout, `Element ${selName} not found`);
}
public async waitForElementVisible (selName:string, timeout:number) {
return await browser.wait(protractor.ExpectedConditions.visibilityOf(this.element(selName)), timeout, `Element ${selName} not found`);
}
public async waitForElementInVisible (selName:string, timeout:number) {
return await browser.wait(protractor.ExpectedConditions.invisibilityOf(this.element(selName)), timeout, `Element ${selName} not found`);
}
public async waitForElementClickable (selName:string, timeout:number) {
return await browser.wait(protractor.ExpectedConditions.elementToBeClickable(this.element(selName)), timeout, `Element ${selName} not found`);
}
public async waitForElementSelected (selName:string, timeout:number) {
return await browser.wait(protractor.ExpectedConditions.elementToBeSelected(this.element(selName)), timeout, `Element ${selName} not found`);
}
public async waitForElementValue (selName:string, text:string, timeout:number) {
return await browser.wait(protractor.ExpectedConditions.textToBePresentInElementValue(this.element(selName), text), timeout, `Element ${selName} not found`);
}
public async isElementPresent (selName:string) {
return await this.element(selName).isPresent();
}
} |
285bd5b8948e0c0e506bc5a3f5c3065bfed41005 | TypeScript | aperdizs/rdr2-animals | /src/animals/animal.controller.ts | 2.609375 | 3 | import { CreateAnimalDto } from './dto/create-animal.dto';
import { AnimalDto } from './dto/animal.dto';
import { PaginationDto } from 'common/dto/pagination.dto';
import { Controller, Req, Get, ParseIntPipe, Param, Post, Body, Put, Delete, Query } from "@nestjs/common";
import { ApiUseTags, ApiResponse, ApiBearerAuth, ApiImplicitQuery, ApiOperation, ApiImplicitParam, ApiImplicitBody } from '@nestjs/swagger';
import { Pagination } from "common/decorators/pagination.decorator";
import { AnimalService } from './animal.service';
import { AnimalResponseDto } from './dto/animal-response.dto';
import { UpdateAnimalDto } from './dto/update-animal.dto';
const logger = require('logger');
@ApiUseTags('Animal')
@Controller('api/v1/animal')
export class AnimalController {
constructor(private readonly animalService: AnimalService) {}
@Get()
@ApiOperation({
title: 'Get all animals', description: `
Get all animals
`, operationId: 'GetAll'
})
@ApiResponse({ status: 200, description: 'Animals have been successfully returned', isArray: false, type: AnimalResponseDto })
@ApiResponse({ status: 403, description: 'Not authorized.' })
@ApiResponse({ status: 401, description: 'Not authenticated.' })
@ApiImplicitQuery({ name: 'page[size]', description: 'Page size. Default 10', type: String, required: false })
@ApiImplicitQuery({ name: 'page[number]', description: 'Page number', type: String, required: false })
@ApiImplicitQuery({ name: 'type', description: 'Filter by type', type: String, required: false })
async findAll(@Pagination() pagination: PaginationDto, @Query('type') type: string) {
logger.info('Getting all animals');
const data = await this.animalService.findAll(pagination, { type });
return new AnimalResponseDto(data[0], data[1], pagination);
}
@Get('/:id')
@ApiOperation({
title: 'Get animal by id', description: `
Get animal by id
`, operationId: 'GetById'
})
@ApiImplicitParam({ name: 'id', description: 'Id of the animal', type: Number, required: true })
@ApiResponse({ status: 200, description: 'Animals have been successfully returned', isArray: false, type: AnimalDto })
@ApiResponse({ status: 403, description: 'Not authorized.' })
@ApiResponse({ status: 404, description: 'Animal not found' })
@ApiResponse({ status: 401, description: 'Not authenticated.' })
async findOne(@Param('id', new ParseIntPipe()) id: number) {
logger.info('Getting animal by id', id);
const data = await this.animalService.findById(id);
return data;
}
@Post()
@ApiOperation({
title: 'Create Animal', description: `
Create Animal
`, operationId: 'Create'
})
@ApiResponse({ status: 200, description: 'Animal have been successfully created', isArray: false, type: AnimalDto })
@ApiResponse({ status: 403, description: 'Not authorized.' })
@ApiResponse({ status: 400, description: 'Validation error' })
@ApiResponse({ status: 401, description: 'Not authenticated.' })
async create(@Body() createAnimalDto: CreateAnimalDto) {
logger.info('Creating animal');
const data = await this.animalService.create(createAnimalDto)
return data;
}
@Put('/:id')
@ApiOperation({
title: 'Update Animal', description: `
Update Animal
`, operationId: 'Update'
})
@ApiImplicitParam({ name: 'id', description: 'Id of the animal', type: Number, required: true })
@ApiResponse({ status: 200, description: 'Animal have been successfully update', isArray: false, type: AnimalDto })
@ApiResponse({ status: 403, description: 'Not authorized.' })
@ApiResponse({ status: 400, description: 'Validation error' })
@ApiResponse({ status: 404, description: 'Animal not found' })
@ApiResponse({ status: 401, description: 'Not authenticated.' })
async update(@Param('id', new ParseIntPipe()) id: number, @Body() updateAnimalDto: UpdateAnimalDto) {
logger.info('Updating animal with id', id);
const data = await this.animalService.update(id, updateAnimalDto)
return data;
}
@Delete('/:id')
@ApiOperation({
title: 'Remove Animal', description: `
Remove Animal
`, operationId: 'Remove'
})
@ApiImplicitParam({ name: 'id', description: 'Id of the animal', type: Number, required: true })
@ApiResponse({ status: 200, description: 'Animal have been successfully deleted', isArray: false, type: AnimalDto })
@ApiResponse({ status: 403, description: 'Not authorized.' })
@ApiResponse({ status: 404, description: 'Animal not found' })
@ApiResponse({ status: 401, description: 'Not authenticated.' })
async delete(@Param('id', new ParseIntPipe()) id: number) {
logger.info('Deleting animal with id', id);
const data = await this.animalService.remove(id);
return data;
}
}
|
4b56c2f724bb6a001a2729227a2e80ae1109208b | TypeScript | maurer2/kfz | /src/components/Plate.ts | 3.578125 | 4 |
interface LicencePlate {
key: string;
district: string;
state: string;
isCurrent: boolean;
country: string;
getPlate(): string;
getDistrict(): string;
getState(): string;
getLetterAtPosition(position: number): string;
startsWith(letter: string): boolean;
hasLetterAtPosition(position: number, letter: string): boolean;
}
class LicencePlate {
key: string;
district: string;
state: string;
isCurrent: boolean;
country: string;
constructor(key, { district = "", state = "", country = "de" }, isCurrent) {
this.key = key;
this.district = district;
this.state = state;
this.isCurrent = isCurrent;
this.country = country;
if (this.key.length > 3) {
throw new Error("LicencePlate length error");
}
}
getPlate() {
return this.key;
}
getDistrict() {
return this.district;
}
getState() {
return this.country;
}
getIsCurrent() {
return this.isCurrent;
}
getLetterAtPosition(position: number) {
return this.key.charAt(position);
}
startsWith(letter: string) {
return this.key.charAt(0) === letter.charAt(0);
}
hasLetterAtPosition(position: number, letter: string) {
if (position > this.key.length) {
return false;
}
return this.key.charAt(position) === letter;
}
}
export default LicencePlate;
|
f6d00b74d5d966d3967fca1ff4678a3853a2aa60 | TypeScript | crejb/bgg-list | /src/app/geek-list-filter-criteria/text-filter/text-filter.ts | 2.828125 | 3 | import { ListItemFilter } from '../list-item-filter';
import { GeekListItemDetail } from '../../geek-list-item-detail';
export class TextFilter implements ListItemFilter{
value : string;
constructor(value : string){
this.value = value;
}
GetText(): string {
return `${this.value}`;
}
Passes(item: GeekListItemDetail): boolean {
return !this.value || item.summary.name.toLowerCase().indexOf(this.value) >= 0;
}
} |
2224be66b4899539bdfea1000a3c8b478fe9da87 | TypeScript | abhi6711/speech-portal | /src/app/tabs/view-speech/view-speech.component.ts | 2.640625 | 3 | /******************************* Description of Component *********************************
View speech component interacts with the dataservice and when the page initializes it calls
dataservice to send the data which user wants to view. If no data is send then it will show
error message otherwise it will show the speech data.
On this page user can edit and delete their speech.
************************************ END *************************************************/
/**
* Import all the angular dependencies here
*/
import { Component, OnInit, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { MatSidenav } from '@angular/material/sidenav';
/**
* Import all the internal module dependencies here
*/
import * as constant from '../../constants';
import { DataService } from '../../services/dataservice.service';
import { DialogBoxService } from '../../services/dialog-box.service';
@Component({
selector: 'app-view',
templateUrl: './view-speech.component.html',
styleUrls: ['./view-speech.component.scss']
})
export class ViewSpeechComponent implements OnInit {
@ViewChild('sidenav') sidenav: MatSidenav;
date = new FormControl(new Date());
serializedDate = new FormControl((new Date()).toISOString());
authorName: string;
keyWords: string;
speechText: string;
speechName: string;
showSpeech: boolean;
noSpeechData: boolean;
speechData: object ;
constructor(private dataService: DataService, private dailogService: DialogBoxService) {
}
/**
* This function is fired after constructor is initialized.
* It takes the speech data from dataservice. If data is present
* then it shows the data else it will not show the data
*/
ngOnInit() {
const speechData = this.dataService.getViewSpeechData();
if (speechData[1]) {
this.showSpeech = true;
this.setSpeechData(speechData[0]);
} else {
this.noSpeechData = true;
}
}
/**
* This function set the data in the speech form
* @param data : contains speech details
* @returns void
*/
public setSpeechData(data: object) {
this.speechData = data;
this.authorName = data[constant.AUTHORNAME];
this.keyWords = data[constant.KEYWORDS];
this.speechName = data[constant.SPEECHTITLE];
this.speechText = data[constant.SPEECHTEXT];
}
/*
* This function save the speech and call a function to update the speech details
* @return void
*/
public saveSpeech(): void {
const data = this.updateSpeechData();
this.dataService.updateSpeech(data, 'save');
this.dailogService.openMsgModal(constant.SAVEMESSAGE);
}
/**
* This function update speech data with new values
* @return object
*/
public updateSpeechData(): object {
this.speechData[constant.SPEECHTITLE] = this.speechName;
this.speechData[constant.AUTHORNAME] = this.authorName;
this.speechData[constant.KEYWORDS] = this.keyWords;
this.speechData[constant.SPEECHTEXT] = this.speechText;
this.speechData[constant.DATE] = this.date.value;
return this.speechData;
}
/**
* This function is trigerred when user clicks the dialog box open after clicking delete button
* If user click delete button on dialog box then it deleted the speech data by calling
* dtaservice function
* @param isSpeechDeleted : boolean variable which cheeck whether to delete the speech or not
*/
public submitResponse(isSpeechDeleted: boolean): void {
if(isSpeechDeleted) {
this.dataService.updateSpeech(this.speechData, 'delete');
this.dailogService.openDeleteModal(constant.DELETESPEECHMSG, 'Speech-history');
}
}
}
|
17a6893bfb9023259bff68fbede23ce23e07635b | TypeScript | midrock/vue-mapp | /src/helpers/calc.ts | 2.8125 | 3 | import { VMCalcAxisPosition } from "./types";
export function getAxisPositionStyle(params: VMCalcAxisPosition): object {
const {
triggerDistance,
triggerSize,
windowLength,
contentSize,
offset,
backPositionName,
frontPositionName,
distanceProp,
contentSizeProp,
space,
position,
floatTrigger
} = params;
const style: object = {};
const min = space;
const max = windowLength - space;
const maxContent = max - min;
const endBack = Math.min(triggerDistance + triggerSize - offset, max);
const startFront = triggerDistance + offset;
const endFront = startFront + contentSize;
const startBack = endBack - contentSize;
const maxContentBack = endBack - min;
const maxContentFront = max - startFront;
const backRegExp = new RegExp(backPositionName);
const frontRegExp = new RegExp(frontPositionName);
function setSize(max) {
if (contentSize > max) {
style[contentSizeProp] = max;
}
}
if (frontRegExp.test(position)) {
if (floatTrigger) {
style[distanceProp] = startFront;
if (contentSize > maxContentFront) {
if (maxContentBack > maxContentFront) {
style[distanceProp] = Math.max(startBack, min);
setSize(maxContentBack);
} else {
setSize(maxContentFront);
}
}
} else {
if (endFront > max) {
style[distanceProp] = Math.max(startFront - endFront + max, min);
} else {
style[distanceProp] = startFront;
}
}
} else if (backRegExp.test(position)) {
if (floatTrigger) {
style[distanceProp] = Math.max(startBack, min);
if (contentSize > maxContentBack) {
if (maxContentFront > maxContentBack) {
style[distanceProp] = Math.max(startFront, min);
setSize(maxContentFront);
} else {
setSize(maxContentBack);
}
}
} else {
style[distanceProp] = startBack < min ? min : startBack;
}
} else {
const startCenter = Math.max(triggerDistance + (triggerSize / 2) - (contentSize / 2), min);
const endCenter = startCenter + contentSize;
if (endCenter > max) {
style[distanceProp] = Math.max(startCenter - endCenter + max, min);
} else {
style[distanceProp] = startCenter;
}
}
if (typeof style[contentSizeProp] !== 'number') {
setSize(maxContent);
}
return style;
}
|
765c7d85de7b01599431bdd6d8bd6fdee161fbfc | TypeScript | Rhadow/nature_of_code | /src/elements/Vehicle.ts | 2.640625 | 3 | import * as numjs from 'numjs';
import { IVehicle } from './ElementInterface';
import { ICanvasState } from '../components/Canvas/CanvasInterfaces';
import { magnitude, normalize, getCoordinateAfterRotation, limit, mapping, findNormalPoint } from '../utils/math';
import FlowField from './FlowField';
import Path from './Path';
export default class Vehicle implements IVehicle {
mass: number;
size: number;
location: nj.NdArray;
velocity: nj.NdArray = numjs.array([0, 0]);
maxVelocity: number;
maxSteeringForce: number;
isDebugging: boolean = false;
private angle: number = mapping(Math.random(), 0, 1, 0, Math.PI * 2);
private targetDistanceThreshold: number = 0;
private predictDistance: number = 0;
private predictRadius: number = 0;
private nextWanderLocation: nj.NdArray = numjs.array([0, 0]);
private futurePosition: nj.NdArray = numjs.array([0, 0]);
private normalPointOnPath: nj.NdArray = numjs.array([0, 0]);
private isWandering: boolean = false;
private isFollowingPath: boolean = false;
protected acceleration: nj.NdArray = numjs.array([0, 0]);
protected mainColor: string = '#ffcf00';
protected subColor: string = '#0f0b19';
constructor(mass: number, location: nj.NdArray, maxVelocity: number, maxSteeringForce: number, mainColor?: string, subColor?: string, isDebugging?: boolean) {
this.mass = mass;
this.size = mass;
this.predictDistance = mass * 6;
this.predictRadius = mass * 2;
this.targetDistanceThreshold = mass * 5;
this.maxVelocity = maxVelocity;
this.maxSteeringForce = maxSteeringForce;
this.location = location;
this.mainColor = mainColor ? mainColor : this.mainColor;
this.subColor = subColor ? subColor : this.subColor;
this.isDebugging = isDebugging || this.isDebugging;
}
applyForce(force: nj.NdArray) {
this.acceleration = this.acceleration.add(force);
}
run(state: ICanvasState): void {
this.step(state);
this.display(state);
this.isWandering = false;
this.isFollowingPath = false;
}
step(state: ICanvasState): void {
this.velocity = limit(this.velocity.add(this.acceleration), this.maxVelocity);
this.location = this.location.add(this.velocity);
if (magnitude(this.velocity) > 0) {
this.angle = Math.atan2(this.velocity.get(1), this.velocity.get(0));
}
this.checkEdges(state.worldWidth, state.worldHeight);
this.acceleration = this.acceleration.multiply(0);
}
display(state: ICanvasState): void {
const x = this.location.get(0);
const y = this.location.get(1);
const [newX, newY] = getCoordinateAfterRotation(x, y, this.angle);
if (state.ctx) {
state.ctx.beginPath();
state.ctx.rotate(this.angle);
state.ctx.moveTo(newX + this.size / 2, newY);
state.ctx.lineTo(newX - this.size / 2, newY - this.size / 2);
state.ctx.lineTo(newX - this.size / 4, newY);
state.ctx.lineTo(newX - this.size / 2, newY + this.size / 2);
state.ctx.lineTo(newX + this.size / 2, newY);
state.ctx.fillStyle = this.mainColor;
state.ctx.lineWidth = 2;
state.ctx.strokeStyle = this.subColor;
state.ctx.fill();
state.ctx.stroke();
state.ctx.lineWidth = 1;
state.ctx.strokeStyle = '#000000';
state.ctx.fillStyle = '#ffffff';
if (this.isDebugging) {
if (this.isWandering) {
const [futureX, futureY] = getCoordinateAfterRotation(this.futurePosition.get(0), this.futurePosition.get(1), this.angle);
const [wanderX, wanderY] = getCoordinateAfterRotation(this.nextWanderLocation.get(0), this.nextWanderLocation.get(1), this.angle);
state.ctx.beginPath();
state.ctx.moveTo(newX + this.size / 2, newY);
state.ctx.lineTo(futureX, futureY);
state.ctx.stroke();
state.ctx.beginPath();
state.ctx.arc(futureX, futureY, this.predictRadius, 0, Math.PI * 2);
state.ctx.stroke();
state.ctx.beginPath();
state.ctx.moveTo(futureX, futureY);
state.ctx.lineTo(wanderX, wanderY);
state.ctx.stroke();
}
if (this.isFollowingPath) {
const [futureX, futureY] = getCoordinateAfterRotation(this.futurePosition.get(0), this.futurePosition.get(1), this.angle);
const [normalX, normalY] = getCoordinateAfterRotation(this.normalPointOnPath.get(0), this.normalPointOnPath.get(1), this.angle);
state.ctx.beginPath();
state.ctx.moveTo(newX + this.size / 2, newY);
state.ctx.lineTo(futureX, futureY);
state.ctx.stroke();
state.ctx.beginPath();
state.ctx.moveTo(futureX, futureY);
state.ctx.lineTo(normalX, normalY);
state.ctx.stroke();
}
}
state.ctx.resetTransform();
}
}
seek(target: nj.NdArray): nj.NdArray {
const desiredVector = target.subtract(this.location);
const distance = magnitude(desiredVector);
let desiredVelocity = normalize(desiredVector).multiply(this.maxVelocity);
if (distance < this.targetDistanceThreshold) {
const velocity = mapping(distance, 0, this.targetDistanceThreshold, 0, this.maxVelocity);
desiredVelocity = normalize(desiredVector).multiply(velocity)
}
const steer = desiredVelocity.subtract(this.velocity);
const steeringForce = limit(steer, this.maxSteeringForce);
return steeringForce;
}
wander(): void {
const futureX = this.location.get(0) + this.predictDistance * Math.cos(this.angle);
const futureY = this.location.get(1) + this.predictDistance * Math.sin(this.angle);
this.futurePosition = numjs.array([futureX, futureY]);
const newSubAngle = mapping(Math.random(), 0, 1, 0, 2 * Math.PI);
const xOffset = this.predictRadius * Math.cos(newSubAngle);
const yOffset = this.predictRadius * Math.sin(newSubAngle);
this.nextWanderLocation = numjs.array([futureX + xOffset, futureY + yOffset]);
const seekForce = this.seek(this.nextWanderLocation);
this.applyForce(seekForce);
this.isWandering = true;
}
follow(flowField: FlowField): void {
const force = flowField.getField(this.location);
const desiredVelocity = normalize(force).multiply(this.maxVelocity);
const steer = desiredVelocity.subtract(this.velocity);
const steeringForce = limit(steer, this.maxSteeringForce);
this.applyForce(steeringForce);
}
private getClosestNormalFromPath(path: Path): nj.NdArray[] {
const predictDistance = this.mass * 2;
const futureX = this.location.get(0) + predictDistance * Math.cos(this.angle);
const futureY = this.location.get(1) + predictDistance * Math.sin(this.angle);
const threshold = Math.min(this.size * 2, 10);
let result: nj.NdArray[] = [numjs.array([Infinity, Infinity])];
let minResult: nj.NdArray[] = [numjs.array([Infinity, Infinity])];
let normalFound: boolean = false;
this.futurePosition = numjs.array([futureX, futureY]);
for (let i = 0; i < path.points.length - 1; i++) {
const start = path.points[i];
const end = path.points[i + 1];
if (magnitude(this.futurePosition.subtract(end)) < threshold) {
continue;
}
let normalPoint = findNormalPoint(start, end, this.futurePosition);
const isNormalInPath = normalPoint.get(0) >= Math.min(start.get(0), end.get(0)) && normalPoint.get(0) <= Math.max(start.get(0), end.get(0));
const currentDistance = magnitude(normalPoint.subtract(this.futurePosition));
const minResultDistance = magnitude(minResult[0].subtract(this.futurePosition));
if (currentDistance <= minResultDistance) {
minResult = [normalPoint, start, end];
}
if (isNormalInPath) {
normalFound = true;
const resultDistance = magnitude(result[0].subtract(this.futurePosition));
if (currentDistance <= resultDistance) {
result = [normalPoint, start, end];
}
}
}
if (!normalFound) {
result = minResult;
}
return result;
}
getClosestNormalFromPathV1(path: Path): nj.NdArray[] {
const predictDistance = this.mass * 2;
const futureX = this.location.get(0) + predictDistance * Math.cos(this.angle);
const futureY = this.location.get(1) + predictDistance * Math.sin(this.angle);
let result: nj.NdArray[] = [numjs.array([Infinity, Infinity])];
this.futurePosition = numjs.array([futureX, futureY]);
for (let i = 0; i < path.points.length - 1; i++) {
const start = path.points[i];
const end = path.points[i + 1];
let normalPoint = findNormalPoint(start, end, this.futurePosition);
const isNormalInPath = normalPoint.get(0) >= Math.min(start.get(0), end.get(0)) && normalPoint.get(0) <= Math.max(start.get(0), end.get(0));
if (!isNormalInPath) {
normalPoint = end;
}
const resultDistance = magnitude(result[0].subtract(this.futurePosition));
const currentDistance = magnitude(normalPoint.subtract(this.futurePosition));
if (currentDistance <= resultDistance) {
result = [normalPoint, start, end];
}
}
return result;
}
followPath(path: Path): void {
this.isFollowingPath = true;
const [normalPoint, start, end] = this.getClosestNormalFromPathV1(path);
// const [normalPoint, start, end] = this.getClosestNormalFromPath(path);
this.normalPointOnPath = normalPoint;
const targetDistanceFromNormal = 25;
const distance = magnitude(this.normalPointOnPath.subtract(this.location));
const target = normalize(end.subtract(start)).multiply(targetDistanceFromNormal).add(normalPoint);
if (distance > path.radius || magnitude(this.velocity) === 0) {
const seekForce = this.seek(target);
this.applyForce(seekForce);
}
}
seperate(others: Vehicle[]): nj.NdArray {
let count: number = 0;
let sum: nj.NdArray = numjs.array([0, 0]);
let result: nj.NdArray = numjs.array([0, 0]);
const separation = 50;
for (let i = 0; i < others.length; i++) {
const otherNode = others[i];
const force = this.location.subtract(otherNode.location);
const distance = magnitude(force);
if (distance > 0 && distance < separation) {
sum = sum.add(normalize(force));
count++;
}
}
if (count > 0) {
sum = sum.divide(count);
const desiredVelocity = sum.multiply(this.maxVelocity);
const steer = desiredVelocity.subtract(this.velocity);
result = limit(steer, this.maxSteeringForce);
}
return result;
}
applyBehaviors(others: Vehicle[], target: nj.NdArray, seekMag: number, seperateMag: number): void {
const seekForce = this.seek(target);
const seperateForce = this.seperate(others);
this.applyForce(seekForce.multiply(seekMag));
this.applyForce(seperateForce.multiply(seperateMag));
}
align(others: Vehicle[]): nj.NdArray {
let count: number = 0;
let sum: nj.NdArray = numjs.array([0, 0]);
let result: nj.NdArray = numjs.array([0, 0]);
const radius = 50;
for (let i = 0; i < others.length; i++) {
const otherNode = others[i];
const force = this.location.subtract(otherNode.location);
const distance = magnitude(force);
if (distance > 0 && distance < radius) {
sum = sum.add(others[i].velocity);
count++;
}
}
if (count > 0) {
sum = normalize(sum.divide(count));
const desiredVelocity = sum.multiply(this.maxVelocity);
const steer = desiredVelocity.subtract(this.velocity);
result = limit(steer, this.maxSteeringForce);
}
return result;
}
cohesion(others: Vehicle[]): nj.NdArray {
let count: number = 0;
let sum: nj.NdArray = numjs.array([0, 0]);
let result: nj.NdArray = numjs.array([0, 0]);
const radius = 50;
for (let i = 0; i < others.length; i++) {
const otherNode = others[i];
const force = this.location.subtract(otherNode.location);
const distance = magnitude(force);
if (distance > 0 && distance < radius) {
sum = sum.add(otherNode.location);
count++;
}
}
if (count > 0) {
sum = sum.divide(count);
result = this.seek(sum);
}
return result;
}
flock(others: Vehicle[], seperateMag: number, alignMag: number, cohesionMag: number): void {
const seperateForce = this.seperate(others);
const alignForce = this.align(others);
const cohesionForce = this.cohesion(others);
this.applyForce(seperateForce.multiply(seperateMag));
this.applyForce(alignForce.multiply(alignMag));
this.applyForce(cohesionForce.multiply(cohesionMag));
}
checkEdges(worldWidth: number, worldHeight: number): void {
const x = this.location.get(0);
const y = this.location.get(1);
let newX: number = x;
let newY: number = y;
if (x > worldWidth) {
newX = 0;
}
if (x < 0) {
newX = worldWidth;
}
if (y > worldHeight) {
newY = 0;
}
if (y < 0) {
newY = worldHeight;
}
this.location = numjs.array([newX, newY]);
}
} |
86b9aff5ec19f128b89d6da7ce5f35ca28eac8dd | TypeScript | palantir/redoodle | /src/Action.ts | 2.9375 | 3 | /**
* @license
* Copyright 2017 Palantir Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Basic Redux action type.
*
* This type is purposefully unopinionated and minimal for describing the broad
* Reducer and Dispatch APIs. In practice, consumers of Redoodle will be creating
* TypedActionDefs that yield the far more expressive TypedAction.
*
* @see Dispatch
* @see Reducer
* @see TypedAction
*/
export interface Action {
type: any;
[name: string]: any;
}
|
06bd5585498ddcdf82720fcef1e688004454ca76 | TypeScript | stephschumacher/SkyGoRemoteTest | /pages/ShopOffersPage.ts | 2.765625 | 3 | import { ClientFunction, Selector, t } from 'testcafe';
import { log, LogType } from "../common/log";
import { splitNumberPoundsPence } from "../common/helper"
export default class ShopOffersPage {
tiles: Selector;
offerPrice: Selector;
constructor () {
this.tiles = Selector("#tab-1").find(".u-margin-y-large")
this.offerPrice = Selector("#tab-1").find(".c-costing__price.c-price")
}
/////////////
// checkOfferPrices
// Check the prices on the page against the list of prices given
// offerPrices = array of current prices (££.pp), e.g. [39.00, 27.50, 46]
/////////////
async checkOfferPrices(offerPrices: number []) {
// check there are enough offers
let offerPriceCount = await this.offerPrice.count
await t.expect(offerPriceCount).gte(offerPrices.length)
log(`There are at least ${offerPrices.length} tiles (Found ${offerPriceCount})`, LogType.Success)
let text: string
let numSplit: number []
for (let i = 0; i < offerPrices.length; i++) {
numSplit = splitNumberPoundsPence(offerPrices[i])
text = await this.offerPrice.nth(i).find(".c-price__main").innerText;
await t.expect(text).eql("£"+numSplit[0].toString(), `Price should be ${offerPrices[i]}`)
if(numSplit[1] > 0) {
text = await this.offerPrice.nth(i).find(".c-price__fractional").innerText;
await t.expect(text).eql(numSplit[1].toString(), `Price should be ${offerPrices[i]}`)
}
log(`Price is £${offerPrices[i]}`, LogType.Success)
}
}
} |
802e66f1a0aee3d31920cc461d4ce546306c96c8 | TypeScript | alinz/complex | /src/core/math/util.ts | 2.65625 | 3 | const degree = Math.PI / 180
export const EPSILON = 0.000001
export function toRadian(a: number): number {
return a * degree
}
export function toDegree(radian: number): number {
return radian / degree
} |
d25b023ac04ff1b3fd69f9ca3ea89fd236a231bd | TypeScript | mamunhpath/leetcode | /src/factorial-trailing-zeroes/pro.ts | 2.921875 | 3 | // HELP:
export function trailingZeroes(n: number) {
let res = 0
let f = 1
while (f * 5 <= n) {
f *= 5
res += parseInt(n / f)
}
return res
}
|
18a9e6e2cd0ddb6704352873aba5f2a1108b2f0f | TypeScript | Swrve/swrve-smarttv-sdk | /SwrveSDK/src/utils/platforms/IPlatform.ts | 2.671875 | 3 | import { IKeyMapping } from "./IKeymapping";
import { IAsset } from "./IAsset";
export interface IPlatformName {
readonly name: string;
readonly variation: string;
}
export type DevicePropertyName = "language" | "countryCode" | "timezone" | "firmware" | "deviceHeight" | "deviceWidth";
export type NetworkStatus = number;
export type NetworkListener = (status: NetworkStatus) => void;
export type NetworkMonitorHandle = webOSDev.WebOSSubscriptionHandle | number | [() => void, () => void];
export const NETWORK_DISCONNECTED = 0;
export const NETWORK_CONNECTED = 1;
export interface IPlatform {
readonly firmware: string;
readonly deviceID: string;
readonly model: string;
readonly os: string;
readonly osVersion: string;
readonly language: string;
readonly timezone: string;
readonly countryCode: string;
readonly region: string;
readonly screenDPI: number;
readonly screenHeight: number;
readonly screenWidth: number;
readonly appStore: string;
[key: string]: any; //this is here simply to enable a test
/**
* Get the platform synchronous storage, usually browser localStorage.
*
* Custom implementations should return an object that conforms to the
* Storage API.
*
* See: https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
*/
synchronousStorage: Storage | null;
/**
* Initialize the platform, should be called after DOM is rendered.
* @param callback to be called once initialization is complete
*/
init(deviceProperties: ReadonlyArray<DevicePropertyName>): Promise<void>;
/**
* Platform name.
*/
name(): IPlatformName;
/**
* True if this platform needs a proxy for CORS requests.
*/
getNeedsProxy(): boolean;
/**
* True if this platform supports a magic wand.
*/
getSupportsMagicWandNatively(): boolean;
/**
* Disable the platform screen saver.
*/
disableScreenSaver(): void;
/**
* Enable the platform screen saver.
*/
enableScreenSaver(): void;
/**
* Exit the application.
*
* @param toMenu - True if the application should exit to menu, false if
* it should exit to TV.
*/
exit(toMenu?: boolean): void;
/**
* Get device browser version.
*/
getDeviceBrowserVersion(): string | null;
supportsHDR(): boolean;
getKeymapping(): IKeyMapping;
downloadAssets(assets: ReadonlyArray<IAsset>): Promise<void>;
openLink(link: string): void;
monitorNetwork(networkListener: NetworkListener): NetworkListener;
stopMonitoringNetwork(networkListener: NetworkListener): void;
}
|
69db220bb6d6b407325a6705a85f2fbcc8884e32 | TypeScript | yusukebe/ogpParser | /src/test/e2e.spec.ts | 2.515625 | 3 | import parser, { OgpParserResult } from '../main'
import fs from 'fs'
import path from 'path'
import nock from 'nock';
const html = fs.readFileSync(path.join(__dirname, 'fixture/demo.html'))
const htmlOembed = fs.readFileSync(path.join(__dirname, 'fixture/demo_oembed.html'))
const htmlOembedXml = fs.readFileSync(path.join(__dirname, 'fixture/demo_oembed_xml.html'))
const oembedJson = fs.readFileSync(path.join(__dirname, 'fixture/oembed.json'))
const oembedXml = fs.readFileSync(path.join(__dirname, 'fixture/oembed.xml'))
describe('end 2 end test', () => {
beforeEach(() => {
nock('http://example.com').get('/').reply(200, html);
nock('https://example.com').get('/').reply(200, html);
nock('https://example.com').get('/oembed').reply(200, htmlOembed);
nock('https://example.com').get('/oembed_xml').reply(200, htmlOembedXml);
nock('https://oembed.example.com').get('/jsondata').reply(200, oembedJson);
nock('https://oembed.example.com').get('/xmldata').reply(200, oembedXml);
nock('https://notfound.example.com').get('/').reply(404);
nock('https://abc.example.com').get('/').replyWithError('request error')
})
afterEach(() => {
nock.cleanAll()
})
it ('standard http request', async () => {
const data = await parser('http://example.com')
expect(Object.keys(data))
.toEqual(expect.arrayContaining([ 'title', 'seo', 'ogp' ]))
expect(Object.keys(data)).not.toContain('oembed')
})
it ('standard https request', async () => {
const data = await parser('https://example.com')
expect(Object.keys(data))
.toEqual(expect.arrayContaining([ 'title', 'seo', 'ogp' ]))
expect(Object.keys(data)).not.toContain('oembed')
})
it ('standard https request (including json oembed)', async () => {
const data = await parser('https://example.com/oembed')
expect(Object.keys(data))
.toEqual(expect.arrayContaining([ 'title', 'seo', 'ogp', 'oembed' ]))
})
it ('standard https request (including xml oembed)', async () => {
const data = await parser('https://example.com/oembed_xml')
expect(Object.keys(data))
.toEqual(expect.arrayContaining([ 'title', 'seo', 'ogp', 'oembed' ]))
})
it ('should not contain oembed if call with skipOembed', async () => {
const data = await parser('https://example.com/oembed', { skipOembed: true })
expect(Object.keys(data))
.toEqual(expect.arrayContaining([ 'title', 'seo', 'ogp' ]))
expect(Object.keys(data)).not.toContain('oembed')
})
it ('[irregular case] 404 not found', async () => {
const promise = parser('https://notfound.example.com')
expect(promise).rejects.toThrow()
})
it ('[irregular case] request failed', async () => {
const promise = parser('https://abc.example.com')
expect(promise).rejects.toThrow()
})
})
|
443514c19918e5281e05872213bcf8187db36554 | TypeScript | cvimbert/phaser-test | /src/app/phaser/bones/bone-node.class.ts | 2.84375 | 3 | import { ObjectContainer } from './object-container.class';
export class BoneNode extends ObjectContainer {
//rotation: number = 0;
parentNode: BoneNode;
childrenObjects: ObjectContainer[] = [];
childrenObjectsById: { [key: string]: ObjectContainer } = {};
childrenNodes: ObjectContainer[] = [];
childrenNodesById: { [key: string]: ObjectContainer } = {};
constructor(
scene: Phaser.Scene,
x: number = 0,
y: number = 0,
id: string = ""
) {
super(scene, id, x, y);
}
render() {
super.render();
this.childrenObjects.forEach(obj => {
obj.render();
});
this.childrenNodes.forEach(obj => {
obj.render();
});
}
addChild(child: Phaser.GameObjects.Sprite, id?: string): ObjectContainer {
let container = new ObjectContainer(this.scene, id, child.x, child.y, child);
container.parentContainer = this;
this.childrenObjects.push(container);
if (id) {
this.childrenObjectsById[id] = container;
}
return container;
}
addChildNode(child: BoneNode, id?: string) {
this.childrenNodes.push(child);
child.parentContainer = this;
if (id) {
this.childrenNodesById[id] = child;
}
// child.parentNode = this;
}
removeChild(child: Phaser.GameObjects.Sprite) {
// à faire
/*let index = this.childrenObjects.indexOf(child);
if (index !== -1) {
this.childrenObjects.splice(index, 1);
}*/
}
} |
d74e30e1a6cdb3b7c63ff3e9e6f0cee918a757a7 | TypeScript | pallad-ts/config | /packages/main/src/Providers/EnvProvider.ts | 2.640625 | 3 | import {Provider} from "../Provider";
import {ValueNotAvailable} from '../ValueNotAvailable';
import {fromNullable, just, none} from "@sweet-monads/maybe";
import {left, right} from "@sweet-monads/either";
export class EnvProvider extends Provider<string> {
constructor(private key: string,
private envs: typeof process['env'] = process.env) {
super();
}
getValue(): Provider.Value<string> {
const value = fromNullable(this.envs[this.key])
.chain(value => value === '' ? none() : just(value));
return value.isNone() ? left(new ValueNotAvailable('ENV: ' + this.key)) : right(value.value);
}
}
|
4c6ff6cbd8b9b708acde9d2b3965c26f32e65e58 | TypeScript | green-fox-academy/JafariMahdi | /3-week/4-day/power.ts | 3.328125 | 3 | 'use strict';
function powerIt(baseNumber, power) {
if (power <= 1) {
return baseNumber;
} else {
return baseNumber * powerIt(baseNumber, power - 1)
}
}
console.log(powerIt(2, 9)); |
6f1f0eb5776f3237604a24c1c8b19da7cd77988c | TypeScript | MarinaSachse/Rawmate | /app/src/js/languageHelper.ts | 2.75 | 3 | import Strings from "./strings";
export class LanguageHelperBasic {
_activeLanguage = "de" ;
_strings: {
[propsName:string]: { [propsName: string]: string }
};
constructor(strings: {
[propsName:string]: { [propsName: string]: string }
}) {
this._strings = strings
}
getString = (name: string): string => {
return this._strings[this._activeLanguage] ? this._strings[this._activeLanguage][name] : this._strings["de"][name];
};
setLanguage = (language: string) => {
this._activeLanguage = language
}
}
const LanguageHelper = new LanguageHelperBasic(Strings);
export default LanguageHelper |
976fd3ea7b4ee11157c1c916fafebb731b1e8d9b | TypeScript | dhruv-99/SwabhavRef | /NodeJS/Typescript/CustomerTest.ts | 2.609375 | 3 | import {Customer , Address} from './Customer'
let c = new Customer(1 , "Dhruv", "Ballikar");
console.log(c.ID);
console.log(c.FullName);
let a = new Address(102, "Sheetal nagar", "Mira Road");
console.log(a.Address); |
2fa4ef58cff45f390c7359eabf75e32b905ef092 | TypeScript | timotej-orcic/SBZ-2018-Frontend | /sbz-app/src/app/models/display-file.ts | 2.78125 | 3 | export class DisplayFile {
id: number;
name: string;
type: string;
base64: string;
src: string;
constructor(id: number, name: string, type: string, base64: string) {
this.id = id;
this.name = name;
this.type = type;
this.base64 = base64;
this.src = this.computeSrc(type, base64);
}
computeSrc(type: string, base64: string) {
return 'data:' + type + ';base64,' + base64;
}
}
|
ce032f3849ca2112a3af5337fb661bc70ed57cf4 | TypeScript | gabrielnavas/todo_backend | /src/infra/db/postgresql/repositories/user-repository.ts | 2.515625 | 3 | import {
FindOneUserByEmailRepository,
FindOneUserByIdAndTokenRepository,
InsertOneUserRepository
} from '@/data/interfaces/'
import { PGHelper } from '@/infra/db/postgresql/helpers/pg-helper'
export class UserPostgreSQLRepository
implements
InsertOneUserRepository,
FindOneUserByEmailRepository,
FindOneUserByIdAndTokenRepository {
async insertOne (params: InsertOneUserRepository.Params):
Promise<InsertOneUserRepository.Result> {
const sql = `
INSERT INTO public."user" (name, email, password)
VALUES ($1, $2, $3)
RETURNING id, name, email, password
`
const userMRepository = await PGHelper
.getPool()
.query(sql, [params.name, params.email, params.password])
return userMRepository.rows[0]
}
async findOneByEmail (email: FindOneUserByEmailRepository.Params):
Promise<FindOneUserByEmailRepository.Result> {
const sql = `
SELECT id, name, email, password
FROM public."user"
WHERE email = $1
`
const userMRepository = await PGHelper
.getPool()
.query(sql, [email])
return userMRepository.rowCount > 0 ? userMRepository.rows[0] : null
}
async findOneByIdAndToken (params: FindOneUserByIdAndTokenRepository.Params):
Promise<FindOneUserByIdAndTokenRepository.Result> {
const { idUser, token } = params
const sql = `
SELECT
public."user".id as id, name, email, password
FROM
public."user",
public."user_token_access"
WHERE
public."user".id = public."user_token_access".id_user and
public."user".id = $1 and
token = $2 and
invalid_at is null
`
const userMRepository = await PGHelper
.getPool()
.query(sql, [idUser, token])
if (userMRepository.rowCount === 0) return
return {
id: userMRepository.rows[0].id,
name: userMRepository.rows[0].name,
email: userMRepository.rows[0].email,
password: userMRepository.rows[0].password
}
}
}
|
e74fae2f964ebb43621c6247aaa165aa562f139e | TypeScript | SmartterHealth/healthcare-bots | /src/bots/icd2/commands/search-codes/SearchCodesCommandHandler.ts | 2.6875 | 3 | import { TurnContext } from 'botbuilder';
import * as sql from 'mssql';
import 'reflect-metadata';
import { Assert } from '../../assert';
import log from '../../logger';
import settings from '../../settings';
import { Command, CommandHandlerBase, CommandStatus, ICommandResults, Traceable } from '../CommandHandlerBase';
import { IICD10Code, IICD10SearchResults } from '../IICD10Code';
import { SearchCodesAdaptiveCardHelper } from './SearchCodesAdaptiveCardHelper';
/**
* Simple flag that indicates whether this is the default command.
*/
const IS_DEFAULT = false;
@Command('Search Codes', ['search codes', 'sc', 'search code'], IS_DEFAULT)
export class SearchCodesCommandHandler extends CommandHandlerBase {
@Traceable()
public async execute(context: TurnContext, command: string, args: string): Promise<ICommandResults> {
args = (args === undefined || args === null) ? '' : args;
args = args.trim();
let results: IICD10SearchResults | null = null;
let cmdStatus: CommandStatus = CommandStatus.Success;
let cmdStatusText: string;
try {
const query = parseKeywords(args);
log(`Searching for codes using query '${query}'`);
results = await searchCodes(query);
log(`${results.codes.length} results returned for query '${query}'`);
if (results.codes.length > 0) {
// We got matches!
cmdStatus = CommandStatus.Success;
cmdStatusText = `Your search for **'${args}'** returned **${results.codes.length}** results. Click on a result for more details.`;
} else {
// No matches... :-/
cmdStatus = CommandStatus.FailNoError;
cmdStatusText = `Your search for **'${args}'** returned **${results.codes.length}** results. Please try again.`;
}
} catch (err) {
console.log(err);
cmdStatus = CommandStatus.Error;
cmdStatusText = err.toString();
}
const card = new SearchCodesAdaptiveCardHelper(context);
card.args = args;
card.headerTitle = `${settings.bot.displayName} -> ${this.displayName} -> ${args}`;
// Hide error messages with generic message.
card.headerDescription = (cmdStatus === CommandStatus.Error) ? `An error has occured. Please contact your administrator.` : cmdStatusText;
card.dataSource = results;
// await context.sendActivity('Test');
await context.sendActivity({
attachments: [card.render()],
});
return { status: cmdStatus, message: cmdStatusText};
}
}
/**
* Parses the keywords into a SQL fulltext WHERE clause.
* @param keywords The keywords to parse. Each keyword is joined by the SQL 'AND' operator. Phrases are identified by quotes.
*/
function parseKeywords(keywords: string): string {
Assert.isNotNull<String>(keywords, String);
const regex = /("(.*)")|[^\W\d]+[\u00C0-\u017Fa-zA-Z'](\w|[-'](?=\w))*("(.*)")|[^\W\d]+[\u00C0-\u017Fa-zA-Z'](\w|[-'](?=\w))*/gi;
const tokens = keywords.match(regex);
if (tokens != null) {
return tokens.join(' AND ');
}
return '';
}
/**
* Calls the stored procedure that searches for ICD10 codes.
* @param query The SQL fulltext WHERE clause.
*/
async function searchCodes(query: string): Promise<IICD10SearchResults> {
Assert.isNotNull<string>(query, String);
const codes: IICD10Code[] = [];
const results: IICD10SearchResults = { codes: (codes) };
const pool = await sql.connect(settings.db);
try {
const dbresults = await pool.request()
.input('keywords', sql.VarChar(150), query)
.input('maxrows', sql.Int, settings.searchCodes.maxRows)
.execute('SEARCH_CODES');
results.codes = dbresults.recordset as IICD10Code[];
} finally {
sql.close();
}
return results;
}
|
fd17e6a9fecf420b889a3a0deb4ca4923ce9bbdd | TypeScript | indraraj26/TypeORMCRUD | /src/helper/ResponseFormat.ts | 2.65625 | 3 | var response_format = {
success: '',
status: '',
data: [],
error: []
};
export function extractErrorMessages(error) {
return error.map(a => a.msg);
}
export function setResponse(status = 404, error = null, data = null) {
if (error) {
return {
...response_format,
status,
error: status === 422 ? extractErrorMessages(error) : error,
data: [],
success: false
};
} else {
return {
...response_format,
status,
data,
success: true
};
}
}
|
2f2ea0bf87a7d633695bed7d1f4a377741f3dd2d | TypeScript | thangnt294/ttkt-deploy | /src/middleware/member-leave-team-validation-middleware.ts | 2.640625 | 3 | import { NextFunction, Request, Response } from 'express';
import { getCurrentUserId } from '../utils/RequestUtils';
import TeamService from '../domain/team/service/team-service';
import Team, { TeamDocument } from '../domain/team/Team';
import {getVal, isEqual} from '../utils/ObjectUtils';
import ApplicationError from '../utils/errors/application-error';
import { ReturnMessage } from '../utils/constant/return-message';
import { HttpStatus } from '../utils/constant/http-status';
import {MemberTeamRole} from "../utils/constant/MemberTeamRole";
class MemberLeaveValidationMiddleware {
public throwIfInvalidRequest = async (req: Request, res: Response, next: NextFunction) => {
const reqMemberId: string = getCurrentUserId(req);
const reqTeamId: string = getVal(req.query, '', 'teamId');
const team: TeamDocument = await Team.findById(reqTeamId);
const isTeamOwner: boolean = this.checkIfIsTeamOwner(team, reqMemberId);
if (isTeamOwner) {
return next(new ApplicationError(ReturnMessage.CANNOT_LEAVE_OWNER, HttpStatus.BAD_REQUEST));
}
return next();
}
public checkIfIsTeamOwner = (team: TeamDocument, reqMemberId: string) => {
return team.members.some(member => isEqual(member.memberId.toString(), reqMemberId) && isEqual(member.role, MemberTeamRole.OWNER));
}
}
export default new MemberLeaveValidationMiddleware();
|
02d4ce01ddadeea6d81d216fde8ba4f3b105eae9 | TypeScript | bubkoo/number-abbreviate | /src/index.ts | 3.515625 | 4 | import { round, commatize } from './utils'
export type UnitsType = { [key: string]: number }
export type UnitItem = { unit: string; value: number }
export type CommatizeOptions = {
/**
* Length of each divided parts. Default `3`.
*/
division?: number
/**
* Separator of each divided parts. Default `,`.
*/
separator?: string
}
export type AbbreviateOptions = {
/**
* Specify the precision of decimal part.
*/
precision?: number
/**
* Specify how to commatize the result.
*/
commatize?: boolean | CommatizeOptions
}
export class NumberAbbreviate {
units: UnitItem[]
constructor(units: UnitsType = {}) {
this.units = Object.keys(units)
.map((unit) => ({ unit, value: units[unit] }))
.sort((a, b) => a.value - b.value)
}
abbreviate(num: number, options: AbbreviateOptions = {}) {
const { precision = 2, commatize: commaOptions } = options
const negative = num < 0
const raw = Math.abs(num)
for (let i = this.units.length - 1; i >= 0; i -= 1) {
const unit = this.units[i].unit
const size = this.units[i].value
if (raw >= size) {
const result = round(raw / size, precision)
return (
(negative ? '-' : '') +
(commaOptions
? commatize(result, commaOptions as CommatizeOptions)
: result) +
unit
)
}
}
return `${num}`
}
}
const numabbr = new NumberAbbreviate({
K: 1000,
M: 1000000,
B: 1000000000,
T: 1000000000000,
})
export default function (num: number, options?: AbbreviateOptions) {
return numabbr.abbreviate(num, options)
}
|
cf406df9b3197d727578f25a9472a2ba4cd3f4cb | TypeScript | uwinkler/prof-frisby | /src/either/Left.ts | 3.296875 | 3 | export class Left<T> {
constructor(protected x: T) {}
static of<T>(x: T) {
return new Left(x);
}
map(_func: Function) {
return Left.of(this.x);
}
chain(_func: Function) {
return Left.of(this.x);
}
fold(error: Function, _result: Function) {
return error(this.x);
}
}
|
5380644ffdc25ef5586e7a61b7899f3afd574e8d | TypeScript | Obfuscators-2021/kliveide | /packages/klive-emu/src/renderer/ide/commands/NewProjectCommand.ts | 2.84375 | 3 | import {
CommandBase,
CommandContext,
CommandResult,
TraceMessage,
TraceMessageType,
} from "../tool-area/CommandService";
import { Token, TokenType } from "../../../shared/command-parser/token-stream";
import { ideToEmuMessenger } from "../IdeToEmuMessenger";
import {
CreateKliveProjectResponse,
GetRegisteredMachinesResponse,
} from "../../../shared/messaging/message-types";
/**
* Creates a new Klive project
*/
export class NewProjectCommand extends CommandBase {
readonly id = "new-project";
readonly usage =
"Usage: new-project <machine-id> [<root-folder>] <project-name>";
// --- Command argument placeholders
private _machineTypeArg: string;
private _rootFolderArg: string | null;
private _projectFolderArg: string;
/**
* Validates the input arguments
* @param args Arguments to validate
* @returns A list of issues
*/
async validateArgs(args: Token[]): Promise<TraceMessage | TraceMessage[]> {
// --- Check argument number
if (args.length !== 2 && args.length !== 3) {
return {
type: TraceMessageType.Error,
message: "Invalid number of arguments.",
};
}
// --- Check virtual machine type
const machines = (
await ideToEmuMessenger.sendMessage<GetRegisteredMachinesResponse>({
type: "GetRegisteredMachines",
})
).machines;
this._machineTypeArg = args[0].text;
if (!machines.includes(this._machineTypeArg)) {
return {
type: TraceMessageType.Error,
message: `Cannot find machine with ID '${this._machineTypeArg}'. Available machine types are: ${machines}`,
};
}
// --- Check 2nd argument
this._rootFolderArg = args[1].text;
console.log(args[1]);
if (
args[1].type !== TokenType.Identifier &&
args[1].type !== TokenType.Path
) {
return {
type: TraceMessageType.Error,
message: `Invalid argument: ${this._rootFolderArg}`,
};
}
// --- Check 3rd argument
if (args.length < 3) {
// --- Path is the folder
this._projectFolderArg = this._rootFolderArg;
this._rootFolderArg = null;
} else {
this._projectFolderArg = args[2].text;
if (
args[2].type !== TokenType.Identifier &&
args[2].type !== TokenType.Path
) {
return {
type: TraceMessageType.Error,
message: `Invalid argument: ${this._projectFolderArg}`,
};
}
}
return [];
}
/**
* Executes the command within the specified context
*/
async doExecute(): Promise<CommandResult> {
const operation =
await ideToEmuMessenger.sendMessage<CreateKliveProjectResponse>({
type: "CreateKliveProject",
machineType: this._machineTypeArg,
rootFolder: this._rootFolderArg,
projectFolder: this._projectFolderArg,
});
return {
success: !operation.error,
finalMessage: operation.error
? operation.error
: `Klive project '${operation.targetFolder}' successfully created.`,
};
}
}
|
edbd879b018dd08348d6eae1b109d6ada3192269 | TypeScript | urantialife/react-modal-hook | /src/useModal.ts | 2.84375 | 3 | import { useContext, useEffect, useState, useCallback, useMemo } from "react";
import { ModalContext, ModalType } from "./ModalContext";
/**
* Callback types provided for descriptive type-hints
*/
type ShowModal = () => void;
type HideModal = () => void;
/**
* Utility function to generate unique number per component instance
*/
const generateModalKey = (() => {
let count = 0;
return () => `${++count}`;
})();
/**
* React hook for showing modal windows
*/
export const useModal = (
component: ModalType,
inputs: any[] = []
): [ShowModal, HideModal] => {
const key = useMemo(generateModalKey, []);
const modal = useMemo(() => component, inputs);
const context = useContext(ModalContext);
const [isShown, setShown] = useState<boolean>(false);
const showModal = useCallback(() => setShown(true), []);
const hideModal = useCallback(() => setShown(false), []);
useEffect(
() => {
if (isShown) {
context.showModal(key, modal);
} else {
context.hideModal(key);
}
// Hide modal when parent component unmounts
return () => context.hideModal(key);
},
[modal, isShown]
);
return [showModal, hideModal];
};
|
f0277aabf8896611a8295a23985ff81649aac11f | TypeScript | DSigmund/asm | /src/libs/database.ts | 2.625 | 3 | import moment from 'moment'
const fs = require('fs')
const path = require('path')
const { promisify } = require('util')
class Database {
private _path: string
private _channel: any
private _posts: any
private _writeFile: any
private _readFile: any
constructor (databasePath: string) {
// tslint:disable-next-line: tsr-detect-non-literal-fs-filename
this._writeFile = promisify(fs.writeFile)
// tslint:disable-next-line: tsr-detect-non-literal-fs-filename
this._readFile = promisify(fs.readFile)
this._path = databasePath
}
public async LoadDatabase (): Promise<void> {
this._channel = await this._readFile(path.join(this._path, 'channel.json'), 'utf8')
this._channel = JSON.parse(this._channel)
this._posts = await this._readFile(path.join(this._path, 'posts.json'), 'utf8')
this._posts = JSON.parse(this._posts)
}
public async SaveDatabase (): Promise<void> {
await this._writeFile(path.join(this._path, 'channel.json'), JSON.stringify(this._channel), 'utf8')
await this._writeFile(path.join(this._path, 'posts.json'), JSON.stringify(this._posts), 'utf8')
}
public getPosts (channel: string): any {
return this._posts[channel]
}
public async InsertChannelInfo (channel: string, data: any, main: string): Promise<void> {
let yearKW: any = moment().format('YYYY-WW')
let now: any = moment().format('YYYY-MM-DD')
this.createChannelIfNeeded(channel)
this._channel[channel][yearKW] = {
timestamp: now,
data: data,
main: main
}
}
private createChannelIfNeeded (channel: string): void {
if (!this._channel[channel]) this._channel[channel] = {}
if (!this._posts[channel]) this._posts[channel] = {}
}
public async InsertPost (channel: string, id: string, create: string, title: string, link: string, data: any, main: string): Promise<void> {
let yearKW: any = moment().format('YYYY-WW')
let now: any = moment().format('YYYY-MM-DD')
this.createChannelIfNeeded(channel)
if (!this._posts[channel][id]) {
this._posts[channel][id] = {
id: id,
create: create,
title: title,
link: link,
data: {}
}
}
this._posts[channel][id].data[yearKW] = {
timestamp: now,
data: data,
main: main
}
}
private postsToArray (channel: string): any {
let postsArray = []
for (const post in this._posts[channel]) {
if (this._posts[channel].hasOwnProperty(post)) {
const element = this._posts[channel][post]
postsArray.push(element)
}
}
return postsArray
}
public getPostsInWeek (channel: string, time: moment.Moment): any {
let posts = []
let postsArray = this.postsToArray(channel)
for (let index = 0; index < postsArray.length; index++) {
const post = postsArray[index]
if (moment(post.create).isSame(time, 'week')) {
posts.push(post)
}
}
return posts
}
public getTopPosts (channel: string, upTo: moment.Moment): any {
let posts = this._posts[channel]
let main = posts[Object.keys(posts)[0]].data[upTo.format('YYYY-WW')].main
let postsArray = this.postsToArray(channel)
postsArray.sort(function (a: any, b: any) {
let valA = a.data[upTo.format('YYYY-WW')].data[main]
let valB = b.data[upTo.format('YYYY-WW')].data[main]
if (valA < valB) return -1
if (valA > valB) return 1
return 0
})
return postsArray.slice(0, 10)
}
public GetChannelInfo (channel: string, from?: Date, to?: Date): Promise<any> {
if (!from && !to) {
return this._channel[channel]
} else {
throw new Error('Method not fully implemented.')
}
}
public GetYearData (year: any): any {
throw new Error('Method not implemented.')
}
public GetMonthData (year: any, month: any): any {
throw new Error('Method not implemented.')
}
public GetWeekData (moment: moment.Moment): any {
let yearKW: any = moment.format('YYYY-WW')
let lastyearKW: any = moment.clone().subtract(1, 'week').format('YYYY-WW')
let data: any = {}
data.year = moment.format('YYYY')
data.kw = moment.format('WW')
data.creation = moment.format('DD.MM.YYYY')
data.title = 'Weekly :: ' + moment.format('YYYY / WW')
data.channels = {}
let self = this
Object.keys(self._channel).forEach(function (c) {
let channel = self._channel[c]
data.channels[c] = {
name: c,
now: channel[yearKW].data,
last: channel[lastyearKW].data,
diff: self.getdiff(channel[yearKW].data, channel[lastyearKW].data),
main: channel[yearKW].data.main,
posts: {
new: self.getPostsInWeek(c, moment),
top: self.getTopPosts(c, moment)
}
}
// TODO: get top 10 posts of all timer
})
return data
}
private getdiff (thisWeek: any, lastWeek: any): any {
let diff: any = {}
Object.keys(thisWeek).forEach(function (v) {
if (v !== 'main') {
diff[v] = thisWeek[v] - lastWeek[v]
}
})
return diff
}
}
export default Database
|
e4c01fd53dc89e44c31bfef1ecc8a5ceaf3805ac | TypeScript | wallaceturner/ravendb-nodejs-client | /src/Documents/Session/IDocumentQuery.ts | 2.75 | 3 | import { IDocumentQueryBaseSingle } from "./IDocumentQueryBaseSingle";
import { IEnumerableQuery } from "./IEnumerableQuery";
import { QueryResult } from "../Queries/QueryResult";
import { DocumentType } from "../DocumentAbstractions";
import { QueryData } from "../Queries/QueryData";
import { GroupBy } from "../Queries/GroupBy";
import { IDocumentQueryBase } from "./IDocumentQueryBase";
import { IGroupByDocumentQuery } from "./IGroupByDocumentQuery";
/**
* A query against a Raven index
*/
export interface IDocumentQuery<T extends object>
extends IDocumentQueryBase<T, IDocumentQuery<T>>,
IDocumentQueryBaseSingle<T>,
IEnumerableQuery<T> {
indexName;
/**
* Whether we should apply distinct operation to the query on the server side
* @return true if server should return distinct results
*/
isDistinct;
/**
* Returns the query result. Accessing this property for the first time will execute the query.
* @return query result
*/
getQueryResult(): Promise<QueryResult>;
/**
* Selects the specified fields directly from the index if the are stored.
* If the field is not stored in index, value
* will come from document directly.
* @param <TProjection> projection class
* @param projectionClass projection class
* @return Document query
*/
selectFields<TProjection extends object>(
property: string, projectionClass: DocumentType<TProjection>): IDocumentQuery<TProjection>;
selectFields<TProjection extends object>(
properties: string[], projectionClass: DocumentType<TProjection>): IDocumentQuery<TProjection>;
/**
* Selects the specified fields directly from the index if the are stored.
* If the field is not stored in index, value will come from document directly.
* @param <TProjection> projection class
* @param properties Fields to fetch
* @return Document query
*/
selectFields<TProjection extends object>(properties: string[]): IDocumentQuery<TProjection>;
selectFields<TProjection extends Object>(property: string): IDocumentQuery<TProjection>;
/**
* Selects the specified fields directly from the index if the are stored.
* If the field is not stored in index, value will come from document directly.
* @param <TProjection> projection class
* @param queryData Query data to use
* @param projectionClass projection class
* @return Document query
*/
selectFields<TProjection extends object>(
queryData: QueryData, projectionClass: DocumentType<T>): IDocumentQuery<TProjection>;
/**
* Changes the return type of the query
* @param <TResult> class of result
* @param resultClass class of result
* @return Document query
*/
ofType<TResult extends object>(resultClass: DocumentType<TResult>): IDocumentQuery<TResult>;
groupBy(fieldName: string, ...fieldNames: string[]): IGroupByDocumentQuery<T>;
groupBy(field: GroupBy, ...fields: GroupBy[]): IGroupByDocumentQuery<T>;
//TBD MoreLikeThis
//TBD AggregateBy
//TBD SuggestUsing
} |
53ac00f2fb266c52d9a9efa1d3137fa13317c975 | TypeScript | UTC503-cnam/AlexandreMoro | /S02/ex7.ts | 3.671875 | 4 |
class CloneMap{
private inputArray : number[] = new Array();
Double( e : number[] ): void {
for (let i in e) {
this.inputArray[i] = e[i] * 2;
}
}
Triple( e : number[] ):void {
for (let i in e) {
this.inputArray[i] = e[i]* 3;
}
}
Square( e: number[] ):void {
for (let i in e) {
this.inputArray[i] = Math.pow(e[i],2);
}
}
MapMaximize3( e: number[] ) :void {
for (let i in e) {
if (e[i] > 3 ) {
this.inputArray[i] = 3
}
else {
this.inputArray[i] = e[i];
}
}
}
}
let table:number[] = new Array(1, 5, 2, 4, 3);
let tableDouble = new CloneMap();
tableDouble.Double(table);
let tableTriple = new CloneMap();
tableTriple.Triple(table);
let tableSqare = new CloneMap();
tableSqare.Square(table);
let tableMax3 = new CloneMap();
tableMax3.MapMaximize3(table);
debugger
|
e17ddd2512598dbf4b7b1f818387956423892d30 | TypeScript | folio-org/ui-calendar | /src/typings/stripes/components/lib/Button/Button.d.ts | 2.828125 | 3 | import {
AriaAttributes,
ForwardRefExoticComponent,
MouseEventHandler,
PropsWithoutRef,
ReactNode,
RefAttributes,
} from 'react';
import { LinkProps } from 'react-router-dom';
import { RequireOneOrNone } from '../../util/typeUtils';
export interface ButtonBaseProps extends AriaAttributes {
/** Changes the (flexbox) alignment of the button */
align?: 'start' | 'center' | 'end';
/** Allows the anchor's default onClick */
allowAnchorClick?: boolean;
/** If this button should be automatically focused */
autoFocus?: boolean;
/** Remove the margin from the bottom */
bottomMargin0?: boolean;
/** Add a custom CSS class to the button */
buttonClass?: string;
/** Sets the style of the button */
buttonStyle?:
| 'default'
| 'primary'
| 'success'
| 'warning'
| 'danger'
| 'dropdownItem';
/** The button for the label */
children: ReactNode;
/** Forces the button to 100% width */
fullWidth?: boolean;
/** Remove the margin from the bottom */
marginBottom0?: boolean;
/** Handle an `onClick` event */
onClick?: MouseEventHandler<HTMLAnchorElement | HTMLButtonElement>;
/** Remove the padding from all sides */
paddingSide0?: boolean;
/** Adds a custom role to the button */
role?: JSX.IntrinsicElements['button']['role'];
}
// these are mutually exclusive (and can be entirely omitted, if needed)
export interface ButtonLinkProps {
/** Set the type of `<button>`. Incompatible with `href` and `to` */
type: JSX.IntrinsicElements['button']['type'];
/** Adds a link to the button, like a normal <a>. Incompatible with `type` and `to`. */
href: string;
/**
* Controls where the link should go, like for a `<Link>`.
* This prop is incompatible with `type` and `href`.
* @see https://github.com/remix-run/react-router/blob/master/docs/components/link.md
*/
to: LinkProps['to'];
}
export type ButtonProps = ButtonBaseProps &
RequireOneOrNone<ButtonLinkProps, 'type' | 'href' | 'to'> &
(JSX.IntrinsicElements['button'] | JSX.IntrinsicElements['a']);
/**
* Renders a given button
* @example
* <Button>Sample</Button>
*/
export const Button: ForwardRefExoticComponent<
PropsWithoutRef<ButtonProps> &
RefAttributes<HTMLAnchorElement | HTMLButtonElement>
>;
export default Button;
|
6b2756df17188ef37c3c1df9dd087edf8883bec1 | TypeScript | allmonday/react-pg | /src/page/class/index.ts | 2.71875 | 3 | import * as React from "react";
interface WelcomeProps {
name: string
}
class Welcome extends React.Component<WelcomeProps, undefined> {
render() {
return (React.DOM.h1("Hello" + this.props.name));
}
} |
cc5193f16f94cd5a918daecaa610d22608f15b30 | TypeScript | Surlix/REyeker | /REyeker-DataAnalyses/src/NeedlemanWunsch.ts | 3.25 | 3 | let str = [];
/**
* a function to return the minium value on the left, topleft, top of the current value, used for NW algorithm
*
* @param current_x the current x value in respect to the matrix
* @param current_y the current y value in respect to the matrix
* @param sequence_a the sequence a which is currently encoded in the matrix
* @param sequence_b the sequence b which is currently encoded in the matrix
* @param matrix the matrix which is used of DP of the NW algorithm
*/
function getMin(current_x, current_y, sequence_a, sequence_b, matrix) {
let topLeft = matrix[current_x - 1][current_y - 1];
let left = matrix[current_x - 1][current_y] + 1;
let top = matrix[current_x][current_y - 1] + 1;
if (!(sequence_b[current_x - 1] === sequence_a[current_y - 1])) topLeft++;
return Math.min(topLeft, left, top);
}
/**
* a function to get the result of the NW matrix DP
*
* @param solution where the solution will be stored
* @param sequence_a the sequence a which is currently encoded in the matrix
* @param sequence_b the sequence b which is currently encoded in the matrix
* @param matrix the matrix which is used of DP of the NW algorithm
* @param x the current value of the x backtrace
* @param y the current value of the y backtrace
*/
function backtrace(solution, sequence_a, sequence_b, matrix, x, y) {
if (x === 0 && y === 0) {
return;
}
if (x === 0) {
str.push("top")
solution.unshift({kind: "delete", data: sequence_b[y - 1]});
return backtrace(solution, sequence_a, sequence_b, matrix, x, --y);
}
if (y === 0) {
str.push("left")
solution.unshift({kind: "insert", data: sequence_a[x - 1]});
return backtrace(solution, sequence_a, sequence_b, matrix, --x, y);
}
if (matrix[y - 1][x - 1] <= matrix[y][x - 1] && matrix[y - 1][x - 1] <= matrix[y - 1][x]) {
if (matrix[y][x] === matrix[y - 1][x - 1]) {
str.push("keep")
solution.unshift({kind: "keep", data: sequence_a[x - 1]});
return backtrace(solution, sequence_a, sequence_b, matrix, --x, --y);
}
}
if (matrix[y][x - 1] <= matrix[y - 1][x]) {
str.push("left")
solution.unshift({kind: "insert", data: sequence_a[x - 1]});
return backtrace(solution, sequence_a, sequence_b, matrix, --x, y);
} else {
str.push("top");
solution.unshift({kind: "delete", data: sequence_b[y - 1]});
return backtrace(solution, sequence_a, sequence_b, matrix, x, --y);
}
}
/**
* returns a best fitting sequence of a and b
*
* @param sequence_a the first sequence to analyse
* @param sequence_b the first sequence to analyse
* @param sequence_b the first sequence to analyse
*/
export function NeedlemanWunsch(sequence_a, sequence_b) {
let matrix = [];
for (let j = 0; j <= sequence_b.length; j++) {
let tmp = [];
for (let i = 0; i <= sequence_a.length; i++) {
tmp.push(0)
}
matrix.push(tmp);
}
for (let j = 1; j <= sequence_b.length; j++) {
matrix[j][0] = j;
}
for (let i = 0; i <= sequence_a.length; i++) {
matrix[0][i] = i;
}
for (let j = 1; j <= sequence_b.length; j++) {
for (let i = 1; i <= sequence_a.length; i++) {
matrix[j][i] = getMin(j, i, sequence_a, sequence_b, matrix);
}
}
let solution = [];
str = [];
backtrace(solution, sequence_a, sequence_b, matrix, sequence_a.length, sequence_b.length);
return solution;
} |
33fab0c14e3157398bd96713284f3a8c5d0ebb2c | TypeScript | andyjia/leetcode-typescript | /solutions/subtree_of_another_tree.ts | 3.75 | 4 | import { BinaryTreeNode } from "../data_structures/binary_tree.ts";
// 572. Subtree of Another Tree
// https://leetcode.com/problems/subtree-of-another-tree/
export default function isSubtree<T = number>(
s: BinaryTreeNode<T> | null,
t: BinaryTreeNode<T> | null
): boolean {
return s === null
? s === t
: isSameTree(s, t) || isSubtree(s.left, t) || isSubtree(s.right, t);
}
function isSameTree<T>(
s: BinaryTreeNode<T> | null,
t: BinaryTreeNode<T> | null
): boolean {
if (s === null && t === null) return true;
if (s !== null && t !== null)
return (
s.val === t.val &&
isSameTree(s.left, t.left) &&
isSameTree(s.right, t.right)
);
return false;
}
|
c5d69bd5acaf1bfb76b897b94c7ad91a484640c6 | TypeScript | innovationdigitalbr/copy-image-clipboard | /src/index.ts | 2.875 | 3 | export async function getBlobFromImageSource(
imageSource: string,
): Promise<Blob> {
const response = await fetch(`${imageSource}`)
return await response.blob()
}
export function isJpegBlob(blob: Blob): boolean {
return blob.type.includes('jpeg')
}
export function isPngBlob(blob: Blob): boolean {
return blob.type.includes('png')
}
export async function createImageElement(
imageSource: string,
): Promise<HTMLImageElement> {
return new Promise(function (resolve, reject) {
const imageElement = document.createElement('img')
imageElement.crossOrigin = 'anonymous'
imageElement.src = imageSource
imageElement.onload = function (event) {
const target = event.target as HTMLImageElement
resolve(target)
}
imageElement.onabort = reject
imageElement.onerror = reject
})
}
export async function getBlobFromImageElement(
imageElement: HTMLImageElement,
): Promise<Blob> {
return new Promise(function (resolve, reject) {
const canvas = document.createElement('canvas')
const context = canvas.getContext('2d')
if (context) {
const { width, height } = imageElement
canvas.width = width
canvas.height = height
context.drawImage(imageElement, 0, 0, width, height)
canvas.toBlob(
function (blob) {
if (blob) resolve(blob)
else reject('Cannot get blob from image element')
},
'image/png',
1,
)
}
})
}
export async function convertBlobToPng(imageBlob: Blob): Promise<Blob> {
const imageSource = URL.createObjectURL(imageBlob)
const imageElement = await createImageElement(imageSource)
return await getBlobFromImageElement(imageElement)
}
export async function copyBlobToClipboard(blob: Blob): Promise<void> {
const items = { [blob.type]: blob } as unknown as Record<
string,
ClipboardItemData
>
const clipboardItem = new ClipboardItem(items)
await navigator.clipboard.write([clipboardItem])
}
export async function copyImageToClipboard(imageSource: string): Promise<Blob> {
const blob = await getBlobFromImageSource(imageSource)
if (isJpegBlob(blob)) {
const pngBlob = await convertBlobToPng(blob)
await copyBlobToClipboard(pngBlob)
return blob
} else if (isPngBlob(blob)) {
await copyBlobToClipboard(blob)
return blob
}
throw new Error('Cannot copy this type of image to clipboard')
}
export async function requestClipboardWritePermission(): Promise<boolean> {
if (!navigator?.permissions?.query) return false
const { state } = await navigator.permissions.query({
name: 'clipboard-write' as PermissionName,
})
return state === 'granted'
}
export function canCopyImagesToClipboard(): boolean {
const hasFetch = typeof fetch !== 'undefined'
const hasClipboardItem = typeof ClipboardItem !== 'undefined'
const hasNavigatorClipboardWriteFunction = !!navigator?.clipboard?.write
return hasFetch && hasClipboardItem && hasNavigatorClipboardWriteFunction
}
|
88d2f1ec261e6d6a1ea8c6a29fe506afb6fcdc7d | TypeScript | material-motion/indefinite-observable-js | /dist/IndefiniteObservable.d.ts | 2.828125 | 3 | /** @license
* Copyright 2016 - present The Material Motion Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import { Connect, Observable, ObserverOrNext, Subscription } from './types';
/**
* `Observable` is a standard interface that's useful for modeling multiple,
* asynchronous events.
*
* `IndefiniteObservable` is a minimalist implementation of a subset of the TC39
* Observable proposal. It is indefinite because it will never call `complete`
* or `error` on the provided observer.
*/
export declare class IndefiniteObservable<T> implements Observable<T> {
private _connect;
/**
* The provided function should receive an observer and connect that
* observer's `next` method to an event source (for instance,
* `element.addEventListener('click', observer.next)`).
*
* It must return a function that will disconnect the observer from the event
* source.
*/
constructor(connect: Connect<T>);
/**
* `subscribe` uses the function supplied to the constructor to connect an
* observer to an event source. Each observer is connected independently:
* each call to `subscribe` calls `connect` with the new observer.
*
* To disconnect the observer from the event source, call `unsubscribe` on the
* returned subscription.
*
* Note: `subscribe` accepts either a function or an object with a
* next method.
*/
subscribe(observerOrNext: ObserverOrNext<T>): Subscription;
}
export default IndefiniteObservable;
|
004055342a196ceeba05c892901d878b1aece78e | TypeScript | thundercore/ThunderStorage | /backend/src/util/index.ts | 2.75 | 3 | export function isError(o): o is Error {
return (
o instanceof Error ||
(typeof o.stack === 'string' && typeof o.message === 'string')
)
}
|
872b3b3996675bc9bc707d0faf1e663284fa9599 | TypeScript | one-piece-team1/one-piece-trip | /src/interfaces/response.interface.ts | 2.765625 | 3 | export interface ResponseBase {
statusCode: number;
status: 'error' | 'success';
message: any;
[futureKey: string]: any;
}
export interface SignInResponse extends ResponseBase {
accessToken?: string;
}
type Status = 'error' | 'success';
export interface IResponseBase<T> {
status: Status;
statusCode: number;
message?: T;
}
export interface IPagingResponse {
take: number;
skip: number;
count: number;
}
export interface IPostPagingResponseBase<T> extends IPagingResponse {
posts: T;
}
export interface ITripPagingResponseBase<T> extends IPagingResponse {
trips: T;
}
|
0acb96a28b029d4a717369f31fa7b216f957ec63 | TypeScript | iopa-io/iopa-botadapter | /packages/iopa-botadapter-schema-auth/src/httpAuthCredentials.ts | 2.53125 | 3 | import * as url from 'url'
import * as AuthenticationConstants from './authenticationConstants'
import {
HttpAuthAppCredentials as IHttpAuthAppCredentials,
HttpRequest,
HttpResponse,
} from 'iopa-botadapter-types'
/**
* HttpAuthAppCredentials auth implementation and cache
*/
export class HttpAuthAppCredentials implements IHttpAuthAppCredentials {
private static readonly trustedHostNames: Map<string, Date> = new Map<
string,
Date
>([
['state.botframework.com', new Date(8640000000000000)], // Date.MAX_VALUE,
['api.botframework.com', new Date(8640000000000000)], // Date.MAX_VALUE,
['token.botframework.com', new Date(8640000000000000)], // Date.MAX_VALUE,
['state.botframework.azure.us', new Date(8640000000000000)], // Date.MAX_VALUE,
['api.botframework.azure.us', new Date(8640000000000000)], // Date.MAX_VALUE,
['token.botframework.azure.us', new Date(8640000000000000)], // Date.MAX_VALUE,
['smba.trafficmanager.net', new Date(8640000000000000)], // Date.MAX_VALUE,
])
private static readonly cache: Map<string, OAuthResponse> = new Map<
string,
OAuthResponse
>()
public appPassword: string
public appId: string
public oAuthEndpoint: string
public oAuthScope: string =
AuthenticationConstants.ToChannelFromBotOAuthScope
public readonly tokenCacheKey: string
private refreshingToken: Promise<Response> | null = null
constructor(
appId: string,
appPassword: string,
channelAuthTenant?: string
) {
this.appId = appId
this.appPassword = appPassword
const tenant =
channelAuthTenant && channelAuthTenant.length > 0
? channelAuthTenant
: AuthenticationConstants.DefaultChannelAuthTenant
this.oAuthEndpoint =
AuthenticationConstants.ToChannelFromBotLoginUrlPrefix +
tenant +
AuthenticationConstants.ToChannelFromBotTokenEndpointPath
this.tokenCacheKey = `${appId}-cache`
}
/**
* Adds the host of service url to trusted hosts.
* If expiration time is not provided, the expiration date will be current (utc) date + 1 day.
* @param {string} serviceUrl The service url
* @param {Date} expiration? The expiration date after which this service url is not trusted anymore
*/
public static trustServiceUrl(serviceUrl: string, expiration?: Date): void {
if (!expiration) {
expiration = new Date(Date.now() + 86400000) // 1 day
}
const uri: url.Url = url.parse(serviceUrl)
if (uri.host) {
HttpAuthAppCredentials.trustedHostNames.set(uri.host, expiration)
}
}
/**
* Checks if the service url is for a trusted host or not.
* @param {string} serviceUrl The service url
* @returns {boolean} True if the host of the service url is trusted; False otherwise.
*/
public static isTrustedServiceUrl(serviceUrl: string): boolean {
try {
const uri: url.Url = url.parse(serviceUrl)
if (uri.host) {
return HttpAuthAppCredentials.isTrustedUrl(uri.host)
}
} catch (e) {
// tslint:disable-next-line:no-console
console.error(e)
}
return false
}
private static isTrustedUrl(uri: string): boolean {
const expiration: Date = HttpAuthAppCredentials.trustedHostNames.get(
uri
)
if (expiration) {
// check if the trusted service url is still valid
return expiration.getTime() > Date.now() - 300000 // 5 Minutes
}
console.log(`Untrusted uri ${uri}`)
return false
}
public async signRequest(
url: string,
request: Partial<HttpRequest>
): Promise<void> {
if (this.shouldSetToken(url)) {
const token: string = await this.getToken()
if (request.headers.set) {
request.headers.set('authorization', `Bearer ${token}`)
} else {
request.headers['authorization'] = `Bearer ${token}`
}
}
}
public async getToken(forceRefresh: boolean = false): Promise<string> {
if (!forceRefresh) {
// check the global cache for the token. If we have it, and it's valid, we're done.
const oAuthToken: OAuthResponse = HttpAuthAppCredentials.cache.get(
this.tokenCacheKey
)
if (oAuthToken) {
// we have the token. Is it valid?
if (oAuthToken.expiration_time > Date.now()) {
return oAuthToken.access_token
}
}
}
// We need to refresh the token, because:
// 1. The user requested it via the forceRefresh parameter
// 2. We have it, but it's expired
// 3. We don't have it in the cache.
const res: HttpResponse = await this.refreshToken()
this.refreshingToken = null
let oauthResponse: OAuthResponse
if (res && res.status == 200) {
// `res` is equalivent to the results from the cached promise `this.refreshingToken`.
// Because the promise has been cached, we need to see if the body has been read.
// If the body has not been read yet, we can call res.json() to get the access_token.
// If the body has been read, the OAuthResponse for that call should have been cached already,
// in which case we can return the cache from there. If a cached OAuthResponse does not exist,
// call getToken() again to retry the authentication process.
if (!HttpAuthAppCredentials.cache.has(this.tokenCacheKey)) {
if (res.bodyUsed) {
// ** not in cache but not used so likely just too close
// so come round again
return await this.getToken()
}
oauthResponse = await res.json()
// Subtract 5 minutes from expires_in so they'll we'll get a
// new token before it expires.
oauthResponse.expiration_time =
Date.now() + oauthResponse.expires_in * 1000 - 300000
HttpAuthAppCredentials.cache.set(
this.tokenCacheKey,
oauthResponse
)
return oauthResponse.access_token
} else {
const oAuthToken: OAuthResponse = HttpAuthAppCredentials.cache.get(
this.tokenCacheKey
)
if (oAuthToken) {
return oAuthToken.access_token
} else {
return await this.getToken()
}
}
} else {
throw new Error(res.statusText)
}
}
private async refreshToken(): Promise<HttpResponse> {
if (!this.refreshingToken) {
const params = new url.URLSearchParams() as URLSearchParams
params.append('grant_type', 'client_credentials')
params.append('client_id', this.appId)
params.append('client_secret', this.appPassword)
params.append('scope', this.oAuthScope)
this.refreshingToken = fetch(this.oAuthEndpoint, {
method: 'POST',
headers: [
[
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8',
],
],
body: params,
})
}
return (this.refreshingToken as unknown) as HttpResponse
}
private shouldSetToken(url: string): boolean {
return HttpAuthAppCredentials.isTrustedServiceUrl(url)
}
}
/**
* Member variables to this class follow the RFC Naming conventions, rather than C# naming conventions.
*/
interface OAuthResponse {
token_type: string
expires_in: number
access_token: string
expiration_time: number
}
|
833815641cd99eef294fe33d49f454f40333e2a3 | TypeScript | m-mittal/Ang5 | /ang5app1/my-app/src/app/ng-book-reedit-exercise/LinkItem-class.ts | 2.59375 | 3 | export class linkItemClass{
id: number;
voteCount: number;
Title: String;
Link: String;
voteUp(obj:linkItemClass){
this.voteCount = this.voteCount + 1;
}
voteDown(obj:linkItemClass){
this.voteCount = this.voteCount - 1;
}
}
|
ea526f70205a54cf27c8a4e35ddeb168aa614728 | TypeScript | johanste/adl | /packages/adl/test/checker/global-namespace.ts | 2.578125 | 3 | import { assert } from "console";
import { createTestHost, TestHost } from "../test-host.js";
describe("adl: global namespace", () => {
let testHost: TestHost;
beforeEach(async () => {
testHost = await createTestHost();
});
describe("it adds top level entities to the global namespace", () => {
it("adds top-level namespaces", async () => {
testHost.addAdlFile("main.adl", `namespace Foo {}`);
await testHost.compile("./");
const globalNamespaceType = testHost.program.checker?.getGlobalNamespaceType();
assert(
globalNamespaceType?.namespaces.get("Foo"),
"Namespace Foo was added to global namespace type"
);
});
it("adds top-level models", async () => {
testHost.addAdlFile("main.adl", `model MyModel {}`);
await testHost.compile("./");
const globalNamespaceType = testHost.program.checker?.getGlobalNamespaceType();
assert(
globalNamespaceType?.models.get("MyModel"),
"model MyModel was added to global namespace type"
);
});
it("adds top-level oeprations", async () => {
testHost.addAdlFile("main.adl", `op myOperation(): string;`);
await testHost.compile("./");
const globalNamespaceType = testHost.program.checker?.getGlobalNamespaceType();
assert(
globalNamespaceType?.operations.get("myOperation"),
"operation myOperation was added to global namespace type"
);
});
});
describe("it adds top level entities used in other files to the global namespace", () => {
beforeEach(() => {
testHost.addAdlFile(
"main.adl",
`
import "./a.adl";
model Base {}
`
);
});
it("adds top-level namespaces", async () => {
testHost.addAdlFile("a.adl", `namespace Foo {}`);
await testHost.compile("./");
const globalNamespaceType = testHost.program.checker?.getGlobalNamespaceType();
assert(
globalNamespaceType?.namespaces.get("Foo"),
"Namespace Foo was added to global namespace type"
);
assert(
globalNamespaceType?.namespaces.get("Base"),
"Should still reference main file top-level entities"
);
});
it("adds top-level models", async () => {
testHost.addAdlFile("a.adl", `model MyModel {}`);
await testHost.compile("./");
const globalNamespaceType = testHost.program.checker?.getGlobalNamespaceType();
assert(
globalNamespaceType?.models.get("MyModel"),
"model MyModel was added to global namespace type"
);
});
it("adds top-level oeprations", async () => {
testHost.addAdlFile("a.adl", `op myOperation(): string;`);
await testHost.compile("./");
const globalNamespaceType = testHost.program.checker?.getGlobalNamespaceType();
assert(
globalNamespaceType?.operations.get("myOperation"),
"operation myOperation was added to global namespace type"
);
});
});
});
|
35ad932753ba6c296cb88562fc289db5596060c9 | TypeScript | hpfs74/james-frontend | /src/app/profile/reducers/settings.ts | 2.875 | 3 | import { Settings } from '../models/settings';
import * as SettingsActions from '../actions/settings';
export type Action = SettingsActions.All;
export interface State {
loading: boolean;
loaded: boolean;
settings: Settings | {};
}
export const initialState: State = {
loading: false,
loaded: false,
settings: {}
};
export function reducer(state = initialState, action: Action): State {
switch (action.type) {
case SettingsActions.UPDATE_SETTINGS_REQUEST: {
return Object.assign({}, state, {
loading: true
});
}
case SettingsActions.UPDATE_SETTINGS_SUCCESS: {
return Object.assign({}, state, {
loading: false,
loaded: true,
settings: Object.assign({}, action.payload)
});
}
default: {
return state;
}
}
}
export const getCurrent = (state: State) => state.settings;
export const getLoading = (state: State) => state.loading;
|
b43ccd5659fe778e00c096d33e6d2641db496cd7 | TypeScript | Aden-git/open-source | /libs/forms/core/src/control-mode.types.ts | 2.53125 | 3 | import { DynControlConfig } from './control-config.types';
import { DynControlParams } from './control-params.types';
// edit|display|table|filter
export type DynControlMode = string; // Mode ID
// config overrides per mode, handled by DynFormMode
export type DynControlModes<M extends string = DynControlMode> = {
[K in M]?: Partial<DynControlConfig>;
}
// general params overrides per mode, handled by DynFormMode
export type DynModeParams<M extends string = DynControlMode> = {
[K in M]?: Partial<DynControlParams>;
}
// general config overrides per mode+control, handled by DynFormMode
export type DynModeControls<M extends string = DynControlMode> = {
[K in M]?: DynControlConfig[];
}
|
88e8111c5ba48ba3df5d415b372cff8d74ca17a6 | TypeScript | ozknemoy/staffjs | /src/shared/validators.ts | 3 | 3 | import {HandleData} from "./handle-data";
import {Sequelize} from "sequelize-typescript";
export const phoneRegExp = /\d{11,13}/;
export const innRegExp = /\d{10,10}/;
export function invalidINN(inn: string): boolean {
// разрешаю null and ''
if (inn === null || inn === '') {
return false
}
return (!innRegExp.test(inn) || inn.length !== 10);
}
export function validateINN(inn: string) {
if (invalidINN(inn)) {
throw new Error(`Вы ввели не валидный ИНН "${inn}". Введите 10 цифр`);
}
}
export function hasValue(val: any, msg: string,) {
if (HandleData.isNoValuePrimitive(val)) {
throw new Error(msg);
}
}
export const opHasValue = {[Sequelize.Op.regexp]: '\.'};
export const opAll = {[Sequelize.Op.gt]: 0};
// can't do an equal compare with a NULL value -> use Is (not IN (null, 0))
// то же самое наоборот нельзя IS использовать с 0
export const opZeroOrNull = {[Sequelize.Op.or]: [{[Sequelize.Op.eq]: 0},{[Sequelize.Op.is]: null}]}; |
fcee38d5f75c11ce1e230e1147c1ea3883ca6545 | TypeScript | bpc1985/simple-survey | /src/survey/models/survey.ts | 2.8125 | 3 | /* tslint:disable:no-string-literal */
export interface ISurvey {
$key?: string;
completed: boolean;
createdAt: number;
name: string;
age: string;
colors: string[];
}
export class Survey implements ISurvey {
completed: boolean = false;
createdAt: number = firebase.database['ServerValue']['TIMESTAMP'];
name: string;
age: string;
colors: string[];
constructor(name: string, age: string, colors: string[]) {
this.name = name;
this.age = age;
this.colors = colors;
}
}
|
7e5fce166fe50ca8490812d09b7081c17c0e2338 | TypeScript | Flouics/client | /assets/script/zero/BaseClass.ts | 2.71875 | 3 | import { objToJson, jsonToObj } from "../utils/Decorator";
import UUID from "../utils/UUID";
export default class BaseClass {
_classDbKey:string;
_class = null;
_classId: string = "";
static _instance = null;
constructor(_class?:any){
if (_class != null) {
this._class = _class;
_class._instance = this; //单例
}
this._classId = UUID.gen(16);
this._classDbKey = this.getClassName();
}
public get className() : string {
return this.getClassName();
}
static clearInstance(_class:any){
_class._instance = null
}
//单例
static getInstance(_class:any){
if( _class._instance){
return _class._instance
}else{
let instance = new _class(_class);
return instance
}
}
getClassName(){
return this.constructor.name;
}
getId(){
return this._classId
}
//序列化
serialize(){
return objToJson(this)
}
//反序列号
unserialize(json:string){
jsonToObj(this,json);
}
} |
c655bfbf1e7ab49918e703dd5d08f5db102b8137 | TypeScript | atlassian-labs/compiled | /packages/babel-plugin/src/utils/comments.ts | 3.03125 | 3 | import type { BabelFile } from '@babel/core';
import type { NodePath } from '@babel/traverse';
import type * as t from '@babel/types';
import type { Metadata } from '../types';
/**
* Get comments for `path` in both the line before and on the current line.
*
* e.g.
* `<div css={{color: 'green'}} /> // @compiled-disable-line` will output `{before: [], current: [...]}
*
* @param path {NodePath<t.Node>}
* @param meta {Metadata} Context for the transform
* @returns {before: t.CommentLine[], current: t.CommentLine[]} Comments before and on the current line as the input path
*/
export const getNodeComments = (
path: NodePath<t.Node>,
meta: Metadata
): { before: t.CommentLine[]; current: t.CommentLine[] } => {
const lineNumber = path.node?.loc?.start.line;
if (!lineNumber || lineNumber !== path.node?.loc?.end.line) {
return { before: [], current: [] };
}
const file: BabelFile = meta.state.file;
const commentLines =
file.ast.comments?.filter<t.CommentLine>(
(comment: t.CommentLine | t.CommentBlock): comment is t.CommentLine =>
comment.type === 'CommentLine'
) ?? [];
return {
before: commentLines.filter(
(comment) =>
comment.loc?.start.line === lineNumber - 1 && comment.loc.end.line === lineNumber - 1
),
current: commentLines.filter(
(comment) => comment.loc?.start.line === lineNumber && comment.loc.end.line === lineNumber
),
};
};
|
40386d40e69fe78d1053289924a74bea7ec0242c | TypeScript | Caramel-Pudding/Weather-Forecasting-Sample-App | /src/network/weather-api/__tests__/fetch-weather.test.ts | 2.609375 | 3 | import fetchMock from "jest-fetch-mock";
import { weatherDataStub } from "@/tests//stubs";
import { fetchWeather } from "../methods/fetch-weather";
import { city } from "../../../consts/mocked";
import { buildWeatherAPIRequestRoute } from "../utilities/link-builders";
describe("Fetch Weather", () => {
beforeEach(() => {
fetchMock.resetMocks();
});
it(`if request resolves should return data`, async () => {
// * #TEST: ARRANGE
fetchMock.mockResponseOnce(JSON.stringify(weatherDataStub));
// * #TEST: ACT
const result = await fetchWeather(city);
// * #TEST: ASSERT
expect(result).toEqual(weatherDataStub);
expect(fetchMock.mock.calls).toHaveLength(1);
expect(fetchMock.mock.calls[0][0]).toEqual(
"https://samples.openweathermap.org/data/2.5/forecast?q=M%C3%BCnchen,DE&appid=b6907d289e10d714a6e88b30761fae22"
);
});
it(`if request rejects should return null`, async () => {
// * #TEST: ARRANGE
fetchMock.mockRejectOnce();
// * #TEST: ACT
const result = await fetchWeather(city);
// * #TEST: ASSERT
expect(result).toBeNull();
expect(fetchMock.mock.calls).toHaveLength(1);
expect(fetchMock.mock.calls[0][0]).toEqual(
"https://samples.openweathermap.org/data/2.5/forecast?q=M%C3%BCnchen,DE&appid=b6907d289e10d714a6e88b30761fae22"
);
});
});
describe("Build fetch weather link", () => {
it(`Should return valid url if input is valid`, () => {
// * #TEST: ARRANGE
const result = buildWeatherAPIRequestRoute(city);
// * #TEST: ASSERT
expect(result).toEqual(
"https://samples.openweathermap.org/data/2.5/forecast?q=M%C3%BCnchen,DE&appid=b6907d289e10d714a6e88b30761fae22"
);
});
});
|
4b3535d9c4ef445701b37ffbe53a6681d2b92bfa | TypeScript | Jontem/aoc2019 | /run.ts | 2.921875 | 3 | import * as fs from "fs";
import fetch from "node-fetch";
const usage = `Usage: <day>`;
const cliArgs = process.argv.slice(2);
const day = parseInt(cliArgs[0], 10);
if (!isFinite(day)) {
console.log(`Please specify which day to run`);
console.log(usage);
process.exit(1);
}
const cookie =
"todo";
interface PartModule {
run: (input: ReadonlyArray<string>) => void;
}
(async () => {
const input = await getInput(day, cookie);
await runPart(input, 1);
await runPart(input, 2);
})();
async function runPart(
input: ReadonlyArray<string>,
part: number
): Promise<void> {
const partModulePath = `./solutions/day${day}_${part}.ts`;
if (!fs.existsSync(partModulePath)) {
console.log(`Couldn't find ${partModulePath}`);
return;
}
console.log(`Running part ${part}:`);
const module: PartModule = await import(partModulePath);
const result = module.run(input);
console.log(`Result: ${result}`);
}
async function getInput(
day: number,
cookie: string
): Promise<ReadonlyArray<string>> {
const cacheFile = `solutions/day${day}_input`;
if (!fs.existsSync(cacheFile)) {
console.log("Input not cached. Fetching...");
await fetch(getInputUrl(day), {
headers: {
cookie: cookie
}
})
.then(res => res.text())
.then(text => {
fs.writeFileSync(cacheFile, text);
});
}
return fs
.readFileSync(cacheFile, { encoding: "utf8" })
.split("\n")
.filter(r => r.length > 0);
}
function getInputUrl(day: number): string {
return `https://adventofcode.com/2019/day/${day}/input`;
}
|
0a53e23561b141ea02cae28396f512853cf04e43 | TypeScript | zulianperdana/weather_react | /src/constants/units.ts | 2.578125 | 3 | interface UnitParameter {
temperature: string;
windSpeed: string;
pressure: string;
precip: string;
totalSnow: string;
}
const metric: UnitParameter = {
temperature: 'Celcius',
windSpeed: 'Kilometers/Hour',
pressure: 'Millibar',
precip: 'Millimeters',
totalSnow: 'Centimeters',
};
const scientific: UnitParameter = {
temperature: 'Kelvin',
windSpeed: 'Kilometers/Hour',
pressure: 'Millibar',
precip: 'Millimeters',
totalSnow: 'Centimeters',
};
const fahrenheit: UnitParameter = {
temperature: 'Fahrenheit',
windSpeed: 'Miles/Hour',
pressure: 'Millibar',
precip: 'Inches',
totalSnow: 'Inches',
};
export { metric, scientific, fahrenheit };
|
b9aae7b4894a07c4936d904b67123f5360d81997 | TypeScript | ArcticZeroo/advent-2020-node | /days/day13/solution.ts | 2.5625 | 3 | import { config } from 'dotenv';
import { readFileSync } from 'fs';
import * as path from 'path';
import * as advent from 'advent-api';
import { InfiniteGrid } from '../../common/grid';
import * as reducers from '../../common/reducers';
import { chars, chineseRemainder, first, lcm, lines, paragraphs } from '../../common/utils';
config();
const year = 2020;
const day = 13;
const input = readFileSync(path.resolve(path.join(__dirname, 'input.txt')), 'utf-8');
const submit = async (part: 1 | 2, answer: unknown) => {
const response = await advent.submitAnswer({ year, day, part, answer }, { cookie: process.env.ADVENT_COOKIE });
console.log(response);
const text = await response.text();
console.log(text);
return response;
};
const data = lines(input);
const part1 = async () => {
const departTimestamp = Number(data[0]);
const busesInService = data[1].split(',').filter(value => value !== 'x').map(Number);
let lowestBusId = -1;
let lowestTime = Number.POSITIVE_INFINITY;
for (const bus of busesInService) {
const nextTime = bus - (departTimestamp % bus);
if (nextTime < lowestTime) {
lowestBusId = bus;
lowestTime = nextTime;
}
}
console.log(lowestBusId, lowestTime, lowestBusId * lowestTime);
};
const part2 = async () => {
const departTimestamp = Number(data[0]);
const busesInService = data[1].split(',').map(Number);
const validIdsAndIndices = busesInService.map((value, i) => [value, i] as const).filter(([value]) => !Number.isNaN(value));
const values = validIdsAndIndices.map(([value]) => value);
const remainders = validIdsAndIndices.map(([value, i]) => value - i);
console.log(validIdsAndIndices);
console.log(values, remainders);
console.log(chineseRemainder(values, remainders));
};
const run = async () => {
await part1();
await part2();
};
run().catch(console.error);
|
2ab9c9ea1d0aadccaabe32e3303ce5aef76536a4 | TypeScript | nxtep-io/nano-discovery | /lib/storage/RedisDiscoveryStorage.ts | 2.578125 | 3 | import * as Redis from 'redis';
import { promisify } from 'util';
import { BaseDiscoveryStorage } from './BaseDiscoveryStorage';
export interface RedisDiscoveryStorageOptions extends Redis.ClientOpts {
}
export class RedisDiscoveryStorage implements BaseDiscoveryStorage {
name = 'redis';
protected client: Redis.RedisClient;
constructor(public options: RedisDiscoveryStorageOptions = {}) {
this.client = Redis.createClient(this.options);
}
public async connect(): Promise<void> {
if (!this.client.connected) {
return new Promise<void>((resolve, reject) => {
this.client.on('error', reject);
this.client.on('ready', resolve);
})
}
}
public async disconnect(): Promise<void> {
return new Promise<void>((resolve, reject) => {
this.client.on('error', reject);
this.client.quit(() => resolve());
this.client.quit();
})
}
public async setItem(key: string, value: string): Promise<void> {
const setAsync = promisify(this.client.set).bind(this.client);
await setAsync(key, value);
}
public async getItem(key: string): Promise<string> {
const getAsync = promisify(this.client.get).bind(this.client);
return getAsync(key);
}
public async removeItem(key: string): Promise<void> {
const delAsync = promisify((
key: string,
cb: (error: Error, result: number) => void
) => this.client.del(key, cb)).bind(this.client);;
await delAsync(key);
}
public async clear(): Promise<void> {
const flushdbAsync = promisify(this.client.flushdb).bind(this.client);;
await flushdbAsync();
}
} |
d611aab6d31b350b7fadb43389ed4c1073b47874 | TypeScript | hmcts/rpx-xui-webapp | /src/hearings/converters/hearing-length.answer.converter.ts | 2.734375 | 3 | import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { State } from '../store';
import { AnswerConverter } from './answer.converter';
export class HearingLengthAnswerConverter implements AnswerConverter {
public transformAnswer(hearingState$: Observable<State>): Observable<string> {
return hearingState$.pipe(
map((state) => {
let duration = state.hearingRequest.hearingRequestMainModel.hearingDetails.duration;
if (duration) {
let days = 0;
let hours = 0;
let minutes = 0;
if (duration > 0) {
minutes = duration % 60;
duration = duration - minutes;
days = Math.floor((duration / 60) / 6);
hours = Math.floor((duration / 60) % 6);
let formattedHearingLength = '';
if (days > 0) {
const daysLabel = days > 1 ? 'Days' : 'Day';
formattedHearingLength = `${days} ${daysLabel}`;
}
if (hours > 0) {
const hoursLabel = hours > 1 ? 'Hours' : 'Hour';
formattedHearingLength = formattedHearingLength.length > 0 ? `${formattedHearingLength} ${hours} ${hoursLabel}` : `${hours} ${hoursLabel}`;
}
if (minutes > 0) {
const minutesLabel = 'Minutes';
formattedHearingLength = formattedHearingLength.length > 0 ? `${formattedHearingLength} ${minutes} ${minutesLabel}` : `${minutes} ${minutesLabel}`;
}
if (formattedHearingLength.length > 0) {
return formattedHearingLength;
}
}
}
return '';
})
);
}
}
|
b2893a1b7704d594cfb513b197384d8e5fe88cf8 | TypeScript | richmolj/es-y | /src/conditions/builder.ts | 2.6875 | 3 | import omit = require('lodash.omit')
import pick = require('lodash.pick')
// Order matters! Process not then and/or LAST
const OPERATORS = [
'eq',
'prefix',
'match',
'matchPhrase',
'gt',
'gte',
'lt',
'lte',
'pastFiscalYears',
'exists',
]
// NOT before and/or
const COMBINATORS = [
'not',
'and',
'or'
]
const ACTIONS = OPERATORS.concat(COMBINATORS)
const TOP_LEVEL_KEYS = [
'page',
'sort',
'scoreMode' // nested conditions
]
function buildCondition(condition: any, payload: any) {
ACTIONS.forEach(action => {
if (!payload.hasOwnProperty(action)) return
const value = payload[action]
if (COMBINATORS.includes(action)) {
buildConditions(condition[action], value)
} else {
// Support 'heavy' structure
// match: { query: "foo bar baz", minimumShouldMatch: 2 }
if (typeof value === 'object' && !Array.isArray(value)) {
const { query } = value
const options = omit(value, ACTIONS.concat('query'))
condition = condition[action](query, options)
} else {
// Support 'light' structure
// match: "foo bar baz", minimumShouldMatch: 2
const options = omit(payload, ACTIONS)
condition = condition[action](value, options)
}
}
})
}
export function buildConditions(base: any, input: any) {
if (input) {
TOP_LEVEL_KEYS.forEach((topLevel) => {
if (input[topLevel]) {
if (typeof base[topLevel] === 'function') {
base[topLevel](input[topLevel])
} else {
base[topLevel] = input[topLevel]
}
}
})
let keys = Object.keys(omit(input, TOP_LEVEL_KEYS)) as string[]
// Combinators go last
keys = keys.sort((a: string, b: string) => {
return COMBINATORS.includes(a) ? 1 : -1
})
keys.some(key => {
if (ACTIONS.includes(key)) {
buildCondition(base, input)
return true // rest is handled recursively
} else {
const condition = base[key]
// Accomodate nested conditions
if (condition.isConditions) {
buildConditions(condition, input[key])
} else {
buildCondition(condition, input[key])
}
}
})
}
}
|
47292e0f8bccf367a4a212eca0969ffc9c413db6 | TypeScript | dlorenso/cipher-challenge | /ts/CipherSolver.ts | 3.0625 | 3 | /**
* Copyright (c) 2018 D. Dante Lorenso <dante@lorenso.com>. All Rights Reserved.
* This source file is subject to the MIT license that is bundled with this package
* in the file LICENSE.txt. It is also available at: https://opensource.org/licenses/MIT
*
* Dante's Cipher Solver is based on work by several online references including the following:
*
* http://practicalcryptography.com/cryptanalysis/text-characterisation/quadgrams/
* https://april.eecs.umich.edu/papers/details.php?name=olson2007crypt
* https://www.guballa.de/substitution-solver
* https://en.wikipedia.org/wiki/Substitution_cipher
* https://en.wikipedia.org/wiki/Hill_climbing
* https://repository.cardiffmet.ac.uk/bitstream/handle/10369/8628/Brown%2C%20Ryan%20James.pdf
*
* In numerical analysis, hill climbing is a mathematical optimization technique which belongs to the
* family of local search. It is an iterative algorithm that starts with an arbitrary solution to a
* problem, then attempts to find a better solution by incrementally changing a single element of
* the solution. If the change produces a better solution, an incremental change is made to the new
* solution, repeating until no further improvements can be found. ...
*
* We implement Hill Climbing to find the best Cipher Key that will decode the Cipher Text such that
* the decoded text will yield the "best" fitness score.
*
* Hill climbing achieves optimal solutions in convex problems – otherwise it will find only local
* optima (solutions that cannot be improved by considering a neighbouring configuration), which are
* not necessarily the best possible solution (the global optimum) out of all possible solutions (the
* search space). Examples of algorithms that solve convex problems by hill-climbing include the
* simplex algorithm for linear programming and binary search.[1]:253 To attempt overcoming being
* stuck in local optima, one could use restarts (i.e. repeated local search), or more complex
* schemes based on iterations (like iterated local search), or on memory (like reactive search
* optimization and tabu search), or on memory-less stochastic modifications (like simulated annealing).
*/
class CipherSolver {
// results
private best_score:number = 0;
// stats
private number_keys_tried:number = 0;
private number_rounds:number = 0;
// objects
private key:CipherKey;
private dict:string;
private timer:Timer;
constructor() {
this.timer = new Timer();
}
/**
* https://en.wikipedia.org/wiki/Hill_climbing
* @returns {number}
*/
private hillClimbing(ctext:CipherText) {
let score = 0;
let better_key;
do {
better_key = false;
// iterate over each letter in the alphabet (a-z) as integers
for (let i = 0; i < 25; i++) {
for (let j = i + 1; j < 26; j++) {
// swap the characters in these positions
this.key.swap(i, j);
// count the number of keys processed
this.number_keys_tried++;
// compute the score of this key against the quadgrams dictionary
let new_score = 0;
// decode the first 3 characters
let idx = (this.key.key[ctext.cipher[0]] << 10) + (this.key.key[ctext.cipher[1]] << 5) + this.key.key[ctext.cipher[2]];
/**
* Now shift three characters to the left and decode another character (now we have a quadgram)
* The index into our hash is our decoded quadgram as a 20 bit value [ch=5 bits][ch=5 bits][ch=5 bits][ch=5 bits]
* where each of the 5 bits represents a number from 0 to 25 and therefore will map onto a letter from a to z.
* For example, here are the indexes of several example quadgrams:
*
* AAAA = 0 0 0 0 = 00000 00000 00000 00000 = 0000 0000 0000 0000 0000, 0000 0000 0000 0000 = 0
* PVBD = 15 21 2 4 = 01111 10101 00010 00100 = 0000 0000 0000 0000 0111, 1101 0100 0100 0100 = 513092
* ZZZZ = 25 25 25 25 = 11001 11001 11001 11001 = 0000 0000 0000 0000 1100, 1110 0111 0011 1001 = 845625
*/
let len = ctext.cipher.length;
for (let x = 3; x < len; x++) {
idx = ((idx & 32767) << 5) + this.key.key[ctext.cipher[x]];
new_score += this.dict.charCodeAt(idx);
}
// this is a BETTER score, so it must be a better key
if (new_score > score) {
score = new_score;
better_key = true;
// this is the BEST score so far
this.eventKey(score, ctext);
}
// if this score is not better, swap the characters back
else {
this.key.swap(i, j);
}
}
}
}
while (better_key);
// the score for this run
return score;
}
/**
* @param {CipherText} ctext
*/
public solve(ctext:CipherText) {
this.number_keys_tried = 0;
this.best_score = 0;
this.number_rounds = 0;
// start our timer
this.timer = new Timer();
// never search more than 100,000 random keys
let cntr = 100000;
let nbr_best_scores = 0;
while (cntr--) {
this.number_rounds++;
// create a new random cipher key
this.key = new CipherKey();
this.key.shuffle();
// hill climb with this random cipher key
let score = this.hillClimbing(ctext);
// we found a new best score!
if (score > this.best_score) {
this.best_score = score;
nbr_best_scores = 1;
}
// we found the same best score again
else if (score === this.best_score) {
// stop if we found this same key 3 times
if (++nbr_best_scores === 3) {
break;
}
}
// update status
this.tick();
}
// cipher complete!
this.eventDone();
}
/**
* Save dictionary lookup hash.
* @param {string} dict
*/
public setDictionary(dict:string) {
this.dict = dict;
}
/**
*/
private tick() {
if (this.timer.getTicktime() > 1) {
this.timer.markTicktime();
this.eventUpdate();
}
}
/**
* @param {number} score
* @param {CipherText} ctext
*/
private eventKey(score:number, ctext:CipherText) {
if (score > this.best_score) {
let seconds = this.timer.getRuntime();
// fire the event
postMessage({
// message response type
'resp': 'key',
// message data
'key': this.key.toString(),
'len': ctext.cipher.length,
'nbr_keys': this.number_keys_tried,
'plain': ctext.decodeText(this.key),
'rate': this.number_keys_tried / seconds,
'rounds': this.number_rounds,
'runtime': seconds,
'score': score / (ctext.cipher.length - 3) - 35
});
}
}
/**
*/
private eventUpdate() {
let seconds = this.timer.getRuntime();
// fire event
postMessage({
// message response type
'resp': 'update',
// message data
'nbr_keys': this.number_keys_tried,
'rate': this.number_keys_tried / seconds,
'rounds': this.number_rounds,
'runtime': seconds
});
}
/**
*
*/
private eventDone() {
let seconds = this.timer.getRuntime();
// fire event
postMessage({
// message response type
'resp': 'done',
// message data
'nbr_keys': this.number_keys_tried,
'rate': this.number_keys_tried / seconds,
'rounds': this.number_rounds,
'runtime': seconds
});
}
}
|
1349ee4f0cf94778eb8dd284cbba8f9c499b3d99 | TypeScript | bisignam/automatajs | /src/app/automata-gui/automata-color-picker/automata-color-picker.component.ts | 2.546875 | 3 | import { Component, Output, EventEmitter, Input } from '@angular/core';
import * as THREE from 'three';
@Component({
selector: 'app-color-picker',
templateUrl: './automata-color-picker.component.html',
styleUrls: ['./automata-color-picker.component.scss'],
})
export class AutomataColorPickerComponent {
private _color: THREE.Color;
@Output()
private chosenColor = new EventEmitter<THREE.Color>();
@Input()
get color(): string {
return '#' + this._color.getHexString();
}
set color(color: string) {
//NOTE: when setting up the first time it seems the colors hex have no # prepended
if (!color.startsWith('#')) {
color = '#' + color;
}
this._color = new THREE.Color(color);
this.chosenColor.emit(this._color);
}
}
|
74e88d4f67edd34d578aff739c7fd1caf6ea7081 | TypeScript | Ddeak/ReactNativeTesting | /db/schema.ts | 2.53125 | 3 | const CustomerSchema = {
name: "Customer",
primaryKey: "id",
properties: {
id: { type: "string", indexed: true },
firstName: "string",
surname: "string",
phoneNumber: "string",
notes: "string",
pets: "Pet[]",
createdAt: "date",
updatedAt: "date",
},
};
const PetSchema = {
name: "Pet",
primaryKey: "id",
properties: {
id: { type: "string", indexed: true },
name: "string",
breed: "string",
owner: {
type: "linkingObjects",
objectType: "Customer",
property: "pets",
},
notes: "string",
createdAt: "date",
updatedAt: "date",
},
};
const AppointmentSchema = {
name: "Appointment",
primaryKey: "id",
properties: {
id: { type: "string", indexed: true },
customer: "Customer",
date: "date",
duration: "int",
createdAt: "date",
updatedAt: "date",
},
};
export const schema = [CustomerSchema, PetSchema, AppointmentSchema];
|
0fd48139283f94cb93323efa2b472045393a3866 | TypeScript | Yutiy/react-blog | /server/app/middleware/authHandler.ts | 2.9375 | 3 | import { Context } from 'egg';
/**
* role === 1 需要权限的路由
* @required 'all': get post put delete 均需要权限。
*/
const verifyList1 = [
{ regexp: /\/article\/output/, required: 'get', verifyTokenBy: 'url' }, // 导出文章 verifyTokenBy 从哪里验证 token
{ regexp: /\/article/, required: 'post, put, delete' }, // 普通用户 禁止修改或者删除、添加文章
{ regexp: /\/discuss/, required: 'delete, post' }, // 普通用户 禁止删除评论
{ regexp: /\/user/, required: 'put, delete' }, // 普通用户 禁止获取用户、修改用户、以及删除用户
]
// role === 2 需要权限的路由
const verifyList2 = [
{ regexp: /\/discuss/, required: 'post' }, // 未登录用户 禁止评论
]
/**
* 检查路由是否需要权限,返回一个权限列表
*
* @return {Array} 返回 roleList
*/
function checkAuth(method: string, url: string) {
function _verify(list) {
const target = list.find(v => {
return v.regexp.test(url) && (v.required === 'all' || v.required.toUpperCase().includes(method))
})
return target
}
const roleList: Array<{ role: number, verifyTokenBy: string }> = []
const result1 = _verify(verifyList1)
const result2 = _verify(verifyList2)
result1 && roleList.push({ role: 1, verifyTokenBy: result1.verifyTokenBy || 'headers' })
result2 && roleList.push({ role: 2, verifyTokenBy: result1.verifyTokenBy || 'headers' })
return roleList
}
export default function() {
return async (ctx: Context, next: any): Promise<void> => {
const { method, url, app } = ctx;
const roleList = checkAuth(method, url);
// 该路由需要验证
if (roleList.length > 0) {
if (app.utils.token.checkToken(ctx, roleList)) {
await next()
} else {
ctx.throw(401)
}
} else {
await next()
}
};
}
|
a52e854ccc3579077c2f93914a4da1014faa46cd | TypeScript | Study-Swap/study-swap-web | /src/utils/firebaseUtils/comments.ts | 2.5625 | 3 | // Firebase import
import firebaseApp from "firebase/app";
import firebase from "../../constants/Firebase";
// Constants import
import { collections } from "../../constants/FirebaseStrings";
import { commentModel } from "../../constants/Models";
import { commentAnalytics } from "../analyticsUtils";
// Makes code cleaner
const commentsDB = firebase.firestore().collection(collections.comments);
/*
@type GET -> Comments
@desc get all comments for a certain post
*/
function getComments(postId: string): Promise<any> {
return commentsDB
.where("postId", "==", postId)
.orderBy("timestamp", "desc")
.get()
.then(
(snapshot: any): Array<commentModel> => {
const comments: Array<commentModel> = [];
snapshot.forEach((comment: any): void => {
const data = comment.data();
comments.unshift({
id: comment.id,
userId: data.userId,
postId: data.postId,
commenterName: data.commenterName,
commentText: data.commentText,
timestamp: data.timestamp.toDate().toDateString(),
likedBy: data.likedBy,
commenterProfilePic: data.commenterProfilePic,
});
});
return comments;
}
)
.catch((err: any): void => {
console.error(err); // will be changed to redirect to error screen
});
}
/*
@type GET -> Comments
@desc get all comments for a certain post
*/
function getComment(postId: string): Promise<any> {
return commentsDB
.where("postId", "==", postId)
.orderBy("timestamp", "desc")
.limit(1)
.get()
.then(
(snapshot: any): Array<commentModel> => {
const comments: Array<commentModel> = [];
snapshot.forEach((comment: any): void => {
const data = comment.data();
comments.unshift({
id: comment.id,
userId: data.userId,
postId: data.postId,
commenterName: data.commenterName,
commentText: data.commentText,
timestamp: data.timestamp.toDate().toDateString(),
likedBy: data.likedBy,
commenterProfilePic: data.commenterProfilePic,
});
});
return comments;
}
)
.catch((err: any): void => {
console.error(err); // will be changed to redirect to error screen
});
}
/*
@type POST -> Comments
@desc add new comment
*/
function addComment(comment: commentModel): Promise<any> {
return commentsDB
.add({
timestamp: firebaseApp.firestore.FieldValue.serverTimestamp(),
...comment,
})
.then((ref: firebaseApp.firestore.DocumentData): any => {
const date = new Date();
commentAnalytics(comment.commentText, ref.id);
return {
id: ref.id,
timestamp: date.toDateString(),
};
})
.catch((err: any): any => {
console.error(err); // will be changed to redirect to error screen
return "error";
});
}
/*
@type DELETE -> Comments
@desc delete old comment
*/
function deleteComment(commentId: string): void {
commentsDB
.doc(commentId)
.delete()
.catch((err: any): void => {
console.error(err); // will be changed to redirect to error screen
});
}
/*
@type PATCH -> Comments
@desc edit old comment
*/
function editComment(commentId: string, newText: string): void {
commentsDB
.doc(commentId)
.update({ commentText: newText })
.catch((err: any): void => {
console.error(err); // will be changed to redirect to error screen
});
}
function addCommentLike(commentId: string, userId: string): void {
commentsDB
.doc(commentId)
.update({ likedBy: firebaseApp.firestore.FieldValue.arrayUnion(userId) })
.catch((err: any): void => {
console.error(err); // will be changed to redirect to error screen
});
}
function removeCommentLike(commentId: string, userId: string): void {
commentsDB
.doc(commentId)
.update({ likedBy: firebaseApp.firestore.FieldValue.arrayRemove(userId) })
.catch((err: any): void => {
console.error(err); // will be changed to redirect to error screen
});
}
export {
getComments,
addComment,
deleteComment,
editComment,
addCommentLike,
removeCommentLike,
getComment,
};
|
dcefb37d88cc3a05d97003b40bf13c3740a5a920 | TypeScript | vectoritc/bpmn-studio | /src/services/date-service/date.service.ts | 3.34375 | 3 | export class DateService {
private _date: Date;
private _day: string;
private _month: string;
private _year: string;
private _hour: string;
private _minute: string;
constructor(date: Date) {
this._date = date;
}
public asFormattedDate(): string {
const formattedDate: string = `${this._day}.${this._month}.${this._year} ${this._hour}:${this._minute}`;
return formattedDate;
}
public day(): DateService {
const day: string = `${this._date.getDate()}`;
const dayIsOneChar: boolean = day.length === 1;
this._day = dayIsOneChar ? `0${day}`
: day;
return this;
}
public month(): DateService {
const month: string = `${this._date.getMonth() + 1}`;
const monthIsOneChar: boolean = month.length === 1;
this._month = monthIsOneChar ? `0${month}`
: month;
return this;
}
public year(): DateService {
const year: string = `${this._date.getFullYear()}`;
this._year = year;
return this;
}
public hours(): DateService {
const hours: string = `${this._date.getHours()}`;
const hourIsOneChar: boolean = hours.length === 1;
this._hour = hourIsOneChar ? `0${hours}`
: hours;
return this;
}
public minutes(): DateService {
const minute: string = `${this._date.getMinutes()}`;
const minuteIsOneChar: boolean = minute.length === 1;
this._minute = minuteIsOneChar ? `0${minute}`
: minute;
return this;
}
}
|